DisplayListPlayerSkia.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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. SkPath clip_path; \
  321. for (auto const& path : command.clip_paths) \
  322. clip_path.addPath(to_skia_path(path)); \
  323. surface().canvas().clipPath(clip_path, true); \
  324. }
  325. DisplayListPlayerSkia::SkiaSurface& DisplayListPlayerSkia::surface() const
  326. {
  327. return static_cast<SkiaSurface&>(*m_surface);
  328. }
  329. CommandResult DisplayListPlayerSkia::draw_glyph_run(DrawGlyphRun const& command)
  330. {
  331. auto& canvas = surface().canvas();
  332. SkPaint paint;
  333. paint.setColorFilter(SkColorFilters::Blend(to_skia_color(command.color), SkBlendMode::kSrcIn));
  334. auto const& glyphs = command.glyph_run->glyphs();
  335. auto const& font = command.glyph_run->font();
  336. auto scaled_font = font.with_size(font.point_size() * static_cast<float>(command.scale));
  337. for (auto const& glyph_or_emoji : glyphs) {
  338. auto transformed_glyph = glyph_or_emoji;
  339. transformed_glyph.visit([&](auto& glyph) {
  340. glyph.position = glyph.position.scaled(command.scale).translated(command.translation);
  341. });
  342. if (transformed_glyph.has<Gfx::DrawGlyph>()) {
  343. auto& glyph = transformed_glyph.get<Gfx::DrawGlyph>();
  344. auto const& point = glyph.position;
  345. auto const& code_point = glyph.code_point;
  346. auto top_left = point + Gfx::FloatPoint(scaled_font->glyph_left_bearing(code_point), 0);
  347. auto glyph_position = Gfx::GlyphRasterPosition::get_nearest_fit_for(top_left);
  348. auto maybe_font_glyph = scaled_font->glyph(code_point, glyph_position.subpixel_offset);
  349. if (!maybe_font_glyph.has_value())
  350. continue;
  351. if (maybe_font_glyph->is_color_bitmap()) {
  352. TODO();
  353. } else {
  354. auto sk_bitmap = to_skia_bitmap(*maybe_font_glyph->bitmap());
  355. auto sk_image = SkImages::RasterFromBitmap(sk_bitmap);
  356. auto const& blit_position = glyph_position.blit_position;
  357. canvas.drawImage(sk_image, blit_position.x(), blit_position.y(), SkSamplingOptions(), &paint);
  358. }
  359. }
  360. }
  361. return CommandResult::Continue;
  362. }
  363. CommandResult DisplayListPlayerSkia::fill_rect(FillRect const& command)
  364. {
  365. APPLY_PATH_CLIP_IF_NEEDED
  366. auto const& rect = command.rect;
  367. auto& canvas = surface().canvas();
  368. SkPaint paint;
  369. paint.setColor(to_skia_color(command.color));
  370. canvas.drawRect(to_skia_rect(rect), paint);
  371. return CommandResult::Continue;
  372. }
  373. CommandResult DisplayListPlayerSkia::draw_scaled_bitmap(DrawScaledBitmap const& command)
  374. {
  375. auto src_rect = to_skia_rect(command.src_rect);
  376. auto dst_rect = to_skia_rect(command.dst_rect);
  377. auto bitmap = to_skia_bitmap(command.bitmap);
  378. auto image = SkImages::RasterFromBitmap(bitmap);
  379. auto& canvas = surface().canvas();
  380. SkPaint paint;
  381. canvas.drawImageRect(image, src_rect, dst_rect, to_skia_sampling_options(command.scaling_mode), &paint, SkCanvas::kStrict_SrcRectConstraint);
  382. return CommandResult::Continue;
  383. }
  384. CommandResult DisplayListPlayerSkia::draw_scaled_immutable_bitmap(DrawScaledImmutableBitmap const& command)
  385. {
  386. APPLY_PATH_CLIP_IF_NEEDED
  387. auto src_rect = to_skia_rect(command.src_rect);
  388. auto dst_rect = to_skia_rect(command.dst_rect);
  389. auto bitmap = to_skia_bitmap(command.bitmap->bitmap());
  390. auto image = SkImages::RasterFromBitmap(bitmap);
  391. auto& canvas = surface().canvas();
  392. SkPaint paint;
  393. canvas.drawImageRect(image, src_rect, dst_rect, to_skia_sampling_options(command.scaling_mode), &paint, SkCanvas::kStrict_SrcRectConstraint);
  394. return CommandResult::Continue;
  395. }
  396. CommandResult DisplayListPlayerSkia::add_clip_rect(AddClipRect const& command)
  397. {
  398. auto& canvas = surface().canvas();
  399. auto const& rect = command.rect;
  400. canvas.clipRect(to_skia_rect(rect));
  401. return CommandResult::Continue;
  402. }
  403. CommandResult DisplayListPlayerSkia::save(Save const&)
  404. {
  405. auto& canvas = surface().canvas();
  406. canvas.save();
  407. return CommandResult::Continue;
  408. }
  409. CommandResult DisplayListPlayerSkia::restore(Restore const&)
  410. {
  411. auto& canvas = surface().canvas();
  412. canvas.restore();
  413. return CommandResult::Continue;
  414. }
  415. static SkBitmap alpha_mask_from_bitmap(Gfx::Bitmap const& bitmap, Gfx::Bitmap::MaskKind kind)
  416. {
  417. SkBitmap alpha_mask;
  418. alpha_mask.allocPixels(SkImageInfo::MakeA8(bitmap.width(), bitmap.height()));
  419. for (int y = 0; y < bitmap.height(); y++) {
  420. for (int x = 0; x < bitmap.width(); x++) {
  421. if (kind == Gfx::Bitmap::MaskKind::Luminance) {
  422. auto color = bitmap.get_pixel(x, y);
  423. *alpha_mask.getAddr8(x, y) = color.alpha() * color.luminosity() / 255;
  424. } else {
  425. VERIFY(kind == Gfx::Bitmap::MaskKind::Alpha);
  426. auto color = bitmap.get_pixel(x, y);
  427. *alpha_mask.getAddr8(x, y) = color.alpha();
  428. }
  429. }
  430. }
  431. return alpha_mask;
  432. }
  433. CommandResult DisplayListPlayerSkia::push_stacking_context(PushStackingContext const& command)
  434. {
  435. auto& canvas = surface().canvas();
  436. auto affine_transform = Gfx::extract_2d_affine_transform(command.transform.matrix);
  437. auto new_transform = Gfx::AffineTransform {}
  438. .set_translation(command.post_transform_translation.to_type<float>())
  439. .translate(command.transform.origin)
  440. .multiply(affine_transform)
  441. .translate(-command.transform.origin);
  442. auto matrix = to_skia_matrix(new_transform);
  443. if (command.opacity < 1) {
  444. auto source_paintable_rect = to_skia_rect(command.source_paintable_rect);
  445. SkRect dest;
  446. matrix.mapRect(&dest, source_paintable_rect);
  447. canvas.saveLayerAlphaf(&dest, command.opacity);
  448. } else {
  449. canvas.save();
  450. }
  451. if (command.mask.has_value()) {
  452. auto alpha_mask = alpha_mask_from_bitmap(*command.mask.value().mask_bitmap, command.mask.value().mask_kind);
  453. SkMatrix mask_matrix;
  454. auto mask_position = command.source_paintable_rect.location();
  455. mask_matrix.setTranslate(mask_position.x(), mask_position.y());
  456. auto shader = alpha_mask.makeShader(SkSamplingOptions(), mask_matrix);
  457. canvas.clipShader(shader);
  458. }
  459. if (command.is_fixed_position) {
  460. // FIXME: Resetting matrix is not correct when element is nested in a transformed stacking context
  461. canvas.resetMatrix();
  462. }
  463. canvas.concat(matrix);
  464. return CommandResult::Continue;
  465. }
  466. CommandResult DisplayListPlayerSkia::pop_stacking_context(PopStackingContext const&)
  467. {
  468. surface().canvas().restore();
  469. return CommandResult::Continue;
  470. }
  471. static ColorStopList replace_transition_hints_with_normal_color_stops(ColorStopList const& color_stop_list)
  472. {
  473. ColorStopList stops_with_replaced_transition_hints;
  474. auto const& first_color_stop = color_stop_list.first();
  475. // First color stop in the list should never have transition hint value
  476. VERIFY(!first_color_stop.transition_hint.has_value());
  477. stops_with_replaced_transition_hints.empend(first_color_stop.color, first_color_stop.position);
  478. // This loop replaces transition hints with five regular points, calculated using the
  479. // formula defined in the spec. After rendering using linear interpolation, this will
  480. // produce a result close enough to that obtained if the color of each point were calculated
  481. // using the non-linear formula from the spec.
  482. for (size_t i = 1; i < color_stop_list.size(); i++) {
  483. auto const& color_stop = color_stop_list[i];
  484. if (!color_stop.transition_hint.has_value()) {
  485. stops_with_replaced_transition_hints.empend(color_stop.color, color_stop.position);
  486. continue;
  487. }
  488. auto const& previous_color_stop = color_stop_list[i - 1];
  489. auto const& next_color_stop = color_stop_list[i];
  490. auto distance_between_stops = next_color_stop.position - previous_color_stop.position;
  491. auto transition_hint = color_stop.transition_hint.value();
  492. Array<float, 5> const transition_hint_relative_sampling_positions = {
  493. transition_hint * 0.33f,
  494. transition_hint * 0.66f,
  495. transition_hint,
  496. transition_hint + (1 - transition_hint) * 0.33f,
  497. transition_hint + (1 - transition_hint) * 0.66f,
  498. };
  499. for (auto const& transition_hint_relative_sampling_position : transition_hint_relative_sampling_positions) {
  500. auto position = previous_color_stop.position + transition_hint_relative_sampling_position * distance_between_stops;
  501. auto value = color_stop_step(previous_color_stop, next_color_stop, position);
  502. auto color = previous_color_stop.color.interpolate(next_color_stop.color, value);
  503. stops_with_replaced_transition_hints.empend(color, position);
  504. }
  505. stops_with_replaced_transition_hints.empend(color_stop.color, color_stop.position);
  506. }
  507. return stops_with_replaced_transition_hints;
  508. }
  509. static ColorStopList expand_repeat_length(ColorStopList const& color_stop_list, float repeat_length)
  510. {
  511. // https://drafts.csswg.org/css-images/#repeating-gradients
  512. // When rendered, however, the color-stops are repeated infinitely in both directions, with their
  513. // positions shifted by multiples of the difference between the last specified color-stop’s position
  514. // and the first specified color-stop’s position. For example, repeating-linear-gradient(red 10px, blue 50px)
  515. // is equivalent to linear-gradient(..., red -30px, blue 10px, red 10px, blue 50px, red 50px, blue 90px, ...).
  516. auto first_stop_position = color_stop_list.first().position;
  517. int const negative_repeat_count = AK::ceil(first_stop_position / repeat_length);
  518. int const positive_repeat_count = AK::ceil((1.0f - first_stop_position) / repeat_length);
  519. ColorStopList color_stop_list_with_expanded_repeat = color_stop_list;
  520. auto get_color_between_stops = [](float position, auto const& current_stop, auto const& previous_stop) {
  521. auto distance_between_stops = current_stop.position - previous_stop.position;
  522. auto percentage = (position - previous_stop.position) / distance_between_stops;
  523. return previous_stop.color.interpolate(current_stop.color, percentage);
  524. };
  525. for (auto repeat_count = 1; repeat_count <= negative_repeat_count; repeat_count++) {
  526. for (auto stop : color_stop_list.in_reverse()) {
  527. stop.position += repeat_length * static_cast<float>(-repeat_count);
  528. if (stop.position < 0) {
  529. stop.color = get_color_between_stops(0.0f, stop, color_stop_list_with_expanded_repeat.first());
  530. color_stop_list_with_expanded_repeat.prepend(stop);
  531. break;
  532. }
  533. color_stop_list_with_expanded_repeat.prepend(stop);
  534. }
  535. }
  536. for (auto repeat_count = 0; repeat_count < positive_repeat_count; repeat_count++) {
  537. for (auto stop : color_stop_list) {
  538. stop.position += repeat_length * static_cast<float>(repeat_count);
  539. if (stop.position > 1) {
  540. stop.color = get_color_between_stops(1.0f, stop, color_stop_list_with_expanded_repeat.last());
  541. color_stop_list_with_expanded_repeat.append(stop);
  542. break;
  543. }
  544. color_stop_list_with_expanded_repeat.append(stop);
  545. }
  546. }
  547. return color_stop_list_with_expanded_repeat;
  548. }
  549. CommandResult DisplayListPlayerSkia::paint_linear_gradient(PaintLinearGradient const& command)
  550. {
  551. APPLY_PATH_CLIP_IF_NEEDED
  552. auto const& linear_gradient_data = command.linear_gradient_data;
  553. auto color_stop_list = linear_gradient_data.color_stops.list;
  554. auto const& repeat_length = linear_gradient_data.color_stops.repeat_length;
  555. VERIFY(!color_stop_list.is_empty());
  556. if (repeat_length.has_value())
  557. color_stop_list = expand_repeat_length(color_stop_list, *repeat_length);
  558. auto stops_with_replaced_transition_hints = replace_transition_hints_with_normal_color_stops(color_stop_list);
  559. Vector<SkColor> colors;
  560. Vector<SkScalar> positions;
  561. for (size_t stop_index = 0; stop_index < stops_with_replaced_transition_hints.size(); stop_index++) {
  562. auto const& stop = stops_with_replaced_transition_hints[stop_index];
  563. if (stop_index > 0 && stop == stops_with_replaced_transition_hints[stop_index - 1])
  564. continue;
  565. colors.append(to_skia_color(stop.color));
  566. positions.append(stop.position);
  567. }
  568. auto const& rect = command.gradient_rect;
  569. auto length = calculate_gradient_length<int>(rect.size(), linear_gradient_data.gradient_angle);
  570. auto bottom = rect.center().translated(0, -length / 2);
  571. auto top = rect.center().translated(0, length / 2);
  572. Array<SkPoint, 2> points;
  573. points[0] = to_skia_point(top);
  574. points[1] = to_skia_point(bottom);
  575. auto center = to_skia_rect(rect).center();
  576. SkMatrix matrix;
  577. matrix.setRotate(linear_gradient_data.gradient_angle, center.x(), center.y());
  578. auto shader = SkGradientShader::MakeLinear(points.data(), colors.data(), positions.data(), positions.size(), SkTileMode::kClamp, 0, &matrix);
  579. SkPaint paint;
  580. paint.setShader(shader);
  581. surface().canvas().drawRect(to_skia_rect(rect), paint);
  582. return CommandResult::Continue;
  583. }
  584. static void add_spread_distance_to_border_radius(int& border_radius, int spread_distance)
  585. {
  586. if (border_radius == 0 || spread_distance == 0)
  587. return;
  588. // https://drafts.csswg.org/css-backgrounds/#shadow-shape
  589. // To preserve the box’s shape when spread is applied, the corner radii of the shadow are also increased (decreased,
  590. // for inner shadows) from the border-box (padding-box) radii by adding (subtracting) the spread distance (and flooring
  591. // at zero). However, in order to create a sharper corner when the border radius is small (and thus ensure continuity
  592. // between round and sharp corners), when the border radius is less than the spread distance (or in the case of an inner
  593. // shadow, less than the absolute value of a negative spread distance), the spread distance is first multiplied by the
  594. // proportion 1 + (r-1)^3, where r is the ratio of the border radius to the spread distance, in calculating the corner
  595. // radii of the spread shadow shape.
  596. if (border_radius > AK::abs(spread_distance)) {
  597. border_radius += spread_distance;
  598. } else {
  599. auto r = (float)border_radius / AK::abs(spread_distance);
  600. border_radius += spread_distance * (1 + AK::pow(r - 1, 3.0f));
  601. }
  602. }
  603. CommandResult DisplayListPlayerSkia::paint_outer_box_shadow(PaintOuterBoxShadow const& command)
  604. {
  605. auto const& outer_box_shadow_params = command.box_shadow_params;
  606. auto const& color = outer_box_shadow_params.color;
  607. auto const& spread_distance = outer_box_shadow_params.spread_distance;
  608. auto const& blur_radius = outer_box_shadow_params.blur_radius;
  609. auto content_rrect = to_skia_rrect(outer_box_shadow_params.device_content_rect, outer_box_shadow_params.corner_radii);
  610. auto shadow_rect = outer_box_shadow_params.device_content_rect;
  611. shadow_rect.inflate(spread_distance, spread_distance, spread_distance, spread_distance);
  612. auto offset_x = outer_box_shadow_params.offset_x;
  613. auto offset_y = outer_box_shadow_params.offset_y;
  614. shadow_rect.translate_by(offset_x, offset_y);
  615. auto add_spread_distance_to_corner_radius = [&](auto& corner_radius) {
  616. add_spread_distance_to_border_radius(corner_radius.horizontal_radius, spread_distance);
  617. add_spread_distance_to_border_radius(corner_radius.vertical_radius, spread_distance);
  618. };
  619. auto corner_radii = outer_box_shadow_params.corner_radii;
  620. add_spread_distance_to_corner_radius(corner_radii.top_left);
  621. add_spread_distance_to_corner_radius(corner_radii.top_right);
  622. add_spread_distance_to_corner_radius(corner_radii.bottom_right);
  623. add_spread_distance_to_corner_radius(corner_radii.bottom_left);
  624. auto& canvas = surface().canvas();
  625. canvas.save();
  626. canvas.clipRRect(content_rrect, SkClipOp::kDifference, true);
  627. SkPaint paint;
  628. paint.setColor(to_skia_color(color));
  629. paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, blur_radius / 2));
  630. auto shadow_rounded_rect = to_skia_rrect(shadow_rect, corner_radii);
  631. canvas.drawRRect(shadow_rounded_rect, paint);
  632. canvas.restore();
  633. return CommandResult::Continue;
  634. }
  635. CommandResult DisplayListPlayerSkia::paint_inner_box_shadow(PaintInnerBoxShadow const& command)
  636. {
  637. auto const& outer_box_shadow_params = command.box_shadow_params;
  638. auto color = outer_box_shadow_params.color;
  639. auto device_content_rect = outer_box_shadow_params.device_content_rect;
  640. auto offset_x = outer_box_shadow_params.offset_x;
  641. auto offset_y = outer_box_shadow_params.offset_y;
  642. auto blur_radius = outer_box_shadow_params.blur_radius;
  643. auto spread_distance = outer_box_shadow_params.spread_distance;
  644. auto const& corner_radii = outer_box_shadow_params.corner_radii;
  645. auto outer_shadow_rect = device_content_rect.translated({ offset_x, offset_y });
  646. auto inner_shadow_rect = outer_shadow_rect.inflated(-spread_distance, -spread_distance, -spread_distance, -spread_distance);
  647. outer_shadow_rect.inflate(
  648. blur_radius + offset_y,
  649. blur_radius + abs(offset_x),
  650. blur_radius + abs(offset_y),
  651. blur_radius + offset_x);
  652. auto inner_rect_corner_radii = corner_radii;
  653. auto add_spread_distance_to_corner_radius = [&](auto& corner_radius) {
  654. add_spread_distance_to_border_radius(corner_radius.horizontal_radius, -spread_distance);
  655. add_spread_distance_to_border_radius(corner_radius.vertical_radius, -spread_distance);
  656. };
  657. add_spread_distance_to_corner_radius(inner_rect_corner_radii.top_left);
  658. add_spread_distance_to_corner_radius(inner_rect_corner_radii.top_right);
  659. add_spread_distance_to_corner_radius(inner_rect_corner_radii.bottom_right);
  660. add_spread_distance_to_corner_radius(inner_rect_corner_radii.bottom_left);
  661. auto outer_rect = to_skia_rrect(outer_shadow_rect, corner_radii);
  662. auto inner_rect = to_skia_rrect(inner_shadow_rect, inner_rect_corner_radii);
  663. SkPath outer_path;
  664. outer_path.addRRect(outer_rect);
  665. SkPath inner_path;
  666. inner_path.addRRect(inner_rect);
  667. SkPath result_path;
  668. if (!Op(outer_path, inner_path, SkPathOp::kDifference_SkPathOp, &result_path)) {
  669. VERIFY_NOT_REACHED();
  670. }
  671. auto& canvas = surface().canvas();
  672. SkPaint path_paint;
  673. path_paint.setColor(to_skia_color(color));
  674. path_paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, blur_radius / 2));
  675. canvas.save();
  676. canvas.clipRRect(to_skia_rrect(device_content_rect, corner_radii), true);
  677. canvas.drawPath(result_path, path_paint);
  678. canvas.restore();
  679. return CommandResult::Continue;
  680. }
  681. CommandResult DisplayListPlayerSkia::paint_text_shadow(PaintTextShadow const& command)
  682. {
  683. auto& canvas = surface().canvas();
  684. auto blur_image_filter = SkImageFilters::Blur(command.blur_radius / 2, command.blur_radius / 2, nullptr);
  685. SkPaint blur_paint;
  686. blur_paint.setImageFilter(blur_image_filter);
  687. canvas.saveLayer(SkCanvas::SaveLayerRec(nullptr, &blur_paint, nullptr, 0));
  688. draw_glyph_run({
  689. .glyph_run = command.glyph_run,
  690. .color = command.color,
  691. .rect = command.text_rect,
  692. .translation = command.draw_location.to_type<float>() + command.text_rect.location().to_type<float>(),
  693. .scale = command.glyph_run_scale,
  694. });
  695. canvas.restore();
  696. return CommandResult::Continue;
  697. }
  698. CommandResult DisplayListPlayerSkia::fill_rect_with_rounded_corners(FillRectWithRoundedCorners const& command)
  699. {
  700. APPLY_PATH_CLIP_IF_NEEDED
  701. auto const& rect = command.rect;
  702. auto& canvas = surface().canvas();
  703. SkPaint paint;
  704. paint.setColor(to_skia_color(command.color));
  705. auto rounded_rect = to_skia_rrect(rect, command.corner_radii);
  706. canvas.drawRRect(rounded_rect, paint);
  707. return CommandResult::Continue;
  708. }
  709. CommandResult DisplayListPlayerSkia::fill_path_using_color(FillPathUsingColor const& command)
  710. {
  711. auto& canvas = surface().canvas();
  712. SkPaint paint;
  713. paint.setAntiAlias(true);
  714. paint.setColor(to_skia_color(command.color));
  715. auto path = to_skia_path(command.path);
  716. path.setFillType(to_skia_path_fill_type(command.winding_rule));
  717. path.offset(command.aa_translation.x(), command.aa_translation.y());
  718. canvas.drawPath(path, paint);
  719. return CommandResult::Continue;
  720. }
  721. static SkTileMode to_skia_tile_mode(SVGLinearGradientPaintStyle::SpreadMethod spread_method)
  722. {
  723. switch (spread_method) {
  724. case SVGLinearGradientPaintStyle::SpreadMethod::Pad:
  725. return SkTileMode::kClamp;
  726. case SVGLinearGradientPaintStyle::SpreadMethod::Reflect:
  727. return SkTileMode::kMirror;
  728. case SVGLinearGradientPaintStyle::SpreadMethod::Repeat:
  729. return SkTileMode::kRepeat;
  730. default:
  731. VERIFY_NOT_REACHED();
  732. }
  733. }
  734. static SkPaint paint_style_to_skia_paint(Painting::SVGGradientPaintStyle const& paint_style, Gfx::FloatRect bounding_rect)
  735. {
  736. SkPaint paint;
  737. auto const& color_stops = paint_style.color_stops();
  738. Vector<SkColor> colors;
  739. colors.ensure_capacity(color_stops.size());
  740. Vector<SkScalar> positions;
  741. positions.ensure_capacity(color_stops.size());
  742. for (auto const& color_stop : color_stops) {
  743. colors.append(to_skia_color(color_stop.color));
  744. positions.append(color_stop.position);
  745. }
  746. if (is<SVGLinearGradientPaintStyle>(paint_style)) {
  747. auto const& linear_gradient_paint_style = static_cast<SVGLinearGradientPaintStyle const&>(paint_style);
  748. SkMatrix matrix;
  749. auto scale = linear_gradient_paint_style.scale();
  750. auto start_point = linear_gradient_paint_style.start_point().scaled(scale);
  751. auto end_point = linear_gradient_paint_style.end_point().scaled(scale);
  752. start_point.translate_by(bounding_rect.location());
  753. end_point.translate_by(bounding_rect.location());
  754. Array<SkPoint, 2> points;
  755. points[0] = to_skia_point(start_point);
  756. points[1] = to_skia_point(end_point);
  757. auto shader = SkGradientShader::MakeLinear(points.data(), colors.data(), positions.data(), color_stops.size(), to_skia_tile_mode(paint_style.spread_method()), 0, &matrix);
  758. paint.setShader(shader);
  759. } else if (is<SVGRadialGradientPaintStyle>(paint_style)) {
  760. auto const& radial_gradient_paint_style = static_cast<SVGRadialGradientPaintStyle const&>(paint_style);
  761. SkMatrix matrix;
  762. auto scale = radial_gradient_paint_style.scale();
  763. auto start_center = radial_gradient_paint_style.start_center().scaled(scale);
  764. auto end_center = radial_gradient_paint_style.end_center().scaled(scale);
  765. auto start_radius = radial_gradient_paint_style.start_radius() * scale;
  766. auto end_radius = radial_gradient_paint_style.end_radius() * scale;
  767. start_center.translate_by(bounding_rect.location());
  768. end_center.translate_by(bounding_rect.location());
  769. auto start_sk_point = to_skia_point(start_center);
  770. auto end_sk_point = to_skia_point(end_center);
  771. 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);
  772. paint.setShader(shader);
  773. }
  774. return paint;
  775. }
  776. CommandResult DisplayListPlayerSkia::fill_path_using_paint_style(FillPathUsingPaintStyle const& command)
  777. {
  778. auto path = to_skia_path(command.path);
  779. path.offset(command.aa_translation.x(), command.aa_translation.y());
  780. path.setFillType(to_skia_path_fill_type(command.winding_rule));
  781. auto paint = paint_style_to_skia_paint(*command.paint_style, command.bounding_rect().to_type<float>());
  782. paint.setAntiAlias(true);
  783. paint.setAlphaf(command.opacity);
  784. surface().canvas().drawPath(path, paint);
  785. return CommandResult::Continue;
  786. }
  787. CommandResult DisplayListPlayerSkia::stroke_path_using_color(StrokePathUsingColor const& command)
  788. {
  789. // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.
  790. if (!command.thickness)
  791. return CommandResult::Continue;
  792. auto& canvas = surface().canvas();
  793. SkPaint paint;
  794. paint.setAntiAlias(true);
  795. paint.setStyle(SkPaint::kStroke_Style);
  796. paint.setStrokeWidth(command.thickness);
  797. paint.setColor(to_skia_color(command.color));
  798. auto path = to_skia_path(command.path);
  799. path.offset(command.aa_translation.x(), command.aa_translation.y());
  800. canvas.drawPath(path, paint);
  801. return CommandResult::Continue;
  802. }
  803. CommandResult DisplayListPlayerSkia::stroke_path_using_paint_style(StrokePathUsingPaintStyle const& command)
  804. {
  805. // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.
  806. if (!command.thickness)
  807. return CommandResult::Continue;
  808. auto path = to_skia_path(command.path);
  809. path.offset(command.aa_translation.x(), command.aa_translation.y());
  810. auto paint = paint_style_to_skia_paint(*command.paint_style, command.bounding_rect().to_type<float>());
  811. paint.setAntiAlias(true);
  812. paint.setAlphaf(command.opacity);
  813. paint.setStyle(SkPaint::Style::kStroke_Style);
  814. paint.setStrokeWidth(command.thickness);
  815. surface().canvas().drawPath(path, paint);
  816. return CommandResult::Continue;
  817. }
  818. CommandResult 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 CommandResult::Continue;
  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. return CommandResult::Continue;
  832. }
  833. CommandResult DisplayListPlayerSkia::fill_ellipse(FillEllipse const& command)
  834. {
  835. auto const& rect = command.rect;
  836. auto& canvas = surface().canvas();
  837. SkPaint paint;
  838. paint.setAntiAlias(true);
  839. paint.setColor(to_skia_color(command.color));
  840. canvas.drawOval(to_skia_rect(rect), paint);
  841. return CommandResult::Continue;
  842. }
  843. CommandResult DisplayListPlayerSkia::draw_line(DrawLine const& command)
  844. {
  845. // Skia treats zero thickness as a special case and will draw a hairline, while we want to draw nothing.
  846. if (!command.thickness)
  847. return CommandResult::Continue;
  848. auto from = to_skia_point(command.from);
  849. auto to = to_skia_point(command.to);
  850. auto& canvas = surface().canvas();
  851. SkPaint paint;
  852. paint.setStrokeWidth(command.thickness);
  853. paint.setColor(to_skia_color(command.color));
  854. switch (command.style) {
  855. case Gfx::LineStyle::Solid:
  856. break;
  857. case Gfx::LineStyle::Dotted: {
  858. auto length = command.to.distance_from(command.from);
  859. auto dot_count = floor(length / (static_cast<float>(command.thickness) * 2));
  860. auto interval = length / dot_count;
  861. SkScalar intervals[] = { 0, interval };
  862. paint.setPathEffect(SkDashPathEffect::Make(intervals, 2, 0));
  863. paint.setStrokeCap(SkPaint::Cap::kRound_Cap);
  864. // NOTE: As Skia doesn't render a dot exactly at the end of a line, we need
  865. // to extend it by less then an interval.
  866. auto direction = to - from;
  867. direction.normalize();
  868. to += direction * (interval / 2.0f);
  869. break;
  870. }
  871. case Gfx::LineStyle::Dashed: {
  872. auto length = command.to.distance_from(command.from) + command.thickness;
  873. auto dash_count = floor(length / static_cast<float>(command.thickness) / 4) * 2 + 1;
  874. auto interval = length / dash_count;
  875. SkScalar intervals[] = { interval, interval };
  876. paint.setPathEffect(SkDashPathEffect::Make(intervals, 2, 0));
  877. auto direction = to - from;
  878. direction.normalize();
  879. from -= direction * (command.thickness / 2.0f);
  880. to += direction * (command.thickness / 2.0f);
  881. break;
  882. }
  883. }
  884. canvas.drawLine(from, to, paint);
  885. return CommandResult::Continue;
  886. }
  887. CommandResult DisplayListPlayerSkia::apply_backdrop_filter(ApplyBackdropFilter const& command)
  888. {
  889. auto& canvas = surface().canvas();
  890. auto rect = to_skia_rect(command.backdrop_region);
  891. canvas.save();
  892. canvas.clipRect(rect);
  893. ScopeGuard guard = [&] { canvas.restore(); };
  894. for (auto const& filter_function : command.backdrop_filter.filters) {
  895. // See: https://drafts.fxtf.org/filter-effects-1/#supported-filter-functions
  896. filter_function.visit(
  897. [&](CSS::ResolvedBackdropFilter::Blur const& blur_filter) {
  898. auto blur_image_filter = SkImageFilters::Blur(blur_filter.radius, blur_filter.radius, nullptr);
  899. canvas.saveLayer(SkCanvas::SaveLayerRec(nullptr, nullptr, blur_image_filter.get(), 0));
  900. canvas.restore();
  901. },
  902. [&](CSS::ResolvedBackdropFilter::ColorOperation const& color) {
  903. auto amount = clamp(color.amount, 0.0f, 1.0f);
  904. // Matrices are taken from https://drafts.fxtf.org/filter-effects-1/#FilterPrimitiveRepresentation
  905. sk_sp<SkColorFilter> color_filter;
  906. switch (color.operation) {
  907. case CSS::Filter::Color::Operation::Grayscale: {
  908. float matrix[20] = {
  909. 0.2126f + 0.7874f * (1 - amount), 0.7152f - 0.7152f * (1 - amount), 0.0722f - 0.0722f * (1 - amount), 0, 0,
  910. 0.2126f - 0.2126f * (1 - amount), 0.7152f + 0.2848f * (1 - amount), 0.0722f - 0.0722f * (1 - amount), 0, 0,
  911. 0.2126f - 0.2126f * (1 - amount), 0.7152f - 0.7152f * (1 - amount), 0.0722f + 0.9278f * (1 - amount), 0, 0,
  912. 0, 0, 0, 1, 0
  913. };
  914. color_filter = SkColorFilters::Matrix(matrix);
  915. break;
  916. }
  917. case CSS::Filter::Color::Operation::Brightness: {
  918. float matrix[20] = {
  919. amount, 0, 0, 0, 0,
  920. 0, amount, 0, 0, 0,
  921. 0, 0, amount, 0, 0,
  922. 0, 0, 0, 1, 0
  923. };
  924. color_filter = SkColorFilters::Matrix(matrix);
  925. break;
  926. }
  927. case CSS::Filter::Color::Operation::Contrast: {
  928. float intercept = -(0.5f * amount) + 0.5f;
  929. float matrix[20] = {
  930. amount, 0, 0, 0, intercept,
  931. 0, amount, 0, 0, intercept,
  932. 0, 0, amount, 0, intercept,
  933. 0, 0, 0, 1, 0
  934. };
  935. color_filter = SkColorFilters::Matrix(matrix);
  936. break;
  937. }
  938. case CSS::Filter::Color::Operation::Invert: {
  939. float matrix[20] = {
  940. 1 - 2 * amount, 0, 0, 0, amount,
  941. 0, 1 - 2 * amount, 0, 0, amount,
  942. 0, 0, 1 - 2 * amount, 0, amount,
  943. 0, 0, 0, 1, 0
  944. };
  945. color_filter = SkColorFilters::Matrix(matrix);
  946. break;
  947. }
  948. case CSS::Filter::Color::Operation::Opacity: {
  949. float matrix[20] = {
  950. 1, 0, 0, 0, 0,
  951. 0, 1, 0, 0, 0,
  952. 0, 0, 1, 0, 0,
  953. 0, 0, 0, amount, 0
  954. };
  955. color_filter = SkColorFilters::Matrix(matrix);
  956. break;
  957. }
  958. case CSS::Filter::Color::Operation::Sepia: {
  959. float matrix[20] = {
  960. 0.393f + 0.607f * (1 - amount), 0.769f - 0.769f * (1 - amount), 0.189f - 0.189f * (1 - amount), 0, 0,
  961. 0.349f - 0.349f * (1 - amount), 0.686f + 0.314f * (1 - amount), 0.168f - 0.168f * (1 - amount), 0, 0,
  962. 0.272f - 0.272f * (1 - amount), 0.534f - 0.534f * (1 - amount), 0.131f + 0.869f * (1 - amount), 0, 0,
  963. 0, 0, 0, 1, 0
  964. };
  965. color_filter = SkColorFilters::Matrix(matrix);
  966. break;
  967. }
  968. case CSS::Filter::Color::Operation::Saturate: {
  969. float matrix[20] = {
  970. 0.213f + 0.787f * amount, 0.715f - 0.715f * amount, 0.072f - 0.072f * amount, 0, 0,
  971. 0.213f - 0.213f * amount, 0.715f + 0.285f * amount, 0.072f - 0.072f * amount, 0, 0,
  972. 0.213f - 0.213f * amount, 0.715f - 0.715f * amount, 0.072f + 0.928f * amount, 0, 0,
  973. 0, 0, 0, 1, 0
  974. };
  975. color_filter = SkColorFilters::Matrix(matrix);
  976. break;
  977. }
  978. default:
  979. VERIFY_NOT_REACHED();
  980. }
  981. auto image_filter = SkImageFilters::ColorFilter(color_filter, nullptr);
  982. canvas.saveLayer(SkCanvas::SaveLayerRec(nullptr, nullptr, image_filter.get(), 0));
  983. canvas.restore();
  984. },
  985. [&](CSS::ResolvedBackdropFilter::HueRotate const& hue_rotate) {
  986. float radians = AK::to_radians(hue_rotate.angle_degrees);
  987. auto cosA = cos(radians);
  988. auto sinA = sin(radians);
  989. auto a00 = 0.213f + cosA * 0.787f - sinA * 0.213f;
  990. auto a01 = 0.715f - cosA * 0.715f - sinA * 0.715f;
  991. auto a02 = 0.072f - cosA * 0.072f + sinA * 0.928f;
  992. auto a10 = 0.213f - cosA * 0.213f + sinA * 0.143f;
  993. auto a11 = 0.715f + cosA * 0.285f + sinA * 0.140f;
  994. auto a12 = 0.072f - cosA * 0.072f - sinA * 0.283f;
  995. auto a20 = 0.213f - cosA * 0.213f - sinA * 0.787f;
  996. auto a21 = 0.715f - cosA * 0.715f + sinA * 0.715f;
  997. auto a22 = 0.072f + cosA * 0.928f + sinA * 0.072f;
  998. float matrix[20] = {
  999. a00, a01, a02, 0, 0,
  1000. a10, a11, a12, 0, 0,
  1001. a20, a21, a22, 0, 0,
  1002. 0, 0, 0, 1, 0
  1003. };
  1004. auto color_filter = SkColorFilters::Matrix(matrix);
  1005. auto image_filter = SkImageFilters::ColorFilter(color_filter, nullptr);
  1006. canvas.saveLayer(SkCanvas::SaveLayerRec(nullptr, nullptr, image_filter.get(), 0));
  1007. canvas.restore();
  1008. },
  1009. [&](CSS::ResolvedBackdropFilter::DropShadow const&) {
  1010. dbgln("TODO: Implement drop-shadow() filter function!");
  1011. });
  1012. }
  1013. return CommandResult::Continue;
  1014. }
  1015. CommandResult DisplayListPlayerSkia::draw_rect(DrawRect const& command)
  1016. {
  1017. auto const& rect = command.rect;
  1018. auto& canvas = surface().canvas();
  1019. SkPaint paint;
  1020. paint.setStyle(SkPaint::kStroke_Style);
  1021. paint.setStrokeWidth(1);
  1022. paint.setColor(to_skia_color(command.color));
  1023. canvas.drawRect(to_skia_rect(rect), paint);
  1024. return CommandResult::Continue;
  1025. }
  1026. CommandResult DisplayListPlayerSkia::paint_radial_gradient(PaintRadialGradient const& command)
  1027. {
  1028. APPLY_PATH_CLIP_IF_NEEDED
  1029. auto const& radial_gradient_data = command.radial_gradient_data;
  1030. auto color_stop_list = radial_gradient_data.color_stops.list;
  1031. VERIFY(!color_stop_list.is_empty());
  1032. auto const& repeat_length = radial_gradient_data.color_stops.repeat_length;
  1033. if (repeat_length.has_value())
  1034. color_stop_list = expand_repeat_length(color_stop_list, repeat_length.value());
  1035. auto stops_with_replaced_transition_hints = replace_transition_hints_with_normal_color_stops(color_stop_list);
  1036. Vector<SkColor> colors;
  1037. Vector<SkScalar> positions;
  1038. for (size_t stop_index = 0; stop_index < stops_with_replaced_transition_hints.size(); stop_index++) {
  1039. auto const& stop = stops_with_replaced_transition_hints[stop_index];
  1040. if (stop_index > 0 && stop == stops_with_replaced_transition_hints[stop_index - 1])
  1041. continue;
  1042. colors.append(to_skia_color(stop.color));
  1043. positions.append(stop.position);
  1044. }
  1045. auto const& rect = command.rect;
  1046. auto center = to_skia_point(command.center.translated(command.rect.location()));
  1047. auto const size = command.size.to_type<float>();
  1048. SkMatrix matrix;
  1049. // Skia does not support specifying of horizontal and vertical radius's separately,
  1050. // so instead we apply scale matrix
  1051. matrix.setScale(size.width() / size.height(), 1.0f, center.x(), center.y());
  1052. SkTileMode tile_mode = SkTileMode::kClamp;
  1053. if (repeat_length.has_value())
  1054. tile_mode = SkTileMode::kRepeat;
  1055. auto shader = SkGradientShader::MakeRadial(center, size.height(), colors.data(), positions.data(), positions.size(), tile_mode, 0, &matrix);
  1056. SkPaint paint;
  1057. paint.setShader(shader);
  1058. surface().canvas().drawRect(to_skia_rect(rect), paint);
  1059. return CommandResult::Continue;
  1060. }
  1061. CommandResult DisplayListPlayerSkia::paint_conic_gradient(PaintConicGradient const& command)
  1062. {
  1063. APPLY_PATH_CLIP_IF_NEEDED
  1064. auto const& conic_gradient_data = command.conic_gradient_data;
  1065. auto color_stop_list = conic_gradient_data.color_stops.list;
  1066. auto const& repeat_length = conic_gradient_data.color_stops.repeat_length;
  1067. if (repeat_length.has_value())
  1068. color_stop_list = expand_repeat_length(color_stop_list, repeat_length.value());
  1069. VERIFY(!color_stop_list.is_empty());
  1070. auto stops_with_replaced_transition_hints = replace_transition_hints_with_normal_color_stops(color_stop_list);
  1071. Vector<SkColor> colors;
  1072. Vector<SkScalar> positions;
  1073. for (size_t stop_index = 0; stop_index < stops_with_replaced_transition_hints.size(); stop_index++) {
  1074. auto const& stop = stops_with_replaced_transition_hints[stop_index];
  1075. if (stop_index > 0 && stop == stops_with_replaced_transition_hints[stop_index - 1])
  1076. continue;
  1077. colors.append(to_skia_color(stop.color));
  1078. positions.append(stop.position);
  1079. }
  1080. auto const& rect = command.rect;
  1081. auto center = command.position.translated(rect.location()).to_type<float>();
  1082. SkMatrix matrix;
  1083. matrix.setRotate(-90 + conic_gradient_data.start_angle, center.x(), center.y());
  1084. auto shader = SkGradientShader::MakeSweep(center.x(), center.y(), colors.data(), positions.data(), positions.size(), SkTileMode::kRepeat, 0, 360, 0, &matrix);
  1085. SkPaint paint;
  1086. paint.setShader(shader);
  1087. surface().canvas().drawRect(to_skia_rect(rect), paint);
  1088. return CommandResult::Continue;
  1089. }
  1090. CommandResult DisplayListPlayerSkia::draw_triangle_wave(DrawTriangleWave const&)
  1091. {
  1092. return CommandResult::Continue;
  1093. }
  1094. void DisplayListPlayerSkia::prepare_to_execute(size_t)
  1095. {
  1096. }
  1097. CommandResult DisplayListPlayerSkia::sample_under_corners(SampleUnderCorners const& command)
  1098. {
  1099. auto rounded_rect = to_skia_rrect(command.border_rect, command.corner_radii);
  1100. auto& canvas = surface().canvas();
  1101. canvas.save();
  1102. auto clip_op = command.corner_clip == CornerClip::Inside ? SkClipOp::kDifference : SkClipOp::kIntersect;
  1103. canvas.clipRRect(rounded_rect, clip_op, true);
  1104. return CommandResult::Continue;
  1105. }
  1106. CommandResult DisplayListPlayerSkia::blit_corner_clipping(BlitCornerClipping const&)
  1107. {
  1108. auto& canvas = surface().canvas();
  1109. canvas.restore();
  1110. return CommandResult::Continue;
  1111. }
  1112. bool DisplayListPlayerSkia::would_be_fully_clipped_by_painter(Gfx::IntRect rect) const
  1113. {
  1114. return surface().canvas().quickReject(to_skia_rect(rect));
  1115. }
  1116. }