move font code into main source
Initially I wanted to make the font code separate from the main wterm executable in the hope that it would be reusable. However, we do need to be able to reach in to both the font implementation and the SDL texture implementation in order to capture the glyph data into textures, so let's just embrace it all being in the same crate.
This commit is contained in:
1 parent
739d25c21b
commit
79bf022f68
9 files changed
+324
-378
No files matched your search
+3
-3
@@ -5,13 +5,13 @@ version = "0.1.0"
|
||||
|
||||
[dependencies]
|
||||
failure = "0.1.1"
|
||||
freetype = "0.3.0"
|
||||
harfbuzz-sys = "0.1.15"
|
||||
hexdump = "0.1.0"
|
||||
servo-fontconfig = "0.4.0"
|
||||
unicode-width = "0.1.4"
|
||||
vte = "0.3.2"
|
||||
|
||||
[dependencies.font]
|
||||
path = "font"
|
||||
|
||||
[dependencies.sdl2]
|
||||
features = [
|
||||
"bundled",
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
[package]
|
||||
authors = ["Wez Furlong <wez@wezfurlong.org>"]
|
||||
name = "font"
|
||||
version = "0.1.0"
|
||||
|
||||
[dependencies]
|
||||
failure = "0.1.1"
|
||||
freetype = "0.3.0"
|
||||
harfbuzz-sys = "0.1.15"
|
||||
servo-fontconfig = "0.4.0"
|
||||
@@ -1,16 +0,0 @@
|
||||
use failure::Error;
|
||||
pub mod ftwrap;
|
||||
pub mod hbwrap;
|
||||
pub mod fcwrap;
|
||||
use self::ftwrap::Library;
|
||||
|
||||
pub struct FTEngine {
|
||||
lib: Library,
|
||||
}
|
||||
|
||||
|
||||
impl ::FontEngine for FTEngine {
|
||||
fn new() -> Result<FTEngine, Error> {
|
||||
Ok(FTEngine { lib: Library::new()? })
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
#[macro_use]
|
||||
extern crate failure;
|
||||
|
||||
extern crate harfbuzz_sys;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
extern crate fontconfig; // from servo-fontconfig
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
extern crate freetype;
|
||||
|
||||
use failure::Error;
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub mod ft;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub use ft::FTEngine as Engine;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct FontDescription {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// A user provided font description that can be used
|
||||
/// to lookup a font
|
||||
impl FontDescription {
|
||||
pub fn new<S>(name: S) -> FontDescription
|
||||
where
|
||||
S: Into<String>,
|
||||
{
|
||||
FontDescription { name: name.into() }
|
||||
}
|
||||
}
|
||||
|
||||
trait FontEngine {
|
||||
fn new() -> Result<Self, Error>
|
||||
where
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn it_works() {
|
||||
assert_eq!(2 + 2, 4);
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,7 @@ impl FontSet {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn add(&mut self, pat: &Pattern) {
|
||||
unsafe {
|
||||
FcFontSetAdd(self.fonts, pat.pat);
|
||||
@@ -62,6 +63,7 @@ impl FontSet {
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[allow(dead_code)]
|
||||
pub enum MatchKind {
|
||||
Pattern = FcMatchPattern as isize,
|
||||
Font = FcMatchFont as isize,
|
||||
@@ -90,6 +92,7 @@ impl FcResultWrap {
|
||||
}
|
||||
|
||||
pub fn result<T>(&self, t: T) -> Result<T, Error> {
|
||||
#[allow(non_upper_case_globals)]
|
||||
match self.0 {
|
||||
FcResultMatch => Ok(t),
|
||||
_ => Err(self.as_err()),
|
||||
@@ -102,6 +105,7 @@ pub struct Pattern {
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
#[allow(dead_code)]
|
||||
pub fn new() -> Result<Pattern, Error> {
|
||||
unsafe {
|
||||
let p = FcPatternCreate();
|
||||
@@ -110,6 +114,7 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn add_string(&mut self, key: &str, value: &str) -> Result<(), Error> {
|
||||
let key = CString::new(key)?;
|
||||
let value = CString::new(value)?;
|
||||
@@ -124,6 +129,7 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn add_integer(&mut self, key: &str, value: i32) -> Result<(), Error> {
|
||||
let key = CString::new(key)?;
|
||||
unsafe {
|
||||
@@ -137,21 +143,24 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn family(&mut self, family: &str) -> Result<(), Error> {
|
||||
self.add_string("family", family)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn monospace(&mut self) -> Result<(), Error> {
|
||||
self.add_integer("spacing", FC_MONO)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn print(&self) {
|
||||
unsafe {
|
||||
FcPatternPrint(self.pat);
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn format(&self, fmt: &str) -> Result<String, Error> {
|
||||
let fmt = CString::new(fmt)?;
|
||||
unsafe {
|
||||
@@ -199,6 +208,7 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn find_match(&self) -> Result<Pattern, Error> {
|
||||
unsafe {
|
||||
let mut res = FcResultWrap(0);
|
||||
File renamed without changes.
@@ -44,7 +44,7 @@ impl Drop for Font {
|
||||
|
||||
impl Font {
|
||||
/// Create a harfbuzz face from a freetype font
|
||||
pub fn new(face: &::ft::ftwrap::Face) -> Font {
|
||||
pub fn new(face: &::ftwrap::Face) -> Font {
|
||||
// hb_ft_font_create_referenced always returns a
|
||||
// pointer to something, or derefs a nullptr internally
|
||||
// if everything fails, so there's nothing for us to
|
||||
@@ -89,6 +89,7 @@ impl Buffer {
|
||||
}
|
||||
|
||||
/// Reset the buffer back to its initial post-creation state
|
||||
#[allow(dead_code)]
|
||||
pub fn reset(&mut self) {
|
||||
unsafe {
|
||||
hb_buffer_reset(self.buf);
|
||||
@@ -113,6 +114,7 @@ impl Buffer {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn add(&mut self, codepoint: hb_codepoint_t, cluster: u32) {
|
||||
unsafe {
|
||||
hb_buffer_add(self.buf, codepoint, cluster);
|
||||
@@ -132,15 +134,7 @@ impl Buffer {
|
||||
}
|
||||
|
||||
pub fn add_str(&mut self, s: &str) {
|
||||
unsafe {
|
||||
hb_buffer_add_utf8(
|
||||
self.buf,
|
||||
s.as_ptr() as *const i8,
|
||||
s.len() as i32,
|
||||
0,
|
||||
s.len() as i32,
|
||||
);
|
||||
}
|
||||
self.add_utf8(s.as_bytes())
|
||||
}
|
||||
|
||||
/// Returns glyph information. This is only valid after calling
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
use failure::{self, Error};
|
||||
use std::slice;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
pub mod ftwrap;
|
||||
pub mod hbwrap;
|
||||
pub mod fcwrap;
|
||||
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GlyphInfo {
|
||||
/// We only retain text in debug mode for diagnostic purposes
|
||||
#[cfg(debug_assertions)]
|
||||
pub text: String,
|
||||
pub num_cells: u8,
|
||||
pub font_idx: usize,
|
||||
pub glyph_pos: u32,
|
||||
pub cluster: u32,
|
||||
pub x_advance: i32,
|
||||
pub y_advance: i32,
|
||||
pub x_offset: i32,
|
||||
pub y_offset: i32,
|
||||
}
|
||||
|
||||
impl GlyphInfo {
|
||||
pub fn new(
|
||||
text: &str,
|
||||
font_idx: usize,
|
||||
info: &hbwrap::hb_glyph_info_t,
|
||||
pos: &hbwrap::hb_glyph_position_t,
|
||||
) -> GlyphInfo {
|
||||
let num_cells = UnicodeWidthStr::width(text) as u8;
|
||||
GlyphInfo {
|
||||
#[cfg(debug_assertions)]
|
||||
text: text.into(),
|
||||
num_cells,
|
||||
font_idx,
|
||||
glyph_pos: info.codepoint,
|
||||
cluster: info.cluster,
|
||||
x_advance: pos.x_advance / 64,
|
||||
y_advance: pos.y_advance / 64,
|
||||
x_offset: pos.x_offset / 64,
|
||||
y_offset: pos.y_offset / 64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FontInfo {
|
||||
face: ftwrap::Face,
|
||||
font: hbwrap::Font,
|
||||
cell_height: i64,
|
||||
cell_width: i64,
|
||||
}
|
||||
|
||||
pub struct FontHolder {
|
||||
lib: ftwrap::Library,
|
||||
size: i64,
|
||||
pattern: fcwrap::Pattern,
|
||||
font_list: fcwrap::FontSet,
|
||||
fonts: Vec<FontInfo>,
|
||||
}
|
||||
|
||||
impl Drop for FontHolder {
|
||||
fn drop(&mut self) {
|
||||
// Ensure that we drop the fonts before we drop the
|
||||
// library, otherwise we will end up faulting
|
||||
self.fonts.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl FontHolder {
|
||||
pub fn new(size: i64) -> Result<FontHolder, Error> {
|
||||
let mut lib = ftwrap::Library::new()?;
|
||||
lib.set_lcd_filter(
|
||||
ftwrap::FT_LcdFilter::FT_LCD_FILTER_DEFAULT,
|
||||
)?;
|
||||
|
||||
let mut pattern = fcwrap::Pattern::parse("Operator Mono SSm:size=12:weight=SemiLight")?;
|
||||
//pattern.family("Operator Mono SSm")?;
|
||||
pattern.monospace()?;
|
||||
pattern.config_substitute(fcwrap::MatchKind::Pattern)?;
|
||||
pattern.default_substitute();
|
||||
let font_list = pattern.sort(true)?;
|
||||
|
||||
Ok(FontHolder {
|
||||
lib,
|
||||
size,
|
||||
font_list,
|
||||
pattern,
|
||||
fonts: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn load_next_fallback(&mut self) -> Result<(), Error> {
|
||||
let idx = self.fonts.len();
|
||||
let pat = self.font_list.iter().nth(idx).ok_or(failure::err_msg(
|
||||
"no more fallbacks",
|
||||
))?;
|
||||
let pat = self.pattern.render_prepare(&pat)?;
|
||||
let file = pat.get_file()?;
|
||||
|
||||
println!("load_next_fallback: file={}", file);
|
||||
|
||||
let mut face = self.lib.new_face(file, 0)?;
|
||||
match face.set_char_size(0, self.size * 64, 96, 96) {
|
||||
Err(err) => {
|
||||
let sizes = unsafe {
|
||||
let rec = &(*face.face);
|
||||
slice::from_raw_parts(rec.available_sizes, rec.num_fixed_sizes as usize)
|
||||
};
|
||||
if sizes.len() == 0 {
|
||||
return Err(err);
|
||||
} else {
|
||||
// Find the best matching size.
|
||||
// We just take the biggest.
|
||||
let mut size = 0i16;
|
||||
for info in sizes.iter() {
|
||||
size = size.max(info.height);
|
||||
}
|
||||
face.set_pixel_sizes(size as u32, size as u32)?;
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
}
|
||||
let font = hbwrap::Font::new(&face);
|
||||
|
||||
// Compute metrics for the nominal monospace cell
|
||||
let (cell_width, cell_height) = face.cell_metrics();
|
||||
println!("metrics: width={} height={}", cell_width, cell_height);
|
||||
|
||||
self.fonts.push(FontInfo {
|
||||
face,
|
||||
font,
|
||||
cell_height,
|
||||
cell_width,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_font(&mut self, idx: usize) -> Result<&mut FontInfo, Error> {
|
||||
if idx >= self.fonts.len() {
|
||||
self.load_next_fallback()?;
|
||||
ensure!(
|
||||
idx < self.fonts.len(),
|
||||
"should not ask for a font later than the next prepared font"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(&mut self.fonts[idx])
|
||||
}
|
||||
|
||||
pub fn get_metrics(&mut self) -> Result<(i64, i64), Error> {
|
||||
let font = self.get_font(0)?;
|
||||
Ok((font.cell_height, font.cell_width))
|
||||
}
|
||||
|
||||
pub fn shape(&mut self, font_idx: usize, s: &str) -> Result<Vec<GlyphInfo>, Error> {
|
||||
println!(
|
||||
"shape text for font_idx {} with len {} {}",
|
||||
font_idx,
|
||||
s.len(),
|
||||
s
|
||||
);
|
||||
let features = vec![
|
||||
// kerning
|
||||
hbwrap::feature_from_string("kern")?,
|
||||
// ligatures
|
||||
hbwrap::feature_from_string("liga")?,
|
||||
// contextual ligatures
|
||||
hbwrap::feature_from_string("clig")?,
|
||||
];
|
||||
|
||||
let mut buf = hbwrap::Buffer::new()?;
|
||||
buf.set_script(hbwrap::HB_SCRIPT_LATIN);
|
||||
buf.set_direction(hbwrap::HB_DIRECTION_LTR);
|
||||
buf.set_language(hbwrap::language_from_string("en")?);
|
||||
buf.add_str(s);
|
||||
|
||||
self.shape_with_font(font_idx, &mut buf, &features)?;
|
||||
let infos = buf.glyph_infos();
|
||||
let positions = buf.glyph_positions();
|
||||
|
||||
let mut cluster = Vec::new();
|
||||
|
||||
let mut last_text_pos = None;
|
||||
let mut first_fallback_pos = None;
|
||||
|
||||
// Compute the lengths of the text clusters.
|
||||
// Ligatures and combining characters mean
|
||||
// that a single glyph can take the place of
|
||||
// multiple characters. The 'cluster' member
|
||||
// of the glyph info is set to the position
|
||||
// in the input utf8 text, so we make a pass
|
||||
// over the set of clusters to look for differences
|
||||
// greater than 1 and backfill the length of
|
||||
// the corresponding text fragment. We need
|
||||
// the fragments to properly handle fallback,
|
||||
// and they're handy to have for debugging
|
||||
// purposes too.
|
||||
let mut sizes = Vec::new();
|
||||
for (i, info) in infos.iter().enumerate() {
|
||||
let pos = info.cluster as usize;
|
||||
let mut size = 1;
|
||||
if let Some(last_pos) = last_text_pos {
|
||||
let diff = pos - last_pos;
|
||||
if diff > 1 {
|
||||
sizes[i - 1] = diff;
|
||||
}
|
||||
} else if pos != 0 {
|
||||
size = pos;
|
||||
}
|
||||
last_text_pos = Some(pos);
|
||||
sizes.push(size);
|
||||
}
|
||||
if let Some(last_pos) = last_text_pos {
|
||||
let diff = s.len() - last_pos;
|
||||
if diff > 1 {
|
||||
let last = sizes.len() - 1;
|
||||
sizes[last] = diff;
|
||||
}
|
||||
}
|
||||
println!("sizes: {:?}", sizes);
|
||||
|
||||
// Now make a second pass to determine if we need
|
||||
// to perform fallback to a later font.
|
||||
// We can determine this by looking at the codepoint.
|
||||
for (i, info) in infos.iter().enumerate() {
|
||||
let pos = info.cluster as usize;
|
||||
if info.codepoint == 0 {
|
||||
if first_fallback_pos.is_none() {
|
||||
// Start of a run that needs fallback
|
||||
first_fallback_pos = Some(pos);
|
||||
}
|
||||
} else if let Some(start) = first_fallback_pos {
|
||||
// End of a fallback run
|
||||
println!("range: {:?}-{:?} needs fallback", start, pos);
|
||||
|
||||
let substr = &s[start..pos];
|
||||
let mut shape = self.shape(font_idx + 1, substr)?;
|
||||
cluster.append(&mut shape);
|
||||
|
||||
first_fallback_pos = None;
|
||||
}
|
||||
if info.codepoint != 0 {
|
||||
let text = &s[pos..pos + sizes[i]];
|
||||
println!("glyph from `{}`", text);
|
||||
cluster.push(GlyphInfo::new(text, font_idx, info, &positions[i]));
|
||||
}
|
||||
}
|
||||
|
||||
// Check to see if we started and didn't finish a
|
||||
// fallback run.
|
||||
if let Some(start) = first_fallback_pos {
|
||||
let substr = &s[start..];
|
||||
println!(
|
||||
"at end {:?}-{:?} needs fallback {}",
|
||||
start,
|
||||
s.len() - 1,
|
||||
substr,
|
||||
);
|
||||
let mut shape = self.shape(font_idx + 1, substr)?;
|
||||
cluster.append(&mut shape);
|
||||
}
|
||||
|
||||
println!("shaped: {:#?}", cluster);
|
||||
|
||||
Ok(cluster)
|
||||
}
|
||||
|
||||
fn shape_with_font(
|
||||
&mut self,
|
||||
idx: usize,
|
||||
buf: &mut hbwrap::Buffer,
|
||||
features: &Vec<hbwrap::hb_feature_t>,
|
||||
) -> Result<(), Error> {
|
||||
let info = self.get_font(idx)?;
|
||||
info.font.shape(buf, Some(features.as_slice()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_glyph(
|
||||
&mut self,
|
||||
font_idx: usize,
|
||||
glyph_pos: u32,
|
||||
) -> Result<&ftwrap::FT_GlyphSlotRec_, Error> {
|
||||
let info = &mut self.fonts[font_idx];
|
||||
info.face.load_and_render_glyph(
|
||||
glyph_pos,
|
||||
(ftwrap::FT_LOAD_COLOR) as i32,
|
||||
ftwrap::FT_Render_Mode::FT_RENDER_MODE_LCD,
|
||||
)
|
||||
}
|
||||
}
|
||||
+13
-293
@@ -2,11 +2,15 @@
|
||||
extern crate failure;
|
||||
extern crate hexdump;
|
||||
extern crate unicode_width;
|
||||
extern crate harfbuzz_sys;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
extern crate fontconfig; // from servo-fontconfig
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
extern crate freetype;
|
||||
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
mod font;
|
||||
|
||||
use failure::Error;
|
||||
extern crate font;
|
||||
extern crate sdl2;
|
||||
use sdl2::event::{Event, WindowEvent};
|
||||
use sdl2::keyboard::Keycode;
|
||||
@@ -14,50 +18,11 @@ use sdl2::pixels::{Color, PixelFormatEnum};
|
||||
use sdl2::rect::Rect;
|
||||
use sdl2::render::{BlendMode, Texture, TextureCreator};
|
||||
|
||||
use font::ft::fcwrap;
|
||||
use font::ft::ftwrap;
|
||||
use font::ft::hbwrap;
|
||||
use font::ftwrap;
|
||||
use std::mem;
|
||||
use std::slice;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct GlyphInfo {
|
||||
/// We only retain text in debug mode for diagnostic purposes
|
||||
#[cfg(debug_assertions)]
|
||||
text: String,
|
||||
num_cells: u8,
|
||||
font_idx: usize,
|
||||
glyph_pos: u32,
|
||||
cluster: u32,
|
||||
x_advance: i32,
|
||||
y_advance: i32,
|
||||
x_offset: i32,
|
||||
y_offset: i32,
|
||||
}
|
||||
|
||||
impl GlyphInfo {
|
||||
pub fn new(
|
||||
text: &str,
|
||||
font_idx: usize,
|
||||
info: &hbwrap::hb_glyph_info_t,
|
||||
pos: &hbwrap::hb_glyph_position_t,
|
||||
) -> GlyphInfo {
|
||||
let num_cells = UnicodeWidthStr::width(text) as u8;
|
||||
GlyphInfo {
|
||||
#[cfg(debug_assertions)]
|
||||
text: text.into(),
|
||||
num_cells,
|
||||
font_idx,
|
||||
glyph_pos: info.codepoint,
|
||||
cluster: info.cluster,
|
||||
x_advance: pos.x_advance / 64,
|
||||
y_advance: pos.y_advance / 64,
|
||||
x_offset: pos.x_offset / 64,
|
||||
y_offset: pos.y_offset / 64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use font::{FontHolder, GlyphInfo};
|
||||
|
||||
struct Glyph<'a> {
|
||||
has_color: bool,
|
||||
@@ -82,13 +47,12 @@ impl<'a> Glyph<'a> {
|
||||
let mut tex = None;
|
||||
let mut width = glyph.bitmap.width as u32;
|
||||
let mut height = glyph.bitmap.rows as u32;
|
||||
let has_color = false;
|
||||
let mut has_color = false;
|
||||
|
||||
if width == 0 || height == 0 {
|
||||
// Special case for zero sized bitmaps; we can't
|
||||
// build a texture with zero dimenions, so we return
|
||||
// a Glyph with tex=None.
|
||||
tex = None;
|
||||
} else {
|
||||
|
||||
let mode: ftwrap::FT_Pixel_Mode =
|
||||
@@ -107,6 +71,7 @@ impl<'a> Glyph<'a> {
|
||||
.map_err(failure::err_msg)?
|
||||
}
|
||||
ftwrap::FT_Pixel_Mode::FT_PIXEL_MODE_BGRA => {
|
||||
has_color = true;
|
||||
texture_creator
|
||||
.create_texture_static(
|
||||
// Note: the pixelformat is BGRA and we really
|
||||
@@ -164,8 +129,8 @@ impl<'a> Glyph<'a> {
|
||||
}
|
||||
|
||||
Ok(Glyph {
|
||||
has_color: false,
|
||||
tex: tex,
|
||||
has_color,
|
||||
tex,
|
||||
width,
|
||||
height,
|
||||
info,
|
||||
@@ -175,248 +140,6 @@ impl<'a> Glyph<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
struct FontInfo {
|
||||
face: ftwrap::Face,
|
||||
font: hbwrap::Font,
|
||||
cell_height: i64,
|
||||
cell_width: i64,
|
||||
}
|
||||
|
||||
struct FontHolder {
|
||||
lib: ftwrap::Library,
|
||||
size: i64,
|
||||
pattern: fcwrap::Pattern,
|
||||
font_list: fcwrap::FontSet,
|
||||
fonts: Vec<FontInfo>,
|
||||
}
|
||||
|
||||
impl Drop for FontHolder {
|
||||
fn drop(&mut self) {
|
||||
// Ensure that we drop the fonts before we drop the
|
||||
// library, otherwise we will end up faulting
|
||||
self.fonts.clear();
|
||||
}
|
||||
}
|
||||
|
||||
impl FontHolder {
|
||||
fn new(size: i64) -> Result<FontHolder, Error> {
|
||||
let mut lib = ftwrap::Library::new()?;
|
||||
lib.set_lcd_filter(
|
||||
ftwrap::FT_LcdFilter::FT_LCD_FILTER_DEFAULT,
|
||||
)?;
|
||||
|
||||
let mut pattern = fcwrap::Pattern::parse("Operator Mono SSm:size=12:weight=SemiLight")?;
|
||||
//pattern.family("Operator Mono SSm")?;
|
||||
pattern.monospace()?;
|
||||
pattern.config_substitute(fcwrap::MatchKind::Pattern)?;
|
||||
pattern.default_substitute();
|
||||
let font_list = pattern.sort(true)?;
|
||||
|
||||
Ok(FontHolder {
|
||||
lib,
|
||||
size,
|
||||
font_list,
|
||||
pattern,
|
||||
fonts: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn load_next_fallback(&mut self) -> Result<(), Error> {
|
||||
let idx = self.fonts.len();
|
||||
let pat = self.font_list.iter().nth(idx).ok_or(failure::err_msg(
|
||||
"no more fallbacks",
|
||||
))?;
|
||||
let pat = self.pattern.render_prepare(&pat)?;
|
||||
let file = pat.get_file()?;
|
||||
|
||||
println!("load_next_fallback: file={}", file);
|
||||
|
||||
let mut face = self.lib.new_face(file, 0)?;
|
||||
match face.set_char_size(0, self.size * 64, 96, 96) {
|
||||
Err(err) => {
|
||||
let sizes = unsafe {
|
||||
let rec = &(*face.face);
|
||||
slice::from_raw_parts(rec.available_sizes, rec.num_fixed_sizes as usize)
|
||||
};
|
||||
if sizes.len() == 0 {
|
||||
return Err(err);
|
||||
} else {
|
||||
// Find the best matching size.
|
||||
// We just take the biggest.
|
||||
let mut size = 0i16;
|
||||
for info in sizes.iter() {
|
||||
size = size.max(info.height);
|
||||
}
|
||||
face.set_pixel_sizes(size as u32, size as u32)?;
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
}
|
||||
let font = hbwrap::Font::new(&face);
|
||||
|
||||
// Compute metrics for the nominal monospace cell
|
||||
let (cell_width, cell_height) = face.cell_metrics();
|
||||
println!("metrics: width={} height={}", cell_width, cell_height);
|
||||
|
||||
self.fonts.push(FontInfo {
|
||||
face,
|
||||
font,
|
||||
cell_height,
|
||||
cell_width,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_font(&mut self, idx: usize) -> Result<&mut FontInfo, Error> {
|
||||
if idx >= self.fonts.len() {
|
||||
self.load_next_fallback()?;
|
||||
ensure!(
|
||||
idx < self.fonts.len(),
|
||||
"should not ask for a font later than the next prepared font"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(&mut self.fonts[idx])
|
||||
}
|
||||
|
||||
fn shape(&mut self, font_idx: usize, s: &str) -> Result<Vec<GlyphInfo>, Error> {
|
||||
println!(
|
||||
"shape text for font_idx {} with len {} {}",
|
||||
font_idx,
|
||||
s.len(),
|
||||
s
|
||||
);
|
||||
let features = vec![
|
||||
// kerning
|
||||
hbwrap::feature_from_string("kern")?,
|
||||
// ligatures
|
||||
hbwrap::feature_from_string("liga")?,
|
||||
// contextual ligatures
|
||||
hbwrap::feature_from_string("clig")?,
|
||||
];
|
||||
|
||||
let mut buf = hbwrap::Buffer::new()?;
|
||||
buf.set_script(hbwrap::HB_SCRIPT_LATIN);
|
||||
buf.set_direction(hbwrap::HB_DIRECTION_LTR);
|
||||
buf.set_language(hbwrap::language_from_string("en")?);
|
||||
buf.add_str(s);
|
||||
|
||||
self.shape_with_font(font_idx, &mut buf, &features)?;
|
||||
let infos = buf.glyph_infos();
|
||||
let positions = buf.glyph_positions();
|
||||
|
||||
let mut cluster = Vec::new();
|
||||
|
||||
let mut last_text_pos = None;
|
||||
let mut first_fallback_pos = None;
|
||||
|
||||
// Compute the lengths of the text clusters.
|
||||
// Ligatures and combining characters mean
|
||||
// that a single glyph can take the place of
|
||||
// multiple characters. The 'cluster' member
|
||||
// of the glyph info is set to the position
|
||||
// in the input utf8 text, so we make a pass
|
||||
// over the set of clusters to look for differences
|
||||
// greater than 1 and backfill the length of
|
||||
// the corresponding text fragment. We need
|
||||
// the fragments to properly handle fallback,
|
||||
// and they're handy to have for debugging
|
||||
// purposes too.
|
||||
let mut sizes = Vec::new();
|
||||
for (i, info) in infos.iter().enumerate() {
|
||||
let pos = info.cluster as usize;
|
||||
let mut size = 1;
|
||||
if let Some(last_pos) = last_text_pos {
|
||||
let diff = pos - last_pos;
|
||||
if diff > 1 {
|
||||
sizes[i - 1] = diff;
|
||||
}
|
||||
} else if pos != 0 {
|
||||
size = pos;
|
||||
}
|
||||
last_text_pos = Some(pos);
|
||||
sizes.push(size);
|
||||
}
|
||||
if let Some(last_pos) = last_text_pos {
|
||||
let diff = s.len() - last_pos;
|
||||
if diff > 1 {
|
||||
let last = sizes.len() - 1;
|
||||
sizes[last] = diff;
|
||||
}
|
||||
}
|
||||
println!("sizes: {:?}", sizes);
|
||||
|
||||
// Now make a second pass to determine if we need
|
||||
// to perform fallback to a later font.
|
||||
// We can determine this by looking at the codepoint.
|
||||
for (i, info) in infos.iter().enumerate() {
|
||||
let pos = info.cluster as usize;
|
||||
if info.codepoint == 0 {
|
||||
if first_fallback_pos.is_none() {
|
||||
// Start of a run that needs fallback
|
||||
first_fallback_pos = Some(pos);
|
||||
}
|
||||
} else if let Some(start) = first_fallback_pos {
|
||||
// End of a fallback run
|
||||
println!("range: {:?}-{:?} needs fallback", start, pos);
|
||||
|
||||
let substr = &s[start..pos];
|
||||
let mut shape = self.shape(font_idx + 1, substr)?;
|
||||
cluster.append(&mut shape);
|
||||
|
||||
first_fallback_pos = None;
|
||||
}
|
||||
if info.codepoint != 0 {
|
||||
let text = &s[pos..pos + sizes[i]];
|
||||
println!("glyph from `{}`", text);
|
||||
cluster.push(GlyphInfo::new(text, font_idx, info, &positions[i]));
|
||||
}
|
||||
}
|
||||
|
||||
// Check to see if we started and didn't finish a
|
||||
// fallback run.
|
||||
if let Some(start) = first_fallback_pos {
|
||||
let substr = &s[start..];
|
||||
println!(
|
||||
"at end {:?}-{:?} needs fallback {}",
|
||||
start,
|
||||
s.len() - 1,
|
||||
substr,
|
||||
);
|
||||
let mut shape = self.shape(font_idx + 1, substr)?;
|
||||
cluster.append(&mut shape);
|
||||
}
|
||||
|
||||
println!("shaped: {:#?}", cluster);
|
||||
|
||||
Ok(cluster)
|
||||
}
|
||||
|
||||
fn shape_with_font(
|
||||
&mut self,
|
||||
idx: usize,
|
||||
buf: &mut hbwrap::Buffer,
|
||||
features: &Vec<hbwrap::hb_feature_t>,
|
||||
) -> Result<(), Error> {
|
||||
let info = self.get_font(idx)?;
|
||||
info.font.shape(buf, Some(features.as_slice()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_glyph(
|
||||
&mut self,
|
||||
font_idx: usize,
|
||||
glyph_pos: u32,
|
||||
) -> Result<&ftwrap::FT_GlyphSlotRec_, Error> {
|
||||
let info = &mut self.fonts[font_idx];
|
||||
info.face.load_and_render_glyph(
|
||||
glyph_pos,
|
||||
(ftwrap::FT_LOAD_COLOR) as i32,
|
||||
ftwrap::FT_Render_Mode::FT_RENDER_MODE_LCD,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn glyphs_for_text<'a, T>(
|
||||
texture_creator: &'a TextureCreator<T>,
|
||||
s: &str,
|
||||
@@ -427,10 +150,7 @@ fn glyphs_for_text<'a, T>(
|
||||
// We always load the cell_height for font 0,
|
||||
// regardless of which font we are shaping here,
|
||||
// so that we can scale glyphs appropriately
|
||||
let (cell_height, cell_width) = {
|
||||
let font = font_holder.get_font(0)?;
|
||||
(font.cell_height, font.cell_width)
|
||||
};
|
||||
let (cell_height, cell_width) = font_holder.get_metrics()?;
|
||||
|
||||
let mut result = Vec::new();
|
||||
for info in font_holder.shape(0, s)? {
|
||||
|
||||
Reference in new issue
Block a user