diff options
Diffstat (limited to 'font')
-rw-r--r-- | font/src/darwin/byte_order.rs | 2 | ||||
-rw-r--r-- | font/src/darwin/mod.rs | 78 | ||||
-rw-r--r-- | font/src/directwrite/mod.rs | 12 | ||||
-rw-r--r-- | font/src/ft/fc/char_set.rs | 2 | ||||
-rw-r--r-- | font/src/ft/fc/config.rs | 2 | ||||
-rw-r--r-- | font/src/ft/fc/font_set.rs | 4 | ||||
-rw-r--r-- | font/src/ft/fc/mod.rs | 12 | ||||
-rw-r--r-- | font/src/ft/fc/pattern.rs | 34 | ||||
-rw-r--r-- | font/src/ft/mod.rs | 79 | ||||
-rw-r--r-- | font/src/lib.rs | 36 |
10 files changed, 131 insertions, 130 deletions
diff --git a/font/src/darwin/byte_order.rs b/font/src/darwin/byte_order.rs index 1574cf19..aac215cf 100644 --- a/font/src/darwin/byte_order.rs +++ b/font/src/darwin/byte_order.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//! Constants for bitmap byte order +//! Constants for bitmap byte order. #![allow(non_upper_case_globals)] pub const kCGBitmapByteOrder32Little: u32 = 2 << 12; pub const kCGBitmapByteOrder32Big: u32 = 4 << 12; diff --git a/font/src/darwin/mod.rs b/font/src/darwin/mod.rs index b9266a84..250805d3 100644 --- a/font/src/darwin/mod.rs +++ b/font/src/darwin/mod.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//! Font rendering based on CoreText +//! Font rendering based on CoreText. #![allow(improper_ctypes)] use std::collections::HashMap; use std::path::PathBuf; @@ -49,7 +49,7 @@ use super::{ BitmapBuffer, FontDesc, FontKey, GlyphKey, Metrics, RasterizedGlyph, Size, Slant, Style, Weight, }; -/// Font descriptor +/// Font descriptor. /// /// The descriptor provides data about a font and supports creating a font. #[derive(Debug)] @@ -76,7 +76,7 @@ impl Descriptor { } } -/// Rasterizer, the main type exported by this package +/// Rasterizer, the main type exported by this package. /// /// Given a fontdesc, can rasterize fonts. pub struct Rasterizer { @@ -86,16 +86,16 @@ pub struct Rasterizer { use_thin_strokes: bool, } -/// Errors occurring when using the core text rasterizer +/// Errors occurring when using the core text rasterizer. #[derive(Debug)] pub enum Error { - /// Tried to rasterize a glyph but it was not available + /// Tried to rasterize a glyph but it was not available. MissingGlyph(char), - /// Couldn't find font matching description + /// Couldn't find font matching description. MissingFont(FontDesc), - /// Requested an operation with a FontKey that isn't known to the rasterizer + /// Requested an operation with a FontKey that isn't known to the rasterizer. FontNotLoaded, } @@ -136,7 +136,7 @@ impl crate::Rasterize for Rasterizer { }) } - /// Get metrics for font specified by FontKey + /// 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)?; @@ -156,21 +156,21 @@ impl crate::Rasterize for Rasterizer { }) } - /// Get rasterized glyph for given glyph key + /// Get rasterized glyph for given glyph key. fn get_glyph(&mut self, glyph: GlyphKey) -> Result<RasterizedGlyph, Error> { - // get loaded font + // Get loaded font. let font = self.fonts.get(&glyph.font_key).ok_or(Error::FontNotLoaded)?; - // first try the font itself as a direct hit + // First try the font itself as a direct hit. self.maybe_get_glyph(glyph, font).unwrap_or_else(|| { - // then try fallbacks + // Then try fallbacks. for fallback in &font.fallbacks { if let Some(result) = self.maybe_get_glyph(glyph, &fallback) { - // found a fallback + // found a fallback. return result; } } - // no fallback, give up. + // No fallback, give up. Err(Error::MissingGlyph(glyph.c)) }) } @@ -190,7 +190,7 @@ impl Rasterizer { let descriptors = descriptors_for_family(&desc.name[..]); for descriptor in descriptors { if descriptor.style_name == style { - // Found the font we want + // Found the font we want. let scaled_size = f64::from(size.as_f32_pts()) * f64::from(self.device_pixel_ratio); let font = descriptor.to_font(scaled_size, true); return Ok(font); @@ -221,7 +221,7 @@ impl Rasterizer { for descriptor in descriptors { let font = descriptor.to_font(scaled_size, true); if font.is_bold() == bold && font.is_italic() == italic { - // Found the font we want + // Found the font we want. return Ok(font); } } @@ -238,7 +238,7 @@ impl Rasterizer { } } - // Helper to try and get a glyph for a given font. Used for font fallback. + /// Helper to try and get a glyph for a given font. Used for font fallback. fn maybe_get_glyph( &self, glyph: GlyphKey, @@ -254,7 +254,7 @@ impl Rasterizer { } } -/// Specifies the intended rendering orientation of the font for obtaining glyph metrics +/// Specifies the intended rendering orientation of the font for obtaining glyph metrics. #[derive(Debug)] pub enum FontOrientation { Default = kCTFontDefaultOrientation as isize, @@ -268,7 +268,7 @@ impl Default for FontOrientation { } } -/// A font +/// A font. #[derive(Clone)] pub struct Font { ct_font: CTFont, @@ -278,9 +278,9 @@ pub struct Font { unsafe impl Send for Font {} -/// List all family names +/// List all family names. pub fn get_family_names() -> Vec<String> { - // CFArray of CFStringRef + // CFArray of CFStringRef. let names = ct_get_family_names(); let mut owned_names = Vec::new(); @@ -291,23 +291,23 @@ pub fn get_family_names() -> Vec<String> { owned_names } -/// Return fallback descriptors for font/language list +/// Return fallback descriptors for font/language list. fn cascade_list_for_languages(ct_font: &CTFont, languages: &[String]) -> Vec<Descriptor> { - // convert language type &Vec<String> -> CFArray + // Convert language type &Vec<String> -> CFArray. let langarr: CFArray<CFString> = { let tmp: Vec<CFString> = languages.iter().map(|language| CFString::new(&language)).collect(); CFArray::from_CFTypes(&tmp) }; - // CFArray of CTFontDescriptorRef (again) + // CFArray of CTFontDescriptorRef (again). let list = ct_cascade_list_for_languages(ct_font, &langarr); - // convert CFArray to Vec<Descriptor> + // Convert CFArray to Vec<Descriptor>. list.into_iter().map(|fontdesc| Descriptor::new(fontdesc.clone())).collect() } -/// Get descriptors for family name +/// Get descriptors for family name. pub fn descriptors_for_family(family: &str) -> Vec<Descriptor> { let mut out = Vec::new(); @@ -318,7 +318,7 @@ pub fn descriptors_for_family(family: &str) -> Vec<Descriptor> { create_for_family("Menlo").expect("Menlo exists") }); - // CFArray of CTFontDescriptorRef (i think) + // CFArray of CTFontDescriptorRef (i think). let descriptors = ct_collection.get_descriptors(); if let Some(descriptors) = descriptors { for descriptor in descriptors.iter() { @@ -330,7 +330,7 @@ pub fn descriptors_for_family(family: &str) -> Vec<Descriptor> { } impl Descriptor { - /// Create a Font from this descriptor + /// Create a Font from this descriptor. 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(); @@ -342,7 +342,7 @@ impl Descriptor { .map(|descriptor| { let menlo = ct_new_from_descriptor(&descriptor.ct_descriptor, size); - // TODO fixme, hardcoded en for english + // TODO fixme, hardcoded en for english. let mut fallbacks = cascade_list_for_languages(&menlo, &["en".to_owned()]) .into_iter() .filter(|desc| !desc.font_path.as_os_str().is_empty()) @@ -361,7 +361,7 @@ impl Descriptor { fallbacks.push(descriptor.to_font(size, false)) }; - // Include Menlo in the fallback list as well + // Include Menlo in the fallback list as well. fallbacks.insert(0, Font { cg_font: menlo.copy_to_CGFont(), ct_font: menlo, @@ -380,7 +380,7 @@ impl Descriptor { } impl Font { - /// The the bounding rect of a glyph + /// The the bounding rect of a glyph. pub fn bounding_rect_for_glyph( &self, orientation: FontOrientation, @@ -488,7 +488,7 @@ impl Font { kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, ); - // Give the context an opaque, black background + // 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), @@ -510,7 +510,7 @@ impl Font { cg_context.set_allows_antialiasing(true); cg_context.set_should_antialias(true); - // Set fill color to white for drawing the glyph + // 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) }; @@ -540,15 +540,15 @@ impl Font { } fn glyph_index(&self, character: char) -> Option<u32> { - // encode this char as utf-16 + // Encode this char as utf-16. let mut buf = [0; 2]; let encoded: &[u16] = character.encode_utf16(&mut buf); - // and use the utf-16 buffer to get the index + // And use the utf-16 buffer to get the index. self.glyph_index_utf16(encoded) } fn glyph_index_utf16(&self, encoded: &[u16]) -> Option<u32> { - // output buffer for the glyph. for non-BMP glyphs, like + // 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]; @@ -586,11 +586,11 @@ mod tests { assert!(!list.is_empty()); println!("{:?}", list); - // Check to_font + // Check to_font. let fonts = list.iter().map(|desc| desc.to_font(72., false)).collect::<Vec<_>>(); for font in fonts { - // Get a glyph + // Get a glyph. for c in &['a', 'b', 'c', 'd'] { let glyph = font.get_glyph(*c, 72., false).unwrap(); @@ -599,7 +599,7 @@ mod tests { BitmapBuffer::RGBA(buf) => buf, }; - // Debug the glyph.. sigh + // Debug the glyph.. sigh. for row in 0..glyph.height { for col in 0..glyph.width { let index = ((glyph.width * 3 * row) + (col * 3)) as usize; diff --git a/font/src/directwrite/mod.rs b/font/src/directwrite/mod.rs index ccb43b33..ab39814b 100644 --- a/font/src/directwrite/mod.rs +++ b/font/src/directwrite/mod.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//! Rasterization powered by DirectWrite +//! Rasterization powered by DirectWrite. use std::borrow::Cow; use std::collections::HashMap; use std::ffi::OsString; @@ -114,7 +114,7 @@ impl DirectWriteRasterizer { let idx = *face .get_glyph_indices(&[c as u32]) .first() - // DirectWrite returns 0 if the glyph does not exist in the font + // DirectWrite returns 0 if the glyph does not exist in the font. .filter(|glyph_index| **glyph_index != 0) .ok_or_else(|| Error::MissingGlyph(c))?; @@ -184,7 +184,7 @@ impl crate::Rasterize for DirectWriteRasterizer { let line_height = f64::from(ascent - descent + line_gap); - // Since all monospace characters have the same width, we use `!` for horizontal metrics + // Since all monospace characters have the same width, we use `!` for horizontal metrics. let c = '!'; let glyph_index = self.get_glyph_index(face, c)?; @@ -205,7 +205,7 @@ impl crate::Rasterize for DirectWriteRasterizer { } fn load_font(&mut self, desc: &FontDesc, _size: Size) -> Result<FontKey, Error> { - // Fast path if face is already loaded + // Fast path if face is already loaded. if let Some(key) = self.keys.get(desc) { return Ok(*key); } @@ -218,7 +218,7 @@ impl crate::Rasterize for DirectWriteRasterizer { let font = match desc.style { Style::Description { weight, slant } => { // This searches for the "best" font - should mean we don't have to worry about - // fallbacks if our exact desired weight/style isn't available + // fallbacks if our exact desired weight/style isn't available. Ok(family.get_first_matching_font(weight.into(), FontStretch::Normal, slant.into())) }, Style::Specific(ref style) => { @@ -332,7 +332,7 @@ fn get_current_locale() -> String { let mut buf = vec![0u16; LOCALE_NAME_MAX_LENGTH]; let len = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as i32) as usize }; - // `len` includes null byte, which we don't need in Rust + // `len` includes null byte, which we don't need in Rust. OsString::from_wide(&buf[..len - 1]).into_string().expect("Locale not valid unicode") } diff --git a/font/src/ft/fc/char_set.rs b/font/src/ft/fc/char_set.rs index 4bba4818..a60513c2 100644 --- a/font/src/ft/fc/char_set.rs +++ b/font/src/ft/fc/char_set.rs @@ -70,7 +70,7 @@ impl CharSetRef { pub fn merge(&self, other: &CharSetRef) -> Result<bool, ()> { unsafe { - // Value is just an indicator whether something was added or not + // Value is just an indicator whether something was added or not. let mut value: FcBool = 0; let res = FcCharSetMerge(self.as_ptr() as _, other.as_ptr() as _, &mut value); if res == 0 { diff --git a/font/src/ft/fc/config.rs b/font/src/ft/fc/config.rs index 44bb9986..868d2c42 100644 --- a/font/src/ft/fc/config.rs +++ b/font/src/ft/fc/config.rs @@ -24,7 +24,7 @@ foreign_type! { } impl Config { - /// Get the current configuration + /// Get the current configuration. pub fn get_current() -> &'static ConfigRef { unsafe { ConfigRef::from_ptr(FcConfigGetCurrent()) } } diff --git a/font/src/ft/fc/font_set.rs b/font/src/ft/fc/font_set.rs index ae746f45..241ee344 100644 --- a/font/src/ft/fc/font_set.rs +++ b/font/src/ft/fc/font_set.rs @@ -39,7 +39,7 @@ impl FontSet { FcFontSetList( config.as_ptr(), &mut source.as_ptr(), - 1, // nsets + 1, // nsets. pattern.as_ptr(), objects.as_ptr(), ) @@ -48,7 +48,7 @@ impl FontSet { } } -/// Iterator over a font set +/// Iterator over a font set. pub struct Iter<'a> { font_set: &'a FontSetRef, num_fonts: usize, diff --git a/font/src/ft/fc/mod.rs b/font/src/ft/fc/mod.rs index ecb056f7..b1b66be6 100644 --- a/font/src/ft/fc/mod.rs +++ b/font/src/ft/fc/mod.rs @@ -72,7 +72,7 @@ pub fn font_sort(config: &ConfigRef, pattern: &PatternRef) -> Option<FontSet> { let ptr = FcFontSort( config.as_ptr(), pattern.as_ptr(), - 1, // Trim font list + 1, // Trim font list. &mut charsets, &mut result, ); @@ -102,14 +102,14 @@ pub fn font_list( } } -/// Available font sets +/// Available font sets. #[derive(Debug, Copy, Clone)] pub enum SetName { System = FcSetSystem as isize, Application = FcSetApplication as isize, } -/// When matching, how to match +/// When matching, how to match. #[derive(Debug, Copy, Clone)] pub enum MatchKind { Font = FcMatchFont as isize, @@ -187,7 +187,7 @@ impl From<isize> for Width { } } -/// Subpixel geometry +/// Subpixel geometry. #[derive(Debug)] pub enum Rgba { Unknown, @@ -237,7 +237,7 @@ impl From<isize> for Rgba { } } -/// Hinting Style +/// Hinting Style. #[derive(Debug, Copy, Clone)] pub enum HintStyle { None, @@ -257,7 +257,7 @@ impl fmt::Display for HintStyle { } } -/// Lcd filter, used to reduce color fringing with subpixel rendering +/// Lcd filter, used to reduce color fringing with subpixel rendering. pub enum LcdFilter { None, Default, diff --git a/font/src/ft/fc/pattern.rs b/font/src/ft/fc/pattern.rs index 53641f67..f40cc9c9 100644 --- a/font/src/ft/fc/pattern.rs +++ b/font/src/ft/fc/pattern.rs @@ -54,7 +54,7 @@ impl<'a> StringPropertyIter<'a> { }; if result == FcResultMatch { - // Transmute here is to extend lifetime of the str to that of the iterator + // Transmute here is to extend lifetime of the str to that of the iterator. // // Potential unsafety? What happens if the pattern is modified while this ptr is // borrowed out? @@ -67,7 +67,7 @@ impl<'a> StringPropertyIter<'a> { } } -/// Iterator over integer properties +/// Iterator over integer properties. pub struct BooleanPropertyIter<'a> { pattern: &'a PatternRef, object: &'a [u8], @@ -99,7 +99,7 @@ impl<'a> BooleanPropertyIter<'a> { } } -/// Iterator over integer properties +/// Iterator over integer properties. pub struct IntPropertyIter<'a> { pattern: &'a PatternRef, object: &'a [u8], @@ -204,7 +204,7 @@ impl<'a> LcdFilterPropertyIter<'a> { } } -/// Iterator over integer properties +/// Iterator over integer properties. pub struct DoublePropertyIter<'a> { pattern: &'a PatternRef, object: &'a [u8], @@ -236,7 +236,7 @@ impl<'a> DoublePropertyIter<'a> { } } -/// Implement debug for a property iterator +/// Implement debug for a property iterator. macro_rules! impl_property_iter_debug { ($iter:ty => $item:ty) => { impl<'a> fmt::Debug for $iter { @@ -260,7 +260,7 @@ macro_rules! impl_property_iter_debug { }; } -/// Implement Iterator and Debug for a property iterator +/// Implement Iterator and Debug for a property iterator. macro_rules! impl_property_iter { ($($iter:ty => $item:ty),*) => { $( @@ -310,7 +310,7 @@ macro_rules! impl_derived_property_iter { } } -// Basic Iterators +// Basic Iterators. impl_property_iter! { StringPropertyIter<'a> => &'a str, IntPropertyIter<'a> => isize, @@ -318,7 +318,7 @@ impl_property_iter! { BooleanPropertyIter<'a> => bool } -// Derived Iterators +// Derived Iterators. impl_derived_property_iter! { RgbaPropertyIter<'a> => Rgba, HintStylePropertyIter<'a> => HintStyle, @@ -460,23 +460,23 @@ impl PatternRef { 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. + /// 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()) } } - /// Add a string value to the pattern + /// Add a string value to the pattern. /// /// If the returned value is `true`, the value is added at the end of /// any existing list, otherwise it is inserted at the beginning. /// /// # Unsafety /// - /// `object` is not checked to be a valid null-terminated string + /// `object` is not checked to be a valid null-terminated string. unsafe fn add_string(&mut self, object: &[u8], value: &str) -> bool { let value = CString::new(&value[..]).unwrap(); let value = value.as_ptr(); @@ -556,9 +556,9 @@ impl PatternRef { unsafe { PatternHash(FcPatternHash(self.as_ptr())) } } - /// Add charset to the pattern + /// Add charset to the pattern. /// - /// The referenced charset is copied by fontconfig internally using + /// The referenced charset is copied by Fontconfig internally using /// FcValueSave so that no references to application provided memory are /// retained. That is, the CharSet can be safely dropped immediately /// after being added to the pattern. diff --git a/font/src/ft/mod.rs b/font/src/ft/mod.rs index d393b63f..ef1afb5f 100644 --- a/font/src/ft/mod.rs +++ b/font/src/ft/mod.rs @@ -46,7 +46,7 @@ impl FallbackFont { impl FontKey { fn from_pattern_hashes(lhs: PatternHash, rhs: PatternHash) -> Self { - // XOR two hashes to get a font ID + // XOR two hashes to get a font ID. Self { token: lhs.0.rotate_left(1) ^ rhs.0 } } } @@ -121,18 +121,18 @@ impl Rasterize for FreeTypeRasterizer { let height = (full.size_metrics.height / 64) as f64; let descent = (full.size_metrics.descender / 64) as f32; - // Get underline position and thickness in device pixels + // Get underline position and thickness in device pixels. let x_scale = full.size_metrics.x_scale as f32 / 65536.0; let mut underline_position = f32::from(face.ft_face.underline_position()) * x_scale / 64.; let mut underline_thickness = f32::from(face.ft_face.underline_thickness()) * x_scale / 64.; - // Fallback for bitmap fonts which do not provide underline metrics + // Fallback for bitmap fonts which do not provide underline metrics. if underline_position == 0. { underline_thickness = (descent.abs() / 5.).round(); underline_position = descent / 2.; } - // Get strikeout position and thickness in device pixels + // Get strikeout position and thickness in device pixels. let (strikeout_position, strikeout_thickness) = match TrueTypeOS2Table::from_face(&mut (*face.ft_face).clone()) { Some(os2) => { @@ -141,7 +141,7 @@ impl Rasterize for FreeTypeRasterizer { (strikeout_position, strikeout_thickness) }, _ => { - // Fallback if font doesn't provide info about strikeout + // 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) @@ -206,9 +206,9 @@ struct FullMetrics { } impl FreeTypeRasterizer { - /// Load a font face according to `FontDesc` + /// Load a font face according to `FontDesc`. fn get_face(&mut self, desc: &FontDesc, size: Size) -> Result<FontKey, Error> { - // Adjust for DPI + // Adjust for DPR. let size = f64::from(size.as_f32_pts() * self.device_pixel_ratio * 96. / 72.); let config = fc::Config::get_current(); @@ -216,26 +216,26 @@ impl FreeTypeRasterizer { pattern.add_family(&desc.name); pattern.add_pixelsize(size); - // Add style to a pattern + // Add style to a pattern. match desc.style { Style::Description { slant, weight } => { - // Match nearest font + // Match nearest font. pattern.set_weight(weight.into_fontconfig_type()); pattern.set_slant(slant.into_fontconfig_type()); }, Style::Specific(ref style) => { - // If a name was specified, try and load specifically that font + // If a name was specified, try and load specifically that font. pattern.add_style(style); }, } - // Hash requested pattern + // Hash requested pattern. let hash = pattern.hash(); pattern.config_substitute(config, fc::MatchKind::Pattern); pattern.default_substitute(); - // Get font list using pattern. First font is the primary one while the rest are fallbacks + // Get font list using pattern. First font is the primary one while the rest are fallbacks. let matched_fonts = fc::font_sort(&config, &pattern).ok_or_else(|| Error::MissingFont(desc.to_owned()))?; let mut matched_fonts = matched_fonts.into_iter(); @@ -243,24 +243,24 @@ impl FreeTypeRasterizer { let primary_font = matched_fonts.next().ok_or_else(|| Error::MissingFont(desc.to_owned()))?; - // We should render patterns to get values like `pixelsizefixupfactor` + // We should render patterns to get values like `pixelsizefixupfactor`. let primary_font = pattern.render_prepare(config, primary_font); - // Hash pattern together with request pattern to include requested font size in the hash + // Hash pattern together with request pattern to include requested font size in the hash. let primary_font_key = FontKey::from_pattern_hashes(hash, primary_font.hash()); - // Return if we already have the same primary font + // Return if we already have the same primary font. if self.fallback_lists.contains_key(&primary_font_key) { return Ok(primary_font_key); } - // Load font if we haven't loaded it yet + // Load font if we haven't loaded it yet. if !self.faces.contains_key(&primary_font_key) { self.face_from_pattern(&primary_font, primary_font_key) .and_then(|pattern| pattern.ok_or_else(|| Error::MissingFont(desc.to_owned())))?; } - // Coverage for fallback fonts + // Coverage for fallback fonts. let coverage = CharSet::new(); let empty_charset = CharSet::new(); @@ -268,7 +268,7 @@ impl FreeTypeRasterizer { .map(|fallback_font| { let charset = fallback_font.get_charset().unwrap_or(&empty_charset); - // Use original pattern to preserve loading flags + // Use original pattern to preserve loading flags. let fallback_font = pattern.render_prepare(config, fallback_font); let fallback_font_key = FontKey::from_pattern_hashes(hash, fallback_font.hash()); @@ -299,7 +299,7 @@ impl FreeTypeRasterizer { let mut ft_face = self.library.new_face(&ft_face_location.path, ft_face_location.index)?; if ft_face.has_color() { unsafe { - // Select the colored bitmap size to use from the array of available sizes + // Select the colored bitmap size to use from the array of available sizes. freetype_sys::FT_Select_Size(ft_face.raw_mut(), 0); } } @@ -370,7 +370,7 @@ impl FreeTypeRasterizer { fn load_face_with_glyph(&mut self, glyph: GlyphKey) -> Result<FontKey, Error> { let fallback_list = self.fallback_lists.get(&glyph.font_key).unwrap(); - // Check whether glyph is presented in any fallback font + // Check whether glyph is presented in any fallback font. if !fallback_list.coverage.has_char(glyph.c) { return Ok(glyph.font_key); } @@ -382,7 +382,7 @@ impl FreeTypeRasterizer { Some(face) => { let index = face.ft_face.get_char_index(glyph.c as usize); - // We found something in a current face, so let's use it + // We found something in a current face, so let's use it. if index != 0 { return Ok(font_key); } @@ -400,12 +400,12 @@ impl FreeTypeRasterizer { } } - // You can hit this return, if you're failing to get charset from a pattern + // You can hit this return, if you're failing to get charset from a pattern. Ok(glyph.font_key) } fn get_rendered_glyph(&mut self, glyph_key: GlyphKey) -> Result<RasterizedGlyph, Error> { - // Render a normal character if it's not a cursor + // Render a normal character if it's not a cursor. let font_key = self.face_for_glyph(glyph_key)?; let face = &self.faces[&font_key]; let index = face.ft_face.get_char_index(glyph_key.c as usize); @@ -442,7 +442,7 @@ impl FreeTypeRasterizer { let fixup_factor = if let Some(pixelsize_fixup_factor) = face.pixelsize_fixup_factor { pixelsize_fixup_factor } else { - // Fallback if user has bitmap scaling disabled + // Fallback if user has bitmap scaling disabled. let metrics = face.ft_face.size_metrics().ok_or(Error::MissingSizeMetrics)?; f64::from(pixelsize) / f64::from(metrics.y_ppem) }; @@ -465,7 +465,7 @@ impl FreeTypeRasterizer { (false, fc::HintStyle::None, _) => LoadFlag::NO_HINTING | 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 + // `hintslight` does *not* use LCD hinting even when a subpixel mode // is selected. // // According to the FreeType docs, @@ -478,7 +478,7 @@ impl FreeTypeRasterizer { // In practice, this means we can have `FT_LOAD_TARGET_LIGHT` with // subpixel render modes like `FT_RENDER_MODE_LCD`. Libraries like // cairo take the same approach and consider `hintslight` to always - // prefer `FT_LOAD_TARGET_LIGHT` + // prefer `FT_LOAD_TARGET_LIGHT`. (true, fc::HintStyle::Slight, _) => LoadFlag::TARGET_LIGHT, // If LCD hinting is to be used, must select hintmedium or hintfull, // have AA enabled, and select a subpixel mode. @@ -565,7 +565,7 @@ impl FreeTypeRasterizer { while count != 0 { let value = ((byte >> bit) & 1) * 255; // Push value 3x since result buffer should be 1 byte - // per channel + // per channel. res.push(value); res.push(value); res.push(value); @@ -623,7 +623,7 @@ impl FreeTypeRasterizer { /// This will take the `bitmap_glyph` as input and return the glyph's content downscaled by /// `fixup_factor`. fn downsample_bitmap(mut bitmap_glyph: RasterizedGlyph, fixup_factor: f64) -> RasterizedGlyph { - // Only scale colored buffers which are bigger than required + // Only scale colored buffers which are bigger than required. let bitmap_buffer = match (&bitmap_glyph.buf, fixup_factor.partial_cmp(&1.0)) { (BitmapBuffer::RGBA(buffer), Some(Ordering::Less)) => buffer, _ => return bitmap_glyph, @@ -635,19 +635,20 @@ fn downsample_bitmap(mut bitmap_glyph: RasterizedGlyph, fixup_factor: f64) -> Ra let target_width = (bitmap_width as f64 * fixup_factor) as usize; let target_height = (bitmap_height as f64 * fixup_factor) as usize; - // Number of pixels in the input buffer, per pixel in the output buffer + // Number of pixels in the input buffer, per pixel in the output buffer. let downsampling_step = 1.0 / fixup_factor; let mut downsampled_buffer = Vec::<u8>::with_capacity(target_width * target_height * 4); for line_index in 0..target_height { - // Get the first and last line which will be consolidated in the current output pixel + // Get the first and last line which will be consolidated in the current output pixel. let line_index = line_index as f64; let source_line_start = (line_index * downsampling_step).round() as usize; let source_line_end = ((line_index + 1.) * downsampling_step).round() as usize; for column_index in 0..target_width { - // Get the first and last column which will be consolidated in the current output pixel + // Get the first and last column which will be consolidated in the current output + // pixel. let column_index = column_index as f64; let source_column_start = (column_index * downsampling_step).round() as usize; let source_column_end = ((column_index + 1.) * downsampling_step).round() as usize; @@ -655,7 +656,7 @@ fn downsample_bitmap(mut bitmap_glyph: RasterizedGlyph, fixup_factor: f64) -> Ra let (mut r, mut g, mut b, mut a) = (0u32, 0u32, 0u32, 0u32); let mut pixels_picked: u32 = 0; - // Consolidate all pixels within the source rectangle into a single averaged pixel + // Consolidate all pixels within the source rectangle into a single averaged pixel. for source_line in source_line_start..source_line_end { let source_pixel_index = source_line * bitmap_width; @@ -669,7 +670,7 @@ fn downsample_bitmap(mut bitmap_glyph: RasterizedGlyph, fixup_factor: f64) -> Ra } } - // Add a single pixel to the output buffer for the downscaled source rectangle + // Add a single pixel to the output buffer for the downscaled source rectangle. downsampled_buffer.push((r / pixels_picked) as u8); downsampled_buffer.push((g / pixels_picked) as u8); downsampled_buffer.push((b / pixels_picked) as u8); @@ -679,7 +680,7 @@ fn downsample_bitmap(mut bitmap_glyph: RasterizedGlyph, fixup_factor: f64) -> Ra bitmap_glyph.buf = BitmapBuffer::RGBA(downsampled_buffer); - // Downscale the metrics + // Downscale the metrics. bitmap_glyph.top = (f64::from(bitmap_glyph.top) * fixup_factor) as i32; bitmap_glyph.left = (f64::from(bitmap_glyph.left) * fixup_factor) as i32; bitmap_glyph.width = target_width as i32; @@ -688,19 +689,19 @@ fn downsample_bitmap(mut bitmap_glyph: RasterizedGlyph, fixup_factor: f64) -> Ra bitmap_glyph } -/// Errors occurring when using the freetype rasterizer +/// Errors occurring when using the freetype rasterizer. #[derive(Debug)] pub enum Error { - /// Error occurred within the FreeType library + /// Error occurred within the FreeType library. FreeType(freetype::Error), - /// Couldn't find font matching description + /// Couldn't find font matching description. MissingFont(FontDesc), - /// Tried to get size metrics from a Face that didn't have a size + /// Tried to get size metrics from a Face that didn't have a size. MissingSizeMetrics, - /// Requested an operation with a FontKey that isn't known to the rasterizer + /// Requested an operation with a FontKey that isn't known to the rasterizer. FontNotLoaded, } diff --git a/font/src/lib.rs b/font/src/lib.rs index 5ed255ad..2a19f620 100644 --- a/font/src/lib.rs +++ b/font/src/lib.rs @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. // -//! Compatibility layer for different font engines +//! Compatibility layer for different font engines. //! //! CoreText is used on Mac OS. //! FreeType is used on everything that's not Mac OS. -//! Eventually, ClearType support will be available for windows +//! Eventually, ClearType support will be available for windows. #![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use, clippy::wrong_pub_self_convention)] @@ -24,7 +24,7 @@ use std::fmt; use std::ops::{Add, Mul}; use std::sync::atomic::{AtomicUsize, Ordering}; -// If target isn't macos or windows, reexport everything from ft +// If target isn't macos or windows, reexport everything from ft. #[cfg(not(any(target_os = "macos", windows)))] pub mod ft; #[cfg(not(any(target_os = "macos", windows)))] @@ -35,7 +35,7 @@ pub mod directwrite; #[cfg(windows)] pub use directwrite::{DirectWriteRasterizer as Rasterizer, Error}; -// If target is macos, reexport everything from darwin +// If target is macos, reexport everything from darwin. #[cfg(target_os = "macos")] mod darwin; #[cfg(target_os = "macos")] @@ -60,7 +60,7 @@ pub enum Weight { Bold, } -/// Style of font +/// Style of font. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Style { Specific(String), @@ -93,16 +93,16 @@ impl fmt::Display for FontDesc { } } -/// Identifier for a Font for use in maps/etc +/// Identifier for a Font for use in maps/etc. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub struct FontKey { token: u32, } impl FontKey { - /// Get next font key for given size + /// Get next font key for given size. /// - /// The generated key will be globally unique + /// The generated key will be globally unique. pub fn next() -> FontKey { static TOKEN: AtomicUsize = AtomicUsize::new(0); @@ -117,23 +117,23 @@ pub struct GlyphKey { pub size: Size, } -/// Font size stored as integer +/// Font size stored as integer. #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct Size(i16); impl Size { - /// Create a new `Size` from a f32 size in points + /// Create a new `Size` from a f32 size in points. pub fn new(size: f32) -> Size { Size((size * Size::factor()) as i16) } - /// Scale factor between font "Size" type and point size + /// Scale factor between font "Size" type and point size. #[inline] pub fn factor() -> f32 { 2.0 } - /// Get the f32 size in points + /// Get the f32 size in points. pub fn as_f32_pts(self) -> f32 { f32::from(self.0) / Size::factor() } @@ -215,23 +215,23 @@ pub struct Metrics { } pub trait Rasterize { - /// Errors occurring in Rasterize methods + /// Errors occurring in Rasterize methods. type Err: ::std::error::Error + Send + Sync + 'static; - /// Create a new Rasterizer + /// Create a new Rasterizer. fn new(device_pixel_ratio: f32, use_thin_strokes: bool) -> Result<Self, Self::Err> where Self: Sized; - /// Get `Metrics` for the given `FontKey` + /// Get `Metrics` for the given `FontKey`. fn metrics(&self, _: FontKey, _: Size) -> Result<Metrics, Self::Err>; - /// Load the font described by `FontDesc` and `Size` + /// Load the font described by `FontDesc` and `Size`. fn load_font(&mut self, _: &FontDesc, _: Size) -> Result<FontKey, Self::Err>; - /// Rasterize the glyph described by `GlyphKey`. + /// Rasterize the glyph described by `GlyphKey`.. fn get_glyph(&mut self, _: GlyphKey) -> Result<RasterizedGlyph, Self::Err>; - /// Update the Rasterizer's DPI factor + /// Update the Rasterizer's DPI factor. fn update_dpr(&mut self, device_pixel_ratio: f32); } |