DisplayListPlayerSkia.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. /*
  2. * Copyright (c) 2024, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <core/SkBitmap.h>
  7. #include <core/SkBlurTypes.h>
  8. #include <core/SkCanvas.h>
  9. #include <core/SkColorFilter.h>
  10. #include <core/SkFont.h>
  11. #include <core/SkFontMgr.h>
  12. #include <core/SkMaskFilter.h>
  13. #include <core/SkPath.h>
  14. #include <core/SkPathBuilder.h>
  15. #include <core/SkPathEffect.h>
  16. #include <core/SkRRect.h>
  17. #include <core/SkSurface.h>
  18. #include <effects/SkDashPathEffect.h>
  19. #include <effects/SkGradientShader.h>
  20. #include <effects/SkImageFilters.h>
  21. #include <gpu/GrDirectContext.h>
  22. #include <gpu/ganesh/SkSurfaceGanesh.h>
  23. #include <pathops/SkPathOps.h>
  24. #include <LibGfx/Font/ScaledFont.h>
  25. #include <LibWeb/CSS/ComputedValues.h>
  26. #include <LibWeb/Painting/DisplayListPlayerSkia.h>
  27. #include <LibWeb/Painting/ShadowPainting.h>
  28. #ifdef USE_VULKAN
  29. # include <gpu/ganesh/vk/GrVkDirectContext.h>
  30. # include <gpu/vk/GrVkBackendContext.h>
  31. # include <gpu/vk/VulkanBackendContext.h>
  32. # include <gpu/vk/VulkanExtensions.h>
  33. #endif
  34. #ifdef AK_OS_MACOS
  35. # define FixedPoint FixedPointMacOS
  36. # define Duration DurationMacOS
  37. # include <gpu/GrBackendSurface.h>
  38. # include <gpu/ganesh/mtl/GrMtlBackendContext.h>
  39. # include <gpu/ganesh/mtl/GrMtlDirectContext.h>
  40. # undef FixedPoint
  41. # undef Duration
  42. #endif
  43. namespace Web::Painting {
  44. class DisplayListPlayerSkia::SkiaSurface {
  45. public:
  46. SkCanvas& canvas() const { return *m_surface->getCanvas(); }
  47. SkiaSurface(sk_sp<SkSurface> surface)
  48. : m_surface(move(surface))
  49. {
  50. }
  51. void read_into_bitmap(Gfx::Bitmap& bitmap)
  52. {
  53. auto image_info = SkImageInfo::Make(bitmap.width(), bitmap.height(), kBGRA_8888_SkColorType, kPremul_SkAlphaType);
  54. SkPixmap pixmap(image_info, bitmap.begin(), bitmap.pitch());
  55. m_surface->readPixels(pixmap, 0, 0);
  56. }
  57. sk_sp<SkSurface> make_surface(int width, int height)
  58. {
  59. return m_surface->makeSurface(width, height);
  60. }
  61. private:
  62. sk_sp<SkSurface> m_surface;
  63. };
  64. #ifdef USE_VULKAN
  65. class SkiaVulkanBackendContext final : public SkiaBackendContext {
  66. AK_MAKE_NONCOPYABLE(SkiaVulkanBackendContext);
  67. AK_MAKE_NONMOVABLE(SkiaVulkanBackendContext);
  68. public:
  69. SkiaVulkanBackendContext(sk_sp<GrDirectContext> context, NonnullOwnPtr<skgpu::VulkanExtensions> extensions)
  70. : m_context(move(context))
  71. , m_extensions(move(extensions))
  72. {
  73. }
  74. ~SkiaVulkanBackendContext() override {};
  75. void flush_and_submit() override
  76. {
  77. m_context->flush();
  78. m_context->submit(GrSyncCpu::kYes);
  79. }
  80. sk_sp<SkSurface> create_surface(int width, int height)
  81. {
  82. auto image_info = SkImageInfo::Make(width, height, kBGRA_8888_SkColorType, kPremul_SkAlphaType);
  83. return SkSurfaces::RenderTarget(m_context.get(), skgpu::Budgeted::kYes, image_info);
  84. }
  85. skgpu::VulkanExtensions const* extensions() const { return m_extensions.ptr(); }
  86. private:
  87. sk_sp<GrDirectContext> m_context;
  88. NonnullOwnPtr<skgpu::VulkanExtensions> m_extensions;
  89. };
  90. OwnPtr<SkiaBackendContext> DisplayListPlayerSkia::create_vulkan_context(Core::VulkanContext& vulkan_context)
  91. {
  92. GrVkBackendContext backend_context;
  93. backend_context.fInstance = vulkan_context.instance;
  94. backend_context.fDevice = vulkan_context.logical_device;
  95. backend_context.fQueue = vulkan_context.graphics_queue;
  96. backend_context.fPhysicalDevice = vulkan_context.physical_device;
  97. backend_context.fMaxAPIVersion = vulkan_context.api_version;
  98. backend_context.fGetProc = [](char const* proc_name, VkInstance instance, VkDevice device) {
  99. if (device != VK_NULL_HANDLE) {
  100. return vkGetDeviceProcAddr(device, proc_name);
  101. }
  102. return vkGetInstanceProcAddr(instance, proc_name);
  103. };
  104. auto extensions = make<skgpu::VulkanExtensions>();
  105. backend_context.fVkExtensions = extensions.ptr();
  106. sk_sp<GrDirectContext> ctx = GrDirectContexts::MakeVulkan(backend_context);
  107. VERIFY(ctx);
  108. return make<SkiaVulkanBackendContext>(ctx, move(extensions));
  109. }
  110. DisplayListPlayerSkia::DisplayListPlayerSkia(SkiaBackendContext& context, Gfx::Bitmap& bitmap)
  111. {
  112. VERIFY(bitmap.format() == Gfx::BitmapFormat::BGRA8888);
  113. auto surface = static_cast<SkiaVulkanBackendContext&>(context).create_surface(bitmap.width(), bitmap.height());
  114. m_surface = make<SkiaSurface>(surface);
  115. m_flush_context = [&bitmap, &surface = m_surface, &context] {
  116. context.flush_and_submit();
  117. surface->read_into_bitmap(bitmap);
  118. };
  119. }
  120. #endif
  121. #ifdef AK_OS_MACOS
  122. class SkiaMetalBackendContext final : public SkiaBackendContext {
  123. AK_MAKE_NONCOPYABLE(SkiaMetalBackendContext);
  124. AK_MAKE_NONMOVABLE(SkiaMetalBackendContext);
  125. public:
  126. SkiaMetalBackendContext(sk_sp<GrDirectContext> context)
  127. : m_context(move(context))
  128. {
  129. }
  130. ~SkiaMetalBackendContext() override {};
  131. sk_sp<SkSurface> wrap_metal_texture(Core::MetalTexture& metal_texture)
  132. {
  133. GrMtlTextureInfo mtl_info;
  134. mtl_info.fTexture = sk_ret_cfp(metal_texture.texture());
  135. auto backend_render_target = GrBackendRenderTarget(metal_texture.width(), metal_texture.height(), mtl_info);
  136. return SkSurfaces::WrapBackendRenderTarget(m_context.get(), backend_render_target, kTopLeft_GrSurfaceOrigin, kBGRA_8888_SkColorType, nullptr, nullptr);
  137. }
  138. void flush_and_submit() override
  139. {
  140. m_context->flush();
  141. m_context->submit(GrSyncCpu::kYes);
  142. }
  143. private:
  144. sk_sp<GrDirectContext> m_context;
  145. };
  146. OwnPtr<SkiaBackendContext> DisplayListPlayerSkia::create_metal_context(Core::MetalContext const& metal_context)
  147. {
  148. GrMtlBackendContext backend_context;
  149. backend_context.fDevice.retain((GrMTLHandle)metal_context.device());
  150. backend_context.fQueue.retain((GrMTLHandle)metal_context.queue());
  151. sk_sp<GrDirectContext> ctx = GrDirectContexts::MakeMetal(backend_context);
  152. return make<SkiaMetalBackendContext>(ctx);
  153. }
  154. DisplayListPlayerSkia::DisplayListPlayerSkia(SkiaBackendContext& context, Core::MetalTexture& metal_texture)
  155. {
  156. auto image_info = SkImageInfo::Make(metal_texture.width(), metal_texture.height(), kBGRA_8888_SkColorType, kPremul_SkAlphaType);
  157. VERIFY(is<SkiaMetalBackendContext>(context));
  158. auto surface = static_cast<SkiaMetalBackendContext&>(context).wrap_metal_texture(metal_texture);
  159. if (!surface) {
  160. dbgln("Failed to create Skia surface from Metal texture");
  161. VERIFY_NOT_REACHED();
  162. }
  163. m_surface = make<SkiaSurface>(surface);
  164. m_flush_context = [&context] mutable {
  165. context.flush_and_submit();
  166. };
  167. }
  168. #endif
  169. DisplayListPlayerSkia::DisplayListPlayerSkia(Gfx::Bitmap& bitmap)
  170. {
  171. VERIFY(bitmap.format() == Gfx::BitmapFormat::BGRA8888);
  172. auto image_info = SkImageInfo::Make(bitmap.width(), bitmap.height(), kBGRA_8888_SkColorType, kPremul_SkAlphaType);
  173. auto surface = SkSurfaces::WrapPixels(image_info, bitmap.begin(), bitmap.pitch());
  174. VERIFY(surface);
  175. m_surface = make<SkiaSurface>(surface);
  176. }
  177. DisplayListPlayerSkia::~DisplayListPlayerSkia()
  178. {
  179. if (m_flush_context)
  180. m_flush_context();
  181. }
  182. static SkPoint to_skia_point(auto const& point)
  183. {
  184. return SkPoint::Make(point.x(), point.y());
  185. }
  186. static SkRect to_skia_rect(auto const& rect)
  187. {
  188. return SkRect::MakeXYWH(rect.x(), rect.y(), rect.width(), rect.height());
  189. }
  190. static SkColor to_skia_color(Gfx::Color const& color)
  191. {
  192. return SkColorSetARGB(color.alpha(), color.red(), color.green(), color.blue());
  193. }
  194. static SkColor4f to_skia_color4f(Gfx::Color const& color)
  195. {
  196. return {
  197. .fR = color.red() / 255.0f,
  198. .fG = color.green() / 255.0f,
  199. .fB = color.blue() / 255.0f,
  200. .fA = color.alpha() / 255.0f,
  201. };
  202. }
  203. static SkPath to_skia_path(Gfx::DeprecatedPath const& path)
  204. {
  205. Optional<Gfx::FloatPoint> subpath_start_point;
  206. Optional<Gfx::FloatPoint> subpath_last_point;
  207. SkPathBuilder path_builder;
  208. auto close_subpath_if_needed = [&](auto last_point) {
  209. if (subpath_start_point == last_point)
  210. path_builder.close();
  211. };
  212. for (auto const& segment : path) {
  213. auto point = segment.point();
  214. switch (segment.command()) {
  215. case Gfx::DeprecatedPathSegment::Command::MoveTo: {
  216. if (subpath_start_point.has_value() && subpath_last_point.has_value())
  217. close_subpath_if_needed(subpath_last_point.value());
  218. subpath_start_point = point;
  219. path_builder.moveTo({ point.x(), point.y() });
  220. break;
  221. }
  222. case Gfx::DeprecatedPathSegment::Command::LineTo: {
  223. if (!subpath_start_point.has_value())
  224. subpath_start_point = Gfx::FloatPoint { 0.0f, 0.0f };
  225. path_builder.lineTo({ point.x(), point.y() });
  226. break;
  227. }
  228. case Gfx::DeprecatedPathSegment::Command::QuadraticBezierCurveTo: {
  229. if (!subpath_start_point.has_value())
  230. subpath_start_point = Gfx::FloatPoint { 0.0f, 0.0f };
  231. SkPoint pt1 = { segment.through().x(), segment.through().y() };
  232. SkPoint pt2 = { segment.point().x(), segment.point().y() };
  233. path_builder.quadTo(pt1, pt2);
  234. break;
  235. }
  236. case Gfx::DeprecatedPathSegment::Command::CubicBezierCurveTo: {
  237. if (!subpath_start_point.has_value())
  238. subpath_start_point = Gfx::FloatPoint { 0.0f, 0.0f };
  239. SkPoint pt1 = { segment.through_0().x(), segment.through_0().y() };
  240. SkPoint pt2 = { segment.through_1().x(), segment.through_1().y() };
  241. SkPoint pt3 = { segment.point().x(), segment.point().y() };
  242. path_builder.cubicTo(pt1, pt2, pt3);
  243. break;
  244. }
  245. default:
  246. VERIFY_NOT_REACHED();
  247. }
  248. subpath_last_point = point;
  249. }
  250. close_subpath_if_needed(subpath_last_point);
  251. return path_builder.snapshot();
  252. }
  253. static SkPathFillType to_skia_path_fill_type(Gfx::WindingRule winding_rule)
  254. {
  255. switch (winding_rule) {
  256. case Gfx::WindingRule::Nonzero:
  257. return SkPathFillType::kWinding;
  258. case Gfx::WindingRule::EvenOdd:
  259. return SkPathFillType::kEvenOdd;
  260. }
  261. VERIFY_NOT_REACHED();
  262. }
  263. static SkRRect to_skia_rrect(auto const& rect, CornerRadii const& corner_radii)
  264. {
  265. SkRRect rrect;
  266. SkVector radii[4];
  267. radii[0].set(corner_radii.top_left.horizontal_radius, corner_radii.top_left.vertical_radius);
  268. radii[1].set(corner_radii.top_right.horizontal_radius, corner_radii.top_right.vertical_radius);
  269. radii[2].set(corner_radii.bottom_right.horizontal_radius, corner_radii.bottom_right.vertical_radius);
  270. radii[3].set(corner_radii.bottom_left.horizontal_radius, corner_radii.bottom_left.vertical_radius);
  271. rrect.setRectRadii(to_skia_rect(rect), radii);
  272. return rrect;
  273. }
  274. static SkColorType to_skia_color_type(Gfx::BitmapFormat format)
  275. {
  276. switch (format) {
  277. case Gfx::BitmapFormat::Invalid:
  278. return kUnknown_SkColorType;
  279. case Gfx::BitmapFormat::BGRA8888:
  280. case Gfx::BitmapFormat::BGRx8888:
  281. return kBGRA_8888_SkColorType;
  282. case Gfx::BitmapFormat::RGBA8888:
  283. return kRGBA_8888_SkColorType;
  284. default:
  285. return kUnknown_SkColorType;
  286. }
  287. }
  288. static SkBitmap to_skia_bitmap(Gfx::Bitmap const& bitmap)
  289. {
  290. SkColorType color_type = to_skia_color_type(bitmap.format());
  291. SkAlphaType alpha_type = bitmap.alpha_type() == Gfx::AlphaType::Premultiplied ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
  292. SkImageInfo image_info = SkImageInfo::Make(bitmap.width(), bitmap.height(), color_type, alpha_type);
  293. SkBitmap sk_bitmap;
  294. sk_bitmap.setInfo(image_info);
  295. if (!sk_bitmap.installPixels(image_info, const_cast<Gfx::ARGB32*>(bitmap.begin()), bitmap.width() * 4)) {
  296. VERIFY_NOT_REACHED();
  297. }
  298. sk_bitmap.setImmutable();
  299. return sk_bitmap;
  300. }
  301. static SkMatrix to_skia_matrix(Gfx::AffineTransform const& affine_transform)
  302. {
  303. SkScalar affine[6];
  304. affine[0] = affine_transform.a();
  305. affine[1] = affine_transform.b();
  306. affine[2] = affine_transform.c();
  307. affine[3] = affine_transform.d();
  308. affine[4] = affine_transform.e();
  309. affine[5] = affine_transform.f();
  310. SkMatrix matrix;
  311. matrix.setAffine(affine);
  312. return matrix;
  313. }
  314. static SkSamplingOptions to_skia_sampling_options(Gfx::ScalingMode scaling_mode)
  315. {
  316. switch (scaling_mode) {
  317. case Gfx::ScalingMode::NearestNeighbor:
  318. return SkSamplingOptions(SkFilterMode::kNearest);
  319. case Gfx::ScalingMode::BilinearBlend:
  320. case Gfx::ScalingMode::SmoothPixels:
  321. return SkSamplingOptions(SkFilterMode::kLinear);
  322. case Gfx::ScalingMode::BoxSampling:
  323. return SkSamplingOptions(SkCubicResampler::Mitchell());
  324. default:
  325. VERIFY_NOT_REACHED();
  326. }
  327. }
  328. DisplayListPlayerSkia::SkiaSurface& DisplayListPlayerSkia::surface() const
  329. {
  330. return static_cast<SkiaSurface&>(*m_surface);
  331. }
  332. void DisplayListPlayerSkia::draw_glyph_run(DrawGlyphRun const& command)
  333. {
  334. auto const& gfx_font = static_cast<Gfx::ScaledFont const&>(command.glyph_run->font());
  335. auto sk_font = gfx_font.skia_font(command.scale);
  336. auto glyph_count = command.glyph_run->glyphs().size();
  337. Vector<SkGlyphID> glyphs;
  338. glyphs.ensure_capacity(glyph_count);
  339. Vector<SkPoint> positions;
  340. positions.ensure_capacity(glyph_count);
  341. auto font_ascent = gfx_font.pixel_metrics().ascent;
  342. for (auto const& glyph_or_emoji : command.glyph_run->glyphs()) {
  343. auto transformed_glyph = glyph_or_emoji;
  344. transformed_glyph.visit([&](auto& glyph) {
  345. glyph.position.set_y(glyph.position.y() + font_ascent);
  346. glyph.position = glyph.position.scaled(command.scale);
  347. });
  348. if (transformed_glyph.has<Gfx::DrawGlyph>()) {
  349. auto& glyph = transformed_glyph.get<Gfx::DrawGlyph>();
  350. auto const& point = glyph.position;
  351. glyphs.append(glyph.glyph_id);
  352. positions.append(to_skia_point(point));
  353. }
  354. }
  355. SkPaint paint;
  356. paint.setColor(to_skia_color(command.color));
  357. surface().canvas().drawGlyphs(glyphs.size(), glyphs.data(), positions.data(), to_skia_point(command.translation), sk_font, paint);
  358. }
  359. void DisplayListPlayerSkia::fill_rect(FillRect const& command)
  360. {
  361. auto const& rect = command.rect;
  362. auto& canvas = surface().canvas();
  363. SkPaint paint;
  364. paint.setColor(to_skia_color(command.color));
  365. canvas.drawRect(to_skia_rect(rect), paint);
  366. }
  367. void DisplayListPlayerSkia::draw_scaled_bitmap(DrawScaledBitmap const& command)
  368. {
  369. auto src_rect = to_skia_rect(command.src_rect);
  370. auto dst_rect = to_skia_rect(command.dst_rect);
  371. auto bitmap = to_skia_bitmap(command.bitmap);
  372. auto image = SkImages::RasterFromBitmap(bitmap);
  373. auto& canvas = surface().canvas();
  374. SkPaint paint;
  375. canvas.drawImageRect(image, src_rect, dst_rect, to_skia_sampling_options(command.scaling_mode), &paint, SkCanvas::kStrict_SrcRectConstraint);
  376. }
  377. void DisplayListPlayerSkia::draw_scaled_immutable_bitmap(DrawScaledImmutableBitmap const& command)
  378. {
  379. auto src_rect = to_skia_rect(command.src_rect);
  380. auto dst_rect = to_skia_rect(command.dst_rect);
  381. auto bitmap = to_skia_bitmap(command.bitmap->bitmap());
  382. auto image = SkImages::RasterFromBitmap(bitmap);
  383. auto& canvas = surface().canvas();
  384. SkPaint paint;
  385. canvas.drawImageRect(image, src_rect, dst_rect, to_skia_sampling_options(command.scaling_mode), &paint, SkCanvas::kStrict_SrcRectConstraint);
  386. }
  387. void DisplayListPlayerSkia::draw_repeated_immutable_bitmap(DrawRepeatedImmutableBitmap const& command)
  388. {
  389. auto bitmap = to_skia_bitmap(command.bitmap->bitmap());
  390. auto image = SkImages::RasterFromBitmap(bitmap);
  391. SkMatrix matrix;
  392. auto dst_rect = command.dst_rect.to_type<float>();
  393. auto src_size = command.bitmap->size().to_type<float>();
  394. matrix.setScale(dst_rect.width() / src_size.width(), dst_rect.height() / src_size.height());
  395. matrix.postTranslate(dst_rect.x(), dst_rect.y());
  396. auto sampling_options = to_skia_sampling_options(command.scaling_mode);
  397. auto tile_mode_x = command.repeat.x ? SkTileMode::kRepeat : SkTileMode::kDecal;
  398. auto tile_mode_y = command.repeat.y ? SkTileMode::kRepeat : SkTileMode::kDecal;
  399. auto shader = image->makeShader(tile_mode_x, tile_mode_y, sampling_options, matrix);
  400. SkPaint paint;
  401. paint.setShader(shader);
  402. auto& canvas = surface().canvas();
  403. canvas.drawPaint(paint);
  404. }
  405. void DisplayListPlayerSkia::add_clip_rect(AddClipRect const& command)
  406. {
  407. auto& canvas = surface().canvas();
  408. auto const& rect = command.rect;
  409. canvas.clipRect(to_skia_rect(rect));
  410. }
  411. void DisplayListPlayerSkia::save(Save const&)
  412. {
  413. auto& canvas = surface().canvas();
  414. canvas.save();
  415. }
  416. void DisplayListPlayerSkia::restore(Restore const&)
  417. {
  418. auto& canvas = surface().canvas();
  419. canvas.restore();
  420. }
  421. static SkBitmap alpha_mask_from_bitmap(Gfx::Bitmap const& bitmap, Gfx::Bitmap::MaskKind kind)
  422. {
  423. SkBitmap alpha_mask;
  424. alpha_mask.allocPixels(SkImageInfo::MakeA8(bitmap.width(), bitmap.height()));
  425. for (int y = 0; y < bitmap.height(); y++) {
  426. for (int x = 0; x < bitmap.width(); x++) {
  427. if (kind == Gfx::Bitmap::MaskKind::Luminance) {
  428. auto color = bitmap.get_pixel(x, y);
  429. *alpha_mask.getAddr8(x, y) = color.alpha() * color.luminosity() / 255;
  430. } else {
  431. VERIFY(kind == Gfx::Bitmap::MaskKind::Alpha);
  432. auto color = bitmap.get_pixel(x, y);
  433. *alpha_mask.getAddr8(x, y) = color.alpha();
  434. }
  435. }
  436. }
  437. return alpha_mask;
  438. }
  439. void DisplayListPlayerSkia::push_stacking_context(PushStackingContext const& command)
  440. {
  441. auto& canvas = surface().canvas();
  442. auto affine_transform = Gfx::extract_2d_affine_transform(command.transform.matrix);
  443. auto new_transform = Gfx::AffineTransform {}
  444. .set_translation(command.post_transform_translation.to_type<float>())
  445. .translate(command.transform.origin)
  446. .multiply(affine_transform)
  447. .translate(-command.transform.origin);
  448. auto matrix = to_skia_matrix(new_transform);
  449. if (command.opacity < 1) {
  450. auto source_paintable_rect = to_skia_rect(command.source_paintable_rect);
  451. SkRect dest;
  452. matrix.mapRect(&dest, source_paintable_rect);
  453. canvas.saveLayerAlphaf(&dest, command.opacity);
  454. } else {
  455. canvas.save();
  456. }
  457. if (command.mask.has_value()) {
  458. auto alpha_mask = alpha_mask_from_bitmap(*command.mask.value().mask_bitmap, command.mask.value().mask_kind);
  459. SkMatrix mask_matrix;
  460. auto mask_position = command.source_paintable_rect.location();
  461. mask_matrix.setTranslate(mask_position.x(), mask_position.y());
  462. auto shader = alpha_mask.makeShader(SkSamplingOptions(), mask_matrix);
  463. canvas.clipShader(shader);
  464. }
  465. if (command.is_fixed_position) {
  466. // FIXME: Resetting matrix is not correct when element is nested in a transformed stacking context
  467. canvas.resetMatrix();
  468. }
  469. canvas.concat(matrix);
  470. }
  471. void DisplayListPlayerSkia::pop_stacking_context(PopStackingContext const&)
  472. {
  473. surface().canvas().restore();
  474. }
  475. static ColorStopList replace_transition_hints_with_normal_color_stops(ColorStopList const& color_stop_list)
  476. {
  477. ColorStopList stops_with_replaced_transition_hints;
  478. auto const& first_color_stop = color_stop_list.first();
  479. // First color stop in the list should never have transition hint value
  480. VERIFY(!first_color_stop.transition_hint.has_value());
  481. stops_with_replaced_transition_hints.empend(first_color_stop.color, first_color_stop.position);
  482. // This loop replaces transition hints with five regular points, calculated using the
  483. // formula defined in the spec. After rendering using linear interpolation, this will
  484. // produce a result close enough to that obtained if the color of each point were calculated
  485. // using the non-linear formula from the spec.
  486. for (size_t i = 1; i < color_stop_list.size(); i++) {
  487. auto const& color_stop = color_stop_list[i];
  488. if (!color_stop.transition_hint.has_value()) {
  489. stops_with_replaced_transition_hints.empend(color_stop.color, color_stop.position);
  490. continue;
  491. }
  492. auto const& previous_color_stop = color_stop_list[i - 1];
  493. auto const& next_color_stop = color_stop_list[i];
  494. auto distance_between_stops = next_color_stop.position - previous_color_stop.position;
  495. auto transition_hint = color_stop.transition_hint.value();
  496. Array<float, 5> const transition_hint_relative_sampling_positions = {
  497. transition_hint * 0.33f,
  498. transition_hint * 0.66f,
  499. transition_hint,
  500. transition_hint + (1 - transition_hint) * 0.33f,
  501. transition_hint + (1 - transition_hint) * 0.66f,
  502. };
  503. for (auto const& transition_hint_relative_sampling_position : transition_hint_relative_sampling_positions) {
  504. auto position = previous_color_stop.position + transition_hint_relative_sampling_position * distance_between_stops;
  505. auto value = color_stop_step(previous_color_stop, next_color_stop, position);
  506. auto color = previous_color_stop.color.interpolate(next_color_stop.color, value);
  507. stops_with_replaced_transition_hints.empend(color, position);
  508. }
  509. stops_with_replaced_transition_hints.empend(color_stop.color, color_stop.position);
  510. }
  511. return stops_with_replaced_transition_hints;
  512. }
  513. static ColorStopList expand_repeat_length(ColorStopList const& color_stop_list, float repeat_length)
  514. {
  515. // https://drafts.csswg.org/css-images/#repeating-gradients
  516. // When rendered, however, the color-stops are repeated infinitely in both directions, with their
  517. // positions shifted by multiples of the difference between the last specified color-stop’s position
  518. // and the first specified color-stop’s position. For example, repeating-linear-gradient(red 10px, blue 50px)
  519. // is equivalent to linear-gradient(..., red -30px, blue 10px, red 10px, blue 50px, red 50px, blue 90px, ...).
  520. auto first_stop_position = color_stop_list.first().position;
  521. int const negative_repeat_count = AK::ceil(first_stop_position / repeat_length);
  522. int const positive_repeat_count = AK::ceil((1.0f - first_stop_position) / repeat_length);
  523. ColorStopList color_stop_list_with_expanded_repeat = color_stop_list;
  524. auto get_color_between_stops = [](float position, auto const& current_stop, auto const& previous_stop) {
  525. auto distance_between_stops = current_stop.position - previous_stop.position;
  526. auto percentage = (position - previous_stop.position) / distance_between_stops;
  527. return previous_stop.color.interpolate(current_stop.color, percentage);
  528. };
  529. for (auto repeat_count = 1; repeat_count <= negative_repeat_count; repeat_count++) {
  530. for (auto stop : color_stop_list.in_reverse()) {
  531. stop.position += repeat_length * static_cast<float>(-repeat_count);
  532. if (stop.position < 0) {
  533. stop.color = get_color_between_stops(0.0f, stop, color_stop_list_with_expanded_repeat.first());
  534. color_stop_list_with_expanded_repeat.prepend(stop);
  535. break;
  536. }
  537. color_stop_list_with_expanded_repeat.prepend(stop);
  538. }
  539. }
  540. for (auto repeat_count = 0; repeat_count < positive_repeat_count; repeat_count++) {
  541. for (auto stop : color_stop_list) {
  542. stop.position += repeat_length * static_cast<float>(repeat_count);
  543. if (stop.position > 1) {
  544. stop.color = get_color_between_stops(1.0f, stop, color_stop_list_with_expanded_repeat.last());
  545. color_stop_list_with_expanded_repeat.append(stop);
  546. break;
  547. }
  548. color_stop_list_with_expanded_repeat.append(stop);
  549. }
  550. }
  551. return color_stop_list_with_expanded_repeat;
  552. }
  553. void DisplayListPlayerSkia::paint_linear_gradient(PaintLinearGradient const& command)
  554. {
  555. auto const& linear_gradient_data = command.linear_gradient_data;
  556. auto color_stop_list = linear_gradient_data.color_stops.list;
  557. auto const& repeat_length = linear_gradient_data.color_stops.repeat_length;
  558. VERIFY(!color_stop_list.is_empty());
  559. if (repeat_length.has_value())
  560. color_stop_list = expand_repeat_length(color_stop_list, *repeat_length);
  561. auto stops_with_replaced_transition_hints = replace_transition_hints_with_normal_color_stops(color_stop_list);
  562. Vector<SkColor4f> colors;
  563. Vector<SkScalar> positions;
  564. for (size_t stop_index = 0; stop_index < stops_with_replaced_transition_hints.size(); stop_index++) {
  565. auto const& stop = stops_with_replaced_transition_hints[stop_index];
  566. if (stop_index > 0 && stop == stops_with_replaced_transition_hints[stop_index - 1])
  567. continue;
  568. colors.append(to_skia_color4f(stop.color));
  569. positions.append(stop.position);
  570. }
  571. auto const& rect = command.gradient_rect;
  572. auto length = calculate_gradient_length<int>(rect.size(), linear_gradient_data.gradient_angle);
  573. auto bottom = rect.center().translated(0, -length / 2);
  574. auto top = rect.center().translated(0, length / 2);
  575. Array<SkPoint, 2> points;
  576. points[0] = to_skia_point(top);
  577. points[1] = to_skia_point(bottom);
  578. auto center = to_skia_rect(rect).center();
  579. SkMatrix matrix;
  580. matrix.setRotate(linear_gradient_data.gradient_angle, center.x(), center.y());
  581. auto color_space = SkColorSpace::MakeSRGB();
  582. SkGradientShader::Interpolation interpolation = {};
  583. interpolation.fColorSpace = SkGradientShader::Interpolation::ColorSpace::kSRGB;
  584. interpolation.fInPremul = SkGradientShader::Interpolation::InPremul::kYes;
  585. auto shader = SkGradientShader::MakeLinear(points.data(), colors.data(), color_space, positions.data(), positions.size(), SkTileMode::kClamp, interpolation, &matrix);
  586. SkPaint paint;
  587. paint.setShader(shader);
  588. surface().canvas().drawRect(to_skia_rect(rect), paint);
  589. }
  590. static void add_spread_distance_to_border_radius(int& border_radius, int spread_distance)
  591. {
  592. if (border_radius == 0 || spread_distance == 0)
  593. return;
  594. // https://drafts.csswg.org/css-backgrounds/#shadow-shape
  595. // To preserve the box’s shape when spread is applied, the corner radii of the shadow are also increased (decreased,
  596. // for inner shadows) from the border-box (padding-box) radii by adding (subtracting) the spread distance (and flooring
  597. // at zero). However, in order to create a sharper corner when the border radius is small (and thus ensure continuity
  598. // between round and sharp corners), when the border radius is less than the spread distance (or in the case of an inner
  599. // shadow, less than the absolute value of a negative spread distance), the spread distance is first multiplied by the
  600. // proportion 1 + (r-1)^3, where r is the ratio of the border radius to the spread distance, in calculating the corner
  601. // radii of the spread shadow shape.
  602. if (border_radius > AK::abs(spread_distance)) {
  603. border_radius += spread_distance;
  604. } else {
  605. auto r = (float)border_radius / AK::abs(spread_distance);
  606. border_radius += spread_distance * (1 + AK::pow(r - 1, 3.0f));
  607. }
  608. }
  609. void DisplayListPlayerSkia::paint_outer_box_shadow(PaintOuterBoxShadow const& command)
  610. {
  611. auto const& outer_box_shadow_params = command.box_shadow_params;
  612. auto const& color = outer_box_shadow_params.color;
  613. auto const& spread_distance = outer_box_shadow_params.spread_distance;
  614. auto const& blur_radius = outer_box_shadow_params.blur_radius;
  615. auto content_rrect = to_skia_rrect(outer_box_shadow_params.device_content_rect, outer_box_shadow_params.corner_radii);
  616. auto shadow_rect = outer_box_shadow_params.device_content_rect;
  617. shadow_rect.inflate(spread_distance, spread_distance, spread_distance, spread_distance);
  618. auto offset_x = outer_box_shadow_params.offset_x;
  619. auto offset_y = outer_box_shadow_params.offset_y;
  620. shadow_rect.translate_by(offset_x, offset_y);
  621. auto add_spread_distance_to_corner_radius = [&](auto& corner_radius) {
  622. add_spread_distance_to_border_radius(corner_radius.horizontal_radius, spread_distance);
  623. add_spread_distance_to_border_radius(corner_radius.vertical_radius, spread_distance);
  624. };
  625. auto corner_radii = outer_box_shadow_params.corner_radii;
  626. add_spread_distance_to_corner_radius(corner_radii.top_left);
  627. add_spread_distance_to_corner_radius(corner_radii.top_right);
  628. add_spread_distance_to_corner_radius(corner_radii.bottom_right);
  629. add_spread_distance_to_corner_radius(corner_radii.bottom_left);
  630. auto& canvas = surface().canvas();
  631. canvas.save();
  632. canvas.clipRRect(content_rrect, SkClipOp::kDifference, true);
  633. SkPaint paint;
  634. paint.setAntiAlias(true);
  635. paint.setColor(to_skia_color(color));
  636. paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, blur_radius / 2));
  637. auto shadow_rounded_rect = to_skia_rrect(shadow_rect, corner_radii);
  638. canvas.drawRRect(shadow_rounded_rect, paint);
  639. canvas.restore();
  640. }
  641. void DisplayListPlayerSkia::paint_inner_box_shadow(PaintInnerBoxShadow const& command)
  642. {
  643. auto const& outer_box_shadow_params = command.box_shadow_params;
  644. auto color = outer_box_shadow_params.color;
  645. auto device_content_rect = outer_box_shadow_params.device_content_rect;
  646. auto offset_x = outer_box_shadow_params.offset_x;
  647. auto offset_y = outer_box_shadow_params.offset_y;
  648. auto blur_radius = outer_box_shadow_params.blur_radius;
  649. auto spread_distance = outer_box_shadow_params.spread_distance;
  650. auto const& corner_radii = outer_box_shadow_params.corner_radii;
  651. auto outer_shadow_rect = device_content_rect.translated({ offset_x, offset_y });
  652. auto inner_shadow_rect = outer_shadow_rect.inflated(-spread_distance, -spread_distance, -spread_distance, -spread_distance);
  653. outer_shadow_rect.inflate(
  654. blur_radius + offset_y,
  655. blur_radius + abs(offset_x),
  656. blur_radius + abs(offset_y),
  657. blur_radius + offset_x);
  658. auto inner_rect_corner_radii = corner_radii;
  659. auto add_spread_distance_to_corner_radius = [&](auto& corner_radius) {
  660. add_spread_distance_to_border_radius(corner_radius.horizontal_radius, -spread_distance);
  661. add_spread_distance_to_border_radius(corner_radius.vertical_radius, -spread_distance);
  662. };
  663. add_spread_distance_to_corner_radius(inner_rect_corner_radii.top_left);
  664. add_spread_distance_to_corner_radius(inner_rect_corner_radii.top_right);
  665. add_spread_distance_to_corner_radius(inner_rect_corner_radii.bottom_right);
  666. add_spread_distance_to_corner_radius(inner_rect_corner_radii.bottom_left);
  667. auto outer_rect = to_skia_rrect(outer_shadow_rect, corner_radii);
  668. auto inner_rect = to_skia_rrect(inner_shadow_rect, inner_rect_corner_radii);
  669. SkPath outer_path;
  670. outer_path.addRRect(outer_rect);
  671. SkPath inner_path;
  672. inner_path.addRRect(inner_rect);
  673. SkPath result_path;
  674. if (!Op(outer_path, inner_path, SkPathOp::kDifference_SkPathOp, &result_path)) {
  675. VERIFY_NOT_REACHED();
  676. }
  677. auto& canvas = surface().canvas();
  678. SkPaint path_paint;
  679. path_paint.setAntiAlias(true);
  680. path_paint.setColor(to_skia_color(color));
  681. path_paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, blur_radius / 2));
  682. canvas.save();
  683. canvas.clipRRect(to_skia_rrect(device_content_rect, corner_radii), true);
  684. canvas.drawPath(result_path, path_paint);
  685. canvas.restore();
  686. }
  687. void DisplayListPlayerSkia::paint_text_shadow(PaintTextShadow const& command)
  688. {
  689. auto& canvas = surface().canvas();
  690. auto blur_image_filter = SkImageFilters::Blur(command.blur_radius / 2, command.blur_radius / 2, nullptr);
  691. SkPaint blur_paint;
  692. blur_paint.setImageFilter(blur_image_filter);
  693. canvas.saveLayer(SkCanvas::SaveLayerRec(nullptr, &blur_paint, nullptr, 0));
  694. draw_glyph_run({
  695. .glyph_run = command.glyph_run,
  696. .color = command.color,
  697. .rect = command.text_rect,
  698. .translation = command.draw_location.to_type<float>() + command.text_rect.location().to_type<float>(),
  699. .scale = command.glyph_run_scale,
  700. });
  701. canvas.restore();
  702. }
  703. void DisplayListPlayerSkia::fill_rect_with_rounded_corners(FillRectWithRoundedCorners const& command)
  704. {
  705. auto const& rect = command.rect;
  706. auto& canvas = surface().canvas();
  707. SkPaint paint;
  708. paint.setColor(to_skia_color(command.color));
  709. paint.setAntiAlias(true);
  710. auto rounded_rect = to_skia_rrect(rect, command.corner_radii);
  711. canvas.drawRRect(rounded_rect, paint);
  712. }
  713. void DisplayListPlayerSkia::fill_path_using_color(FillPathUsingColor const& command)
  714. {
  715. auto& canvas = surface().canvas();
  716. SkPaint paint;
  717. paint.setAntiAlias(true);
  718. paint.setColor(to_skia_color(command.color));
  719. auto path = to_skia_path(command.path);
  720. path.setFillType(to_skia_path_fill_type(command.winding_rule));
  721. path.offset(command.aa_translation.x(), command.aa_translation.y());
  722. canvas.drawPath(path, paint);
  723. }
  724. static SkTileMode to_skia_tile_mode(SVGLinearGradientPaintStyle::SpreadMethod spread_method)
  725. {
  726. switch (spread_method) {
  727. case SVGLinearGradientPaintStyle::SpreadMethod::Pad:
  728. return SkTileMode::kClamp;
  729. case SVGLinearGradientPaintStyle::SpreadMethod::Reflect:
  730. return SkTileMode::kMirror;
  731. case SVGLinearGradientPaintStyle::SpreadMethod::Repeat:
  732. return SkTileMode::kRepeat;
  733. default:
  734. VERIFY_NOT_REACHED();
  735. }
  736. }
  737. static SkPaint paint_style_to_skia_paint(Painting::SVGGradientPaintStyle const& paint_style, Gfx::FloatRect bounding_rect)
  738. {
  739. SkPaint paint;
  740. auto const& color_stops = paint_style.color_stops();
  741. Vector<SkColor> colors;
  742. colors.ensure_capacity(color_stops.size());
  743. Vector<SkScalar> positions;
  744. positions.ensure_capacity(color_stops.size());
  745. for (auto const& color_stop : color_stops) {
  746. colors.append(to_skia_color(color_stop.color));
  747. positions.append(color_stop.position);
  748. }
  749. if (is<SVGLinearGradientPaintStyle>(paint_style)) {
  750. auto const& linear_gradient_paint_style = static_cast<SVGLinearGradientPaintStyle const&>(paint_style);
  751. SkMatrix matrix;
  752. auto scale = linear_gradient_paint_style.scale();
  753. auto start_point = linear_gradient_paint_style.start_point().scaled(scale);
  754. auto end_point = linear_gradient_paint_style.end_point().scaled(scale);
  755. start_point.translate_by(bounding_rect.location());
  756. end_point.translate_by(bounding_rect.location());
  757. Array<SkPoint, 2> points;
  758. points[0] = to_skia_point(start_point);
  759. points[1] = to_skia_point(end_point);
  760. auto shader = SkGradientShader::MakeLinear(points.data(), colors.data(), positions.data(), color_stops.size(), to_skia_tile_mode(paint_style.spread_method()), 0, &matrix);
  761. paint.setShader(shader);
  762. } else if (is<SVGRadialGradientPaintStyle>(paint_style)) {
  763. auto const& radial_gradient_paint_style = static_cast<SVGRadialGradientPaintStyle const&>(paint_style);
  764. SkMatrix matrix;
  765. auto scale = radial_gradient_paint_style.scale();
  766. auto start_center = radial_gradient_paint_style.start_center().scaled(scale);
  767. auto end_center = radial_gradient_paint_style.end_center().scaled(scale);
  768. auto start_radius = radial_gradient_paint_style.start_radius() * scale;
  769. auto end_radius = radial_gradient_paint_style.end_radius() * scale;
  770. start_center.translate_by(bounding_rect.location());
  771. end_center.translate_by(bounding_rect.location());
  772. auto start_sk_point = to_skia_point(start_center);
  773. auto end_sk_point = to_skia_point(end_center);
  774. auto shader = SkGradientShader::MakeTwoPointConical(start_sk_point, start_radius, end_sk_point, end_radius, colors.data(), positions.data(), color_stops.size(), to_skia_tile_mode(paint_style.spread_method()), 0, &matrix);
  775. paint.setShader(shader);
  776. }
  777. return paint;
  778. }
  779. void DisplayListPlayerSkia::fill_path_using_paint_style(FillPathUsingPaintStyle const& command)
  780. {
  781. auto path = to_skia_path(command.path);
  782. path.offset(command.aa_translation.x(), command.aa_translation.y());
  783. path.setFillType(to_skia_path_fill_type(command.winding_rule));
  784. auto paint = paint_style_to_skia_paint(*command.paint_style, command.bounding_rect().to_type<float>());
  785. paint.setAntiAlias(true);
  786. paint.setAlphaf(command.opacity);
  787. surface().canvas().drawPath(path, paint);
  788. }
  789. void DisplayListPlayerSkia::stroke_path_using_color(StrokePathUsingColor const& command)
  790. {
  791. // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.
  792. if (!command.thickness)
  793. return;
  794. auto& canvas = surface().canvas();
  795. SkPaint paint;
  796. paint.setAntiAlias(true);
  797. paint.setStyle(SkPaint::kStroke_Style);
  798. paint.setStrokeWidth(command.thickness);
  799. paint.setColor(to_skia_color(command.color));
  800. auto path = to_skia_path(command.path);
  801. path.offset(command.aa_translation.x(), command.aa_translation.y());
  802. canvas.drawPath(path, paint);
  803. }
  804. void DisplayListPlayerSkia::stroke_path_using_paint_style(StrokePathUsingPaintStyle const& command)
  805. {
  806. // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.
  807. if (!command.thickness)
  808. return;
  809. auto path = to_skia_path(command.path);
  810. path.offset(command.aa_translation.x(), command.aa_translation.y());
  811. auto paint = paint_style_to_skia_paint(*command.paint_style, command.bounding_rect().to_type<float>());
  812. paint.setAntiAlias(true);
  813. paint.setAlphaf(command.opacity);
  814. paint.setStyle(SkPaint::Style::kStroke_Style);
  815. paint.setStrokeWidth(command.thickness);
  816. surface().canvas().drawPath(path, paint);
  817. }
  818. void DisplayListPlayerSkia::draw_ellipse(DrawEllipse const& command)
  819. {
  820. // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.
  821. if (!command.thickness)
  822. return;
  823. auto const& rect = command.rect;
  824. auto& canvas = surface().canvas();
  825. SkPaint paint;
  826. paint.setAntiAlias(true);
  827. paint.setStyle(SkPaint::kStroke_Style);
  828. paint.setStrokeWidth(command.thickness);
  829. paint.setColor(to_skia_color(command.color));
  830. canvas.drawOval(to_skia_rect(rect), paint);
  831. }
  832. void DisplayListPlayerSkia::fill_ellipse(FillEllipse const& command)
  833. {
  834. auto const& rect = command.rect;
  835. auto& canvas = surface().canvas();
  836. SkPaint paint;
  837. paint.setAntiAlias(true);
  838. paint.setColor(to_skia_color(command.color));
  839. canvas.drawOval(to_skia_rect(rect), paint);
  840. }
  841. void DisplayListPlayerSkia::draw_line(DrawLine const& command)
  842. {
  843. // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.
  844. if (!command.thickness)
  845. return;
  846. auto from = to_skia_point(command.from);
  847. auto to = to_skia_point(command.to);
  848. auto& canvas = surface().canvas();
  849. SkPaint paint;
  850. paint.setAntiAlias(true);
  851. paint.setStrokeWidth(command.thickness);
  852. paint.setColor(to_skia_color(command.color));
  853. switch (command.style) {
  854. case Gfx::LineStyle::Solid:
  855. break;
  856. case Gfx::LineStyle::Dotted: {
  857. auto length = command.to.distance_from(command.from);
  858. auto dot_count = floor(length / (static_cast<float>(command.thickness) * 2));
  859. auto interval = length / dot_count;
  860. SkScalar intervals[] = { 0, interval };
  861. paint.setPathEffect(SkDashPathEffect::Make(intervals, 2, 0));
  862. paint.setStrokeCap(SkPaint::Cap::kRound_Cap);
  863. // NOTE: As Skia doesn't render a dot exactly at the end of a line, we need
  864. // to extend it by less then an interval.
  865. auto direction = to - from;
  866. direction.normalize();
  867. to += direction * (interval / 2.0f);
  868. break;
  869. }
  870. case Gfx::LineStyle::Dashed: {
  871. auto length = command.to.distance_from(command.from) + command.thickness;
  872. auto dash_count = floor(length / static_cast<float>(command.thickness) / 4) * 2 + 1;
  873. auto interval = length / dash_count;
  874. SkScalar intervals[] = { interval, interval };
  875. paint.setPathEffect(SkDashPathEffect::Make(intervals, 2, 0));
  876. auto direction = to - from;
  877. direction.normalize();
  878. from -= direction * (command.thickness / 2.0f);
  879. to += direction * (command.thickness / 2.0f);
  880. break;
  881. }
  882. }
  883. canvas.drawLine(from, to, paint);
  884. }
  885. void DisplayListPlayerSkia::apply_backdrop_filter(ApplyBackdropFilter const& command)
  886. {
  887. auto& canvas = surface().canvas();
  888. auto rect = to_skia_rect(command.backdrop_region);
  889. canvas.save();
  890. canvas.clipRect(rect);
  891. ScopeGuard guard = [&] { canvas.restore(); };
  892. for (auto const& filter_function : command.backdrop_filter.filters) {
  893. // See: https://drafts.fxtf.org/filter-effects-1/#supported-filter-functions
  894. filter_function.visit(
  895. [&](CSS::ResolvedBackdropFilter::Blur const& blur_filter) {
  896. auto blur_image_filter = SkImageFilters::Blur(blur_filter.radius, blur_filter.radius, nullptr);
  897. canvas.saveLayer(SkCanvas::SaveLayerRec(nullptr, nullptr, blur_image_filter.get(), 0));
  898. canvas.restore();
  899. },
  900. [&](CSS::ResolvedBackdropFilter::ColorOperation const& color) {
  901. auto amount = clamp(color.amount, 0.0f, 1.0f);
  902. // Matrices are taken from https://drafts.fxtf.org/filter-effects-1/#FilterPrimitiveRepresentation
  903. sk_sp<SkColorFilter> color_filter;
  904. switch (color.operation) {
  905. case CSS::Filter::Color::Operation::Grayscale: {
  906. float matrix[20] = {
  907. 0.2126f + 0.7874f * (1 - amount), 0.7152f - 0.7152f * (1 - amount), 0.0722f - 0.0722f * (1 - amount), 0, 0,
  908. 0.2126f - 0.2126f * (1 - amount), 0.7152f + 0.2848f * (1 - amount), 0.0722f - 0.0722f * (1 - amount), 0, 0,
  909. 0.2126f - 0.2126f * (1 - amount), 0.7152f - 0.7152f * (1 - amount), 0.0722f + 0.9278f * (1 - amount), 0, 0,
  910. 0, 0, 0, 1, 0
  911. };
  912. color_filter = SkColorFilters::Matrix(matrix);
  913. break;
  914. }
  915. case CSS::Filter::Color::Operation::Brightness: {
  916. float matrix[20] = {
  917. amount, 0, 0, 0, 0,
  918. 0, amount, 0, 0, 0,
  919. 0, 0, amount, 0, 0,
  920. 0, 0, 0, 1, 0
  921. };
  922. color_filter = SkColorFilters::Matrix(matrix);
  923. break;
  924. }
  925. case CSS::Filter::Color::Operation::Contrast: {
  926. float intercept = -(0.5f * amount) + 0.5f;
  927. float matrix[20] = {
  928. amount, 0, 0, 0, intercept,
  929. 0, amount, 0, 0, intercept,
  930. 0, 0, amount, 0, intercept,
  931. 0, 0, 0, 1, 0
  932. };
  933. color_filter = SkColorFilters::Matrix(matrix);
  934. break;
  935. }
  936. case CSS::Filter::Color::Operation::Invert: {
  937. float matrix[20] = {
  938. 1 - 2 * amount, 0, 0, 0, amount,
  939. 0, 1 - 2 * amount, 0, 0, amount,
  940. 0, 0, 1 - 2 * amount, 0, amount,
  941. 0, 0, 0, 1, 0
  942. };
  943. color_filter = SkColorFilters::Matrix(matrix);
  944. break;
  945. }
  946. case CSS::Filter::Color::Operation::Opacity: {
  947. float matrix[20] = {
  948. 1, 0, 0, 0, 0,
  949. 0, 1, 0, 0, 0,
  950. 0, 0, 1, 0, 0,
  951. 0, 0, 0, amount, 0
  952. };
  953. color_filter = SkColorFilters::Matrix(matrix);
  954. break;
  955. }
  956. case CSS::Filter::Color::Operation::Sepia: {
  957. float matrix[20] = {
  958. 0.393f + 0.607f * (1 - amount), 0.769f - 0.769f * (1 - amount), 0.189f - 0.189f * (1 - amount), 0, 0,
  959. 0.349f - 0.349f * (1 - amount), 0.686f + 0.314f * (1 - amount), 0.168f - 0.168f * (1 - amount), 0, 0,
  960. 0.272f - 0.272f * (1 - amount), 0.534f - 0.534f * (1 - amount), 0.131f + 0.869f * (1 - amount), 0, 0,
  961. 0, 0, 0, 1, 0
  962. };
  963. color_filter = SkColorFilters::Matrix(matrix);
  964. break;
  965. }
  966. case CSS::Filter::Color::Operation::Saturate: {
  967. float matrix[20] = {
  968. 0.213f + 0.787f * amount, 0.715f - 0.715f * amount, 0.072f - 0.072f * amount, 0, 0,
  969. 0.213f - 0.213f * amount, 0.715f + 0.285f * amount, 0.072f - 0.072f * amount, 0, 0,
  970. 0.213f - 0.213f * amount, 0.715f - 0.715f * amount, 0.072f + 0.928f * amount, 0, 0,
  971. 0, 0, 0, 1, 0
  972. };
  973. color_filter = SkColorFilters::Matrix(matrix);
  974. break;
  975. }
  976. default:
  977. VERIFY_NOT_REACHED();
  978. }
  979. auto image_filter = SkImageFilters::ColorFilter(color_filter, nullptr);
  980. canvas.saveLayer(SkCanvas::SaveLayerRec(nullptr, nullptr, image_filter.get(), 0));
  981. canvas.restore();
  982. },
  983. [&](CSS::ResolvedBackdropFilter::HueRotate const& hue_rotate) {
  984. float radians = AK::to_radians(hue_rotate.angle_degrees);
  985. auto cosA = cos(radians);
  986. auto sinA = sin(radians);
  987. auto a00 = 0.213f + cosA * 0.787f - sinA * 0.213f;
  988. auto a01 = 0.715f - cosA * 0.715f - sinA * 0.715f;
  989. auto a02 = 0.072f - cosA * 0.072f + sinA * 0.928f;
  990. auto a10 = 0.213f - cosA * 0.213f + sinA * 0.143f;
  991. auto a11 = 0.715f + cosA * 0.285f + sinA * 0.140f;
  992. auto a12 = 0.072f - cosA * 0.072f - sinA * 0.283f;
  993. auto a20 = 0.213f - cosA * 0.213f - sinA * 0.787f;
  994. auto a21 = 0.715f - cosA * 0.715f + sinA * 0.715f;
  995. auto a22 = 0.072f + cosA * 0.928f + sinA * 0.072f;
  996. float matrix[20] = {
  997. a00, a01, a02, 0, 0,
  998. a10, a11, a12, 0, 0,
  999. a20, a21, a22, 0, 0,
  1000. 0, 0, 0, 1, 0
  1001. };
  1002. auto color_filter = SkColorFilters::Matrix(matrix);
  1003. auto image_filter = SkImageFilters::ColorFilter(color_filter, nullptr);
  1004. canvas.saveLayer(SkCanvas::SaveLayerRec(nullptr, nullptr, image_filter.get(), 0));
  1005. canvas.restore();
  1006. },
  1007. [&](CSS::ResolvedBackdropFilter::DropShadow const&) {
  1008. dbgln("TODO: Implement drop-shadow() filter function!");
  1009. });
  1010. }
  1011. }
  1012. void DisplayListPlayerSkia::draw_rect(DrawRect const& command)
  1013. {
  1014. auto const& rect = command.rect;
  1015. auto& canvas = surface().canvas();
  1016. SkPaint paint;
  1017. paint.setAntiAlias(true);
  1018. paint.setStyle(SkPaint::kStroke_Style);
  1019. paint.setStrokeWidth(1);
  1020. paint.setColor(to_skia_color(command.color));
  1021. canvas.drawRect(to_skia_rect(rect), paint);
  1022. }
  1023. void DisplayListPlayerSkia::paint_radial_gradient(PaintRadialGradient const& command)
  1024. {
  1025. auto const& radial_gradient_data = command.radial_gradient_data;
  1026. auto color_stop_list = radial_gradient_data.color_stops.list;
  1027. VERIFY(!color_stop_list.is_empty());
  1028. auto const& repeat_length = radial_gradient_data.color_stops.repeat_length;
  1029. if (repeat_length.has_value())
  1030. color_stop_list = expand_repeat_length(color_stop_list, repeat_length.value());
  1031. auto stops_with_replaced_transition_hints = replace_transition_hints_with_normal_color_stops(color_stop_list);
  1032. Vector<SkColor4f> colors;
  1033. Vector<SkScalar> positions;
  1034. for (size_t stop_index = 0; stop_index < stops_with_replaced_transition_hints.size(); stop_index++) {
  1035. auto const& stop = stops_with_replaced_transition_hints[stop_index];
  1036. if (stop_index > 0 && stop == stops_with_replaced_transition_hints[stop_index - 1])
  1037. continue;
  1038. colors.append(to_skia_color4f(stop.color));
  1039. positions.append(stop.position);
  1040. }
  1041. auto const& rect = command.rect;
  1042. auto center = to_skia_point(command.center.translated(command.rect.location()));
  1043. auto const size = command.size.to_type<float>();
  1044. SkMatrix matrix;
  1045. // Skia does not support specifying of horizontal and vertical radius's separately,
  1046. // so instead we apply scale matrix
  1047. matrix.setScale(size.width() / size.height(), 1.0f, center.x(), center.y());
  1048. SkTileMode tile_mode = SkTileMode::kClamp;
  1049. if (repeat_length.has_value())
  1050. tile_mode = SkTileMode::kRepeat;
  1051. auto color_space = SkColorSpace::MakeSRGB();
  1052. SkGradientShader::Interpolation interpolation = {};
  1053. interpolation.fColorSpace = SkGradientShader::Interpolation::ColorSpace::kSRGB;
  1054. interpolation.fInPremul = SkGradientShader::Interpolation::InPremul::kYes;
  1055. auto shader = SkGradientShader::MakeRadial(center, size.height(), colors.data(), color_space, positions.data(), positions.size(), tile_mode, interpolation, &matrix);
  1056. SkPaint paint;
  1057. paint.setAntiAlias(true);
  1058. paint.setShader(shader);
  1059. surface().canvas().drawRect(to_skia_rect(rect), paint);
  1060. }
  1061. void DisplayListPlayerSkia::paint_conic_gradient(PaintConicGradient const& command)
  1062. {
  1063. auto const& conic_gradient_data = command.conic_gradient_data;
  1064. auto color_stop_list = conic_gradient_data.color_stops.list;
  1065. auto const& repeat_length = conic_gradient_data.color_stops.repeat_length;
  1066. if (repeat_length.has_value())
  1067. color_stop_list = expand_repeat_length(color_stop_list, repeat_length.value());
  1068. VERIFY(!color_stop_list.is_empty());
  1069. auto stops_with_replaced_transition_hints = replace_transition_hints_with_normal_color_stops(color_stop_list);
  1070. Vector<SkColor4f> colors;
  1071. Vector<SkScalar> positions;
  1072. for (size_t stop_index = 0; stop_index < stops_with_replaced_transition_hints.size(); stop_index++) {
  1073. auto const& stop = stops_with_replaced_transition_hints[stop_index];
  1074. if (stop_index > 0 && stop == stops_with_replaced_transition_hints[stop_index - 1])
  1075. continue;
  1076. colors.append(to_skia_color4f(stop.color));
  1077. positions.append(stop.position);
  1078. }
  1079. auto const& rect = command.rect;
  1080. auto center = command.position.translated(rect.location()).to_type<float>();
  1081. SkMatrix matrix;
  1082. matrix.setRotate(-90 + conic_gradient_data.start_angle, center.x(), center.y());
  1083. auto color_space = SkColorSpace::MakeSRGB();
  1084. SkGradientShader::Interpolation interpolation = {};
  1085. interpolation.fColorSpace = SkGradientShader::Interpolation::ColorSpace::kSRGB;
  1086. interpolation.fInPremul = SkGradientShader::Interpolation::InPremul::kYes;
  1087. auto shader = SkGradientShader::MakeSweep(center.x(), center.y(), colors.data(), color_space, positions.data(), positions.size(), SkTileMode::kRepeat, 0, 360, interpolation, &matrix);
  1088. SkPaint paint;
  1089. paint.setAntiAlias(true);
  1090. paint.setShader(shader);
  1091. surface().canvas().drawRect(to_skia_rect(rect), paint);
  1092. }
  1093. void DisplayListPlayerSkia::draw_triangle_wave(DrawTriangleWave const&)
  1094. {
  1095. }
  1096. void DisplayListPlayerSkia::add_rounded_rect_clip(AddRoundedRectClip const& command)
  1097. {
  1098. auto rounded_rect = to_skia_rrect(command.border_rect, command.corner_radii);
  1099. auto& canvas = surface().canvas();
  1100. auto clip_op = command.corner_clip == CornerClip::Inside ? SkClipOp::kDifference : SkClipOp::kIntersect;
  1101. canvas.clipRRect(rounded_rect, clip_op, true);
  1102. }
  1103. void DisplayListPlayerSkia::add_mask(AddMask const& command)
  1104. {
  1105. auto const& rect = command.rect;
  1106. if (rect.is_empty())
  1107. return;
  1108. auto mask_surface = m_surface->make_surface(rect.width(), rect.height());
  1109. auto previous_surface = move(m_surface);
  1110. m_surface = make<SkiaSurface>(mask_surface);
  1111. execute(*command.display_list);
  1112. m_surface = move(previous_surface);
  1113. SkMatrix mask_matrix;
  1114. mask_matrix.setTranslate(rect.x(), rect.y());
  1115. auto image = mask_surface->makeImageSnapshot();
  1116. auto shader = image->makeShader(SkSamplingOptions(), mask_matrix);
  1117. surface().canvas().save();
  1118. surface().canvas().clipShader(shader);
  1119. }
  1120. void DisplayListPlayerSkia::paint_nested_display_list(PaintNestedDisplayList const& command)
  1121. {
  1122. auto& canvas = surface().canvas();
  1123. canvas.translate(command.rect.x(), command.rect.y());
  1124. execute(*command.display_list);
  1125. }
  1126. void DisplayListPlayerSkia::paint_scrollbar(PaintScrollBar const& command)
  1127. {
  1128. auto rect = to_skia_rect(command.rect);
  1129. auto radius = rect.width() / 2;
  1130. auto rrect = SkRRect::MakeRectXY(rect, radius, radius);
  1131. auto& canvas = surface().canvas();
  1132. auto fill_color = Color(Color::NamedColor::DarkGray).with_alpha(128);
  1133. SkPaint fill_paint;
  1134. fill_paint.setColor(to_skia_color(fill_color));
  1135. canvas.drawRRect(rrect, fill_paint);
  1136. auto stroke_color = Color(Color::NamedColor::LightGray).with_alpha(128);
  1137. SkPaint stroke_paint;
  1138. stroke_paint.setStroke(true);
  1139. stroke_paint.setStrokeWidth(1);
  1140. stroke_paint.setColor(to_skia_color(stroke_color));
  1141. canvas.drawRRect(rrect, stroke_paint);
  1142. }
  1143. bool DisplayListPlayerSkia::would_be_fully_clipped_by_painter(Gfx::IntRect rect) const
  1144. {
  1145. return surface().canvas().quickReject(to_skia_rect(rect));
  1146. }
  1147. }