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

View file

@ -1,186 +1,197 @@
#![cfg_attr(any(not(target_os = "macos"), feature = "macos-blade"), allow(unused))] #![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: consider generating shader code for WGSL
//TODO: deprecate "runtime-shaders" and "macos-blade" //TODO: deprecate "runtime-shaders" and "macos-blade"
fn main() { fn main() {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
generate_dispatch_bindings(); macos::build();
#[cfg(all(target_os = "macos", not(feature = "macos-blade")))] }
let header_path = generate_shader_bindings();
#[cfg(all(target_os = "macos", not(feature = "macos-blade")))] #[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")] #[cfg(feature = "runtime_shaders")]
emit_stitched_shaders(&header_path); fn emit_stitched_shaders(header_path: &Path) {
#[cfg(all(target_os = "macos", not(feature = "macos-blade")))] 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"))] #[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() { let output = Command::new("xcrun")
println!("cargo:rustc-link-lib=framework=System"); .args([
println!("cargo:rerun-if-changed=src/platform/mac/dispatch.h"); "-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() if !output.status.success() {
.header("src/platform/mac/dispatch.h") eprintln!(
.allowlist_var("_dispatch_main_q") "metal shader compilation failed:\n{}",
.allowlist_var("_dispatch_source_type_data_add") String::from_utf8_lossy(&output.stderr)
.allowlist_var("DISPATCH_QUEUE_PRIORITY_DEFAULT") );
.allowlist_var("DISPATCH_QUEUE_PRIORITY_HIGH") process::exit(1);
.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()); let output = Command::new("xcrun")
bindings .args(["-sdk", "macosx", "metallib"])
.write_to_file(out_path.join("dispatch_sys.rs")) .arg(air_output_path)
.expect("couldn't write dispatch bindings"); .arg("-o")
} .arg(metallib_output_path)
.output()
.unwrap();
fn generate_shader_bindings() -> PathBuf { if !output.status.success() {
let output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("scene.h"); eprintln!(
let crate_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); "metallib compilation failed:\n{}",
let mut config = Config::default(); String::from_utf8_lossy(&output.stderr)
config.include_guard = Some("SCENE_H".into()); );
config.language = cbindgen::Language::C; process::exit(1);
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);
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -425,9 +425,8 @@ impl MacTextSystemState {
); );
if params.is_emoji { 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) { for pixel in bytes.chunks_exact_mut(4) {
pixel.swap(0, 2);
let a = pixel[3] as f32 / 255.; let a = pixel[3] as f32 / 255.;
pixel[0] = (pixel[0] as f32 / a) as u8; pixel[0] = (pixel[0] as f32 / a) as u8;
pixel[1] = (pixel[1] as f32 / a) as u8; pixel[1] = (pixel[1] as f32 / a) as u8;

View file

@ -213,11 +213,19 @@ impl WindowsTextSystemState {
_features: FontFeatures, _features: FontFeatures,
) -> Result<SmallVec<[FontId; 4]>> { ) -> Result<SmallVec<[FontId; 4]>> {
let mut font_ids = SmallVec::new(); let mut font_ids = SmallVec::new();
let family = self let families = self
.font_system .font_system
.get_font_matches(Attrs::new().family(cosmic_text::Family::Name(name))); .db()
for font in family.as_ref() { .faces()
let font = self.font_system.get_font(*font).unwrap(); .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 // TODO: figure out why this is causing fluent icons from loading
// if font.as_swash().charmap().map('m') == 0 { // if font.as_swash().charmap().map('m') == 0 {
// self.font_system.db_mut().remove_face(font.id()); // self.font_system.db_mut().remove_face(font.id());
@ -227,6 +235,8 @@ impl WindowsTextSystemState {
let font_id = FontId(self.fonts.len()); let font_id = FontId(self.fonts.len());
font_ids.push(font_id); font_ids.push(font_id);
self.fonts.push(font); self.fonts.push(font);
self.postscript_names_by_font_id
.insert(font_id, postscript_name);
} }
Ok(font_ids) Ok(font_ids)
} }
@ -274,6 +284,7 @@ impl WindowsTextSystemState {
params.glyph_id.0 as u16, params.glyph_id.0 as u16,
(params.font_size * params.scale_factor).into(), (params.font_size * params.scale_factor).into(),
(0.0, 0.0), (0.0, 0.0),
cosmic_text::CacheKeyFlags::empty(),
) )
.0, .0,
) )
@ -307,6 +318,7 @@ impl WindowsTextSystemState {
params.glyph_id.0 as u16, params.glyph_id.0 as u16,
(params.font_size * params.scale_factor).into(), (params.font_size * params.scale_factor).into(),
(0.0, 0.0), (0.0, 0.0),
cosmic_text::CacheKeyFlags::empty(),
) )
.0, .0,
) )
@ -342,6 +354,7 @@ impl WindowsTextSystemState {
font_size.0, font_size.0,
f32::MAX, // todo(windows) we don't have a width cause this should technically not be wrapped I believe f32::MAX, // todo(windows) we don't have a width cause this should technically not be wrapped I believe
cosmic_text::Wrap::None, cosmic_text::Wrap::None,
None,
); );
let mut runs = Vec::new(); 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 // 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 crate::{AssetSource, DevicePixels, IsZero, Result, SharedString, Size};
use anyhow::anyhow; use anyhow::anyhow;
use std::{hash::Hash, sync::Arc}; use std::{
hash::Hash,
sync::{Arc, OnceLock},
};
#[derive(Clone, PartialEq, Hash, Eq)] #[derive(Clone, PartialEq, Hash, Eq)]
pub(crate) struct RenderSvgParams { pub(crate) struct RenderSvgParams {
@ -24,15 +27,19 @@ impl SvgRenderer {
// Load the tree. // Load the tree.
let bytes = self.asset_source.load(&params.path)?; 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. // Render the SVG to a pixmap with the specified width and height.
let mut pixmap = 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( resvg::render(
&tree, &tree,
usvg::FitTo::Width(params.size.width.into()), resvg::tiny_skia::Transform::from_scale(ratio, ratio),
pixmap.as_mut(), &mut pixmap.as_mut(),
); );
// Convert the pixmap's pixels into an alpha mask. // Convert the pixmap's pixels into an alpha mask.
@ -44,3 +51,13 @@ impl SvgRenderer {
Ok(alpha_mask) 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::*; use super::*;
pub use crate::bindings::{ pub use crate::bindings::{
kCVPixelFormatType_32BGRA, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8Planar, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8Planar,
}; };
use crate::bindings::{kCVReturnSuccess, CVReturn, OSType}; use crate::bindings::{kCVReturnSuccess, CVReturn, OSType};