logiguard fork v3: full patch set on verified 8c74db0 tree
Includes prior-session patches (carry forward so the app compiles): - crates/gpui/build.rs: cross-compile manifest fix - crates/gpui/src/platform.rs: PlatformWindow::activate_with_token trait method - crates/gpui/src/window.rs: Window::activate_with_token public API - crates/gpui_linux/src/linux/wayland/window.rs: WaylandWindow::activate_with_token + activate() keyboard-serial fix Plus the focus-serial fix: - serial.rs: SerialKind::KeyboardEnter - client.rs: store wl_keyboard.enter serial; latest_serial_of() Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
46
crates/gpui_wgpu/Cargo.toml
Normal file
46
crates/gpui_wgpu/Cargo.toml
Normal file
@@ -0,0 +1,46 @@
|
||||
[package]
|
||||
name = "gpui_wgpu"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
license = "Apache-2.0"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
path = "src/gpui_wgpu.rs"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
font-kit = ["dep:font-kit"]
|
||||
|
||||
[dependencies]
|
||||
gpui.workspace = true
|
||||
anyhow.workspace = true
|
||||
bytemuck = "1"
|
||||
collections.workspace = true
|
||||
cosmic-text = "0.17.0"
|
||||
etagere = "0.2"
|
||||
itertools.workspace = true
|
||||
log.workspace = true
|
||||
parking_lot.workspace = true
|
||||
profiling.workspace = true
|
||||
raw-window-handle = "0.6"
|
||||
smallvec.workspace = true
|
||||
swash = "0.2.6"
|
||||
gpui_util.workspace = true
|
||||
wgpu.workspace = true
|
||||
|
||||
# Optional: only needed on platforms with multiple font sources (e.g. Linux)
|
||||
# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io
|
||||
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", optional = true }
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
pollster.workspace = true
|
||||
|
||||
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||
wasm-bindgen.workspace = true
|
||||
wasm-bindgen-futures = "0.4"
|
||||
web-sys = { version = "0.3", features = ["HtmlCanvasElement"] }
|
||||
js-sys = "0.3"
|
||||
1
crates/gpui_wgpu/LICENSE-APACHE
Symbolic link
1
crates/gpui_wgpu/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../../LICENSE-APACHE
|
||||
653
crates/gpui_wgpu/src/cosmic_text_system.rs
Normal file
653
crates/gpui_wgpu/src/cosmic_text_system.rs
Normal file
@@ -0,0 +1,653 @@
|
||||
use anyhow::{Context as _, Ok, Result};
|
||||
use collections::HashMap;
|
||||
use cosmic_text::{
|
||||
Attrs, AttrsList, Family, Font as CosmicTextFont, FontFeatures as CosmicFontFeatures,
|
||||
FontSystem, ShapeBuffer, ShapeLine,
|
||||
};
|
||||
use gpui::{
|
||||
Bounds, DevicePixels, Font, FontFeatures, FontId, FontMetrics, FontRun, GlyphId, LineLayout,
|
||||
Pixels, PlatformTextSystem, RenderGlyphParams, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y,
|
||||
ShapedGlyph, ShapedRun, SharedString, Size, TextRenderingMode, point, size,
|
||||
};
|
||||
|
||||
use itertools::Itertools;
|
||||
use parking_lot::RwLock;
|
||||
use smallvec::SmallVec;
|
||||
use std::{borrow::Cow, sync::Arc};
|
||||
use swash::{
|
||||
scale::{Render, ScaleContext, Source, StrikeWith},
|
||||
zeno::{Format, Vector},
|
||||
};
|
||||
|
||||
pub struct CosmicTextSystem(RwLock<CosmicTextSystemState>);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
struct FontKey {
|
||||
family: SharedString,
|
||||
features: FontFeatures,
|
||||
}
|
||||
|
||||
impl FontKey {
|
||||
fn new(family: SharedString, features: FontFeatures) -> Self {
|
||||
Self { family, features }
|
||||
}
|
||||
}
|
||||
|
||||
struct CosmicTextSystemState {
|
||||
font_system: FontSystem,
|
||||
scratch: ShapeBuffer,
|
||||
swash_scale_context: ScaleContext,
|
||||
/// Contains all already loaded fonts, including all faces. Indexed by `FontId`.
|
||||
loaded_fonts: Vec<LoadedFont>,
|
||||
/// Caches the `FontId`s associated with a specific family to avoid iterating the font database
|
||||
/// for every font face in a family.
|
||||
font_ids_by_family_cache: HashMap<FontKey, SmallVec<[FontId; 4]>>,
|
||||
system_font_fallback: String,
|
||||
}
|
||||
|
||||
struct LoadedFont {
|
||||
font: Arc<CosmicTextFont>,
|
||||
features: CosmicFontFeatures,
|
||||
is_known_emoji_font: bool,
|
||||
}
|
||||
|
||||
impl CosmicTextSystem {
|
||||
pub fn new(system_font_fallback: &str) -> Self {
|
||||
let font_system = FontSystem::new();
|
||||
|
||||
Self(RwLock::new(CosmicTextSystemState {
|
||||
font_system,
|
||||
scratch: ShapeBuffer::default(),
|
||||
swash_scale_context: ScaleContext::new(),
|
||||
loaded_fonts: Vec::new(),
|
||||
font_ids_by_family_cache: HashMap::default(),
|
||||
system_font_fallback: system_font_fallback.to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn new_without_system_fonts(system_font_fallback: &str) -> Self {
|
||||
let font_system = FontSystem::new_with_locale_and_db(
|
||||
"en-US".to_string(),
|
||||
cosmic_text::fontdb::Database::new(),
|
||||
);
|
||||
|
||||
Self(RwLock::new(CosmicTextSystemState {
|
||||
font_system,
|
||||
scratch: ShapeBuffer::default(),
|
||||
swash_scale_context: ScaleContext::new(),
|
||||
loaded_fonts: Vec::new(),
|
||||
font_ids_by_family_cache: HashMap::default(),
|
||||
system_font_fallback: system_font_fallback.to_string(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformTextSystem for CosmicTextSystem {
|
||||
fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
|
||||
self.0.write().add_fonts(fonts)
|
||||
}
|
||||
|
||||
fn all_font_names(&self) -> Vec<String> {
|
||||
let mut result = self
|
||||
.0
|
||||
.read()
|
||||
.font_system
|
||||
.db()
|
||||
.faces()
|
||||
.filter_map(|face| face.families.first().map(|family| family.0.clone()))
|
||||
.collect_vec();
|
||||
result.sort();
|
||||
result.dedup();
|
||||
result
|
||||
}
|
||||
|
||||
fn font_id(&self, font: &Font) -> Result<FontId> {
|
||||
let mut state = self.0.write();
|
||||
let key = FontKey::new(font.family.clone(), font.features.clone());
|
||||
let candidates = if let Some(font_ids) = state.font_ids_by_family_cache.get(&key) {
|
||||
font_ids.as_slice()
|
||||
} else {
|
||||
let font_ids = state.load_family(&font.family, &font.features)?;
|
||||
state.font_ids_by_family_cache.insert(key.clone(), font_ids);
|
||||
state.font_ids_by_family_cache[&key].as_ref()
|
||||
};
|
||||
|
||||
let ix = find_best_match(font, candidates, &state)?;
|
||||
|
||||
Ok(candidates[ix])
|
||||
}
|
||||
|
||||
fn font_metrics(&self, font_id: FontId) -> FontMetrics {
|
||||
let metrics = self
|
||||
.0
|
||||
.read()
|
||||
.loaded_font(font_id)
|
||||
.font
|
||||
.as_swash()
|
||||
.metrics(&[]);
|
||||
|
||||
FontMetrics {
|
||||
units_per_em: metrics.units_per_em as u32,
|
||||
ascent: metrics.ascent,
|
||||
descent: -metrics.descent,
|
||||
line_gap: metrics.leading,
|
||||
underline_position: metrics.underline_offset,
|
||||
underline_thickness: metrics.stroke_size,
|
||||
cap_height: metrics.cap_height,
|
||||
x_height: metrics.x_height,
|
||||
bounding_box: Bounds {
|
||||
origin: point(0.0, 0.0),
|
||||
size: size(metrics.max_width, metrics.ascent + metrics.descent),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
|
||||
let lock = self.0.read();
|
||||
let glyph_metrics = lock.loaded_font(font_id).font.as_swash().glyph_metrics(&[]);
|
||||
let glyph_id = glyph_id.0 as u16;
|
||||
Ok(Bounds {
|
||||
origin: point(0.0, 0.0),
|
||||
size: size(
|
||||
glyph_metrics.advance_width(glyph_id),
|
||||
glyph_metrics.advance_height(glyph_id),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
|
||||
self.0.read().advance(font_id, glyph_id)
|
||||
}
|
||||
|
||||
fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
|
||||
self.0.read().glyph_for_char(font_id, ch)
|
||||
}
|
||||
|
||||
fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
|
||||
self.0.write().raster_bounds(params)
|
||||
}
|
||||
|
||||
fn rasterize_glyph(
|
||||
&self,
|
||||
params: &RenderGlyphParams,
|
||||
raster_bounds: Bounds<DevicePixels>,
|
||||
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
|
||||
self.0.write().rasterize_glyph(params, raster_bounds)
|
||||
}
|
||||
|
||||
fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
|
||||
self.0.write().layout_line(text, font_size, runs)
|
||||
}
|
||||
|
||||
fn recommended_rendering_mode(
|
||||
&self,
|
||||
_font_id: FontId,
|
||||
_font_size: Pixels,
|
||||
) -> TextRenderingMode {
|
||||
TextRenderingMode::Subpixel
|
||||
}
|
||||
}
|
||||
|
||||
impl CosmicTextSystemState {
|
||||
fn loaded_font(&self, font_id: FontId) -> &LoadedFont {
|
||||
&self.loaded_fonts[font_id.0]
|
||||
}
|
||||
|
||||
#[profiling::function]
|
||||
fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
|
||||
let db = self.font_system.db_mut();
|
||||
for bytes in fonts {
|
||||
match bytes {
|
||||
Cow::Borrowed(embedded_font) => {
|
||||
db.load_font_data(embedded_font.to_vec());
|
||||
}
|
||||
Cow::Owned(bytes) => {
|
||||
db.load_font_data(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[profiling::function]
|
||||
fn load_family(
|
||||
&mut self,
|
||||
name: &str,
|
||||
features: &FontFeatures,
|
||||
) -> Result<SmallVec<[FontId; 4]>> {
|
||||
let name = gpui::font_name_with_fallbacks(name, &self.system_font_fallback);
|
||||
|
||||
let families = self
|
||||
.font_system
|
||||
.db()
|
||||
.faces()
|
||||
.filter(|face| face.families.iter().any(|family| *name == family.0))
|
||||
.map(|face| (face.id, face.post_script_name.clone()))
|
||||
.collect::<SmallVec<[_; 4]>>();
|
||||
|
||||
let mut loaded_font_ids = SmallVec::new();
|
||||
for (font_id, postscript_name) in families {
|
||||
let font = self
|
||||
.font_system
|
||||
.get_font(font_id, cosmic_text::Weight::NORMAL)
|
||||
.context("Could not load font")?;
|
||||
|
||||
// HACK: To let the storybook run and render Windows caption icons. We should actually do better font fallback.
|
||||
let allowed_bad_font_names = [
|
||||
"SegoeFluentIcons", // NOTE: Segoe fluent icons postscript name is inconsistent
|
||||
"Segoe Fluent Icons",
|
||||
];
|
||||
|
||||
if font.as_swash().charmap().map('m') == 0
|
||||
&& !allowed_bad_font_names.contains(&postscript_name.as_str())
|
||||
{
|
||||
self.font_system.db_mut().remove_face(font.id());
|
||||
continue;
|
||||
};
|
||||
|
||||
let font_id = FontId(self.loaded_fonts.len());
|
||||
loaded_font_ids.push(font_id);
|
||||
self.loaded_fonts.push(LoadedFont {
|
||||
font,
|
||||
features: cosmic_font_features(features)?,
|
||||
is_known_emoji_font: check_is_known_emoji_font(&postscript_name),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(loaded_font_ids)
|
||||
}
|
||||
|
||||
fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
|
||||
let glyph_metrics = self.loaded_font(font_id).font.as_swash().glyph_metrics(&[]);
|
||||
Ok(Size {
|
||||
width: glyph_metrics.advance_width(glyph_id.0 as u16),
|
||||
height: glyph_metrics.advance_height(glyph_id.0 as u16),
|
||||
})
|
||||
}
|
||||
|
||||
fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
|
||||
let glyph_id = self.loaded_font(font_id).font.as_swash().charmap().map(ch);
|
||||
if glyph_id == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(GlyphId(glyph_id.into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn raster_bounds(&mut self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
|
||||
let image = self.render_glyph_image(params)?;
|
||||
Ok(Bounds {
|
||||
origin: point(image.placement.left.into(), (-image.placement.top).into()),
|
||||
size: size(image.placement.width.into(), image.placement.height.into()),
|
||||
})
|
||||
}
|
||||
|
||||
#[profiling::function]
|
||||
fn rasterize_glyph(
|
||||
&mut self,
|
||||
params: &RenderGlyphParams,
|
||||
glyph_bounds: Bounds<DevicePixels>,
|
||||
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
|
||||
if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
|
||||
anyhow::bail!("glyph bounds are empty");
|
||||
}
|
||||
|
||||
let mut image = self.render_glyph_image(params)?;
|
||||
let bitmap_size = glyph_bounds.size;
|
||||
match image.content {
|
||||
swash::scale::image::Content::Color | swash::scale::image::Content::SubpixelMask => {
|
||||
// Convert from RGBA to BGRA.
|
||||
for pixel in image.data.chunks_exact_mut(4) {
|
||||
pixel.swap(0, 2);
|
||||
}
|
||||
Ok((bitmap_size, image.data))
|
||||
}
|
||||
swash::scale::image::Content::Mask => {
|
||||
if params.subpixel_rendering {
|
||||
// We must always return RGBA data when subpixel rendering is requested.
|
||||
let expanded = image.data.iter().flat_map(|&a| [a, a, a, a]).collect();
|
||||
Ok((bitmap_size, expanded))
|
||||
} else {
|
||||
Ok((bitmap_size, image.data))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_glyph_image(
|
||||
&mut self,
|
||||
params: &RenderGlyphParams,
|
||||
) -> Result<swash::scale::image::Image> {
|
||||
let loaded_font = &self.loaded_fonts[params.font_id.0];
|
||||
let font_ref = loaded_font.font.as_swash();
|
||||
let pixel_size = f32::from(params.font_size);
|
||||
|
||||
let subpixel_offset = Vector::new(
|
||||
params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor,
|
||||
params.subpixel_variant.y as f32 / SUBPIXEL_VARIANTS_Y as f32 / params.scale_factor,
|
||||
);
|
||||
|
||||
let mut scaler = self
|
||||
.swash_scale_context
|
||||
.builder(font_ref)
|
||||
.size(pixel_size * params.scale_factor)
|
||||
.hint(true)
|
||||
.build();
|
||||
|
||||
let sources: &[Source] = if params.is_emoji {
|
||||
&[
|
||||
Source::ColorOutline(0),
|
||||
Source::ColorBitmap(StrikeWith::BestFit),
|
||||
Source::Outline,
|
||||
]
|
||||
} else {
|
||||
&[Source::Bitmap(StrikeWith::ExactSize), Source::Outline]
|
||||
};
|
||||
|
||||
let mut renderer = Render::new(sources);
|
||||
if params.subpixel_rendering {
|
||||
// There seems to be a bug in Swash where the B and R values are swapped.
|
||||
renderer
|
||||
.format(Format::subpixel_bgra())
|
||||
.offset(subpixel_offset);
|
||||
} else {
|
||||
renderer.format(Format::Alpha).offset(subpixel_offset);
|
||||
}
|
||||
|
||||
let glyph_id: u16 = params.glyph_id.0.try_into()?;
|
||||
renderer
|
||||
.render(&mut scaler, glyph_id)
|
||||
.with_context(|| format!("unable to render glyph via swash for {params:?}"))
|
||||
}
|
||||
|
||||
/// This is used when cosmic_text has chosen a fallback font instead of using the requested
|
||||
/// font, typically to handle some unicode characters. When this happens, `loaded_fonts` may not
|
||||
/// yet have an entry for this fallback font, and so one is added.
|
||||
///
|
||||
/// Note that callers shouldn't use this `FontId` somewhere that will retrieve the corresponding
|
||||
/// `LoadedFont.features`, as it will have an arbitrarily chosen or empty value. The only
|
||||
/// current use of this field is for the *input* of `layout_line`, and so it's fine to use
|
||||
/// `font_id_for_cosmic_id` when computing the *output* of `layout_line`.
|
||||
fn font_id_for_cosmic_id(&mut self, id: cosmic_text::fontdb::ID) -> Result<FontId> {
|
||||
if let Some(ix) = self
|
||||
.loaded_fonts
|
||||
.iter()
|
||||
.position(|loaded_font| loaded_font.font.id() == id)
|
||||
{
|
||||
Ok(FontId(ix))
|
||||
} else {
|
||||
let font = self
|
||||
.font_system
|
||||
.get_font(id, cosmic_text::Weight::NORMAL)
|
||||
.context("failed to get fallback font from cosmic-text font system")?;
|
||||
let face = self
|
||||
.font_system
|
||||
.db()
|
||||
.face(id)
|
||||
.context("fallback font face not found in cosmic-text database")?;
|
||||
|
||||
let font_id = FontId(self.loaded_fonts.len());
|
||||
self.loaded_fonts.push(LoadedFont {
|
||||
font,
|
||||
features: CosmicFontFeatures::new(),
|
||||
is_known_emoji_font: check_is_known_emoji_font(&face.post_script_name),
|
||||
});
|
||||
|
||||
Ok(font_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[profiling::function]
|
||||
fn layout_line(&mut self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
|
||||
let mut attrs_list = AttrsList::new(&Attrs::new());
|
||||
let mut offs = 0;
|
||||
for run in font_runs {
|
||||
let loaded_font = self.loaded_font(run.font_id);
|
||||
let Some(face) = self.font_system.db().face(loaded_font.font.id()) else {
|
||||
log::warn!(
|
||||
"font face not found in database for font_id {:?}",
|
||||
run.font_id
|
||||
);
|
||||
offs += run.len;
|
||||
continue;
|
||||
};
|
||||
let Some(first_family) = face.families.first() else {
|
||||
log::warn!(
|
||||
"font face has no family names for font_id {:?}",
|
||||
run.font_id
|
||||
);
|
||||
offs += run.len;
|
||||
continue;
|
||||
};
|
||||
|
||||
attrs_list.add_span(
|
||||
offs..(offs + run.len),
|
||||
&Attrs::new()
|
||||
.metadata(run.font_id.0)
|
||||
.family(Family::Name(&first_family.0))
|
||||
.stretch(face.stretch)
|
||||
.style(face.style)
|
||||
.weight(face.weight)
|
||||
.font_features(loaded_font.features.clone()),
|
||||
);
|
||||
offs += run.len;
|
||||
}
|
||||
|
||||
let line = ShapeLine::new(
|
||||
&mut self.font_system,
|
||||
text,
|
||||
&attrs_list,
|
||||
cosmic_text::Shaping::Advanced,
|
||||
4,
|
||||
);
|
||||
let mut layout_lines = Vec::with_capacity(1);
|
||||
line.layout_to_buffer(
|
||||
&mut self.scratch,
|
||||
f32::from(font_size),
|
||||
None, // We do our own wrapping
|
||||
cosmic_text::Wrap::None,
|
||||
None,
|
||||
&mut layout_lines,
|
||||
None,
|
||||
cosmic_text::Hinting::Disabled,
|
||||
);
|
||||
|
||||
let Some(layout) = layout_lines.first() else {
|
||||
return LineLayout {
|
||||
font_size,
|
||||
width: Pixels::ZERO,
|
||||
ascent: Pixels::ZERO,
|
||||
descent: Pixels::ZERO,
|
||||
runs: Vec::new(),
|
||||
len: text.len(),
|
||||
};
|
||||
};
|
||||
|
||||
let mut runs: Vec<ShapedRun> = Vec::new();
|
||||
for glyph in &layout.glyphs {
|
||||
let mut font_id = FontId(glyph.metadata);
|
||||
let mut loaded_font = self.loaded_font(font_id);
|
||||
if loaded_font.font.id() != glyph.font_id {
|
||||
match self.font_id_for_cosmic_id(glyph.font_id) {
|
||||
std::result::Result::Ok(resolved_id) => {
|
||||
font_id = resolved_id;
|
||||
loaded_font = self.loaded_font(font_id);
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"failed to resolve cosmic font id {:?}: {error:#}",
|
||||
glyph.font_id
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let is_emoji = loaded_font.is_known_emoji_font;
|
||||
|
||||
// HACK: Prevent crash caused by variation selectors.
|
||||
if glyph.glyph_id == 3 && is_emoji {
|
||||
continue;
|
||||
}
|
||||
|
||||
let shaped_glyph = ShapedGlyph {
|
||||
id: GlyphId(glyph.glyph_id as u32),
|
||||
position: point(glyph.x.into(), glyph.y.into()),
|
||||
index: glyph.start,
|
||||
is_emoji,
|
||||
};
|
||||
|
||||
if let Some(last_run) = runs
|
||||
.last_mut()
|
||||
.filter(|last_run| last_run.font_id == font_id)
|
||||
{
|
||||
last_run.glyphs.push(shaped_glyph);
|
||||
} else {
|
||||
runs.push(ShapedRun {
|
||||
font_id,
|
||||
glyphs: vec![shaped_glyph],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
LineLayout {
|
||||
font_size,
|
||||
width: layout.w.into(),
|
||||
ascent: layout.max_ascent.into(),
|
||||
descent: layout.max_descent.into(),
|
||||
runs,
|
||||
len: text.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "font-kit")]
|
||||
fn find_best_match(
|
||||
font: &Font,
|
||||
candidates: &[FontId],
|
||||
state: &CosmicTextSystemState,
|
||||
) -> Result<usize> {
|
||||
let candidate_properties = candidates
|
||||
.iter()
|
||||
.map(|font_id| {
|
||||
let database_id = state.loaded_font(*font_id).font.id();
|
||||
let face_info = state
|
||||
.font_system
|
||||
.db()
|
||||
.face(database_id)
|
||||
.context("font face not found in database")?;
|
||||
Ok(face_info_into_properties(face_info))
|
||||
})
|
||||
.collect::<Result<SmallVec<[_; 4]>>>()?;
|
||||
|
||||
let ix =
|
||||
font_kit::matching::find_best_match(&candidate_properties, &font_into_properties(font))
|
||||
.context("requested font family contains no font matching the other parameters")?;
|
||||
|
||||
Ok(ix)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "font-kit"))]
|
||||
fn find_best_match(
|
||||
font: &Font,
|
||||
candidates: &[FontId],
|
||||
state: &CosmicTextSystemState,
|
||||
) -> Result<usize> {
|
||||
if candidates.is_empty() {
|
||||
anyhow::bail!("requested font family contains no font matching the other parameters");
|
||||
}
|
||||
if candidates.len() == 1 {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let target_weight = font.weight.0;
|
||||
let target_italic = matches!(
|
||||
font.style,
|
||||
gpui::FontStyle::Italic | gpui::FontStyle::Oblique
|
||||
);
|
||||
|
||||
let mut best_index = 0;
|
||||
let mut best_score = u32::MAX;
|
||||
|
||||
for (index, font_id) in candidates.iter().enumerate() {
|
||||
let database_id = state.loaded_font(*font_id).font.id();
|
||||
let face_info = state
|
||||
.font_system
|
||||
.db()
|
||||
.face(database_id)
|
||||
.context("font face not found in database")?;
|
||||
|
||||
let is_italic = matches!(
|
||||
face_info.style,
|
||||
cosmic_text::Style::Italic | cosmic_text::Style::Oblique
|
||||
);
|
||||
let style_penalty: u32 = if is_italic == target_italic { 0 } else { 1000 };
|
||||
let weight_diff = (face_info.weight.0 as i32 - target_weight as i32).unsigned_abs();
|
||||
let score = style_penalty + weight_diff;
|
||||
|
||||
if score < best_score {
|
||||
best_score = score;
|
||||
best_index = index;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(best_index)
|
||||
}
|
||||
|
||||
fn cosmic_font_features(features: &FontFeatures) -> Result<CosmicFontFeatures> {
|
||||
let mut result = CosmicFontFeatures::new();
|
||||
for feature in features.0.iter() {
|
||||
let name_bytes: [u8; 4] = feature
|
||||
.0
|
||||
.as_bytes()
|
||||
.try_into()
|
||||
.context("Incorrect feature flag format")?;
|
||||
|
||||
let tag = cosmic_text::FeatureTag::new(&name_bytes);
|
||||
|
||||
result.set(tag, feature.1);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(feature = "font-kit")]
|
||||
fn font_into_properties(font: &gpui::Font) -> font_kit::properties::Properties {
|
||||
font_kit::properties::Properties {
|
||||
style: match font.style {
|
||||
gpui::FontStyle::Normal => font_kit::properties::Style::Normal,
|
||||
gpui::FontStyle::Italic => font_kit::properties::Style::Italic,
|
||||
gpui::FontStyle::Oblique => font_kit::properties::Style::Oblique,
|
||||
},
|
||||
weight: font_kit::properties::Weight(font.weight.0),
|
||||
stretch: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "font-kit")]
|
||||
fn face_info_into_properties(
|
||||
face_info: &cosmic_text::fontdb::FaceInfo,
|
||||
) -> font_kit::properties::Properties {
|
||||
font_kit::properties::Properties {
|
||||
style: match face_info.style {
|
||||
cosmic_text::Style::Normal => font_kit::properties::Style::Normal,
|
||||
cosmic_text::Style::Italic => font_kit::properties::Style::Italic,
|
||||
cosmic_text::Style::Oblique => font_kit::properties::Style::Oblique,
|
||||
},
|
||||
weight: font_kit::properties::Weight(face_info.weight.0.into()),
|
||||
stretch: match face_info.stretch {
|
||||
cosmic_text::Stretch::Condensed => font_kit::properties::Stretch::CONDENSED,
|
||||
cosmic_text::Stretch::Expanded => font_kit::properties::Stretch::EXPANDED,
|
||||
cosmic_text::Stretch::ExtraCondensed => font_kit::properties::Stretch::EXTRA_CONDENSED,
|
||||
cosmic_text::Stretch::ExtraExpanded => font_kit::properties::Stretch::EXTRA_EXPANDED,
|
||||
cosmic_text::Stretch::Normal => font_kit::properties::Stretch::NORMAL,
|
||||
cosmic_text::Stretch::SemiCondensed => font_kit::properties::Stretch::SEMI_CONDENSED,
|
||||
cosmic_text::Stretch::SemiExpanded => font_kit::properties::Stretch::SEMI_EXPANDED,
|
||||
cosmic_text::Stretch::UltraCondensed => font_kit::properties::Stretch::ULTRA_CONDENSED,
|
||||
cosmic_text::Stretch::UltraExpanded => font_kit::properties::Stretch::ULTRA_EXPANDED,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn check_is_known_emoji_font(postscript_name: &str) -> bool {
|
||||
// TODO: Include other common emoji fonts
|
||||
postscript_name == "NotoColorEmoji"
|
||||
}
|
||||
10
crates/gpui_wgpu/src/gpui_wgpu.rs
Normal file
10
crates/gpui_wgpu/src/gpui_wgpu.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
mod cosmic_text_system;
|
||||
mod wgpu_atlas;
|
||||
mod wgpu_context;
|
||||
mod wgpu_renderer;
|
||||
|
||||
pub use cosmic_text_system::*;
|
||||
pub use wgpu;
|
||||
pub use wgpu_atlas::*;
|
||||
pub use wgpu_context::*;
|
||||
pub use wgpu_renderer::{GpuContext, WgpuRenderer, WgpuSurfaceConfig};
|
||||
1336
crates/gpui_wgpu/src/shaders.wgsl
Normal file
1336
crates/gpui_wgpu/src/shaders.wgsl
Normal file
File diff suppressed because it is too large
Load Diff
56
crates/gpui_wgpu/src/shaders_subpixel.wgsl
Normal file
56
crates/gpui_wgpu/src/shaders_subpixel.wgsl
Normal file
@@ -0,0 +1,56 @@
|
||||
// --- subpixel sprites --- //
|
||||
|
||||
struct SubpixelSprite {
|
||||
order: u32,
|
||||
pad: u32,
|
||||
bounds: Bounds,
|
||||
content_mask: Bounds,
|
||||
color: Hsla,
|
||||
tile: AtlasTile,
|
||||
transformation: TransformationMatrix,
|
||||
}
|
||||
@group(1) @binding(0) var<storage, read> b_subpixel_sprites: array<SubpixelSprite>;
|
||||
|
||||
struct SubpixelSpriteOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) tile_position: vec2<f32>,
|
||||
@location(1) @interpolate(flat) color: vec4<f32>,
|
||||
@location(3) clip_distances: vec4<f32>,
|
||||
}
|
||||
|
||||
struct SubpixelSpriteFragmentOutput {
|
||||
@location(0) @blend_src(0) foreground: vec4<f32>,
|
||||
@location(0) @blend_src(1) alpha: vec4<f32>,
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_subpixel_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> SubpixelSpriteOutput {
|
||||
let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
|
||||
let sprite = b_subpixel_sprites[instance_id];
|
||||
|
||||
var out = SubpixelSpriteOutput();
|
||||
out.position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
|
||||
out.tile_position = to_tile_position(unit_vertex, sprite.tile);
|
||||
out.color = hsla_to_rgba(sprite.color);
|
||||
out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_subpixel_sprite(input: SubpixelSpriteOutput) -> SubpixelSpriteFragmentOutput {
|
||||
var sample = textureSample(t_sprite, s_sprite, input.tile_position).rgb;
|
||||
if (gamma_params.is_bgr != 0u) {
|
||||
sample = sample.bgr;
|
||||
}
|
||||
let alpha_corrected = apply_contrast_and_gamma_correction3(sample, input.color.rgb, gamma_params.subpixel_enhanced_contrast, gamma_params.gamma_ratios);
|
||||
|
||||
// Alpha clip after using the derivatives.
|
||||
if (any(input.clip_distances < vec4<f32>(0.0))) {
|
||||
return SubpixelSpriteFragmentOutput(vec4<f32>(0.0), vec4<f32>(0.0));
|
||||
}
|
||||
|
||||
var out = SubpixelSpriteFragmentOutput();
|
||||
out.foreground = vec4<f32>(input.color.rgb, 1.0);
|
||||
out.alpha = vec4<f32>(input.color.a * alpha_corrected, 1.0);
|
||||
return out;
|
||||
}
|
||||
481
crates/gpui_wgpu/src/wgpu_atlas.rs
Normal file
481
crates/gpui_wgpu/src/wgpu_atlas.rs
Normal file
@@ -0,0 +1,481 @@
|
||||
use anyhow::{Context as _, Result};
|
||||
use collections::FxHashMap;
|
||||
use etagere::{BucketedAtlasAllocator, size2};
|
||||
use gpui::{
|
||||
AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTextureList, AtlasTile, Bounds, DevicePixels,
|
||||
PlatformAtlas, Point, Size,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use std::{borrow::Cow, ops, sync::Arc};
|
||||
|
||||
use crate::WgpuContext;
|
||||
|
||||
fn device_size_to_etagere(size: Size<DevicePixels>) -> etagere::Size {
|
||||
size2(size.width.0, size.height.0)
|
||||
}
|
||||
|
||||
fn etagere_point_to_device(point: etagere::Point) -> Point<DevicePixels> {
|
||||
Point {
|
||||
x: DevicePixels(point.x),
|
||||
y: DevicePixels(point.y),
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WgpuAtlas(Mutex<WgpuAtlasState>);
|
||||
|
||||
struct PendingUpload {
|
||||
id: AtlasTextureId,
|
||||
bounds: Bounds<DevicePixels>,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
struct WgpuAtlasState {
|
||||
device: Arc<wgpu::Device>,
|
||||
queue: Arc<wgpu::Queue>,
|
||||
max_texture_size: u32,
|
||||
color_texture_format: wgpu::TextureFormat,
|
||||
storage: WgpuAtlasStorage,
|
||||
tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
|
||||
pending_uploads: Vec<PendingUpload>,
|
||||
}
|
||||
|
||||
pub struct WgpuTextureInfo {
|
||||
pub view: wgpu::TextureView,
|
||||
}
|
||||
|
||||
impl WgpuAtlas {
|
||||
pub fn new(
|
||||
device: Arc<wgpu::Device>,
|
||||
queue: Arc<wgpu::Queue>,
|
||||
color_texture_format: wgpu::TextureFormat,
|
||||
) -> Self {
|
||||
let max_texture_size = device.limits().max_texture_dimension_2d;
|
||||
WgpuAtlas(Mutex::new(WgpuAtlasState {
|
||||
device,
|
||||
queue,
|
||||
max_texture_size,
|
||||
color_texture_format,
|
||||
storage: WgpuAtlasStorage::default(),
|
||||
tiles_by_key: Default::default(),
|
||||
pending_uploads: Vec::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn from_context(context: &WgpuContext) -> Self {
|
||||
Self::new(
|
||||
context.device.clone(),
|
||||
context.queue.clone(),
|
||||
context.color_texture_format(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn before_frame(&self) {
|
||||
let mut lock = self.0.lock();
|
||||
lock.flush_uploads();
|
||||
}
|
||||
|
||||
pub fn get_texture_info(&self, id: AtlasTextureId) -> WgpuTextureInfo {
|
||||
let lock = self.0.lock();
|
||||
let texture = &lock.storage[id];
|
||||
WgpuTextureInfo {
|
||||
view: texture.view.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears all cached textures and tiles, forcing them to be recreated.
|
||||
/// Use this for incremental recovery when the device is still valid.
|
||||
pub fn clear(&self) {
|
||||
let mut lock = self.0.lock();
|
||||
lock.storage = WgpuAtlasStorage::default();
|
||||
lock.tiles_by_key.clear();
|
||||
lock.pending_uploads.clear();
|
||||
}
|
||||
|
||||
/// Handles device lost by clearing all textures and cached tiles.
|
||||
/// The atlas will lazily recreate textures as needed on subsequent frames.
|
||||
pub fn handle_device_lost(&self, context: &WgpuContext) {
|
||||
let mut lock = self.0.lock();
|
||||
lock.device = context.device.clone();
|
||||
lock.queue = context.queue.clone();
|
||||
lock.color_texture_format = context.color_texture_format();
|
||||
lock.storage = WgpuAtlasStorage::default();
|
||||
lock.tiles_by_key.clear();
|
||||
lock.pending_uploads.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformAtlas for WgpuAtlas {
|
||||
fn get_or_insert_with<'a>(
|
||||
&self,
|
||||
key: &AtlasKey,
|
||||
build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
|
||||
) -> Result<Option<AtlasTile>> {
|
||||
let mut lock = self.0.lock();
|
||||
if let Some(tile) = lock.tiles_by_key.get(key) {
|
||||
Ok(Some(*tile))
|
||||
} else {
|
||||
profiling::scope!("new tile");
|
||||
let Some((size, bytes)) = build()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let tile = lock
|
||||
.allocate(size, key.texture_kind())
|
||||
.context("failed to allocate")?;
|
||||
lock.upload_texture(tile.texture_id, tile.bounds, &bytes);
|
||||
lock.tiles_by_key.insert(key.clone(), tile);
|
||||
Ok(Some(tile))
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&self, key: &AtlasKey) {
|
||||
let mut lock = self.0.lock();
|
||||
|
||||
let Some(id) = lock.tiles_by_key.remove(key).map(|tile| tile.texture_id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(texture_slot) = lock.storage[id.kind].textures.get_mut(id.index as usize) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(mut texture) = texture_slot.take() {
|
||||
texture.decrement_ref_count();
|
||||
if texture.is_unreferenced() {
|
||||
lock.pending_uploads
|
||||
.retain(|upload| upload.id != texture.id);
|
||||
lock.storage[id.kind]
|
||||
.free_list
|
||||
.push(texture.id.index as usize);
|
||||
} else {
|
||||
*texture_slot = Some(texture);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WgpuAtlasState {
|
||||
fn allocate(
|
||||
&mut self,
|
||||
size: Size<DevicePixels>,
|
||||
texture_kind: AtlasTextureKind,
|
||||
) -> Option<AtlasTile> {
|
||||
{
|
||||
let textures = &mut self.storage[texture_kind];
|
||||
|
||||
if let Some(tile) = textures
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find_map(|texture| texture.allocate(size))
|
||||
{
|
||||
return Some(tile);
|
||||
}
|
||||
}
|
||||
|
||||
let texture = self.push_texture(size, texture_kind);
|
||||
texture.allocate(size)
|
||||
}
|
||||
|
||||
fn push_texture(
|
||||
&mut self,
|
||||
min_size: Size<DevicePixels>,
|
||||
kind: AtlasTextureKind,
|
||||
) -> &mut WgpuAtlasTexture {
|
||||
const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
|
||||
width: DevicePixels(1024),
|
||||
height: DevicePixels(1024),
|
||||
};
|
||||
let max_texture_size = self.max_texture_size as i32;
|
||||
let max_atlas_size = Size {
|
||||
width: DevicePixels(max_texture_size),
|
||||
height: DevicePixels(max_texture_size),
|
||||
};
|
||||
|
||||
let size = min_size.min(&max_atlas_size).max(&DEFAULT_ATLAS_SIZE);
|
||||
let format = match kind {
|
||||
AtlasTextureKind::Monochrome => wgpu::TextureFormat::R8Unorm,
|
||||
AtlasTextureKind::Subpixel | AtlasTextureKind::Polychrome => self.color_texture_format,
|
||||
};
|
||||
|
||||
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("atlas"),
|
||||
size: wgpu::Extent3d {
|
||||
width: size.width.0 as u32,
|
||||
height: size.height.0 as u32,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let texture_list = &mut self.storage[kind];
|
||||
let index = texture_list.free_list.pop();
|
||||
|
||||
let atlas_texture = WgpuAtlasTexture {
|
||||
id: AtlasTextureId {
|
||||
index: index.unwrap_or(texture_list.textures.len()) as u32,
|
||||
kind,
|
||||
},
|
||||
allocator: BucketedAtlasAllocator::new(device_size_to_etagere(size)),
|
||||
format,
|
||||
texture,
|
||||
view,
|
||||
live_atlas_keys: 0,
|
||||
};
|
||||
|
||||
if let Some(ix) = index {
|
||||
texture_list.textures[ix] = Some(atlas_texture);
|
||||
texture_list
|
||||
.textures
|
||||
.get_mut(ix)
|
||||
.and_then(|t| t.as_mut())
|
||||
.expect("texture must exist")
|
||||
} else {
|
||||
texture_list.textures.push(Some(atlas_texture));
|
||||
texture_list
|
||||
.textures
|
||||
.last_mut()
|
||||
.and_then(|t| t.as_mut())
|
||||
.expect("texture must exist")
|
||||
}
|
||||
}
|
||||
|
||||
fn upload_texture(&mut self, id: AtlasTextureId, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
|
||||
let data = self
|
||||
.storage
|
||||
.get(id)
|
||||
.map(|texture| swizzle_upload_data(bytes, texture.format))
|
||||
.unwrap_or_else(|| bytes.to_vec());
|
||||
|
||||
self.pending_uploads
|
||||
.push(PendingUpload { id, bounds, data });
|
||||
}
|
||||
|
||||
fn flush_uploads(&mut self) {
|
||||
for upload in self.pending_uploads.drain(..) {
|
||||
let Some(texture) = self.storage.get(upload.id) else {
|
||||
continue;
|
||||
};
|
||||
let bytes_per_pixel = texture.bytes_per_pixel();
|
||||
|
||||
self.queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture.texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d {
|
||||
x: upload.bounds.origin.x.0 as u32,
|
||||
y: upload.bounds.origin.y.0 as u32,
|
||||
z: 0,
|
||||
},
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
&upload.data,
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(upload.bounds.size.width.0 as u32 * bytes_per_pixel as u32),
|
||||
rows_per_image: None,
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width: upload.bounds.size.width.0 as u32,
|
||||
height: upload.bounds.size.height.0 as u32,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct WgpuAtlasStorage {
|
||||
monochrome_textures: AtlasTextureList<WgpuAtlasTexture>,
|
||||
subpixel_textures: AtlasTextureList<WgpuAtlasTexture>,
|
||||
polychrome_textures: AtlasTextureList<WgpuAtlasTexture>,
|
||||
}
|
||||
|
||||
impl ops::Index<AtlasTextureKind> for WgpuAtlasStorage {
|
||||
type Output = AtlasTextureList<WgpuAtlasTexture>;
|
||||
fn index(&self, kind: AtlasTextureKind) -> &Self::Output {
|
||||
match kind {
|
||||
AtlasTextureKind::Monochrome => &self.monochrome_textures,
|
||||
AtlasTextureKind::Subpixel => &self.subpixel_textures,
|
||||
AtlasTextureKind::Polychrome => &self.polychrome_textures,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::IndexMut<AtlasTextureKind> for WgpuAtlasStorage {
|
||||
fn index_mut(&mut self, kind: AtlasTextureKind) -> &mut Self::Output {
|
||||
match kind {
|
||||
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
|
||||
AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
|
||||
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WgpuAtlasStorage {
|
||||
fn get(&self, id: AtlasTextureId) -> Option<&WgpuAtlasTexture> {
|
||||
self[id.kind]
|
||||
.textures
|
||||
.get(id.index as usize)
|
||||
.and_then(|t| t.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Index<AtlasTextureId> for WgpuAtlasStorage {
|
||||
type Output = WgpuAtlasTexture;
|
||||
fn index(&self, id: AtlasTextureId) -> &Self::Output {
|
||||
let textures = match id.kind {
|
||||
AtlasTextureKind::Monochrome => &self.monochrome_textures,
|
||||
AtlasTextureKind::Subpixel => &self.subpixel_textures,
|
||||
AtlasTextureKind::Polychrome => &self.polychrome_textures,
|
||||
};
|
||||
textures[id.index as usize]
|
||||
.as_ref()
|
||||
.expect("texture must exist")
|
||||
}
|
||||
}
|
||||
|
||||
struct WgpuAtlasTexture {
|
||||
id: AtlasTextureId,
|
||||
allocator: BucketedAtlasAllocator,
|
||||
texture: wgpu::Texture,
|
||||
view: wgpu::TextureView,
|
||||
format: wgpu::TextureFormat,
|
||||
live_atlas_keys: u32,
|
||||
}
|
||||
|
||||
impl WgpuAtlasTexture {
|
||||
fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
|
||||
let allocation = self.allocator.allocate(device_size_to_etagere(size))?;
|
||||
let tile = AtlasTile {
|
||||
texture_id: self.id,
|
||||
tile_id: allocation.id.into(),
|
||||
padding: 0,
|
||||
bounds: Bounds {
|
||||
origin: etagere_point_to_device(allocation.rectangle.min),
|
||||
size,
|
||||
},
|
||||
};
|
||||
self.live_atlas_keys += 1;
|
||||
Some(tile)
|
||||
}
|
||||
|
||||
fn bytes_per_pixel(&self) -> u8 {
|
||||
match self.format {
|
||||
wgpu::TextureFormat::R8Unorm => 1,
|
||||
wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm => 4,
|
||||
_ => 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn decrement_ref_count(&mut self) {
|
||||
self.live_atlas_keys -= 1;
|
||||
}
|
||||
|
||||
fn is_unreferenced(&self) -> bool {
|
||||
self.live_atlas_keys == 0
|
||||
}
|
||||
}
|
||||
|
||||
fn swizzle_upload_data(bytes: &[u8], format: wgpu::TextureFormat) -> Vec<u8> {
|
||||
match format {
|
||||
wgpu::TextureFormat::Rgba8Unorm => {
|
||||
let mut data = bytes.to_vec();
|
||||
for pixel in data.chunks_exact_mut(4) {
|
||||
pixel.swap(0, 2);
|
||||
}
|
||||
data
|
||||
}
|
||||
_ => bytes.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_family = "wasm")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpui::block_on;
|
||||
use gpui::{ImageId, RenderImageParams};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn test_device_and_queue() -> anyhow::Result<(Arc<wgpu::Device>, Arc<wgpu::Queue>)> {
|
||||
block_on(async {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::all(),
|
||||
flags: wgpu::InstanceFlags::default(),
|
||||
backend_options: wgpu::BackendOptions::default(),
|
||||
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
|
||||
display: None,
|
||||
});
|
||||
let adapter = instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::LowPower,
|
||||
compatible_surface: None,
|
||||
force_fallback_adapter: false,
|
||||
})
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("failed to request adapter: {error}"))?;
|
||||
let (device, queue) = adapter
|
||||
.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("wgpu_atlas_test_device"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
required_limits: wgpu::Limits::downlevel_defaults()
|
||||
.using_resolution(adapter.limits())
|
||||
.using_alignment(adapter.limits()),
|
||||
memory_hints: wgpu::MemoryHints::MemoryUsage,
|
||||
trace: wgpu::Trace::Off,
|
||||
experimental_features: wgpu::ExperimentalFeatures::disabled(),
|
||||
})
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("failed to request device: {error}"))?;
|
||||
Ok((Arc::new(device), Arc::new(queue)))
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn before_frame_skips_uploads_for_removed_texture() -> anyhow::Result<()> {
|
||||
let (device, queue) = test_device_and_queue()?;
|
||||
|
||||
let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
|
||||
let key = AtlasKey::Image(RenderImageParams {
|
||||
image_id: ImageId(1),
|
||||
frame_index: 0,
|
||||
});
|
||||
let size = Size {
|
||||
width: DevicePixels(1),
|
||||
height: DevicePixels(1),
|
||||
};
|
||||
let mut build = || Ok(Some((size, Cow::Owned(vec![0, 0, 0, 255]))));
|
||||
|
||||
// Regression test: before the fix, this panicked in flush_uploads
|
||||
atlas
|
||||
.get_or_insert_with(&key, &mut build)?
|
||||
.expect("tile should be created");
|
||||
atlas.remove(&key);
|
||||
atlas.before_frame();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swizzle_upload_data_preserves_bgra_uploads() {
|
||||
let input = vec![0x10, 0x20, 0x30, 0x40];
|
||||
assert_eq!(
|
||||
swizzle_upload_data(&input, wgpu::TextureFormat::Bgra8Unorm),
|
||||
input
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swizzle_upload_data_converts_bgra_to_rgba() {
|
||||
let input = vec![0x10, 0x20, 0x30, 0x40, 0xAA, 0xBB, 0xCC, 0xDD];
|
||||
assert_eq!(
|
||||
swizzle_upload_data(&input, wgpu::TextureFormat::Rgba8Unorm),
|
||||
vec![0x30, 0x20, 0x10, 0x40, 0xCC, 0xBB, 0xAA, 0xDD]
|
||||
);
|
||||
}
|
||||
}
|
||||
487
crates/gpui_wgpu/src/wgpu_context.rs
Normal file
487
crates/gpui_wgpu/src/wgpu_context.rs
Normal file
@@ -0,0 +1,487 @@
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use anyhow::Context as _;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use gpui_util::ResultExt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use wgpu::TextureFormat;
|
||||
|
||||
pub struct WgpuContext {
|
||||
pub instance: wgpu::Instance,
|
||||
pub adapter: wgpu::Adapter,
|
||||
pub device: Arc<wgpu::Device>,
|
||||
pub queue: Arc<wgpu::Queue>,
|
||||
dual_source_blending: bool,
|
||||
color_texture_format: wgpu::TextureFormat,
|
||||
device_lost: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CompositorGpuHint {
|
||||
pub vendor_id: u32,
|
||||
pub device_id: u32,
|
||||
}
|
||||
|
||||
impl WgpuContext {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub fn new(
|
||||
instance: wgpu::Instance,
|
||||
surface: &wgpu::Surface<'_>,
|
||||
compositor_gpu: Option<CompositorGpuHint>,
|
||||
) -> anyhow::Result<Self> {
|
||||
Self::new_with_options(instance, surface, compositor_gpu, false)
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub fn new_rejecting_software(
|
||||
instance: wgpu::Instance,
|
||||
surface: &wgpu::Surface<'_>,
|
||||
compositor_gpu: Option<CompositorGpuHint>,
|
||||
) -> anyhow::Result<Self> {
|
||||
Self::new_with_options(instance, surface, compositor_gpu, true)
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn new_with_options(
|
||||
instance: wgpu::Instance,
|
||||
surface: &wgpu::Surface<'_>,
|
||||
compositor_gpu: Option<CompositorGpuHint>,
|
||||
reject_software: bool,
|
||||
) -> anyhow::Result<Self> {
|
||||
let device_id_filter = match std::env::var("ZED_DEVICE_ID") {
|
||||
Ok(val) => parse_pci_id(&val)
|
||||
.context("Failed to parse device ID from `ZED_DEVICE_ID` environment variable")
|
||||
.log_err(),
|
||||
Err(std::env::VarError::NotPresent) => None,
|
||||
err => {
|
||||
err.context("Failed to read value of `ZED_DEVICE_ID` environment variable")
|
||||
.log_err();
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// Select an adapter by actually testing surface configuration with the real device.
|
||||
// This is the only reliable way to determine compatibility on hybrid GPU systems.
|
||||
let (adapter, device, queue, dual_source_blending, color_texture_format) =
|
||||
gpui::block_on(Self::select_adapter_and_device(
|
||||
&instance,
|
||||
device_id_filter,
|
||||
surface,
|
||||
compositor_gpu.as_ref(),
|
||||
reject_software,
|
||||
))?;
|
||||
|
||||
let device_lost = Arc::new(AtomicBool::new(false));
|
||||
device.set_device_lost_callback({
|
||||
let device_lost = Arc::clone(&device_lost);
|
||||
move |reason, message| {
|
||||
log::error!("wgpu device lost: reason={reason:?}, message={message}");
|
||||
if reason != wgpu::DeviceLostReason::Destroyed {
|
||||
device_lost.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
log::info!(
|
||||
"Selected GPU adapter: {:?} ({:?})",
|
||||
adapter.get_info().name,
|
||||
adapter.get_info().backend
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
instance,
|
||||
adapter,
|
||||
device: Arc::new(device),
|
||||
queue: Arc::new(queue),
|
||||
dual_source_blending,
|
||||
color_texture_format,
|
||||
device_lost,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub async fn new_web() -> anyhow::Result<Self> {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL,
|
||||
flags: wgpu::InstanceFlags::default(),
|
||||
backend_options: wgpu::BackendOptions::default(),
|
||||
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
|
||||
display: None,
|
||||
});
|
||||
|
||||
let adapter = instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
compatible_surface: None,
|
||||
force_fallback_adapter: false,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to request GPU adapter: {e}"))?;
|
||||
|
||||
log::info!(
|
||||
"Selected GPU adapter: {:?} ({:?})",
|
||||
adapter.get_info().name,
|
||||
adapter.get_info().backend
|
||||
);
|
||||
|
||||
let device_lost = Arc::new(AtomicBool::new(false));
|
||||
let (device, queue, dual_source_blending, color_texture_format) =
|
||||
Self::create_device(&adapter).await?;
|
||||
|
||||
Ok(Self {
|
||||
instance,
|
||||
adapter,
|
||||
device: Arc::new(device),
|
||||
queue: Arc::new(queue),
|
||||
dual_source_blending,
|
||||
color_texture_format,
|
||||
device_lost,
|
||||
})
|
||||
}
|
||||
|
||||
async fn create_device(
|
||||
adapter: &wgpu::Adapter,
|
||||
) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> {
|
||||
let dual_source_blending = adapter
|
||||
.features()
|
||||
.contains(wgpu::Features::DUAL_SOURCE_BLENDING);
|
||||
|
||||
let mut required_features = wgpu::Features::empty();
|
||||
if dual_source_blending {
|
||||
required_features |= wgpu::Features::DUAL_SOURCE_BLENDING;
|
||||
} else {
|
||||
log::warn!(
|
||||
"Dual-source blending not available on this GPU. \
|
||||
Subpixel text antialiasing will be disabled."
|
||||
);
|
||||
}
|
||||
|
||||
let color_atlas_texture_format = Self::select_color_texture_format(adapter)?;
|
||||
|
||||
let (device, queue) = adapter
|
||||
.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("gpui_device"),
|
||||
required_features,
|
||||
required_limits: wgpu::Limits::downlevel_defaults()
|
||||
.using_resolution(adapter.limits())
|
||||
.using_alignment(adapter.limits()),
|
||||
memory_hints: wgpu::MemoryHints::MemoryUsage,
|
||||
trace: wgpu::Trace::Off,
|
||||
experimental_features: wgpu::ExperimentalFeatures::disabled(),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to create wgpu device: {e}"))?;
|
||||
|
||||
Ok((
|
||||
device,
|
||||
queue,
|
||||
dual_source_blending,
|
||||
color_atlas_texture_format,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub fn instance(display: Box<dyn wgpu::wgt::WgpuHasDisplayHandle>) -> wgpu::Instance {
|
||||
wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::VULKAN | wgpu::Backends::GL,
|
||||
flags: wgpu::InstanceFlags::default(),
|
||||
backend_options: wgpu::BackendOptions::default(),
|
||||
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
|
||||
display: Some(display),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn check_compatible_with_surface(&self, surface: &wgpu::Surface<'_>) -> anyhow::Result<()> {
|
||||
let caps = surface.get_capabilities(&self.adapter);
|
||||
if caps.formats.is_empty() {
|
||||
let info = self.adapter.get_info();
|
||||
anyhow::bail!(
|
||||
"Adapter {:?} (backend={:?}, device={:#06x}) is not compatible with the \
|
||||
display surface for this window.",
|
||||
info.name,
|
||||
info.backend,
|
||||
info.device,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Select an adapter and create a device, testing that the surface can actually be configured.
|
||||
/// This is the only reliable way to determine compatibility on hybrid GPU systems, where
|
||||
/// adapters may report surface compatibility via get_capabilities() but fail when actually
|
||||
/// configuring (e.g., NVIDIA reporting Vulkan Wayland support but failing because the
|
||||
/// Wayland compositor runs on the Intel GPU).
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
async fn select_adapter_and_device(
|
||||
instance: &wgpu::Instance,
|
||||
device_id_filter: Option<u32>,
|
||||
surface: &wgpu::Surface<'_>,
|
||||
compositor_gpu: Option<&CompositorGpuHint>,
|
||||
reject_software: bool,
|
||||
) -> anyhow::Result<(
|
||||
wgpu::Adapter,
|
||||
wgpu::Device,
|
||||
wgpu::Queue,
|
||||
bool,
|
||||
TextureFormat,
|
||||
)> {
|
||||
let mut adapters: Vec<_> = instance.enumerate_adapters(wgpu::Backends::all()).await;
|
||||
|
||||
if adapters.is_empty() {
|
||||
anyhow::bail!("No GPU adapters found");
|
||||
}
|
||||
|
||||
if let Some(device_id) = device_id_filter {
|
||||
log::info!("ZED_DEVICE_ID filter: {:#06x}", device_id);
|
||||
}
|
||||
|
||||
// Sort adapters into a single priority order. Tiers (from highest to lowest):
|
||||
//
|
||||
// 1. ZED_DEVICE_ID match — explicit user override
|
||||
// 2. Compositor GPU match — the GPU the display server is rendering on
|
||||
// 3. Device type (Discrete > Integrated > Other > Virtual > Cpu).
|
||||
// "Other" ranks above "Virtual" because OpenGL seems to count as "Other".
|
||||
// 4. Backend — prefer Vulkan/Metal/Dx12 over GL/etc.
|
||||
adapters.sort_by_key(|adapter| {
|
||||
let info = adapter.get_info();
|
||||
|
||||
// Backends like OpenGL report device=0 for all adapters, so
|
||||
// device-based matching is only meaningful when non-zero.
|
||||
let device_known = info.device != 0;
|
||||
|
||||
let user_override: u8 = match device_id_filter {
|
||||
Some(id) if device_known && info.device == id => 0,
|
||||
_ => 1,
|
||||
};
|
||||
|
||||
let compositor_match: u8 = match compositor_gpu {
|
||||
Some(hint)
|
||||
if device_known
|
||||
&& info.vendor == hint.vendor_id
|
||||
&& info.device == hint.device_id =>
|
||||
{
|
||||
0
|
||||
}
|
||||
_ => 1,
|
||||
};
|
||||
|
||||
let type_priority: u8 = if info.device_type == wgpu::DeviceType::Cpu {
|
||||
4
|
||||
} else {
|
||||
match info.device_type {
|
||||
wgpu::DeviceType::DiscreteGpu => 0,
|
||||
wgpu::DeviceType::IntegratedGpu => 1,
|
||||
wgpu::DeviceType::Other => 2,
|
||||
wgpu::DeviceType::VirtualGpu => 3,
|
||||
wgpu::DeviceType::Cpu => 4,
|
||||
}
|
||||
};
|
||||
|
||||
let backend_priority: u8 = match info.backend {
|
||||
wgpu::Backend::Vulkan | wgpu::Backend::Metal | wgpu::Backend::Dx12 => 0,
|
||||
_ => 1,
|
||||
};
|
||||
|
||||
(
|
||||
user_override,
|
||||
compositor_match,
|
||||
type_priority,
|
||||
backend_priority,
|
||||
)
|
||||
});
|
||||
|
||||
// Log all available adapters (in sorted order)
|
||||
log::info!("Found {} GPU adapter(s):", adapters.len());
|
||||
for adapter in &adapters {
|
||||
let info = adapter.get_info();
|
||||
log::info!(
|
||||
" - {} (vendor={:#06x}, device={:#06x}, backend={:?}, type={:?})",
|
||||
info.name,
|
||||
info.vendor,
|
||||
info.device,
|
||||
info.backend,
|
||||
info.device_type,
|
||||
);
|
||||
}
|
||||
|
||||
// Test each adapter by creating a device and configuring the surface
|
||||
for adapter in adapters {
|
||||
let info = adapter.get_info();
|
||||
|
||||
if reject_software && info.device_type == wgpu::DeviceType::Cpu {
|
||||
log::info!(
|
||||
"Skipping software renderer: {} ({:?})",
|
||||
info.name,
|
||||
info.backend
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
log::info!("Testing adapter: {} ({:?})...", info.name, info.backend);
|
||||
|
||||
match Self::try_adapter_with_surface(&adapter, surface).await {
|
||||
Ok((device, queue, dual_source_blending, color_atlas_texture_format)) => {
|
||||
log::info!(
|
||||
"Selected GPU (passed configuration test): {} ({:?})",
|
||||
info.name,
|
||||
info.backend
|
||||
);
|
||||
return Ok((
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
dual_source_blending,
|
||||
color_atlas_texture_format,
|
||||
));
|
||||
}
|
||||
Err(e) => {
|
||||
log::info!(
|
||||
" Adapter {} ({:?}) failed: {}, trying next...",
|
||||
info.name,
|
||||
info.backend,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
anyhow::bail!("No GPU adapter found that can configure the display surface")
|
||||
}
|
||||
|
||||
/// Try to use an adapter with a surface by creating a device and testing configuration.
|
||||
/// Returns the device and queue if successful, allowing them to be reused.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
async fn try_adapter_with_surface(
|
||||
adapter: &wgpu::Adapter,
|
||||
surface: &wgpu::Surface<'_>,
|
||||
) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> {
|
||||
let caps = surface.get_capabilities(adapter);
|
||||
if caps.formats.is_empty() {
|
||||
anyhow::bail!("no compatible surface formats");
|
||||
}
|
||||
if caps.alpha_modes.is_empty() {
|
||||
anyhow::bail!("no compatible alpha modes");
|
||||
}
|
||||
|
||||
let (device, queue, dual_source_blending, color_atlas_texture_format) =
|
||||
Self::create_device(adapter).await?;
|
||||
let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
|
||||
let test_config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format: caps.formats[0],
|
||||
width: 64,
|
||||
height: 64,
|
||||
present_mode: wgpu::PresentMode::Fifo,
|
||||
desired_maximum_frame_latency: 2,
|
||||
alpha_mode: caps.alpha_modes[0],
|
||||
view_formats: vec![],
|
||||
};
|
||||
|
||||
surface.configure(&device, &test_config);
|
||||
|
||||
let error = error_scope.pop().await;
|
||||
if let Some(e) = error {
|
||||
anyhow::bail!("surface configuration failed: {e}");
|
||||
}
|
||||
|
||||
Ok((
|
||||
device,
|
||||
queue,
|
||||
dual_source_blending,
|
||||
color_atlas_texture_format,
|
||||
))
|
||||
}
|
||||
|
||||
fn select_color_texture_format(adapter: &wgpu::Adapter) -> anyhow::Result<wgpu::TextureFormat> {
|
||||
let required_usages = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
|
||||
let bgra_features = adapter.get_texture_format_features(wgpu::TextureFormat::Bgra8Unorm);
|
||||
if bgra_features.allowed_usages.contains(required_usages) {
|
||||
return Ok(wgpu::TextureFormat::Bgra8Unorm);
|
||||
}
|
||||
|
||||
let rgba_features = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba8Unorm);
|
||||
if rgba_features.allowed_usages.contains(required_usages) {
|
||||
let info = adapter.get_info();
|
||||
log::warn!(
|
||||
"Adapter {} ({:?}) does not support Bgra8Unorm atlas textures with usages {:?}; \
|
||||
falling back to Rgba8Unorm atlas textures.",
|
||||
info.name,
|
||||
info.backend,
|
||||
required_usages,
|
||||
);
|
||||
return Ok(wgpu::TextureFormat::Rgba8Unorm);
|
||||
}
|
||||
|
||||
let info = adapter.get_info();
|
||||
Err(anyhow::anyhow!(
|
||||
"Adapter {} ({:?}, device={:#06x}) does not support a usable color atlas texture \
|
||||
format with usages {:?}. Bgra8Unorm allowed usages: {:?}; \
|
||||
Rgba8Unorm allowed usages: {:?}.",
|
||||
info.name,
|
||||
info.backend,
|
||||
info.device,
|
||||
required_usages,
|
||||
bgra_features.allowed_usages,
|
||||
rgba_features.allowed_usages,
|
||||
))
|
||||
}
|
||||
pub fn supports_dual_source_blending(&self) -> bool {
|
||||
self.dual_source_blending
|
||||
}
|
||||
|
||||
pub fn color_texture_format(&self) -> wgpu::TextureFormat {
|
||||
self.color_texture_format
|
||||
}
|
||||
|
||||
/// Returns true if the GPU device was lost (e.g., due to driver crash, suspend/resume).
|
||||
/// When this returns true, the context should be recreated.
|
||||
pub fn device_lost(&self) -> bool {
|
||||
self.device_lost.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Returns a clone of the device_lost flag for sharing with renderers.
|
||||
pub(crate) fn device_lost_flag(&self) -> Arc<AtomicBool> {
|
||||
Arc::clone(&self.device_lost)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn parse_pci_id(id: &str) -> anyhow::Result<u32> {
|
||||
let mut id = id.trim();
|
||||
|
||||
if id.starts_with("0x") || id.starts_with("0X") {
|
||||
id = &id[2..];
|
||||
}
|
||||
let is_hex_string = id.chars().all(|c| c.is_ascii_hexdigit());
|
||||
let is_4_chars = id.len() == 4;
|
||||
anyhow::ensure!(
|
||||
is_4_chars && is_hex_string,
|
||||
"Expected a 4 digit PCI ID in hexadecimal format"
|
||||
);
|
||||
|
||||
u32::from_str_radix(id, 16).context("parsing PCI ID as hex")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_pci_id;
|
||||
|
||||
#[test]
|
||||
fn test_parse_device_id() {
|
||||
assert!(parse_pci_id("0xABCD").is_ok());
|
||||
assert!(parse_pci_id("ABCD").is_ok());
|
||||
assert!(parse_pci_id("abcd").is_ok());
|
||||
assert!(parse_pci_id("1234").is_ok());
|
||||
assert!(parse_pci_id("123").is_err());
|
||||
assert_eq!(
|
||||
parse_pci_id(&format!("{:x}", 0x1234)).unwrap(),
|
||||
parse_pci_id(&format!("{:X}", 0x1234)).unwrap(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
parse_pci_id(&format!("{:#x}", 0x1234)).unwrap(),
|
||||
parse_pci_id(&format!("{:#X}", 0x1234)).unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
1909
crates/gpui_wgpu/src/wgpu_renderer.rs
Normal file
1909
crates/gpui_wgpu/src/wgpu_renderer.rs
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user