cosmic-text/src/font/system/no_std.rs

83 lines
1.9 KiB
Rust
Raw Normal View History

2022-11-08 08:43:27 -07:00
// SPDX-License-Identifier: MIT OR Apache-2.0
use alloc::{
string::{String, ToString},
sync::Arc,
vec::Vec,
};
2023-03-01 02:50:10 +01:00
use crate::{Attrs, Font, FontKey};
2022-11-08 08:43:27 -07:00
/// Access system fonts
2023-01-04 20:03:03 -07:00
pub struct FontSystem {
2022-11-08 08:43:27 -07:00
locale: String,
db: fontdb::Database,
}
impl FontSystem {
pub fn new() -> Self {
let locale = "en-US".to_string();
let mut db = fontdb::Database::new();
{
db.set_monospace_family("Fira Mono");
db.set_sans_serif_family("Fira Sans");
db.set_serif_family("DejaVu Serif");
}
2023-01-04 20:03:03 -07:00
Self { locale, db }
2022-11-08 08:43:27 -07:00
}
pub fn new_with_locale_and_db(locale: &str, db: fontdb::Database) -> Self {
Self {
locale: locale.to_string(),
2023-01-04 20:03:03 -07:00
db,
}
}
2022-11-08 08:43:27 -07:00
pub fn locale(&self) -> &str {
&self.locale
}
pub fn db(&self) -> &fontdb::Database {
&self.db
}
// Clippy false positive
#[allow(clippy::needless_lifetimes)]
2023-03-01 02:50:10 +01:00
pub fn get_font<'a>(&'a self, key: FontKey) -> Option<Font<'a>> {
match Font::from_key(&self.db, key) {
Some(font) => Some(font),
2022-11-08 08:43:27 -07:00
None => {
2023-03-01 02:50:10 +01:00
let face = self.db.face(key.id)?;
2022-11-08 08:43:27 -07:00
log::warn!("failed to load font '{}'", face.post_script_name);
None
}
}
}
2023-03-01 02:50:10 +01:00
pub fn get_font_key(&self, id: fontdb::ID) -> Option<FontKey> {
Some(Font::new(self.db.face(id)?)?.key())
}
pub fn get_font_matches(&self, attrs: Attrs) -> Arc<Vec<FontKey>> {
let mut font_keys = Vec::new();
2022-11-08 08:43:27 -07:00
for face in self.db.faces() {
if !attrs.matches(face) {
continue;
}
2023-03-01 02:50:10 +01:00
let font_key = match self.get_font_key(face.id) {
Some(font_key) => font_key,
None => continue,
};
if self.get_font(font_key).is_some() {
font_keys.push(font_key);
2022-11-08 08:43:27 -07:00
}
}
2023-03-01 02:50:10 +01:00
Arc::new(font_keys)
2022-11-08 08:43:27 -07:00
}
}