gpui: Update dependencies (second attempt) (#9836)

Updated version of #9741 with fixes for the problems raised in #9774. I
only verified that the images no longer look blueish on Linux, because I
don't have a Mac.

cc @osiewicz

Release Notes:

- N/A

---------

Signed-off-by: Niklas Wimmer <mail@nwimmer.me>
This commit is contained in:
Niklas Wimmer 2024-03-28 18:22:31 +01:00 committed by GitHub
parent 94c51c6ac9
commit e2d6b0deba
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 743 additions and 613 deletions

891
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -40,7 +40,7 @@ etagere = "0.2"
futures.workspace = true
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "5a5c4d4" }
gpui_macros.workspace = true
image = "0.23"
image = "0.25"
itertools.workspace = true
lazy_static.workspace = true
linkme = "0.3"
@ -54,7 +54,7 @@ profiling.workspace = true
rand.workspace = true
raw-window-handle = "0.6"
refineable.workspace = true
resvg = "0.14"
resvg = "0.40"
schemars.workspace = true
seahash = "4.1"
serde.workspace = true
@ -67,8 +67,6 @@ sum_tree.workspace = true
taffy = { git = "https://github.com/DioxusLabs/taffy", rev = "1876f72bee5e376023eaa518aa7b8a34c769bd1b" }
thiserror.workspace = true
time.workspace = true
tiny-skia = "0.5"
usvg = { version = "0.14", features = [] }
util.workspace = true
uuid = { version = "1.1.2", features = ["v4", "v5"] }
waker-fn = "1.1.0"
@ -78,7 +76,7 @@ backtrace = "0.3"
collections = { workspace = true, features = ["test-support"] }
util = { workspace = true, features = ["test-support"] }
[build-dependencies]
[target.'cfg(target_os = "macos")'.build-dependencies]
bindgen = "0.65.1"
cbindgen = "0.26.0"
@ -101,13 +99,15 @@ blade-graphics.workspace = true
blade-macros.workspace = true
blade-rwh.workspace = true
bytemuck = "1"
cosmic-text = "0.10.0"
cosmic-text = "0.11.2"
copypasta = "0.10.1"
[target.'cfg(target_os = "linux")'.dependencies]
open = "5.0.1"
ashpd = "0.7.0"
x11rb = { version = "0.13.0", features = ["allow-unsafe-code", "xkb", "randr"] }
as-raw-xcb-connection = "1"
ashpd = "0.8.0"
calloop = "0.12.4"
calloop-wayland-source = "0.2.0"
wayland-backend = { version = "0.3.3", features = ["client_system"] }
wayland-client = { version = "0.31.2" }
wayland-cursor = "0.31.1"
wayland-protocols = { version = "0.31.2", features = [
@ -115,12 +115,10 @@ wayland-protocols = { version = "0.31.2", features = [
"staging",
"unstable",
] }
wayland-backend = { version = "0.3.3", features = ["client_system"] }
xkbcommon = { version = "0.7", features = ["wayland", "x11"] }
as-raw-xcb-connection = "1"
calloop = "0.12.4"
calloop-wayland-source = "0.2.0"
oo7 = "0.3.0"
open = "5.1.2"
x11rb = { version = "0.13.0", features = ["allow-unsafe-code", "xkb", "randr"] }
xkbcommon = { version = "0.7", features = ["wayland", "x11"] }
[target.'cfg(windows)'.dependencies]
windows.workspace = true

View File

@ -1,186 +1,197 @@
#![cfg_attr(any(not(target_os = "macos"), feature = "macos-blade"), allow(unused))]
use std::{
env,
path::{Path, PathBuf},
};
use cbindgen::Config;
//TODO: consider generating shader code for WGSL
//TODO: deprecate "runtime-shaders" and "macos-blade"
fn main() {
#[cfg(target_os = "macos")]
generate_dispatch_bindings();
#[cfg(all(target_os = "macos", not(feature = "macos-blade")))]
let header_path = generate_shader_bindings();
#[cfg(all(target_os = "macos", not(feature = "macos-blade")))]
macos::build();
}
#[cfg(target_os = "macos")]
mod macos {
use std::{
env,
path::{Path, PathBuf},
};
use cbindgen::Config;
pub(super) fn build() {
generate_dispatch_bindings();
#[cfg(not(feature = "macos-blade"))]
{
let header_path = generate_shader_bindings();
#[cfg(feature = "runtime_shaders")]
emit_stitched_shaders(&header_path);
#[cfg(not(feature = "runtime_shaders"))]
compile_metal_shaders(&header_path);
}
}
fn generate_dispatch_bindings() {
println!("cargo:rustc-link-lib=framework=System");
println!("cargo:rerun-if-changed=src/platform/mac/dispatch.h");
let bindings = bindgen::Builder::default()
.header("src/platform/mac/dispatch.h")
.allowlist_var("_dispatch_main_q")
.allowlist_var("_dispatch_source_type_data_add")
.allowlist_var("DISPATCH_QUEUE_PRIORITY_DEFAULT")
.allowlist_var("DISPATCH_QUEUE_PRIORITY_HIGH")
.allowlist_var("DISPATCH_TIME_NOW")
.allowlist_function("dispatch_get_global_queue")
.allowlist_function("dispatch_async_f")
.allowlist_function("dispatch_after_f")
.allowlist_function("dispatch_time")
.allowlist_function("dispatch_source_merge_data")
.allowlist_function("dispatch_source_create")
.allowlist_function("dispatch_source_set_event_handler_f")
.allowlist_function("dispatch_resume")
.allowlist_function("dispatch_suspend")
.allowlist_function("dispatch_source_cancel")
.allowlist_function("dispatch_set_context")
.parse_callbacks(Box::new(bindgen::CargoCallbacks))
.layout_tests(false)
.generate()
.expect("unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("dispatch_sys.rs"))
.expect("couldn't write dispatch bindings");
}
fn generate_shader_bindings() -> PathBuf {
let output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("scene.h");
let crate_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut config = Config::default();
config.include_guard = Some("SCENE_H".into());
config.language = cbindgen::Language::C;
config.export.include.extend([
"Bounds".into(),
"Corners".into(),
"Edges".into(),
"Size".into(),
"Pixels".into(),
"PointF".into(),
"Hsla".into(),
"ContentMask".into(),
"Uniforms".into(),
"AtlasTile".into(),
"PathRasterizationInputIndex".into(),
"PathVertex_ScaledPixels".into(),
"ShadowInputIndex".into(),
"Shadow".into(),
"QuadInputIndex".into(),
"Underline".into(),
"UnderlineInputIndex".into(),
"Quad".into(),
"SpriteInputIndex".into(),
"MonochromeSprite".into(),
"PolychromeSprite".into(),
"PathSprite".into(),
"SurfaceInputIndex".into(),
"SurfaceBounds".into(),
"TransformationMatrix".into(),
]);
config.no_includes = true;
config.enumeration.prefix_with_name = true;
let mut builder = cbindgen::Builder::new();
let src_paths = [
crate_dir.join("src/scene.rs"),
crate_dir.join("src/geometry.rs"),
crate_dir.join("src/color.rs"),
crate_dir.join("src/window.rs"),
crate_dir.join("src/platform.rs"),
crate_dir.join("src/platform/mac/metal_renderer.rs"),
];
for src_path in src_paths {
println!("cargo:rerun-if-changed={}", src_path.display());
builder = builder.with_src(src_path);
}
builder
.with_config(config)
.generate()
.expect("Unable to generate bindings")
.write_to_file(&output_path);
output_path
}
/// To enable runtime compilation, we need to "stitch" the shaders file with the generated header
/// so that it is self-contained.
#[cfg(feature = "runtime_shaders")]
emit_stitched_shaders(&header_path);
#[cfg(all(target_os = "macos", not(feature = "macos-blade")))]
fn emit_stitched_shaders(header_path: &Path) {
use std::str::FromStr;
fn stitch_header(header: &Path, shader_path: &Path) -> std::io::Result<PathBuf> {
let header_contents = std::fs::read_to_string(header)?;
let shader_contents = std::fs::read_to_string(shader_path)?;
let stitched_contents = format!("{header_contents}\n{shader_contents}");
let out_path =
PathBuf::from(env::var("OUT_DIR").unwrap()).join("stitched_shaders.metal");
std::fs::write(&out_path, stitched_contents)?;
Ok(out_path)
}
let shader_source_path = "./src/platform/mac/shaders.metal";
let shader_path = PathBuf::from_str(shader_source_path).unwrap();
stitch_header(header_path, &shader_path).unwrap();
println!("cargo:rerun-if-changed={}", &shader_source_path);
}
#[cfg(not(feature = "runtime_shaders"))]
compile_metal_shaders(&header_path);
}
fn compile_metal_shaders(header_path: &Path) {
use std::process::{self, Command};
let shader_path = "./src/platform/mac/shaders.metal";
let air_output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("shaders.air");
let metallib_output_path =
PathBuf::from(env::var("OUT_DIR").unwrap()).join("shaders.metallib");
println!("cargo:rerun-if-changed={}", shader_path);
fn generate_dispatch_bindings() {
println!("cargo:rustc-link-lib=framework=System");
println!("cargo:rerun-if-changed=src/platform/mac/dispatch.h");
let output = Command::new("xcrun")
.args([
"-sdk",
"macosx",
"metal",
"-gline-tables-only",
"-mmacosx-version-min=10.15.7",
"-MO",
"-c",
shader_path,
"-include",
&header_path.to_str().unwrap(),
"-o",
])
.arg(&air_output_path)
.output()
.unwrap();
let bindings = bindgen::Builder::default()
.header("src/platform/mac/dispatch.h")
.allowlist_var("_dispatch_main_q")
.allowlist_var("_dispatch_source_type_data_add")
.allowlist_var("DISPATCH_QUEUE_PRIORITY_DEFAULT")
.allowlist_var("DISPATCH_QUEUE_PRIORITY_HIGH")
.allowlist_var("DISPATCH_TIME_NOW")
.allowlist_function("dispatch_get_global_queue")
.allowlist_function("dispatch_async_f")
.allowlist_function("dispatch_after_f")
.allowlist_function("dispatch_time")
.allowlist_function("dispatch_source_merge_data")
.allowlist_function("dispatch_source_create")
.allowlist_function("dispatch_source_set_event_handler_f")
.allowlist_function("dispatch_resume")
.allowlist_function("dispatch_suspend")
.allowlist_function("dispatch_source_cancel")
.allowlist_function("dispatch_set_context")
.parse_callbacks(Box::new(bindgen::CargoCallbacks))
.layout_tests(false)
.generate()
.expect("unable to generate bindings");
if !output.status.success() {
eprintln!(
"metal shader compilation failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
process::exit(1);
}
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("dispatch_sys.rs"))
.expect("couldn't write dispatch bindings");
}
let output = Command::new("xcrun")
.args(["-sdk", "macosx", "metallib"])
.arg(air_output_path)
.arg("-o")
.arg(metallib_output_path)
.output()
.unwrap();
fn generate_shader_bindings() -> PathBuf {
let output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("scene.h");
let crate_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut config = Config::default();
config.include_guard = Some("SCENE_H".into());
config.language = cbindgen::Language::C;
config.export.include.extend([
"Bounds".into(),
"Corners".into(),
"Edges".into(),
"Size".into(),
"Pixels".into(),
"PointF".into(),
"Hsla".into(),
"ContentMask".into(),
"Uniforms".into(),
"AtlasTile".into(),
"PathRasterizationInputIndex".into(),
"PathVertex_ScaledPixels".into(),
"ShadowInputIndex".into(),
"Shadow".into(),
"QuadInputIndex".into(),
"Underline".into(),
"UnderlineInputIndex".into(),
"Quad".into(),
"SpriteInputIndex".into(),
"MonochromeSprite".into(),
"PolychromeSprite".into(),
"PathSprite".into(),
"SurfaceInputIndex".into(),
"SurfaceBounds".into(),
"TransformationMatrix".into(),
]);
config.no_includes = true;
config.enumeration.prefix_with_name = true;
let mut builder = cbindgen::Builder::new();
let src_paths = [
crate_dir.join("src/scene.rs"),
crate_dir.join("src/geometry.rs"),
crate_dir.join("src/color.rs"),
crate_dir.join("src/window.rs"),
crate_dir.join("src/platform.rs"),
crate_dir.join("src/platform/mac/metal_renderer.rs"),
];
for src_path in src_paths {
println!("cargo:rerun-if-changed={}", src_path.display());
builder = builder.with_src(src_path);
}
builder
.with_config(config)
.generate()
.expect("Unable to generate bindings")
.write_to_file(&output_path);
output_path
}
/// To enable runtime compilation, we need to "stitch" the shaders file with the generated header
/// so that it is self-contained.
#[cfg(feature = "runtime_shaders")]
fn emit_stitched_shaders(header_path: &Path) {
use std::str::FromStr;
fn stitch_header(header: &Path, shader_path: &Path) -> std::io::Result<PathBuf> {
let header_contents = std::fs::read_to_string(header)?;
let shader_contents = std::fs::read_to_string(shader_path)?;
let stitched_contents = format!("{header_contents}\n{shader_contents}");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("stitched_shaders.metal");
std::fs::write(&out_path, stitched_contents)?;
Ok(out_path)
}
let shader_source_path = "./src/platform/mac/shaders.metal";
let shader_path = PathBuf::from_str(shader_source_path).unwrap();
stitch_header(header_path, &shader_path).unwrap();
println!("cargo:rerun-if-changed={}", &shader_source_path);
}
#[cfg(not(feature = "runtime_shaders"))]
fn compile_metal_shaders(header_path: &Path) {
use std::process::{self, Command};
let shader_path = "./src/platform/mac/shaders.metal";
let air_output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("shaders.air");
let metallib_output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("shaders.metallib");
println!("cargo:rerun-if-changed={}", shader_path);
let output = Command::new("xcrun")
.args([
"-sdk",
"macosx",
"metal",
"-gline-tables-only",
"-mmacosx-version-min=10.15.7",
"-MO",
"-c",
shader_path,
"-include",
&header_path.to_str().unwrap(),
"-o",
])
.arg(&air_output_path)
.output()
.unwrap();
if !output.status.success() {
eprintln!(
"metal shader compilation failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
process::exit(1);
}
let output = Command::new("xcrun")
.args(["-sdk", "macosx", "metallib"])
.arg(air_output_path)
.arg("-o")
.arg(metallib_output_path)
.output()
.unwrap();
if !output.status.success() {
eprintln!(
"metallib compilation failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
process::exit(1);
if !output.status.success() {
eprintln!(
"metallib compilation failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
process::exit(1);
}
}
}

View File

@ -1,6 +1,6 @@
use crate::{size, DevicePixels, Result, SharedString, Size};
use anyhow::anyhow;
use image::{Bgra, ImageBuffer};
use image::RgbaImage;
use std::{
borrow::Cow,
fmt,
@ -38,12 +38,12 @@ pub struct ImageId(usize);
pub struct ImageData {
/// The ID associated with this image
pub id: ImageId,
data: ImageBuffer<Bgra<u8>, Vec<u8>>,
data: RgbaImage,
}
impl ImageData {
/// Create a new image from the given data.
pub fn new(data: ImageBuffer<Bgra<u8>, Vec<u8>>) -> Self {
pub fn new(data: RgbaImage) -> Self {
static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
Self {

View File

@ -91,7 +91,7 @@ impl ImageCache {
async move {
match uri_or_path {
UriOrPath::Path(uri) => {
let image = image::open(uri.as_ref())?.into_bgra8();
let image = image::open(uri.as_ref())?.into_rgba8();
Ok(Arc::new(ImageData::new(image)))
}
UriOrPath::Uri(uri) => {
@ -110,7 +110,7 @@ impl ImageCache {
let format = image::guess_format(&body)?;
let image =
image::load_from_memory_with_format(&body, format)?
.into_bgra8();
.into_rgba8();
Ok(Arc::new(ImageData::new(image)))
}
}

View File

@ -159,7 +159,7 @@ impl BladeAtlasState {
usage = gpu::TextureUsage::COPY | gpu::TextureUsage::RESOURCE;
}
AtlasTextureKind::Polychrome => {
format = gpu::TextureFormat::Bgra8Unorm;
format = gpu::TextureFormat::Rgba8Unorm;
usage = gpu::TextureUsage::COPY | gpu::TextureUsage::RESOURCE;
}
AtlasTextureKind::Path => {

View File

@ -286,6 +286,7 @@ impl LinuxTextSystemState {
params.glyph_id.0 as u16,
(params.font_size * params.scale_factor).into(),
(0.0, 0.0),
cosmic_text::CacheKeyFlags::empty(),
)
.0,
)
@ -319,6 +320,7 @@ impl LinuxTextSystemState {
params.glyph_id.0 as u16,
(params.font_size * params.scale_factor).into(),
(0.0, 0.0),
cosmic_text::CacheKeyFlags::empty(),
)
.0,
)
@ -381,6 +383,7 @@ impl LinuxTextSystemState {
font_size.0,
f32::MAX, // We do our own wrapping
cosmic_text::Wrap::None,
None,
);
let mut runs = Vec::new();

View File

@ -115,7 +115,7 @@ impl MetalAtlasState {
usage = metal::MTLTextureUsage::ShaderRead;
}
AtlasTextureKind::Polychrome => {
pixel_format = metal::MTLPixelFormat::BGRA8Unorm;
pixel_format = metal::MTLPixelFormat::RGBA8Unorm;
usage = metal::MTLTextureUsage::ShaderRead;
}
AtlasTextureKind::Path => {

View File

@ -72,7 +72,7 @@ impl MetalRenderer {
let layer = metal::MetalLayer::new();
layer.set_device(&device);
layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
layer.set_pixel_format(MTLPixelFormat::RGBA8Unorm);
layer.set_opaque(true);
layer.set_maximum_drawable_count(3);
unsafe {
@ -128,7 +128,7 @@ impl MetalRenderer {
"path_sprites",
"path_sprite_vertex",
"path_sprite_fragment",
MTLPixelFormat::BGRA8Unorm,
MTLPixelFormat::RGBA8Unorm,
);
let shadows_pipeline_state = build_pipeline_state(
&device,
@ -136,7 +136,7 @@ impl MetalRenderer {
"shadows",
"shadow_vertex",
"shadow_fragment",
MTLPixelFormat::BGRA8Unorm,
MTLPixelFormat::RGBA8Unorm,
);
let quads_pipeline_state = build_pipeline_state(
&device,
@ -144,7 +144,7 @@ impl MetalRenderer {
"quads",
"quad_vertex",
"quad_fragment",
MTLPixelFormat::BGRA8Unorm,
MTLPixelFormat::RGBA8Unorm,
);
let underlines_pipeline_state = build_pipeline_state(
&device,
@ -152,7 +152,7 @@ impl MetalRenderer {
"underlines",
"underline_vertex",
"underline_fragment",
MTLPixelFormat::BGRA8Unorm,
MTLPixelFormat::RGBA8Unorm,
);
let monochrome_sprites_pipeline_state = build_pipeline_state(
&device,
@ -160,7 +160,7 @@ impl MetalRenderer {
"monochrome_sprites",
"monochrome_sprite_vertex",
"monochrome_sprite_fragment",
MTLPixelFormat::BGRA8Unorm,
MTLPixelFormat::RGBA8Unorm,
);
let polychrome_sprites_pipeline_state = build_pipeline_state(
&device,
@ -168,7 +168,7 @@ impl MetalRenderer {
"polychrome_sprites",
"polychrome_sprite_vertex",
"polychrome_sprite_fragment",
MTLPixelFormat::BGRA8Unorm,
MTLPixelFormat::RGBA8Unorm,
);
let surfaces_pipeline_state = build_pipeline_state(
&device,
@ -176,7 +176,7 @@ impl MetalRenderer {
"surfaces",
"surface_vertex",
"surface_fragment",
MTLPixelFormat::BGRA8Unorm,
MTLPixelFormat::RGBA8Unorm,
);
let command_queue = device.new_command_queue();

View File

@ -425,9 +425,8 @@ impl MacTextSystemState {
);
if params.is_emoji {
// Convert from RGBA with premultiplied alpha to BGRA with straight alpha.
// Convert from RGBA with premultiplied alpha to RGBA with straight alpha.
for pixel in bytes.chunks_exact_mut(4) {
pixel.swap(0, 2);
let a = pixel[3] as f32 / 255.;
pixel[0] = (pixel[0] as f32 / a) as u8;
pixel[1] = (pixel[1] as f32 / a) as u8;

View File

@ -213,11 +213,19 @@ impl WindowsTextSystemState {
_features: FontFeatures,
) -> Result<SmallVec<[FontId; 4]>> {
let mut font_ids = SmallVec::new();
let family = self
let families = self
.font_system
.get_font_matches(Attrs::new().family(cosmic_text::Family::Name(name)));
for font in family.as_ref() {
let font = self.font_system.get_font(*font).unwrap();
.db()
.faces()
.filter(|face| face.families.iter().any(|family| *name == family.0))
.map(|face| (face.id, face.post_script_name.clone()))
.collect::<SmallVec<[_; 4]>>();
for (font_id, postscript_name) in families {
let font = self
.font_system
.get_font(font_id)
.ok_or_else(|| anyhow!("Could not load font"))?;
// TODO: figure out why this is causing fluent icons from loading
// if font.as_swash().charmap().map('m') == 0 {
// self.font_system.db_mut().remove_face(font.id());
@ -227,6 +235,8 @@ impl WindowsTextSystemState {
let font_id = FontId(self.fonts.len());
font_ids.push(font_id);
self.fonts.push(font);
self.postscript_names_by_font_id
.insert(font_id, postscript_name);
}
Ok(font_ids)
}
@ -274,6 +284,7 @@ impl WindowsTextSystemState {
params.glyph_id.0 as u16,
(params.font_size * params.scale_factor).into(),
(0.0, 0.0),
cosmic_text::CacheKeyFlags::empty(),
)
.0,
)
@ -307,6 +318,7 @@ impl WindowsTextSystemState {
params.glyph_id.0 as u16,
(params.font_size * params.scale_factor).into(),
(0.0, 0.0),
cosmic_text::CacheKeyFlags::empty(),
)
.0,
)
@ -342,6 +354,7 @@ impl WindowsTextSystemState {
font_size.0,
f32::MAX, // todo(windows) we don't have a width cause this should technically not be wrapped I believe
cosmic_text::Wrap::None,
None,
);
let mut runs = Vec::new();
// todo(windows) what I think can happen is layout returns possibly multiple lines which means we should be probably working with it higher up in the text rendering

View File

@ -1,6 +1,9 @@
use crate::{AssetSource, DevicePixels, IsZero, Result, SharedString, Size};
use anyhow::anyhow;
use std::{hash::Hash, sync::Arc};
use std::{
hash::Hash,
sync::{Arc, OnceLock},
};
#[derive(Clone, PartialEq, Hash, Eq)]
pub(crate) struct RenderSvgParams {
@ -24,15 +27,19 @@ impl SvgRenderer {
// Load the tree.
let bytes = self.asset_source.load(&params.path)?;
let tree = usvg::Tree::from_data(&bytes, &usvg::Options::default())?;
let tree =
resvg::usvg::Tree::from_data(&bytes, &resvg::usvg::Options::default(), svg_fontdb())?;
// Render the SVG to a pixmap with the specified width and height.
let mut pixmap =
tiny_skia::Pixmap::new(params.size.width.into(), params.size.height.into()).unwrap();
resvg::tiny_skia::Pixmap::new(params.size.width.into(), params.size.height.into())
.unwrap();
let ratio = params.size.width.0 as f32 / tree.size().width();
resvg::render(
&tree,
usvg::FitTo::Width(params.size.width.into()),
pixmap.as_mut(),
resvg::tiny_skia::Transform::from_scale(ratio, ratio),
&mut pixmap.as_mut(),
);
// Convert the pixmap's pixels into an alpha mask.
@ -44,3 +51,13 @@ impl SvgRenderer {
Ok(alpha_mask)
}
}
/// Returns the global font database used for SVG rendering.
fn svg_fontdb() -> &'static resvg::usvg::fontdb::Database {
static FONTDB: OnceLock<resvg::usvg::fontdb::Database> = OnceLock::new();
FONTDB.get_or_init(|| {
let mut fontdb = resvg::usvg::fontdb::Database::new();
fontdb.load_system_fonts();
fontdb
})
}

View File

@ -36,7 +36,7 @@ pub mod core_video {
use super::*;
pub use crate::bindings::{
kCVPixelFormatType_32BGRA, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8Planar,
};
use crate::bindings::{kCVReturnSuccess, CVReturn, OSType};