DisplayListPlayerSkia.cpp 51 KB

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