diff options
Diffstat (limited to 'font')
-rw-r--r-- | font/src/darwin/byte_order.rs | 11 | ||||
-rw-r--r-- | font/src/darwin/mod.rs | 195 | ||||
-rw-r--r-- | font/src/ft/fc/char_set.rs | 14 | ||||
-rw-r--r-- | font/src/ft/fc/config.rs | 11 | ||||
-rw-r--r-- | font/src/ft/fc/font_set.rs | 34 | ||||
-rw-r--r-- | font/src/ft/fc/mod.rs | 53 | ||||
-rw-r--r-- | font/src/ft/fc/object_set.rs | 6 | ||||
-rw-r--r-- | font/src/ft/fc/pattern.rs | 254 | ||||
-rw-r--r-- | font/src/ft/mod.rs | 175 | ||||
-rw-r--r-- | font/src/lib.rs | 46 | ||||
-rw-r--r-- | font/src/rusttype/mod.rs | 70 |
11 files changed, 355 insertions, 514 deletions
diff --git a/font/src/darwin/byte_order.rs b/font/src/darwin/byte_order.rs index 2ea46fcb..382caa31 100644 --- a/font/src/darwin/byte_order.rs +++ b/font/src/darwin/byte_order.rs @@ -40,9 +40,10 @@ pub fn extract_rgb(bytes: &[u8]) -> Vec<u8> { #[cfg(target_endian = "big")] pub fn extract_rgb(bytes: Vec<u8>) -> Vec<u8> { - bytes.into_iter() - .enumerate() - .filter(|&(index, _)| ((index) % 4) != 0) - .map(|(_, val)| val) - .collect::<Vec<_>>() + bytes + .into_iter() + .enumerate() + .filter(|&(index, _)| ((index) % 4) != 0) + .map(|(_, val)| val) + .collect::<Vec<_>>() } diff --git a/font/src/darwin/mod.rs b/font/src/darwin/mod.rs index 60b1a3e7..15a97e24 100644 --- a/font/src/darwin/mod.rs +++ b/font/src/darwin/mod.rs @@ -17,34 +17,37 @@ //! TODO error handling... just search for unwrap. #![allow(improper_ctypes)] use std::collections::HashMap; -use std::ptr; use std::path::PathBuf; +use std::ptr; -use ::{Slant, Weight, Style}; +use {Slant, Style, Weight}; -use core_foundation::string::{CFString}; -use core_foundation::array::{CFIndex, CFArray}; +use core_foundation::array::{CFArray, CFIndex}; +use core_foundation::string::CFString; use core_graphics::base::kCGImageAlphaPremultipliedFirst; use core_graphics::color_space::CGColorSpace; -use core_graphics::context::{CGContext}; +use core_graphics::context::CGContext; use core_graphics::font::{CGFont, CGGlyph}; use core_graphics::geometry::{CGPoint, CGRect, CGSize}; -use core_text::font::{CTFont, new_from_descriptor as ct_new_from_descriptor, cascade_list_for_languages as ct_cascade_list_for_languages}; +use core_text::font::{ + cascade_list_for_languages as ct_cascade_list_for_languages, + new_from_descriptor as ct_new_from_descriptor, CTFont, +}; use core_text::font_collection::create_for_family; use core_text::font_collection::get_family_names as ct_get_family_names; use core_text::font_descriptor::kCTFontDefaultOrientation; use core_text::font_descriptor::kCTFontHorizontalOrientation; use core_text::font_descriptor::kCTFontVerticalOrientation; -use core_text::font_descriptor::{CTFontDescriptor, CTFontOrientation}; use core_text::font_descriptor::SymbolicTraitAccessors; +use core_text::font_descriptor::{CTFontDescriptor, CTFontOrientation}; use euclid::{Point2D, Rect, Size2D}; -use super::{FontDesc, RasterizedGlyph, Metrics, FontKey, GlyphKey}; +use super::{FontDesc, FontKey, GlyphKey, Metrics, RasterizedGlyph}; pub mod byte_order; -use self::byte_order::kCGBitmapByteOrder32Host; use self::byte_order::extract_rgb; +use self::byte_order::kCGBitmapByteOrder32Host; use super::Size; @@ -59,11 +62,11 @@ pub struct Descriptor { display_name: String, font_path: PathBuf, - ct_descriptor: CTFontDescriptor + ct_descriptor: CTFontDescriptor, } impl Descriptor { - fn new(desc:CTFontDescriptor) -> Descriptor { + fn new(desc: CTFontDescriptor) -> Descriptor { Descriptor { family_name: desc.family_name(), font_name: desc.font_name(), @@ -111,16 +114,14 @@ impl ::std::error::Error for Error { impl ::std::fmt::Display for Error { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { - Error::MissingGlyph(ref c) => { - write!(f, "Glyph not found for char {:?}", c) - }, - Error::MissingFont(ref desc) => { - write!(f, "Couldn't find a font with {}\ - \n\tPlease check the font config in your alacritty.yml.", desc) - }, - Error::FontNotLoaded => { - f.write_str("Tried to use a font that hasn't been loaded") - } + Error::MissingGlyph(ref c) => write!(f, "Glyph not found for char {:?}", c), + Error::MissingFont(ref desc) => write!( + f, + "Couldn't find a font with {}\n\tPlease check the font config in your \ + alacritty.yml.", + desc + ), + Error::FontNotLoaded => f.write_str("Tried to use a font that hasn't been loaded"), } } } @@ -139,50 +140,41 @@ impl ::Rasterize for Rasterizer { /// Get metrics for font specified by FontKey fn metrics(&self, key: FontKey, _size: Size) -> Result<Metrics, Error> { - let font = self.fonts - .get(&key) - .ok_or(Error::FontNotLoaded)?; + let font = self.fonts.get(&key).ok_or(Error::FontNotLoaded)?; Ok(font.metrics()) } fn load_font(&mut self, desc: &FontDesc, size: Size) -> Result<FontKey, Error> { let scaled_size = Size::new(size.as_f32_pts() * self.device_pixel_ratio); - self.keys - .get(&(desc.to_owned(), scaled_size)) - .map(|k| Ok(*k)) - .unwrap_or_else(|| { - let font = self.get_font(desc, size)?; - let key = FontKey::next(); + self.keys.get(&(desc.to_owned(), scaled_size)).map(|k| Ok(*k)).unwrap_or_else(|| { + let font = self.get_font(desc, size)?; + let key = FontKey::next(); - self.fonts.insert(key, font); - self.keys.insert((desc.clone(), scaled_size), key); + self.fonts.insert(key, font); + self.keys.insert((desc.clone(), scaled_size), key); - Ok(key) - }) + Ok(key) + }) } /// Get rasterized glyph for given glyph key fn get_glyph(&mut self, glyph: GlyphKey) -> Result<RasterizedGlyph, Error> { - // get loaded font - let font = self.fonts - .get(&glyph.font_key) - .ok_or(Error::FontNotLoaded)?; + let font = self.fonts.get(&glyph.font_key).ok_or(Error::FontNotLoaded)?; // first try the font itself as a direct hit - self.maybe_get_glyph(glyph, font) - .unwrap_or_else(|| { - // then try fallbacks - for fallback in &font.fallbacks { - if let Some(result) = self.maybe_get_glyph(glyph, &fallback) { - // found a fallback - return result; - } + self.maybe_get_glyph(glyph, font).unwrap_or_else(|| { + // then try fallbacks + for fallback in &font.fallbacks { + if let Some(result) = self.maybe_get_glyph(glyph, &fallback) { + // found a fallback + return result; } - // no fallback, give up. - Err(Error::MissingGlyph(glyph.c)) - }) + } + // no fallback, give up. + Err(Error::MissingGlyph(glyph.c)) + }) } fn update_dpr(&mut self, device_pixel_ratio: f32) { @@ -195,7 +187,7 @@ impl Rasterizer { &mut self, desc: &FontDesc, style: &str, - size: Size + size: Size, ) -> Result<Font, Error> { let descriptors = descriptors_for_family(&desc.name[..]); for descriptor in descriptors { @@ -215,11 +207,11 @@ impl Rasterizer { desc: &FontDesc, slant: Slant, weight: Weight, - size: Size + size: Size, ) -> Result<Font, Error> { let bold = match weight { Weight::Bold => true, - _ => false + _ => false, }; let italic = match slant { Slant::Normal => false, @@ -262,7 +254,6 @@ impl Rasterizer { _ => Some(Err(e)), }) } - } /// Specifies the intended rendering orientation of the font for obtaining glyph metrics @@ -302,18 +293,12 @@ pub fn get_family_names() -> Vec<String> { owned_names } - /// Return fallback descriptors for font/language list -fn cascade_list_for_languages( - ct_font: &CTFont, - languages: &[String] -) -> Vec<Descriptor> { - +fn cascade_list_for_languages(ct_font: &CTFont, languages: &[String]) -> Vec<Descriptor> { // convert language type &Vec<String> -> CFArray - let langarr:CFArray<CFString> = { - let tmp:Vec<CFString> = languages.iter() - .map(|language| CFString::new(&language)) - .collect(); + let langarr: CFArray<CFString> = { + let tmp: Vec<CFString> = + languages.iter().map(|language| CFString::new(&language)).collect(); CFArray::from_CFTypes(&tmp) }; @@ -321,12 +306,9 @@ fn cascade_list_for_languages( let list = ct_cascade_list_for_languages(ct_font, &langarr); // convert CFArray to Vec<Descriptor> - list.into_iter() - .map(|fontdesc| Descriptor::new(fontdesc.clone())) - .collect() + list.into_iter().map(|fontdesc| Descriptor::new(fontdesc.clone())).collect() } - /// Get descriptors for family name pub fn descriptors_for_family(family: &str) -> Vec<Descriptor> { let mut out = Vec::new(); @@ -350,7 +332,7 @@ pub fn descriptors_for_family(family: &str) -> Vec<Descriptor> { impl Descriptor { /// Create a Font from this descriptor - pub fn to_font(&self, size: f64, load_fallbacks:bool) -> Font { + pub fn to_font(&self, size: f64, load_fallbacks: bool) -> Font { let ct_font = ct_new_from_descriptor(&self.ct_descriptor, size); let cg_font = ct_font.copy_to_CGFont(); @@ -385,7 +367,7 @@ impl Descriptor { fallbacks.insert(0, Font { cg_font: menlo.copy_to_CGFont(), ct_font: menlo, - fallbacks: Vec::new() + fallbacks: Vec::new(), }); fallbacks @@ -395,25 +377,16 @@ impl Descriptor { Vec::new() }; - Font { - ct_font, - cg_font, - fallbacks, - } + Font { ct_font, cg_font, fallbacks } } } impl Font { /// The the bounding rect of a glyph - pub fn bounding_rect_for_glyph( - &self, - orientation: FontOrientation, - index: u32 - ) -> Rect<f64> { - let cg_rect = self.ct_font.get_bounding_rects_for_glyphs( - orientation as CTFontOrientation, - &[index as CGGlyph] - ); + pub fn bounding_rect_for_glyph(&self, orientation: FontOrientation, index: u32) -> Rect<f64> { + let cg_rect = self + .ct_font + .get_bounding_rects_for_glyphs(orientation as CTFontOrientation, &[index as CGGlyph]); Rect::new( Point2D::new(cg_rect.origin.x, cg_rect.origin.y), @@ -465,12 +438,17 @@ impl Font { FontOrientation::Default as _, &indices[0], ptr::null_mut(), - 1 + 1, ) } } - pub fn get_glyph(&self, character: char, _size: f64, use_thin_strokes: bool) -> Result<RasterizedGlyph, Error> { + pub fn get_glyph( + &self, + character: char, + _size: f64, + use_thin_strokes: bool, + ) -> Result<RasterizedGlyph, Error> { // Render custom symbols for underline and beam cursor match character { super::UNDERLINE_CURSOR_CHAR => { @@ -480,7 +458,7 @@ impl Font { let width = self.glyph_advance('0') as i32; // Return the new custom glyph return super::get_underline_cursor_glyph(descent, width); - } + }, super::BEAM_CURSOR_CHAR | super::BOX_CURSOR_CHAR => { // Get the top of the bounding box let metrics = self.metrics(); @@ -496,12 +474,12 @@ impl Font { } else { return super::get_box_cursor_glyph(ascent as i32, height as i32, width); } - } - _ => () + }, + _ => (), } - let glyph_index = self.glyph_index(character) - .ok_or_else(|| Error::MissingGlyph(character))?; + let glyph_index = + self.glyph_index(character).ok_or_else(|| Error::MissingGlyph(character))?; let bounds = self.bounding_rect_for_glyph(Default::default(), glyph_index); @@ -519,7 +497,7 @@ impl Font { height: 0, top: 0, left: 0, - buf: Vec::new() + buf: Vec::new(), }); } @@ -530,17 +508,14 @@ impl Font { 8, // bits per component rasterized_width as usize * 4, &CGColorSpace::create_device_rgb(), - kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host + kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, ); // Give the context an opaque, black background cg_context.set_rgb_fill_color(0.0, 0.0, 0.0, 1.0); let context_rect = CGRect::new( &CGPoint::new(0.0, 0.0), - &CGSize::new( - f64::from(rasterized_width), - f64::from(rasterized_height) - ) + &CGSize::new(f64::from(rasterized_width), f64::from(rasterized_height)), ); cg_context.fill_rect(context_rect); @@ -560,14 +535,14 @@ impl Font { // Set fill color to white for drawing the glyph cg_context.set_rgb_fill_color(1.0, 1.0, 1.0, 1.0); - let rasterization_origin = CGPoint { - x: f64::from(-rasterized_left), - y: f64::from(rasterized_descent), - }; + let rasterization_origin = + CGPoint { x: f64::from(-rasterized_left), y: f64::from(rasterized_descent) }; - self.ct_font.draw_glyphs(&[glyph_index as CGGlyph], - &[rasterization_origin], - cg_context.clone()); + self.ct_font.draw_glyphs( + &[glyph_index as CGGlyph], + &[rasterization_origin], + cg_context.clone(), + ); let rasterized_pixels = cg_context.data().to_vec(); @@ -586,22 +561,22 @@ impl Font { fn glyph_index(&self, character: char) -> Option<u32> { // encode this char as utf-16 let mut buf = [0; 2]; - let encoded:&[u16] = character.encode_utf16(&mut buf); + let encoded: &[u16] = character.encode_utf16(&mut buf); // and use the utf-16 buffer to get the index self.glyph_index_utf16(encoded) } - fn glyph_index_utf16(&self, encoded: &[u16]) -> Option<u32> { + fn glyph_index_utf16(&self, encoded: &[u16]) -> Option<u32> { // output buffer for the glyph. for non-BMP glyphs, like // emojis, this will be filled with two chars the second // always being a 0. - let mut glyphs:[CGGlyph; 2] = [0; 2]; + let mut glyphs: [CGGlyph; 2] = [0; 2]; let res = unsafe { self.ct_font.get_glyphs_for_characters( encoded.as_ptr(), glyphs.as_mut_ptr(), - encoded.len() as CFIndex + encoded.len() as CFIndex, ) }; @@ -629,9 +604,7 @@ mod tests { println!("{:?}", list); // Check to_font - let fonts = list.iter() - .map(|desc| desc.to_font(72., false)) - .collect::<Vec<_>>(); + let fonts = list.iter().map(|desc| desc.to_font(72., false)).collect::<Vec<_>>(); for font in fonts { // Get a glyph @@ -649,7 +622,7 @@ mod tests { 101...150 => '~', 151...200 => '*', 201...255 => '#', - _ => unreachable!() + _ => unreachable!(), }; print!("{}", c); } diff --git a/font/src/ft/fc/char_set.rs b/font/src/ft/fc/char_set.rs index 151d14a3..310fa189 100644 --- a/font/src/ft/fc/char_set.rs +++ b/font/src/ft/fc/char_set.rs @@ -11,10 +11,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use foreign_types::{ForeignTypeRef}; +use foreign_types::ForeignTypeRef; -use super::ffi::{FcCharSet, FcCharSetDestroy, FcCharSetAddChar}; -use super::ffi::{FcCharSetCreate}; +use super::ffi::FcCharSetCreate; +use super::ffi::{FcCharSet, FcCharSetAddChar, FcCharSetDestroy}; foreign_type! { type CType = FcCharSet; @@ -37,12 +37,6 @@ impl Default for CharSet { impl CharSetRef { pub fn add(&mut self, glyph: char) -> bool { - unsafe { - FcCharSetAddChar( - self.as_ptr(), - glyph as _ - ) == 1 - } + unsafe { FcCharSetAddChar(self.as_ptr(), glyph as _) == 1 } } } - diff --git a/font/src/ft/fc/config.rs b/font/src/ft/fc/config.rs index 9744b37a..12ec2844 100644 --- a/font/src/ft/fc/config.rs +++ b/font/src/ft/fc/config.rs @@ -11,10 +11,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use foreign_types::{ForeignTypeRef}; +use foreign_types::ForeignTypeRef; -use super::{SetName, FontSetRef}; -use super::ffi::{FcConfigGetCurrent, FcConfigGetFonts, FcConfig, FcConfigDestroy}; +use super::ffi::{FcConfig, FcConfigDestroy, FcConfigGetCurrent, FcConfigGetFonts}; +use super::{FontSetRef, SetName}; foreign_type! { type CType = FcConfig; @@ -25,13 +25,10 @@ foreign_type! { pub struct ConfigRef; } - impl Config { /// Get the current configuration pub fn get_current() -> &'static ConfigRef { - unsafe { - ConfigRef::from_ptr(FcConfigGetCurrent()) - } + unsafe { ConfigRef::from_ptr(FcConfigGetCurrent()) } } } diff --git a/font/src/ft/fc/font_set.rs b/font/src/ft/fc/font_set.rs index 4eccd487..aeb34371 100644 --- a/font/src/ft/fc/font_set.rs +++ b/font/src/ft/fc/font_set.rs @@ -15,9 +15,9 @@ use std::ops::Deref; use foreign_types::{ForeignType, ForeignTypeRef}; -use super::{ConfigRef, PatternRef, ObjectSetRef}; +use super::{ConfigRef, ObjectSetRef, PatternRef}; -use super::ffi::{FcFontSetList, FcFontSetDestroy, FcFontSet}; +use super::ffi::{FcFontSet, FcFontSetDestroy, FcFontSetList}; foreign_type! { type CType = FcFontSet; @@ -33,13 +33,13 @@ impl FontSet { config: &ConfigRef, source: &mut FontSetRef, pattern: &PatternRef, - objects: &ObjectSetRef + objects: &ObjectSetRef, ) -> FontSet { let raw = unsafe { FcFontSetList( config.as_ptr(), &mut source.as_ptr(), - 1 /* nsets */, + 1, // nsets pattern.as_ptr(), objects.as_ptr(), ) @@ -56,38 +56,28 @@ pub struct Iter<'a> { } impl<'a> IntoIterator for &'a FontSet { - type Item = &'a PatternRef; type IntoIter = Iter<'a>; + type Item = &'a PatternRef; + fn into_iter(self) -> Iter<'a> { - let num_fonts = unsafe { - (*self.as_ptr()).nfont as isize - }; + let num_fonts = unsafe { (*self.as_ptr()).nfont as isize }; trace!("Number of fonts is {}", num_fonts); - Iter { - font_set: self.deref(), - num_fonts: num_fonts as _, - current: 0, - } + Iter { font_set: self.deref(), num_fonts: num_fonts as _, current: 0 } } } impl<'a> IntoIterator for &'a FontSetRef { - type Item = &'a PatternRef; type IntoIter = Iter<'a>; + type Item = &'a PatternRef; + fn into_iter(self) -> Iter<'a> { - let num_fonts = unsafe { - (*self.as_ptr()).nfont as isize - }; + let num_fonts = unsafe { (*self.as_ptr()).nfont as isize }; trace!("Number of fonts is {}", num_fonts); - Iter { - font_set: self, - num_fonts: num_fonts as _, - current: 0, - } + Iter { font_set: self, num_fonts: num_fonts as _, current: 0 } } } diff --git a/font/src/ft/fc/mod.rs b/font/src/ft/fc/mod.rs index 5e5deb0c..ae8fb808 100644 --- a/font/src/ft/fc/mod.rs +++ b/font/src/ft/fc/mod.rs @@ -12,21 +12,21 @@ // See the License for the specific language governing permissions and // limitations under the License. // -use std::ptr; use std::fmt; +use std::ptr; use foreign_types::{ForeignType, ForeignTypeRef}; use fontconfig::fontconfig as ffi; -use self::ffi::{FcSetSystem, FcSetApplication}; use self::ffi::FcResultNoMatch; -use self::ffi::{FcFontMatch, FcFontList, FcFontSort}; +use self::ffi::{FcFontList, FcFontMatch, FcFontSort}; use self::ffi::{FcMatchFont, FcMatchPattern, FcMatchScan}; -use self::ffi::{FC_SLANT_OBLIQUE, FC_SLANT_ITALIC, FC_SLANT_ROMAN}; -use self::ffi::{FC_WEIGHT_THIN, FC_WEIGHT_EXTRALIGHT, FC_WEIGHT_LIGHT}; -use self::ffi::{FC_WEIGHT_BOOK, FC_WEIGHT_REGULAR, FC_WEIGHT_MEDIUM, FC_WEIGHT_SEMIBOLD}; -use self::ffi::{FC_WEIGHT_BOLD, FC_WEIGHT_EXTRABOLD, FC_WEIGHT_BLACK, FC_WEIGHT_EXTRABLACK}; +use self::ffi::{FcSetApplication, FcSetSystem}; +use self::ffi::{FC_SLANT_ITALIC, FC_SLANT_OBLIQUE, FC_SLANT_ROMAN}; +use self::ffi::{FC_WEIGHT_BLACK, FC_WEIGHT_BOLD, FC_WEIGHT_EXTRABLACK, FC_WEIGHT_EXTRABOLD}; +use self::ffi::{FC_WEIGHT_BOOK, FC_WEIGHT_MEDIUM, FC_WEIGHT_REGULAR, FC_WEIGHT_SEMIBOLD}; +use self::ffi::{FC_WEIGHT_EXTRALIGHT, FC_WEIGHT_LIGHT, FC_WEIGHT_THIN}; pub mod config; pub use self::config::{Config, ConfigRef}; @@ -46,10 +46,7 @@ pub use self::pattern::{Pattern, PatternRef}; /// Find the font closest matching the provided pattern. /// /// The returned pattern is the result of Pattern::render_prepare. -pub fn font_match( - config: &ConfigRef, - pattern: &mut PatternRef, -) -> Option<Pattern> { +pub fn font_match(config: &ConfigRef, pattern: &mut PatternRef) -> Option<Pattern> { pattern.config_substitute(config, MatchKind::Pattern); pattern.default_substitute(); @@ -57,11 +54,7 @@ pub fn font_match( // What is this result actually used for? Seems redundant with // return type. let mut result = FcResultNoMatch; - let ptr = FcFontMatch( - config.as_ptr(), - pattern.as_ptr(), - &mut result, - ); + let ptr = FcFontMatch(config.as_ptr(), pattern.as_ptr(), &mut result); if ptr.is_null() { None @@ -72,10 +65,7 @@ pub fn font_match( } /// list fonts by closeness to the pattern -pub fn font_sort( - config: &ConfigRef, - pattern: &mut PatternRef, -) -> Option<FontSet> { +pub fn font_sort(config: &ConfigRef, pattern: &mut PatternRef) -> Option<FontSet> { pattern.config_substitute(config, MatchKind::Pattern); pattern.default_substitute(); @@ -112,11 +102,7 @@ pub fn font_list( pattern.default_substitute(); unsafe { - let ptr = FcFontList( - config.as_ptr(), - pattern.as_ptr(), - objects.as_ptr(), - ); + let ptr = FcFontList(config.as_ptr(), pattern.as_ptr(), objects.as_ptr()); if ptr.is_null() { None @@ -174,7 +160,7 @@ pub enum Width { Expanded, Extraexpanded, Ultraexpanded, - Other(i32) + Other(i32), } impl Width { @@ -190,7 +176,7 @@ impl Width { Expanded => 125, Extraexpanded => 150, Ultraexpanded => 200, - Other(value) => value as isize + Other(value) => value as isize, } } } @@ -207,7 +193,7 @@ impl From<isize> for Width { 125 => Width::Expanded, 150 => Width::Extraexpanded, 200 => Width::Ultraexpanded, - _ => Width::Other(value as _) + _ => Width::Other(value as _), } } } @@ -219,7 +205,7 @@ pub enum Rgba { Bgr, Vrgb, Vbgr, - None + None, } impl Rgba { @@ -230,7 +216,7 @@ impl Rgba { Rgba::Bgr => 2, Rgba::Vrgb => 3, Rgba::Vbgr => 4, - Rgba::None => 5 + Rgba::None => 5, } } } @@ -268,7 +254,7 @@ pub enum HintStyle { None, Slight, Medium, - Full + Full, } impl fmt::Display for HintStyle { @@ -287,7 +273,7 @@ pub enum LcdFilter { None, Default, Light, - Legacy + Legacy, } impl fmt::Display for LcdFilter { @@ -334,8 +320,7 @@ mod tests { pattern.set_slant(Slant::Italic); let config = Config::get_current(); - let fonts = super::font_sort(config, &mut pattern) - .expect("sort font monospace"); + let fonts = super::font_sort(config, &mut pattern).expect("sort font monospace"); for font in fonts.into_iter().take(10) { let font = font.render_prepare(&config, &pattern); diff --git a/font/src/ft/fc/object_set.rs b/font/src/ft/fc/object_set.rs index 47d11674..2494b582 100644 --- a/font/src/ft/fc/object_set.rs +++ b/font/src/ft/fc/object_set.rs @@ -13,8 +13,8 @@ // limitations under the License. use libc::c_char; +use super::ffi::{FcObjectSet, FcObjectSetAdd, FcObjectSetCreate, FcObjectSetDestroy}; use foreign_types::ForeignTypeRef; -use super::ffi::{FcObjectSetCreate, FcObjectSetAdd, FcObjectSet, FcObjectSetDestroy}; foreign_type! { type CType = FcObjectSet; @@ -31,9 +31,7 @@ impl ObjectSet { impl Default for ObjectSet { fn default() -> Self { - ObjectSet(unsafe { - FcObjectSetCreate() - }) + ObjectSet(unsafe { FcObjectSetCreate() }) } } diff --git a/font/src/ft/fc/pattern.rs b/font/src/ft/fc/pattern.rs index bb0c4c38..84187aa3 100644 --- a/font/src/ft/fc/pattern.rs +++ b/font/src/ft/fc/pattern.rs @@ -11,38 +11,34 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use std::ptr; -use std::fmt; use std::ffi::{CStr, CString}; +use std::fmt; +use std::mem; use std::path::PathBuf; +use std::ptr; use std::str; -use std::mem; -use libc::{c_char, c_int, c_double}; use foreign_types::{ForeignType, ForeignTypeRef}; +use libc::{c_char, c_double, c_int}; use super::ffi::FcResultMatch; -use super::ffi::{FcPatternDestroy, FcPatternAddCharSet}; -use super::ffi::{FcPatternGetString, FcPatternCreate, FcPatternAddString, FcPatternAddDouble}; -use super::ffi::{FcPatternGetInteger, FcPatternAddInteger, FcPatternPrint}; -use super::ffi::{FcChar8, FcPattern, FcDefaultSubstitute, FcConfigSubstitute}; -use super::ffi::{FcFontRenderPrepare, FcPatternGetBool, FcBool, FcPatternGetDouble}; +use super::ffi::{FcBool, FcFontRenderPrepare, FcPatternGetBool, FcPatternGetDouble}; +use super::ffi::{FcChar8, FcConfigSubstitute, FcDefaultSubstitute, FcPattern}; +use super::ffi::{FcPatternAddCharSet, FcPatternDestroy}; +use super::ffi::{FcPatternAddDouble, FcPatternAddString, FcPatternCreate, FcPatternGetString}; +use super::ffi::{FcPatternAddInteger, FcPatternGetInteger, FcPatternPrint}; -use super::{MatchKind, ConfigRef, CharSetRef, Weight, Slant, Width, Rgba, HintStyle, LcdFilter}; +use super::{CharSetRef, ConfigRef, HintStyle, LcdFilter, MatchKind, Rgba, Slant, Weight, Width}; pub struct StringPropertyIter<'a> { pattern: &'a PatternRef, object: &'a [u8], - index: usize + index: usize, } impl<'a> StringPropertyIter<'a> { fn new<'b>(pattern: &'b PatternRef, object: &'b [u8]) -> StringPropertyIter<'b> { - StringPropertyIter { - pattern, - object, - index: 0 - } + StringPropertyIter { pattern, object, index: 0 } } fn get_value(&self, index: usize) -> Option<&'a str> { @@ -53,7 +49,7 @@ impl<'a> StringPropertyIter<'a> { self.pattern.as_ptr(), self.object.as_ptr() as *mut c_char, index as c_int, - &mut value + &mut value, ) }; @@ -75,17 +71,12 @@ impl<'a> StringPropertyIter<'a> { pub struct BooleanPropertyIter<'a> { pattern: &'a PatternRef, object: &'a [u8], - index: usize + index: usize, } - impl<'a> BooleanPropertyIter<'a> { fn new<'b>(pattern: &'b PatternRef, object: &'b [u8]) -> BooleanPropertyIter<'b> { - BooleanPropertyIter { - pattern, - object, - index: 0 - } + BooleanPropertyIter { pattern, object, index: 0 } } fn get_value(&self, index: usize) -> Option<bool> { @@ -96,7 +87,7 @@ impl<'a> BooleanPropertyIter<'a> { self.pattern.as_ptr(), self.object.as_ptr() as *mut c_char, index as c_int, - &mut value + &mut value, ) }; @@ -112,16 +103,12 @@ impl<'a> BooleanPropertyIter<'a> { pub struct IntPropertyIter<'a> { pattern: &'a PatternRef, object: &'a [u8], - index: usize + index: usize, } impl<'a> IntPropertyIter<'a> { fn new<'b>(pattern: &'b PatternRef, object: &'b [u8]) -> IntPropertyIter<'b> { - IntPropertyIter { - pattern, - object, - index: 0 - } + IntPropertyIter { pattern, object, index: 0 } } fn get_value(&self, index: usize) -> Option<isize> { @@ -132,7 +119,7 @@ impl<'a> IntPropertyIter<'a> { self.pattern.as_ptr(), self.object.as_ptr() as *mut c_char, index as c_int, - &mut value + &mut value, ) }; @@ -150,9 +137,7 @@ pub struct RgbaPropertyIter<'a> { impl<'a> RgbaPropertyIter<'a> { fn new<'b>(pattern: &'b PatternRef, object: &'b [u8]) -> RgbaPropertyIter<'b> { - RgbaPropertyIter { - inner: IntPropertyIter::new(pattern, object) - } + RgbaPropertyIter { inner: IntPropertyIter::new(pattern, object) } } #[inline] @@ -161,8 +146,7 @@ impl<'a> RgbaPropertyIter<'a> { } fn get_value(&self, index: usize) -> Option<Rgba> { - self.inner.get_value(index) - .map(Rgba::from) + self.inner.get_value(index).map(Rgba::from) } } @@ -172,9 +156,7 @@ pub struct HintStylePropertyIter<'a> { impl<'a> HintStylePropertyIter<'a> { fn new(pattern: &PatternRef) -> HintStylePropertyIter { - HintStylePropertyIter { - inner: IntPropertyIter::new(pattern, b"hintstyle\0") - } + HintStylePropertyIter { inner: IntPropertyIter::new(pattern, b"hintstyle\0") } } #[inline] @@ -183,16 +165,15 @@ impl<'a> HintStylePropertyIter<'a> { } fn get_value(&self, index: usize) -> Option<HintStyle> { - self.inner.get_value(index) - .and_then(|hint_style| { - Some(match hint_style { - 0 => HintStyle::None, - 1 => HintStyle::Slight, - 2 => HintStyle::Medium, - 3 => HintStyle::Full, - _ => return None - }) + self.inner.get_value(index).and_then(|hint_style| { + Some(match hint_style { + 0 => HintStyle::None, + 1 => HintStyle::Slight, + 2 => HintStyle::Medium, + 3 => HintStyle::Full, + _ => return None, }) + }) } } @@ -202,9 +183,7 @@ pub struct LcdFilterPropertyIter<'a> { impl<'a> LcdFilterPropertyIter<'a> { fn new(pattern: &PatternRef) -> LcdFilterPropertyIter { - LcdFilterPropertyIter { - inner: IntPropertyIter::new(pattern, b"lcdfilter\0") - } + LcdFilterPropertyIter { inner: IntPropertyIter::new(pattern, b"lcdfilter\0") } } #[inline] @@ -213,16 +192,15 @@ impl<'a> LcdFilterPropertyIter<'a> { } fn get_value(&self, index: usize) -> Option<LcdFilter> { - self.inner.get_value(index) - .and_then(|hint_style| { - Some(match hint_style { - 0 => LcdFilter::None, - 1 => LcdFilter::Default, - 2 => LcdFilter::Light, - 3 => LcdFilter::Legacy, - _ => return None - }) + self.inner.get_value(index).and_then(|hint_style| { + Some(match hint_style { + 0 => LcdFilter::None, + 1 => LcdFilter::Default, + 2 => LcdFilter::Light, + 3 => LcdFilter::Legacy, + _ => return None, }) + }) } } @@ -230,16 +208,12 @@ impl<'a> LcdFilterPropertyIter<'a> { pub struct DoublePropertyIter<'a> { pattern: &'a PatternRef, object: &'a [u8], - index: usize + index: usize, } impl<'a> DoublePropertyIter<'a> { fn new<'b>(pattern: &'b PatternRef, object: &'b [u8]) -> DoublePropertyIter<'b> { - DoublePropertyIter { - pattern, - object, - index: 0 - } + DoublePropertyIter { pattern, object, index: 0 } } fn get_value(&self, index: usize) -> Option<f64> { @@ -250,7 +224,7 @@ impl<'a> DoublePropertyIter<'a> { self.pattern.as_ptr(), self.object.as_ptr() as *mut c_char, index as c_int, - &mut value + &mut value, ) }; @@ -277,13 +251,13 @@ macro_rules! impl_property_iter_debug { write!(f, "{}", val)?; } }, - _ => break + _ => break, } } write!(f, "]") } } - } + }; } /// Implement Iterator and Debug for a property iterator @@ -427,15 +401,55 @@ macro_rules! double_getter { } impl PatternRef { + boolean_getter! { + antialias() => b"antialias\0", + hinting() => b"hinting\0", + verticallayout() => b"verticallayout\0", + autohint() => b"autohint\0", + globaladvance() => b"globaladvance\0", + scalable() => b"scalable\0", + symbol() => b"symbol\0", + color() => b"color\0", + minspace() => b"minspace\0", + embolden() => b"embolden\0", + embeddedbitmap() => b"embeddedbitmap\0", + decorative() => b"decorative\0" + } + + double_getter! { + size() => b"size\0", + aspect() => b"aspect\0", + pixelsize() => b"pixelsize\0", + scale() => b"scale\0", + dpi() => b"dpi\0" + } + + string_accessor! { + [family, add_family] => b"family\0", + [familylang, add_familylang] => b"familylang\0", + [style, add_style] => b"style\0", + [stylelang, add_stylelang] => b"stylelang\0", + [fullname, add_fullname] => b"fullname\0", + [fullnamelang, add_fullnamelang] => b"fullnamelang\0", + [foundry, add_foundry] => b"foundry\0", + [capability, add_capability] => b"capability\0", + [fontformat, add_fontformat] => b"fontformat\0", + [fontfeatures, add_fontfeatures] => b"fontfeatures\0", + [namelang, add_namelang] => b"namelang\0", + [postscriptname, add_postscriptname] => b"postscriptname\0" + } + + pattern_get_integer! { + index() => b"index\0" + } + // Prints the pattern to stdout // // FontConfig doesn't expose a way to iterate over all members of a pattern; // instead, we just defer to FcPatternPrint. Otherwise, this could have been // a `fmt::Debug` impl. pub fn print(&self) { - unsafe { - FcPatternPrint(self.as_ptr()) - } + unsafe { FcPatternPrint(self.as_ptr()) } } /// Add a string value to the pattern @@ -450,27 +464,16 @@ impl PatternRef { let value = CString::new(&value[..]).unwrap(); let value = value.as_ptr(); - FcPatternAddString( - self.as_ptr(), - object.as_ptr() as *mut c_char, - value as *mut FcChar8 - ) == 1 + FcPatternAddString(self.as_ptr(), object.as_ptr() as *mut c_char, value as *mut FcChar8) + == 1 } unsafe fn add_integer(&self, object: &[u8], int: isize) -> bool { - FcPatternAddInteger( - self.as_ptr(), - object.as_ptr() as *mut c_char, - int as c_int - ) == 1 + FcPatternAddInteger(self.as_ptr(), object.as_ptr() as *mut c_char, int as c_int) == 1 } unsafe fn add_double(&self, object: &[u8], value: f64) -> bool { - FcPatternAddDouble( - self.as_ptr(), - object.as_ptr() as *mut c_char, - value as c_double - ) == 1 + FcPatternAddDouble(self.as_ptr(), object.as_ptr() as *mut c_char, value as c_double) == 1 } unsafe fn get_string<'a>(&'a self, object: &'a [u8]) -> StringPropertyIter<'a> { @@ -497,74 +500,24 @@ impl PatternRef { LcdFilterPropertyIter::new(self) } - boolean_getter! { - antialias() => b"antialias\0", - hinting() => b"hinting\0", - verticallayout() => b"verticallayout\0", - autohint() => b"autohint\0", - globaladvance() => b"globaladvance\0", - scalable() => b"scalable\0", - symbol() => b"symbol\0", - color() => b"color\0", - minspace() => b"minspace\0", - embolden() => b"embolden\0", - embeddedbitmap() => b"embeddedbitmap\0", - decorative() => b"decorative\0" - } - - double_getter! { - size() => b"size\0", - aspect() => b"aspect\0", - pixelsize() => b"pixelsize\0", - scale() => b"scale\0", - dpi() => b"dpi\0" - } - - string_accessor! { - [family, add_family] => b"family\0", - [familylang, add_familylang] => b"familylang\0", - [style, add_style] => b"style\0", - [stylelang, add_stylelang] => b"stylelang\0", - [fullname, add_fullname] => b"fullname\0", - [fullnamelang, add_fullnamelang] => b"fullnamelang\0", - [foundry, add_foundry] => b"foundry\0", - [capability, add_capability] => b"capability\0", - [fontformat, add_fontformat] => b"fontformat\0", - [fontfeatures, add_fontfeatures] => b"fontfeatures\0", - [namelang, add_namelang] => b"namelang\0", - [postscriptname, add_postscriptname] => b"postscriptname\0" - } - pub fn set_slant(&mut self, slant: Slant) -> bool { - unsafe { - self.add_integer(b"slant\0", slant as isize) - } + unsafe { self.add_integer(b"slant\0", slant as isize) } } pub fn add_pixelsize(&mut self, size: f64) -> bool { - unsafe { - self.add_double(b"pixelsize\0", size) - } + unsafe { self.add_double(b"pixelsize\0", size) } } pub fn set_weight(&mut self, weight: Weight) -> bool { - unsafe { - self.add_integer(b"weight\0", weight as isize) - } + unsafe { self.add_integer(b"weight\0", weight as isize) } } pub fn set_width(&mut self, width: Width) -> bool { - unsafe { - self.add_integer(b"width\0", width.to_isize()) - } + unsafe { self.add_integer(b"width\0", width.to_isize()) } } pub fn get_width(&self) -> Option<Width> { - unsafe { - self.get_integer(b"width\0") - .nth(0) - .map(Width::from) - } + unsafe { self.get_integer(b"width\0").nth(0).map(Width::from) } } pub fn rgba(&self) -> RgbaPropertyIter { @@ -572,9 +525,7 @@ impl PatternRef { } pub fn set_rgba(&self, rgba: &Rgba) -> bool { - unsafe { - self.add_integer(b"rgba\0", rgba.to_isize()) - } + unsafe { self.add_integer(b"rgba\0", rgba.to_isize()) } } pub fn render_prepare(&self, config: &ConfigRef, request: &PatternRef) -> Pattern { @@ -595,19 +546,13 @@ impl PatternRef { FcPatternAddCharSet( self.as_ptr(), b"charset\0".as_ptr() as *mut c_char, - charset.as_ptr() + charset.as_ptr(), ) == 1 } } pub fn file(&self, index: usize) -> Option<PathBuf> { - unsafe { - self.get_string(b"file\0").nth(index) - }.map(From::from) - } - - pattern_get_integer! { - index() => b"index\0" + unsafe { self.get_string(b"file\0").nth(index) }.map(From::from) } pub fn config_substitute(&mut self, config: &ConfigRef, kind: MatchKind) { @@ -622,4 +567,3 @@ impl PatternRef { } } } - diff --git a/font/src/ft/mod.rs b/font/src/ft/mod.rs index 6bcda2a1..bc6d6d89 100644 --- a/font/src/ft/mod.rs +++ b/font/src/ft/mod.rs @@ -13,19 +13,18 @@ // limitations under the License. // //! Rasterization powered by FreeType and FontConfig -use std::collections::HashMap; use std::cmp::min; -use std::path::PathBuf; +use std::collections::HashMap; use std::fmt; +use std::path::PathBuf; use freetype::tt_os2::TrueTypeOS2Table; use freetype::{self, Library}; use libc::c_uint; - pub mod fc; -use super::{FontDesc, RasterizedGlyph, Metrics, Size, FontKey, GlyphKey, Weight, Slant, Style}; +use super::{FontDesc, FontKey, GlyphKey, Metrics, RasterizedGlyph, Size, Slant, Style, Weight}; struct FixedSize { pixelsize: f64, @@ -37,7 +36,7 @@ struct Face { load_flags: freetype::face::LoadFlag, render_mode: freetype::RenderMode, lcd_filter: c_uint, - non_scalable: Option<FixedSize> + non_scalable: Option<FixedSize>, } impl fmt::Debug for Face { @@ -46,14 +45,17 @@ impl fmt::Debug for Face { .field("ft_face", &self.ft_face) .field("key", &self.key) .field("load_flags", &self.load_flags) - .field("render_mode", &match self.render_mode { - freetype::RenderMode::Normal => "Normal", - freetype::RenderMode::Light => "Light", - freetype::RenderMode::Mono => "Mono", - freetype::RenderMode::Lcd => "Lcd", - freetype::RenderMode::LcdV => "LcdV", - freetype::RenderMode::Max => "Max", - }) + .field( + "render_mode", + &match self.render_mode { + freetype::RenderMode::Normal => "Normal", + freetype::RenderMode::Light => "Light", + freetype::RenderMode::Mono => "Mono", + freetype::RenderMode::Lcd => "Lcd", + freetype::RenderMode::LcdV => "LcdV", + freetype::RenderMode::Max => "Max", + }, + ) .field("lcd_filter", &self.lcd_filter) .finish() } @@ -87,9 +89,7 @@ impl ::Rasterize for FreeTypeRasterizer { } fn metrics(&self, key: FontKey, _size: Size) -> Result<Metrics, Error> { - let face = self.faces - .get(&key) - .ok_or(Error::FontNotLoaded)?; + let face = self.faces.get(&key).ok_or(Error::FontNotLoaded)?; let full = self.full_metrics(key)?; let height = (full.size_metrics.height / 64) as f64; @@ -108,20 +108,19 @@ impl ::Rasterize for FreeTypeRasterizer { // Get strikeout position and thickness in device pixels let (strikeout_position, strikeout_thickness) = - match TrueTypeOS2Table::from_face(&mut face.ft_face.clone()) - { - Some(os2) => { - let strikeout_position = f32::from(os2.y_strikeout_position()) * x_scale / 64.; - let strikeout_thickness = f32::from(os2.y_strikeout_size()) * x_scale / 64.; - (strikeout_position, strikeout_thickness) - }, - _ => { - // Fallback if font doesn't provide info about strikeout - trace!("Using fallback strikeout metrics"); - let strikeout_position = height as f32 / 2. + descent; - (strikeout_position, underline_thickness) - }, - }; + match TrueTypeOS2Table::from_face(&mut face.ft_face.clone()) { + Some(os2) => { + let strikeout_position = f32::from(os2.y_strikeout_position()) * x_scale / 64.; + let strikeout_thickness = f32::from(os2.y_strikeout_size()) * x_scale / 64.; + (strikeout_position, strikeout_thickness) + }, + _ => { + // Fallback if font doesn't provide info about strikeout + trace!("Using fallback strikeout metrics"); + let strikeout_position = height as f32 / 2. + descent; + (strikeout_position, underline_thickness) + }, + }; Ok(Metrics { average_advance: full.cell_width, @@ -154,6 +153,7 @@ pub trait IntoFontconfigType { impl IntoFontconfigType for Slant { type FcType = fc::Slant; + fn into_fontconfig_type(&self) -> Self::FcType { match *self { Slant::Normal => fc::Slant::Roman, @@ -176,7 +176,7 @@ impl IntoFontconfigType for Weight { struct FullMetrics { size_metrics: freetype::ffi::FT_Size_Metrics, - cell_width: f64 + cell_width: f64, } impl FreeTypeRasterizer { @@ -189,31 +189,25 @@ impl FreeTypeRasterizer { Style::Description { slant, weight } => { // Match nearest font self.get_matching_face(&desc, slant, weight, size) - } + }, Style::Specific(ref style) => { // If a name was specified, try and load specifically that font. self.get_specific_face(&desc, &style, size) - } + }, } } fn full_metrics(&self, key: FontKey) -> Result<FullMetrics, Error> { - let face = self.faces - .get(&key) - .ok_or(Error::FontNotLoaded)?; + let face = self.faces.get(&key).ok_or(Error::FontNotLoaded)?; - let size_metrics = face.ft_face.size_metrics() - .ok_or(Error::MissingSizeMetrics)?; + let size_metrics = face.ft_face.size_metrics().ok_or(Error::MissingSizeMetrics)?; let width = match face.ft_face.load_char('0' as usize, face.load_flags) { - Ok(_) => face.ft_face.glyph().metrics().horiAdvance / 64, - Err(_) => size_metrics.max_advance / 64 + Ok(_) => face.ft_face.glyph().metrics().horiAdvance / 64, + Err(_) => size_metrics.max_advance / 64, } as f64; - Ok(FullMetrics { - size_metrics, - cell_width: width - }) + Ok(FullMetrics { size_metrics, cell_width: width }) } fn get_matching_face( @@ -232,12 +226,9 @@ impl FreeTypeRasterizer { let font = fc::font_match(fc::Config::get_current(), &mut pattern) .ok_or_else(|| Error::MissingFont(desc.to_owned()))?; - self.face_from_pattern(&font) - .and_then(|pattern| { - pattern - .map(Ok) - .unwrap_or_else(|| Err(Error::MissingFont(desc.to_owned()))) - }) + self.face_from_pattern(&font).and_then(|pattern| { + pattern.map(Ok).unwrap_or_else(|| Err(Error::MissingFont(desc.to_owned()))) + }) } fn get_specific_face( @@ -253,12 +244,9 @@ impl FreeTypeRasterizer { let font = fc::font_match(fc::Config::get_current(), &mut pattern) .ok_or_else(|| Error::MissingFont(desc.to_owned()))?; - self.face_from_pattern(&font) - .and_then(|pattern| { - pattern - .map(Ok) - .unwrap_or_else(|| Err(Error::MissingFont(desc.to_owned()))) - }) + self.face_from_pattern(&font).and_then(|pattern| { + pattern.map(Ok).unwrap_or_else(|| Err(Error::MissingFont(desc.to_owned()))) + }) } fn face_from_pattern(&mut self, pattern: &fc::Pattern) -> Result<Option<FontKey>, Error> { @@ -277,9 +265,7 @@ impl FreeTypeRasterizer { let mut pixelsize = pattern.pixelsize(); debug!("pixelsizes: {:?}", pixelsize); - Some(FixedSize { - pixelsize: pixelsize.next().expect("has 1+ pixelsize"), - }) + Some(FixedSize { pixelsize: pixelsize.next().expect("has 1+ pixelsize") }) }; let face = Face { @@ -303,7 +289,11 @@ impl FreeTypeRasterizer { } } - fn face_for_glyph(&mut self, glyph_key: GlyphKey, have_recursed: bool) -> Result<FontKey, Error> { + fn face_for_glyph( + &mut self, + glyph_key: GlyphKey, + have_recursed: bool, + ) -> Result<FontKey, Error> { let c = glyph_key.c; let use_initial_face = if let Some(face) = self.faces.get(&glyph_key.font_key) { @@ -322,8 +312,7 @@ impl FreeTypeRasterizer { } } - fn get_rendered_glyph(&mut self, glyph_key: GlyphKey) - -> Result<RasterizedGlyph, Error> { + fn get_rendered_glyph(&mut self, glyph_key: GlyphKey) -> Result<RasterizedGlyph, Error> { // Render a custom symbol for the underline and beam cursor match glyph_key.c { super::UNDERLINE_CURSOR_CHAR => { @@ -370,9 +359,10 @@ impl FreeTypeRasterizer { let face = &self.faces[&font_key]; let index = face.ft_face.get_char_index(glyph_key.c as usize); - let size = face.non_scalable.as_ref() - .map(|v| v.pixelsize as f32) - .unwrap_or_else(|| glyph_key.size.as_f32_pts() * self.device_pixel_ratio * 96. / 72.); + let size = + face.non_scalable.as_ref().map(|v| v.pixelsize as f32).unwrap_or_else(|| { + glyph_key.size.as_f32_pts() * self.device_pixel_ratio * 96. / 72. + }); face.ft_face.set_char_size(to_freetype_26_6(size), 0, 0, 0)?; @@ -405,7 +395,7 @@ impl FreeTypeRasterizer { use freetype::face::LoadFlag; match (antialias, hinting, rgba) { (false, fc::HintStyle::None, _) => LoadFlag::NO_HINTING | LoadFlag::MONOCHROME, - (false, _, _) => LoadFlag::TARGET_MONO | LoadFlag::MONOCHROME, + (false, ..) => LoadFlag::TARGET_MONO | LoadFlag::MONOCHROME, (true, fc::HintStyle::None, _) => LoadFlag::NO_HINTING | LoadFlag::TARGET_NORMAL, // hintslight does *not* use LCD hinting even when a subpixel mode // is selected. @@ -459,7 +449,9 @@ impl FreeTypeRasterizer { /// Given a FreeType `Bitmap`, returns packed buffer with 1 byte per LCD channel. /// /// The i32 value in the return type is the number of pixels per row. - fn normalize_buffer(bitmap: &freetype::bitmap::Bitmap) -> freetype::FtResult<(i32, i32, Vec<u8>)> { + fn normalize_buffer( + bitmap: &freetype::bitmap::Bitmap, + ) -> freetype::FtResult<(i32, i32, Vec<u8>)> { use freetype::bitmap::PixelMode; let buf = bitmap.buffer(); @@ -475,7 +467,7 @@ impl FreeTypeRasterizer { Ok((bitmap.rows(), bitmap.width() / 3, packed)) }, PixelMode::LcdV => { - for i in 0..bitmap.rows()/3 { + for i in 0..bitmap.rows() / 3 { for j in 0..bitmap.width() { for k in 0..3 { let offset = ((i as usize) * 3 + k) * pitch + (j as usize); @@ -529,14 +521,11 @@ impl FreeTypeRasterizer { } Ok((bitmap.rows(), bitmap.width(), packed)) }, - mode => panic!("unhandled pixel mode: {:?}", mode) + mode => panic!("unhandled pixel mode: {:?}", mode), } } - fn load_face_with_glyph( - &mut self, - glyph: char, - ) -> Result<FontKey, Error> { + fn load_face_with_glyph(&mut self, glyph: char) -> Result<FontKey, Error> { let mut charset = fc::CharSet::new(); charset.add(glyph); let mut pattern = fc::Pattern::new(); @@ -560,19 +549,19 @@ impl FreeTypeRasterizer { // and index above. let key = self.face_from_pattern(&pattern)?.unwrap(); Ok(key) - } + }, } - } - else { - Err(Error::MissingFont( - FontDesc::new("fallback-without-path", Style::Specific(glyph.to_string())))) + } else { + Err(Error::MissingFont(FontDesc::new( + "fallback-without-path", + Style::Specific(glyph.to_string()), + ))) } }, - None => { - Err(Error::MissingFont( - FontDesc::new("no-fallback-for", Style::Specific(glyph.to_string())) - )) - } + None => Err(Error::MissingFont(FontDesc::new( + "no-fallback-for", + Style::Specific(glyph.to_string()), + ))), } } } @@ -614,19 +603,17 @@ impl ::std::error::Error for Error { impl ::std::fmt::Display for Error { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { - Error::FreeType(ref err) => { - err.fmt(f) - }, - Error::MissingFont(ref desc) => { - write!(f, "Couldn't find a font with {}\ - \n\tPlease check the font config in your alacritty.yml.", desc) - }, - Error::FontNotLoaded => { - f.write_str("Tried to use a font that hasn't been loaded") - }, + Error::FreeType(ref err) => err.fmt(f), + Error::MissingFont(ref desc) => write!( + f, + "Couldn't find a font with {}\n\tPlease check the font config in your \ + alacritty.yml.", + desc + ), + Error::FontNotLoaded => f.write_str("Tried to use a font that hasn't been loaded"), Error::MissingSizeMetrics => { f.write_str("Tried to get size metrics from a face without a size") - } + }, } } } diff --git a/font/src/lib.rs b/font/src/lib.rs index 8762c0b1..f23d0a0f 100644 --- a/font/src/lib.rs +++ b/font/src/lib.rs @@ -46,8 +46,8 @@ extern crate foreign_types; extern crate log; use std::hash::{Hash, Hasher}; -use std::{fmt, cmp}; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::{cmp, fmt}; // If target isn't macos or windows, reexport everything from ft #[cfg(not(any(target_os = "macos", windows)))] @@ -113,7 +113,7 @@ impl fmt::Display for Style { Style::Specific(ref s) => f.write_str(&s), Style::Description { slant, weight } => { write!(f, "slant={:?}, weight={:?}", slant, weight) - } + }, } } } @@ -123,10 +123,7 @@ impl FontDesc { where S: Into<String>, { - FontDesc { - name: name.into(), - style, - } + FontDesc { name: name.into(), style } } } @@ -149,9 +146,7 @@ impl FontKey { pub fn next() -> FontKey { static TOKEN: AtomicUsize = AtomicUsize::new(0); - FontKey { - token: TOKEN.fetch_add(1, Ordering::SeqCst) as _, - } + FontKey { token: TOKEN.fetch_add(1, Ordering::SeqCst) as _ } } } @@ -170,7 +165,8 @@ impl Hash for GlyphKey { // - If GlyphKey ever becomes a different size, this will fail to compile // - Result is being used for hashing and has no fields (it's a u64) ::std::mem::transmute::<GlyphKey, u64>(*self) - }.hash(state); + } + .hash(state); } } @@ -228,14 +224,7 @@ pub struct RasterizedGlyph { impl Default for RasterizedGlyph { fn default() -> RasterizedGlyph { - RasterizedGlyph { - c: ' ', - width: 0, - height: 0, - top: 0, - left: 0, - buf: Vec::new(), - } + RasterizedGlyph { c: ' ', width: 0, height: 0, top: 0, left: 0, buf: Vec::new() } } } @@ -288,8 +277,11 @@ pub fn get_box_cursor_glyph( let mut buf = Vec::with_capacity((width * height * 3) as usize); for y in 0..height { for x in 0..width { - if y < border_width || y >= height - border_width || - x < border_width || x >= width - border_width { + if y < border_width + || y >= height - border_width + || x < border_width + || x >= width - border_width + { buf.append(&mut vec![255u8; 3]); } else { buf.append(&mut vec![0u8; 3]); @@ -298,24 +290,14 @@ pub fn get_box_cursor_glyph( } // Create a custom glyph with the rectangle data attached to it - Ok(RasterizedGlyph { - c: BOX_CURSOR_CHAR, - top: ascent, - left: 0, - height, - width, - buf, - }) + Ok(RasterizedGlyph { c: BOX_CURSOR_CHAR, top: ascent, left: 0, height, width, buf }) } struct BufDebugger<'a>(&'a [u8]); impl<'a> fmt::Debug for BufDebugger<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("GlyphBuffer") - .field("len", &self.0.len()) - .field("bytes", &self.0) - .finish() + f.debug_struct("GlyphBuffer").field("len", &self.0.len()).field("bytes", &self.0).finish() } } diff --git a/font/src/rusttype/mod.rs b/font/src/rusttype/mod.rs index e8e0bd2c..be39ecc9 100644 --- a/font/src/rusttype/mod.rs +++ b/font/src/rusttype/mod.rs @@ -15,10 +15,7 @@ impl crate::Rasterize for RustTypeRasterizer { type Err = Error; fn new(device_pixel_ratio: f32, _: bool) -> Result<RustTypeRasterizer, Error> { - Ok(RustTypeRasterizer { - fonts: Vec::new(), - dpi_ratio: device_pixel_ratio, - }) + Ok(RustTypeRasterizer { fonts: Vec::new(), dpi_ratio: device_pixel_ratio }) } fn metrics(&self, key: FontKey, size: Size) -> Result<Metrics, Error> { @@ -56,17 +53,13 @@ impl crate::Rasterize for RustTypeRasterizer { } fn load_font(&mut self, desc: &FontDesc, _size: Size) -> Result<FontKey, Error> { - let fp = system_fonts::FontPropertyBuilder::new() - .family(&desc.name) - .monospace(); + let fp = system_fonts::FontPropertyBuilder::new().family(&desc.name).monospace(); let fp = match desc.style { - Style::Specific(ref style) => { - match style.to_lowercase().as_str() { - "italic" => fp.italic(), - "bold" => fp.bold(), - _ => fp, - } + Style::Specific(ref style) => match style.to_lowercase().as_str() { + "italic" => fp.italic(), + "bold" => fp.bold(), + _ => fp, }, Style::Description { slant, weight } => { let fp = match slant { @@ -79,52 +72,52 @@ impl crate::Rasterize for RustTypeRasterizer { Weight::Bold => fp.bold(), Weight::Normal => fp, } - } + }, }; - self.fonts.push(FontCollection::from_bytes( - system_fonts::get(&fp.build()) - .ok_or_else(|| Error::MissingFont(desc.clone()))? - .0, - ).into_font() - .ok_or(Error::UnsupportedFont)?); - Ok(FontKey { - token: (self.fonts.len() - 1) as u16, - }) + self.fonts.push( + FontCollection::from_bytes( + system_fonts::get(&fp.build()).ok_or_else(|| Error::MissingFont(desc.clone()))?.0, + ) + .into_font() + .ok_or(Error::UnsupportedFont)?, + ); + Ok(FontKey { token: (self.fonts.len() - 1) as u16 }) } fn get_glyph(&mut self, glyph_key: GlyphKey) -> Result<RasterizedGlyph, Error> { match glyph_key.c { super::UNDERLINE_CURSOR_CHAR => { let metrics = self.metrics(glyph_key.font_key, glyph_key.size)?; - return super::get_underline_cursor_glyph(metrics.descent as i32, metrics.average_advance as i32); - } + return super::get_underline_cursor_glyph( + metrics.descent as i32, + metrics.average_advance as i32, + ); + }, super::BEAM_CURSOR_CHAR => { let metrics = self.metrics(glyph_key.font_key, glyph_key.size)?; return super::get_beam_cursor_glyph( (metrics.line_height + f64::from(metrics.descent)).round() as i32, metrics.line_height.round() as i32, - metrics.average_advance.round() as i32 + metrics.average_advance.round() as i32, ); - } + }, super::BOX_CURSOR_CHAR => { let metrics = self.metrics(glyph_key.font_key, glyph_key.size)?; return super::get_box_cursor_glyph( (metrics.line_height + f64::from(metrics.descent)).round() as i32, metrics.line_height.round() as i32, - metrics.average_advance.round() as i32 + metrics.average_advance.round() as i32, ); - } - _ => () + }, + _ => (), } let scaled_glyph = self.fonts[glyph_key.font_key.token as usize] .glyph(glyph_key.c) .ok_or(Error::MissingGlyph)? - .scaled(Scale::uniform( - glyph_key.size.as_f32_pts() * self.dpi_ratio * 96. / 72., - )); + .scaled(Scale::uniform(glyph_key.size.as_f32_pts() * self.dpi_ratio * 96. / 72.)); let glyph = scaled_glyph.positioned(point(0.0, 0.0)); @@ -132,10 +125,7 @@ impl crate::Rasterize for RustTypeRasterizer { let bb = match glyph.pixel_bounding_box() { Some(bb) => bb, // Bounding box calculation fails for spaces so we provide a placeholder bounding box - None => rusttype::Rect { - min: point(0, 0), - max: point(0, 0), - }, + None => rusttype::Rect { min: point(0, 0), max: point(0, 0) }, }; let mut buf = Vec::with_capacity((bb.width() * bb.height()) as usize); @@ -185,8 +175,8 @@ impl ::std::fmt::Display for Error { match *self { Error::MissingFont(ref desc) => write!( f, - "Couldn't find a font with {}\ - \n\tPlease check the font config in your alacritty.yml.", + "Couldn't find a font with {}\n\tPlease check the font config in your \ + alacritty.yml.", desc ), Error::UnsupportedFont => write!( @@ -195,7 +185,7 @@ impl ::std::fmt::Display for Error { ), Error::UnsupportedStyle => { write!(f, "The selected font style is not supported by rusttype.") - } + }, Error::MissingGlyph => write!(f, "The selected font did not have the requested glyph."), } } |