Skip to content

Commit

Permalink
remove the system font implementation for now, in a single commit for…
Browse files Browse the repository at this point in the history
… easier retrieval later
  • Loading branch information
TotalKrill committed Nov 12, 2023
1 parent 8cd333d commit be71200
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 347 deletions.
4 changes: 2 additions & 2 deletions crates/bevy_text/src/font_loader.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::Font;
use bevy_asset::{io::Reader, AssetLoader, AsyncReadExt, LoadContext, LoadedAsset};
use bevy_asset::{io::Reader, AssetLoader, AsyncReadExt, LoadContext};
use thiserror::Error;

#[derive(Default)]
Expand All @@ -22,7 +22,7 @@ impl AssetLoader for FontLoader {
&'a self,
reader: &'a mut Reader,
_settings: &'a (),
load_context: &'a mut LoadContext,
_load_context: &'a mut LoadContext,
) -> bevy_utils::BoxedFuture<'a, Result<Font, Self::Error>> {
Box::pin(async move {
let mut bytes = Vec::new();
Expand Down
16 changes: 0 additions & 16 deletions crates/bevy_text/src/glyph_brush.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,22 +168,6 @@ pub struct PositionedGlyph {
pub byte_index: usize,
}

#[cfg(feature = "subpixel_glyph_atlas")]
struct GlyphPlacementAdjuster;

#[cfg(feature = "subpixel_glyph_atlas")]
impl GlyphPlacementAdjuster {
#[inline(always)]
pub fn new(_: &mut Glyph) -> Self {
Self
}

#[inline(always)]
pub fn position(&self, p: Vec2) -> Vec2 {
p
}
}

#[cfg(not(feature = "subpixel_glyph_atlas"))]
struct GlyphPlacementAdjuster(f32);

Expand Down
117 changes: 40 additions & 77 deletions crates/bevy_text/src/pipeline.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::{Arc, Mutex};

use bevy_asset::{AssetId, Assets, Handle};
use bevy_asset::{AssetId, Assets};
use bevy_ecs::{component::Component, reflect::ReflectComponent, system::Resource};
use bevy_math::Vec2;
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
Expand All @@ -14,8 +14,8 @@ use bevy_utils::{
use cosmic_text::{Attrs, AttrsList, Buffer, BufferLine, Family, Metrics, Wrap};

use crate::{
error::TextError, BreakLineOn, Font, FontAtlasSet, FontAtlasSets, FontAtlasWarning, FontRef,
PositionedGlyph, TextAlignment, TextSection, TextSettings, YAxisOrientation,
error::TextError, BreakLineOn, Font, FontAtlasSets, FontAtlasWarning, PositionedGlyph,
TextAlignment, TextSection, TextSettings, YAxisOrientation,
};

// TODO: cache buffers / store buffers on the entity
Expand Down Expand Up @@ -72,8 +72,6 @@ impl Default for SwashCache {
pub struct TextPipeline {
/// Identifies a font [`ID`](cosmic_text::fontdb::ID) by its [`Font`] [`Asset`](bevy_asset::Asset) [`HandleId`].
map_handle_to_font_id: HashMap<AssetId<Font>, cosmic_text::fontdb::ID>,
/// Identifies a [`FontAtlasSet`] by its font [`ID`](cosmic_text::fontdb::ID).
map_font_id_to_atlas: HashMap<cosmic_text::fontdb::ID, FontAtlasSet>,
/// The font system is used to retrieve fonts and their information, including glyph outlines.
///
/// See [`cosmic_text::FontSystem`] for more information.
Expand Down Expand Up @@ -281,31 +279,9 @@ impl TextPipeline {
.map(|(layout_glyph, line_w, line_y)| {
let section_index = layout_glyph.metadata;

let font_atlas_set: &mut FontAtlasSet = match sections[section_index].style.font {
FontRef::Asset(ref font_handle) => {
let handle: Handle<Font> = font_handle.clone_weak();
font_atlas_sets.sets
.entry(handle.id()).or_default()
}
FontRef::Query(ref query) => {
// get the id from the database
// TODO: error handling
// TODO: font may not yet be available, but may be available in future
let font_id = font_system.get_font_matches(cosmic_text::Attrs {
color_opt: None,
family: query.family.as_family(),
stretch: query.stretch,
style: query.style,
weight: query.weight,
metadata: 0,
})[0];
let atlas = self
.map_font_id_to_atlas
.entry(font_id)
.or_default();
atlas
}
};
let font_handle = sections[section_index].style.font.clone_weak();
let font_atlas_set = font_atlas_sets.sets
.entry(font_handle.id()).or_default();

let physical_glyph = layout_glyph.physical((0.,0.),1. );

Expand Down Expand Up @@ -504,53 +480,40 @@ fn add_span(
line_string.push_str(text);
let end = line_string.len();

let attrs = match section.style.font {
FontRef::Asset(ref font_handle) => {
let font_handle_id = font_handle.id();
let face_id = map_handle_to_font_id
.entry(font_handle_id)
.or_insert_with(|| {
let font = fonts.get(font_handle).unwrap();
let data = Arc::clone(&font.data);
font_system
.db_mut()
.load_font_source(cosmic_text::fontdb::Source::Binary(data));
// TODO: it is assumed this is the right font face
// see https://github.com/pop-os/cosmic-text/issues/125
// fontdb 0.14 returns the font ids from `load_font_source`
let face_id = font_system.db().faces().last().unwrap().id;
// TODO: below may be required if we need to offset by the baseline (TBC)
// see https://github.com/pop-os/cosmic-text/issues/123
// let font = font_system.get_font(face_id).unwrap();
// map_font_id_to_metrics
// .entry(face_id)
// .or_insert_with(|| font.as_swash().metrics(&[]));
face_id
});
let face = font_system.db().face(*face_id).unwrap();

// TODO: validate this is the correct string to extract
let family_name = &face.families[0].0;
Attrs::new()
// TODO: validate that we can use metadata
.metadata(section_index)
.family(Family::Name(family_name))
.stretch(face.stretch)
.style(face.style)
.weight(face.weight)
.color(cosmic_text::Color(section.style.color.as_linear_rgba_u32()))
}
FontRef::Query(ref query) => {
Attrs::new()
// TODO: validate that we can use metadata
.metadata(section_index)
.family(query.family.as_family())
.stretch(query.stretch)
.style(query.style)
.weight(query.weight)
.color(cosmic_text::Color(section.style.color.as_linear_rgba_u32()))
}
};
let font_handle = section.style.font.clone();
let font_handle_id = font_handle.id();
let face_id = map_handle_to_font_id
.entry(font_handle_id)
.or_insert_with(|| {
let font = fonts.get(font_handle).unwrap();
let data = Arc::clone(&font.data);
font_system
.db_mut()
.load_font_source(cosmic_text::fontdb::Source::Binary(data));
// TODO: it is assumed this is the right font face
// see https://github.com/pop-os/cosmic-text/issues/125
// fontdb 0.14 returns the font ids from `load_font_source`
let face_id = font_system.db().faces().last().unwrap().id;
// TODO: below may be required if we need to offset by the baseline (TBC)
// see https://github.com/pop-os/cosmic-text/issues/123
// let font = font_system.get_font(face_id).unwrap();
// map_font_id_to_metrics
// .entry(face_id)
// .or_insert_with(|| font.as_swash().metrics(&[]));
face_id
});
let face = font_system.db().face(*face_id).unwrap();

// TODO: validate this is the correct string to extract
let family_name = &face.families[0].0;
let attrs = Attrs::new()
// TODO: validate that we can use metadata
.metadata(section_index)
.family(Family::Name(family_name))
.stretch(face.stretch)
.style(face.style)
.weight(face.weight)
.color(cosmic_text::Color(section.style.color.as_linear_rgba_u32()));

attrs_list.add_span(start..end, attrs);
}
Expand Down
131 changes: 0 additions & 131 deletions crates/bevy_text/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,134 +220,3 @@ pub enum BreakLineOn {
/// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, is still enabled.
NoWrap,
}

/// Identifies a font to use, which is either stored as an [`Asset`](bevy_asset::Asset) or loaded directly from the user's system.
#[derive(Clone, Debug, Reflect)]
pub enum FontRef {
/// A reference to a font loaded as a bevy asset.
Asset(Handle<Font>),
/// A reference to a font queried by font family and attributes.
/// This is useful for example for fonts that are not loaded as a bevy asset,
/// such as system fonts.
// TODO: Support Reflect?
Query(#[reflect(ignore)] FontQuery),
}

impl Default for FontRef {
fn default() -> Self {
Self::Asset(Default::default())
}
}

impl From<Handle<Font>> for FontRef {
fn from(handle: Handle<Font>) -> Self {
Self::Asset(handle)
}
}

/// Queries for a font from those already loaded.
///
/// ```
/// # use bevy_text::{FontQuery, FontWeight, TextStyle};
///
/// let fira_sans_bold = FontQuery::family("FiraSans").weight(FontWeight::BOLD);
///
/// let text_style = TextStyle {
/// font: fira_sans_bold.into(),
/// ..Default::default()
/// };
/// ```
#[derive(Clone, Debug)]
pub struct FontQuery {
/// The font family. See [`cosmic_text::fontdb::Family`] for details.
pub family: FontFamily,
/// The stretch (or width) of the font face in this family, e.g. condensed.
/// See [`cosmic_text::fontdb::Stretch`] for details.
pub stretch: FontStretch,
/// The style of the font face in this family, e.g. italic.
/// See [`cosmic_text::fontdb::Style`] for details.
pub style: FontStyle,
/// The weight of the font face in this family, e.g. bold.
/// See [`cosmic_text::fontdb::Weight`] for details.
pub weight: FontWeight,
}

impl FontQuery {
pub fn sans_serif() -> Self {
Self {
family: FontFamily::SansSerif,
stretch: Default::default(),
style: Default::default(),
weight: Default::default(),
}
}

pub fn serif() -> Self {
Self {
family: FontFamily::Serif,
stretch: Default::default(),
style: Default::default(),
weight: Default::default(),
}
}

pub fn fantasy() -> Self {
Self {
family: FontFamily::Fantasy,
stretch: Default::default(),
style: Default::default(),
weight: Default::default(),
}
}

pub fn cursive() -> Self {
Self {
family: FontFamily::Cursive,
stretch: Default::default(),
style: Default::default(),
weight: Default::default(),
}
}

pub fn monospace() -> Self {
Self {
family: FontFamily::Monospace,
stretch: Default::default(),
style: Default::default(),
weight: Default::default(),
}
}

pub fn family<S: AsRef<str>>(name: S) -> Self {
Self {
family: FontFamily::Name(name.as_ref().to_string()),
stretch: Default::default(),
style: Default::default(),
weight: Default::default(),
}
}

pub fn stretch(self, stretch: FontStretch) -> Self {
Self { stretch, ..self }
}

pub fn style(self, style: FontStyle) -> Self {
Self { style, ..self }
}

pub fn weight(self, weight: FontWeight) -> Self {
Self { weight, ..self }
}
}

impl Default for FontQuery {
fn default() -> Self {
Self::sans_serif()
}
}

impl From<FontQuery> for FontRef {
fn from(query: FontQuery) -> Self {
Self::Query(query)
}
}
Loading

0 comments on commit be71200

Please sign in to comment.