1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 use api::{ColorU, GlyphDimensions, FontKey, FontRenderMode};
6 use api::{FontInstancePlatformOptions, FontLCDFilter, FontHinting};
7 use api::{FontInstanceFlags, FontVariation, NativeFontHandle};
8 use freetype::freetype::{FT_BBox, FT_Outline_Translate, FT_Pixel_Mode, FT_Render_Mode};
9 use freetype::freetype::{FT_Done_Face, FT_Error, FT_Get_Char_Index, FT_Int32};
10 use freetype::freetype::{FT_Done_FreeType, FT_Library_SetLcdFilter, FT_Pos};
11 use freetype::freetype::{FT_F26Dot6, FT_Face, FT_Glyph_Format, FT_Long, FT_UInt};
12 use freetype::freetype::{FT_GlyphSlot, FT_LcdFilter, FT_New_Face, FT_New_Memory_Face};
13 use freetype::freetype::{FT_Init_FreeType, FT_Load_Glyph, FT_Render_Glyph};
14 use freetype::freetype::{FT_Library, FT_Outline_Get_CBox, FT_Set_Char_Size, FT_Select_Size};
15 use freetype::freetype::{FT_Fixed, FT_Matrix, FT_Set_Transform, FT_String, FT_ULong, FT_Vector};
16 use freetype::freetype::{FT_Err_Unimplemented_Feature, FT_MulFix, FT_Outline_Embolden};
17 use freetype::freetype::{FT_LOAD_COLOR, FT_LOAD_DEFAULT, FT_LOAD_FORCE_AUTOHINT};
18 use freetype::freetype::{FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH, FT_LOAD_NO_AUTOHINT};
19 use freetype::freetype::{FT_LOAD_NO_BITMAP, FT_LOAD_NO_HINTING};
20 use freetype::freetype::{FT_FACE_FLAG_SCALABLE, FT_FACE_FLAG_FIXED_SIZES};
21 use freetype::freetype::{FT_FACE_FLAG_MULTIPLE_MASTERS};
22 use freetype::succeeded;
23 use crate::glyph_rasterizer::{FontInstance, GlyphFormat, GlyphKey};
24 use crate::glyph_rasterizer::{GlyphRasterError, GlyphRasterResult, RasterizedGlyph};
25 use crate::internal_types::{FastHashMap, ResourceCacheError};
26 #[cfg(any(not(target_os = "android"), feature = "no_static_freetype"))]
27 use libc::{dlsym, RTLD_DEFAULT};
28 use libc::free;
29 use std::{cmp, mem, ptr, slice};
30 use std::cmp::max;
31 use std::collections::hash_map::Entry;
32 use std::ffi::CString;
33 use std::sync::Arc;
34 
35 // These constants are not present in the freetype
36 // bindings due to bindgen not handling the way
37 // the macros are defined.
38 //const FT_LOAD_TARGET_NORMAL: FT_UInt = 0 << 16;
39 const FT_LOAD_TARGET_LIGHT: FT_UInt  = 1 << 16;
40 const FT_LOAD_TARGET_MONO: FT_UInt   = 2 << 16;
41 const FT_LOAD_TARGET_LCD: FT_UInt    = 3 << 16;
42 const FT_LOAD_TARGET_LCD_V: FT_UInt  = 4 << 16;
43 
44 #[repr(C)]
45 struct FT_Var_Axis {
46     pub name: *mut FT_String,
47     pub minimum: FT_Fixed,
48     pub def: FT_Fixed,
49     pub maximum: FT_Fixed,
50     pub tag: FT_ULong,
51     pub strid: FT_UInt,
52 }
53 
54 #[repr(C)]
55 struct FT_Var_Named_Style {
56     pub coords: *mut FT_Fixed,
57     pub strid: FT_UInt,
58     pub psid: FT_UInt,
59 }
60 
61 #[repr(C)]
62 struct FT_MM_Var {
63     pub num_axis: FT_UInt,
64     pub num_designs: FT_UInt,
65     pub num_namedstyles: FT_UInt,
66     pub axis: *mut FT_Var_Axis,
67     pub namedstyle: *mut FT_Var_Named_Style,
68 }
69 
70 #[inline]
unimplemented(error: FT_Error) -> bool71 pub fn unimplemented(error: FT_Error) -> bool {
72     error == FT_Err_Unimplemented_Feature as FT_Error
73 }
74 
75 // Use dlsym to check for symbols. If not available. just return an unimplemented error.
76 #[cfg(any(not(target_os = "android"), feature = "no_static_freetype"))]
77 macro_rules! ft_dyn_fn {
78     ($func_name:ident($($arg_name:ident:$arg_type:ty),*) -> FT_Error) => {
79         #[allow(non_snake_case)]
80         unsafe fn $func_name($($arg_name:$arg_type),*) -> FT_Error {
81             extern "C" fn unimpl_func($(_:$arg_type),*) -> FT_Error {
82                 FT_Err_Unimplemented_Feature as FT_Error
83             }
84             lazy_static! {
85                 static ref FUNC: unsafe extern "C" fn($($arg_type),*) -> FT_Error = {
86                     unsafe {
87                         let cname = CString::new(stringify!($func_name)).unwrap();
88                         let ptr = dlsym(RTLD_DEFAULT, cname.as_ptr());
89                         if !ptr.is_null() { mem::transmute(ptr) } else { unimpl_func }
90                     }
91                 };
92             }
93             (*FUNC)($($arg_name),*)
94         }
95     }
96 }
97 
98 // On Android, just statically link in the symbols...
99 #[cfg(all(target_os = "android", not(feature = "no_static_freetype")))]
100 macro_rules! ft_dyn_fn {
101     ($($proto:tt)+) => { extern "C" { fn $($proto)+; } }
102 }
103 
104 ft_dyn_fn!(FT_Get_MM_Var(face: FT_Face, desc: *mut *mut FT_MM_Var) -> FT_Error);
105 ft_dyn_fn!(FT_Done_MM_Var(library: FT_Library, desc: *mut FT_MM_Var) -> FT_Error);
106 ft_dyn_fn!(FT_Set_Var_Design_Coordinates(face: FT_Face, num_vals: FT_UInt, vals: *mut FT_Fixed) -> FT_Error);
107 ft_dyn_fn!(FT_Get_Var_Design_Coordinates(face: FT_Face, num_vals: FT_UInt, vals: *mut FT_Fixed) -> FT_Error);
108 
109 extern "C" {
FT_GlyphSlot_Embolden(slot: FT_GlyphSlot)110     fn FT_GlyphSlot_Embolden(slot: FT_GlyphSlot);
111 }
112 
113 // Custom version of FT_GlyphSlot_Embolden to be less aggressive with outline
114 // fonts than the default implementation in FreeType.
115 #[no_mangle]
mozilla_glyphslot_embolden_less(slot: FT_GlyphSlot)116 pub extern "C" fn mozilla_glyphslot_embolden_less(slot: FT_GlyphSlot) {
117     if slot.is_null() {
118         return;
119     }
120 
121     let slot_ = unsafe { &mut *slot };
122     let format = slot_.format;
123     if format != FT_Glyph_Format::FT_GLYPH_FORMAT_OUTLINE {
124         // For non-outline glyphs, just fall back to FreeType's function.
125         unsafe { FT_GlyphSlot_Embolden(slot) };
126         return;
127     }
128 
129     let face_ = unsafe { *slot_.face };
130 
131     // FT_GlyphSlot_Embolden uses a divisor of 24 here; we'll be only half as
132     // bold.
133     let size_ = unsafe { *face_.size };
134     let strength =
135         unsafe { FT_MulFix(face_.units_per_EM as FT_Long,
136                            size_.metrics.y_scale) / 48 };
137     unsafe { FT_Outline_Embolden(&mut slot_.outline, strength) };
138 
139     // Adjust metrics to suit the fattened glyph.
140     if slot_.advance.x != 0 {
141         slot_.advance.x += strength;
142     }
143     if slot_.advance.y != 0 {
144         slot_.advance.y += strength;
145     }
146     slot_.metrics.width += strength;
147     slot_.metrics.height += strength;
148     slot_.metrics.horiAdvance += strength;
149     slot_.metrics.vertAdvance += strength;
150     slot_.metrics.horiBearingY += strength;
151 }
152 
153 enum FontFile {
154     Pathname(CString),
155     Data(Arc<Vec<u8>>),
156 }
157 
158 struct FontFace {
159     // Raw byte data has to live until the font is deleted, according to
160     // https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_New_Memory_Face
161     file: FontFile,
162     index: u32,
163     face: FT_Face,
164     mm_var: *mut FT_MM_Var,
165 }
166 
167 impl Drop for FontFace {
drop(&mut self)168     fn drop(&mut self) {
169         unsafe {
170             if !self.mm_var.is_null() &&
171                unimplemented(FT_Done_MM_Var((*(*self.face).glyph).library, self.mm_var)) {
172                 free(self.mm_var as _);
173             }
174 
175             FT_Done_Face(self.face);
176         }
177     }
178 }
179 
180 struct VariationFace(FT_Face);
181 
182 impl Drop for VariationFace {
drop(&mut self)183     fn drop(&mut self) {
184         unsafe { FT_Done_Face(self.0) };
185     }
186 }
187 
new_ft_face(font_key: &FontKey, lib: FT_Library, file: &FontFile, index: u32) -> Option<FT_Face>188 fn new_ft_face(font_key: &FontKey, lib: FT_Library, file: &FontFile, index: u32) -> Option<FT_Face> {
189     unsafe {
190         let mut face: FT_Face = ptr::null_mut();
191         let result = match file {
192             FontFile::Pathname(ref cstr) => FT_New_Face(
193                 lib,
194                 cstr.as_ptr(),
195                 index as FT_Long,
196                 &mut face,
197             ),
198             FontFile::Data(ref bytes) => FT_New_Memory_Face(
199                 lib,
200                 bytes.as_ptr(),
201                 bytes.len() as FT_Long,
202                 index as FT_Long,
203                 &mut face,
204             ),
205         };
206         if succeeded(result) && !face.is_null() {
207             Some(face)
208         } else {
209             warn!("WARN: webrender failed to load font");
210             debug!("font={:?}, result={:?}", font_key, result);
211             None
212         }
213     }
214 }
215 
216 pub struct FontContext {
217     lib: FT_Library,
218     faces: FastHashMap<FontKey, FontFace>,
219     variations: FastHashMap<(FontKey, Vec<FontVariation>), VariationFace>,
220     lcd_extra_pixels: i64,
221 }
222 
223 // FreeType resources are safe to move between threads as long as they
224 // are not concurrently accessed. In our case, everything is hidden inside
225 // a given FontContext so it is safe to move the latter between threads.
226 unsafe impl Send for FontContext {}
227 
get_skew_bounds(bottom: i32, top: i32, skew_factor: f32, _vertical: bool) -> (f32, f32)228 fn get_skew_bounds(bottom: i32, top: i32, skew_factor: f32, _vertical: bool) -> (f32, f32) {
229     let skew_min = ((bottom as f32 + 0.5) * skew_factor).floor();
230     let skew_max = ((top as f32 - 0.5) * skew_factor).ceil();
231     (skew_min, skew_max)
232 }
233 
skew_bitmap( bitmap: &[u8], width: usize, height: usize, left: i32, top: i32, skew_factor: f32, vertical: bool, ) -> (Vec<u8>, usize, i32)234 fn skew_bitmap(
235     bitmap: &[u8],
236     width: usize,
237     height: usize,
238     left: i32,
239     top: i32,
240     skew_factor: f32,
241     vertical: bool, // TODO: vertical skew not yet implemented!
242 ) -> (Vec<u8>, usize, i32) {
243     let stride = width * 4;
244     // Calculate the skewed horizontal offsets of the bottom and top of the glyph.
245     let (skew_min, skew_max) = get_skew_bounds(top - height as i32, top, skew_factor, vertical);
246     // Allocate enough extra width for the min/max skew offsets.
247     let skew_width = width + (skew_max - skew_min) as usize;
248     let mut skew_buffer = vec![0u8; skew_width * height * 4];
249     for y in 0 .. height {
250         // Calculate a skew offset at the vertical center of the current row.
251         let offset = (top as f32 - y as f32 - 0.5) * skew_factor - skew_min;
252         // Get a blend factor in 0..256 constant across all pixels in the row.
253         let blend = (offset.fract() * 256.0) as u32;
254         let src_row = y * stride;
255         let dest_row = (y * skew_width + offset.floor() as usize) * 4;
256         let mut prev_px = [0u32; 4];
257         for (src, dest) in
258             bitmap[src_row .. src_row + stride].chunks(4).zip(
259                 skew_buffer[dest_row .. dest_row + stride].chunks_mut(4)
260             ) {
261             let px = [src[0] as u32, src[1] as u32, src[2] as u32, src[3] as u32];
262             // Blend current pixel with previous pixel based on blend factor.
263             let next_px = [px[0] * blend, px[1] * blend, px[2] * blend, px[3] * blend];
264             dest[0] = ((((px[0] << 8) - next_px[0]) + prev_px[0] + 128) >> 8) as u8;
265             dest[1] = ((((px[1] << 8) - next_px[1]) + prev_px[1] + 128) >> 8) as u8;
266             dest[2] = ((((px[2] << 8) - next_px[2]) + prev_px[2] + 128) >> 8) as u8;
267             dest[3] = ((((px[3] << 8) - next_px[3]) + prev_px[3] + 128) >> 8) as u8;
268             // Save the remainder for blending onto the next pixel.
269             prev_px = next_px;
270         }
271         // If the skew misaligns the final pixel, write out the remainder.
272         if blend > 0 {
273             let dest = &mut skew_buffer[dest_row + stride .. dest_row + stride + 4];
274             dest[0] = ((prev_px[0] + 128) >> 8) as u8;
275             dest[1] = ((prev_px[1] + 128) >> 8) as u8;
276             dest[2] = ((prev_px[2] + 128) >> 8) as u8;
277             dest[3] = ((prev_px[3] + 128) >> 8) as u8;
278         }
279     }
280     (skew_buffer, skew_width, left + skew_min as i32)
281 }
282 
transpose_bitmap(bitmap: &[u8], width: usize, height: usize) -> Vec<u8>283 fn transpose_bitmap(bitmap: &[u8], width: usize, height: usize) -> Vec<u8> {
284     let mut transposed = vec![0u8; width * height * 4];
285     for (y, row) in bitmap.chunks(width * 4).enumerate() {
286         let mut offset = y * 4;
287         for src in row.chunks(4) {
288             transposed[offset .. offset + 4].copy_from_slice(src);
289             offset += height * 4;
290         }
291     }
292     transposed
293 }
294 
flip_bitmap_x(bitmap: &mut [u8], width: usize, height: usize)295 fn flip_bitmap_x(bitmap: &mut [u8], width: usize, height: usize) {
296     assert!(bitmap.len() == width * height * 4);
297     let pixels = unsafe { slice::from_raw_parts_mut(bitmap.as_mut_ptr() as *mut u32, width * height) };
298     for row in pixels.chunks_mut(width) {
299         row.reverse();
300     }
301 }
302 
flip_bitmap_y(bitmap: &mut [u8], width: usize, height: usize)303 fn flip_bitmap_y(bitmap: &mut [u8], width: usize, height: usize) {
304     assert!(bitmap.len() == width * height * 4);
305     let pixels = unsafe { slice::from_raw_parts_mut(bitmap.as_mut_ptr() as *mut u32, width * height) };
306     for y in 0 .. height / 2 {
307         let low_row = y * width;
308         let high_row = (height - 1 - y) * width;
309         for x in 0 .. width {
310             pixels.swap(low_row + x, high_row + x);
311         }
312     }
313 }
314 
315 impl FontContext {
new() -> Result<FontContext, ResourceCacheError>316     pub fn new() -> Result<FontContext, ResourceCacheError> {
317         let mut lib: FT_Library = ptr::null_mut();
318 
319         // Using an LCD filter may add one full pixel to each side if support is built in.
320         // As of FreeType 2.8.1, an LCD filter is always used regardless of settings
321         // if support for the patent-encumbered LCD filter algorithms is not built in.
322         // Thus, the only reasonable way to guess padding is to unconditonally add it if
323         // subpixel AA is used.
324         let lcd_extra_pixels = 1;
325 
326         let result = unsafe {
327             FT_Init_FreeType(&mut lib)
328         };
329 
330         if succeeded(result) {
331             Ok(FontContext {
332                 lib,
333                 faces: FastHashMap::default(),
334                 variations: FastHashMap::default(),
335                 lcd_extra_pixels,
336             })
337         } else {
338             // TODO(gw): Provide detailed error values.
339             // Once this panic has been here for a while with no issues we should get rid of
340             // ResourceCacheError as this was the only place that could fail previously.
341             panic!("Failed to initialize FreeType - {}", result)
342         }
343     }
344 
has_font(&self, font_key: &FontKey) -> bool345     pub fn has_font(&self, font_key: &FontKey) -> bool {
346         self.faces.contains_key(font_key)
347     }
348 
add_raw_font(&mut self, font_key: &FontKey, bytes: Arc<Vec<u8>>, index: u32)349     pub fn add_raw_font(&mut self, font_key: &FontKey, bytes: Arc<Vec<u8>>, index: u32) {
350         if !self.faces.contains_key(font_key) {
351             let file = FontFile::Data(bytes);
352             if let Some(face) = new_ft_face(font_key, self.lib, &file, index) {
353                 self.faces.insert(*font_key, FontFace { file, index, face, mm_var: ptr::null_mut() });
354             }
355         }
356     }
357 
add_native_font(&mut self, font_key: &FontKey, native_font_handle: NativeFontHandle)358     pub fn add_native_font(&mut self, font_key: &FontKey, native_font_handle: NativeFontHandle) {
359         if !self.faces.contains_key(font_key) {
360             let cstr = CString::new(native_font_handle.path.as_os_str().to_str().unwrap()).unwrap();
361             let file = FontFile::Pathname(cstr);
362             let index = native_font_handle.index;
363             if let Some(face) = new_ft_face(font_key, self.lib, &file, index) {
364                 self.faces.insert(*font_key, FontFace { file, index, face, mm_var: ptr::null_mut() });
365             }
366         }
367     }
368 
delete_font(&mut self, font_key: &FontKey)369     pub fn delete_font(&mut self, font_key: &FontKey) {
370         if self.faces.remove(font_key).is_some() {
371             self.variations.retain(|k, _| k.0 != *font_key);
372         }
373     }
374 
delete_font_instance(&mut self, instance: &FontInstance)375     pub fn delete_font_instance(&mut self, instance: &FontInstance) {
376         // Ensure we don't keep around excessive amounts of stale variations.
377         if !instance.variations.is_empty() {
378             self.variations.remove(&(instance.font_key, instance.variations.clone()));
379         }
380     }
381 
get_ft_face(&mut self, font: &FontInstance) -> Option<FT_Face>382     fn get_ft_face(&mut self, font: &FontInstance) -> Option<FT_Face> {
383         if font.variations.is_empty() {
384             return Some(self.faces.get(&font.font_key)?.face);
385         }
386         match self.variations.entry((font.font_key, font.variations.clone())) {
387             Entry::Occupied(entry) => Some(entry.get().0),
388             Entry::Vacant(entry) => unsafe {
389                 let normal_face = self.faces.get_mut(&font.font_key)?;
390                 if ((*normal_face.face).face_flags & (FT_FACE_FLAG_MULTIPLE_MASTERS as FT_Long)) == 0 {
391                     return Some(normal_face.face);
392                 }
393                 // Clone a new FT face and attempt to set the variation values on it.
394                 // Leave unspecified values at the defaults.
395                 let var_face = new_ft_face(&font.font_key, self.lib, &normal_face.file, normal_face.index)?;
396                 if !normal_face.mm_var.is_null() ||
397                    succeeded(FT_Get_MM_Var(normal_face.face, &mut normal_face.mm_var)) {
398                     let mm_var = normal_face.mm_var;
399                     let num_axis = (*mm_var).num_axis;
400                     let mut coords: Vec<FT_Fixed> = Vec::with_capacity(num_axis as usize);
401 
402                     // Calling this before FT_Set_Var_Design_Coordinates avoids a bug with font variations
403                     // not initialized properly in the font face, even if we ignore the result.
404                     // See bug 1647035.
405                     let mut tmp = [0; 16];
406                     let res = FT_Get_Var_Design_Coordinates(
407                         normal_face.face,
408                         num_axis.min(16),
409                         tmp.as_mut_ptr()
410                     );
411                     debug_assert!(succeeded(res));
412 
413 
414                     for i in 0 .. num_axis {
415                         let axis = (*mm_var).axis.offset(i as isize);
416                         let mut value = (*axis).def;
417                         for var in &font.variations {
418                             if var.tag as FT_ULong == (*axis).tag {
419                                 value = (var.value * 65536.0 + 0.5) as FT_Fixed;
420                                 value = cmp::min(value, (*axis).maximum);
421                                 value = cmp::max(value, (*axis).minimum);
422                                 break;
423                             }
424                         }
425                         coords.push(value);
426                     }
427                     let res = FT_Set_Var_Design_Coordinates(var_face, num_axis, coords.as_mut_ptr());
428                     debug_assert!(succeeded(res));
429                 }
430                 entry.insert(VariationFace(var_face));
431                 Some(var_face)
432             }
433         }
434     }
435 
load_glyph(&mut self, font: &FontInstance, glyph: &GlyphKey) -> Option<(FT_GlyphSlot, f32)>436     fn load_glyph(&mut self, font: &FontInstance, glyph: &GlyphKey) -> Option<(FT_GlyphSlot, f32)> {
437         let face = self.get_ft_face(font)?;
438 
439         let mut load_flags = FT_LOAD_DEFAULT;
440         let FontInstancePlatformOptions { mut hinting, .. } = font.platform_options.unwrap_or_default();
441         // Disable hinting if there is a non-axis-aligned transform.
442         if font.synthetic_italics.is_enabled() ||
443            ((font.transform.scale_x != 0.0 || font.transform.scale_y != 0.0) &&
444             (font.transform.skew_x != 0.0 || font.transform.skew_y != 0.0)) {
445             hinting = FontHinting::None;
446         }
447         match (hinting, font.render_mode) {
448             (FontHinting::None, _) => load_flags |= FT_LOAD_NO_HINTING,
449             (FontHinting::Mono, _) => load_flags = FT_LOAD_TARGET_MONO,
450             (FontHinting::Light, _) => load_flags = FT_LOAD_TARGET_LIGHT,
451             (FontHinting::LCD, FontRenderMode::Subpixel) => {
452                 load_flags = if font.flags.contains(FontInstanceFlags::LCD_VERTICAL) {
453                     FT_LOAD_TARGET_LCD_V
454                 } else {
455                     FT_LOAD_TARGET_LCD
456                 };
457                 if font.flags.contains(FontInstanceFlags::FORCE_AUTOHINT) {
458                     load_flags |= FT_LOAD_FORCE_AUTOHINT;
459                 }
460             }
461             _ => {
462                 if font.flags.contains(FontInstanceFlags::FORCE_AUTOHINT) {
463                     load_flags |= FT_LOAD_FORCE_AUTOHINT;
464                 }
465             }
466         }
467 
468         if font.flags.contains(FontInstanceFlags::NO_AUTOHINT) {
469             load_flags |= FT_LOAD_NO_AUTOHINT;
470         }
471         if !font.flags.contains(FontInstanceFlags::EMBEDDED_BITMAPS) {
472             load_flags |= FT_LOAD_NO_BITMAP;
473         }
474 
475         load_flags |= FT_LOAD_COLOR;
476         load_flags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
477 
478         let (x_scale, y_scale) = font.transform.compute_scale().unwrap_or((1.0, 1.0));
479         let req_size = font.size.to_f64_px();
480         let face_flags = unsafe { (*face).face_flags };
481         let mut result = if (face_flags & (FT_FACE_FLAG_FIXED_SIZES as FT_Long)) != 0 &&
482                             (face_flags & (FT_FACE_FLAG_SCALABLE as FT_Long)) == 0 &&
483                             (load_flags & FT_LOAD_NO_BITMAP) == 0 {
484             unsafe { FT_Set_Transform(face, ptr::null_mut(), ptr::null_mut()) };
485             self.choose_bitmap_size(face, req_size * y_scale)
486         } else {
487             let mut shape = font.transform.invert_scale(x_scale, y_scale);
488             if font.flags.contains(FontInstanceFlags::FLIP_X) {
489                 shape = shape.flip_x();
490             }
491             if font.flags.contains(FontInstanceFlags::FLIP_Y) {
492                 shape = shape.flip_y();
493             }
494             if font.flags.contains(FontInstanceFlags::TRANSPOSE) {
495                 shape = shape.swap_xy();
496             }
497             let (mut tx, mut ty) = (0.0, 0.0);
498             if font.synthetic_italics.is_enabled() {
499                 let (shape_, (tx_, ty_)) = font.synthesize_italics(shape, y_scale * req_size);
500                 shape = shape_;
501                 tx = tx_;
502                 ty = ty_;
503             };
504             let mut ft_shape = FT_Matrix {
505                 xx: (shape.scale_x * 65536.0) as FT_Fixed,
506                 xy: (shape.skew_x * -65536.0) as FT_Fixed,
507                 yx: (shape.skew_y * -65536.0) as FT_Fixed,
508                 yy: (shape.scale_y * 65536.0) as FT_Fixed,
509             };
510             // The delta vector for FT_Set_Transform is in units of 1/64 pixel.
511             let mut ft_delta = FT_Vector {
512                 x: (tx * 64.0) as FT_F26Dot6,
513                 y: (ty * -64.0) as FT_F26Dot6,
514             };
515             unsafe {
516                 FT_Set_Transform(face, &mut ft_shape, &mut ft_delta);
517                 FT_Set_Char_Size(
518                     face,
519                     (req_size * x_scale * 64.0 + 0.5) as FT_F26Dot6,
520                     (req_size * y_scale * 64.0 + 0.5) as FT_F26Dot6,
521                     0,
522                     0,
523                 )
524             }
525         };
526 
527         if !succeeded(result) {
528             error!("Unable to set glyph size and transform: {}", result);
529             //let raw_error = unsafe { FT_Error_String(result) };
530             //if !raw_error.is_ptr() {
531             //    error!("\tcode {:?}", CStr::from_ptr(raw_error));
532             //}
533             debug!(
534                 "\t[{}] for size {:?} and scale {:?} from font {:?}",
535                 glyph.index(),
536                 req_size,
537                 (x_scale, y_scale),
538                 font.font_key,
539             );
540             return None;
541         }
542 
543         result = unsafe { FT_Load_Glyph(face, glyph.index() as FT_UInt, load_flags as FT_Int32) };
544         if !succeeded(result) {
545             error!("Unable to load glyph: {}", result);
546             //let raw_error = unsafe { FT_Error_String(result) };
547             //if !raw_error.is_ptr() {
548             //    error!("\tcode {:?}", CStr::from_ptr(raw_error));
549             //}
550             debug!(
551                 "\t[{}] with flags {:?} from font {:?}",
552                 glyph.index(),
553                 load_flags,
554                 font.font_key,
555             );
556             return None;
557         }
558 
559         let slot = unsafe { (*face).glyph };
560         assert!(slot != ptr::null_mut());
561 
562         if font.flags.contains(FontInstanceFlags::SYNTHETIC_BOLD) {
563             mozilla_glyphslot_embolden_less(slot);
564         }
565 
566         let format = unsafe { (*slot).format };
567         match format {
568             FT_Glyph_Format::FT_GLYPH_FORMAT_BITMAP => {
569                 let bitmap_size = unsafe { (*(*(*slot).face).size).metrics.y_ppem };
570                 Some((slot, req_size as f32 / bitmap_size as f32))
571             }
572             FT_Glyph_Format::FT_GLYPH_FORMAT_OUTLINE => Some((slot, 1.0)),
573             _ => {
574                 error!("Unsupported format");
575                 debug!("format={:?}", format);
576                 None
577             }
578         }
579     }
580 
pad_bounding_box(&self, font: &FontInstance, cbox: &mut FT_BBox)581     fn pad_bounding_box(&self, font: &FontInstance, cbox: &mut FT_BBox) {
582         // Apply extra pixel of padding for subpixel AA, due to the filter.
583         if font.render_mode == FontRenderMode::Subpixel {
584             let padding = (self.lcd_extra_pixels * 64) as FT_Pos;
585             if font.flags.contains(FontInstanceFlags::LCD_VERTICAL) {
586                 cbox.yMin -= padding;
587                 cbox.yMax += padding;
588             } else {
589                 cbox.xMin -= padding;
590                 cbox.xMax += padding;
591             }
592         }
593     }
594 
595     // Get the bounding box for a glyph, accounting for sub-pixel positioning.
get_bounding_box( &self, slot: FT_GlyphSlot, font: &FontInstance, glyph: &GlyphKey, scale: f32, ) -> FT_BBox596     fn get_bounding_box(
597         &self,
598         slot: FT_GlyphSlot,
599         font: &FontInstance,
600         glyph: &GlyphKey,
601         scale: f32,
602     ) -> FT_BBox {
603         // Get the estimated bounding box from FT (control points).
604         let mut cbox = FT_BBox { xMin: 0, yMin: 0, xMax: 0, yMax: 0 };
605 
606         unsafe {
607             FT_Outline_Get_CBox(&(*slot).outline, &mut cbox);
608         }
609 
610         // For spaces and other non-printable characters, early out.
611         if unsafe { (*slot).outline.n_contours } == 0 {
612             return cbox;
613         }
614 
615         self.pad_bounding_box(font, &mut cbox);
616 
617         // Offset the bounding box by subpixel positioning.
618         // Convert to 26.6 fixed point format for FT.
619         let (dx, dy) = font.get_subpx_offset(glyph);
620         let (dx, dy) = (
621             (dx / scale as f64 * 64.0 + 0.5) as FT_Pos,
622             -(dy / scale as f64 * 64.0 + 0.5) as FT_Pos,
623         );
624         cbox.xMin += dx;
625         cbox.xMax += dx;
626         cbox.yMin += dy;
627         cbox.yMax += dy;
628 
629         // Outset the box to device pixel boundaries
630         cbox.xMin &= !63;
631         cbox.yMin &= !63;
632         cbox.xMax = (cbox.xMax + 63) & !63;
633         cbox.yMax = (cbox.yMax + 63) & !63;
634 
635         cbox
636     }
637 
get_glyph_dimensions_impl( &self, slot: FT_GlyphSlot, font: &FontInstance, glyph: &GlyphKey, scale: f32, use_transform: bool, ) -> Option<GlyphDimensions>638     fn get_glyph_dimensions_impl(
639         &self,
640         slot: FT_GlyphSlot,
641         font: &FontInstance,
642         glyph: &GlyphKey,
643         scale: f32,
644         use_transform: bool,
645     ) -> Option<GlyphDimensions> {
646         let format = unsafe { (*slot).format };
647         let (mut left, mut top, mut width, mut height) = match format {
648             FT_Glyph_Format::FT_GLYPH_FORMAT_BITMAP => {
649                 unsafe { (
650                     (*slot).bitmap_left as i32,
651                     (*slot).bitmap_top as i32,
652                     (*slot).bitmap.width as i32,
653                     (*slot).bitmap.rows as i32,
654                 ) }
655             }
656             FT_Glyph_Format::FT_GLYPH_FORMAT_OUTLINE => {
657                 let cbox = self.get_bounding_box(slot, font, glyph, scale);
658                 (
659                     (cbox.xMin >> 6) as i32,
660                     (cbox.yMax >> 6) as i32,
661                     ((cbox.xMax - cbox.xMin) >> 6) as i32,
662                     ((cbox.yMax - cbox.yMin) >> 6) as i32,
663                 )
664             }
665             _ => return None,
666         };
667         let mut advance = unsafe { (*slot).metrics.horiAdvance as f32 / 64.0 };
668         if use_transform {
669             if scale != 1.0 {
670                 let x0 = left as f32 * scale;
671                 let x1 = width as f32 * scale + x0;
672                 let y1 = top as f32 * scale;
673                 let y0 = y1 - height as f32 * scale;
674                 left = x0.round() as i32;
675                 top = y1.round() as i32;
676                 width = (x1.ceil() - x0.floor()) as i32;
677                 height = (y1.ceil() - y0.floor()) as i32;
678                 advance *= scale;
679             }
680             // An outline glyph's cbox would have already been transformed inside FT_Load_Glyph,
681             // so only handle bitmap glyphs which are not handled by FT_Load_Glyph.
682             if format == FT_Glyph_Format::FT_GLYPH_FORMAT_BITMAP {
683                 if font.synthetic_italics.is_enabled() {
684                     let (skew_min, skew_max) = get_skew_bounds(
685                         top - height as i32,
686                         top,
687                         font.synthetic_italics.to_skew(),
688                         font.flags.contains(FontInstanceFlags::VERTICAL),
689                     );
690                     left += skew_min as i32;
691                     width += (skew_max - skew_min) as i32;
692                 }
693                 if font.flags.contains(FontInstanceFlags::TRANSPOSE) {
694                     mem::swap(&mut width, &mut height);
695                     mem::swap(&mut left, &mut top);
696                     left -= width as i32;
697                     top += height as i32;
698                 }
699                 if font.flags.contains(FontInstanceFlags::FLIP_X) {
700                     left = -(left + width as i32);
701                 }
702                 if font.flags.contains(FontInstanceFlags::FLIP_Y) {
703                     top = -(top - height as i32);
704                 }
705             }
706         }
707         Some(GlyphDimensions {
708             left,
709             top,
710             width,
711             height,
712             advance,
713         })
714     }
715 
get_glyph_index(&mut self, font_key: FontKey, ch: char) -> Option<u32>716     pub fn get_glyph_index(&mut self, font_key: FontKey, ch: char) -> Option<u32> {
717         let face = self.faces.get(&font_key)?.face;
718         unsafe {
719             let idx = FT_Get_Char_Index(face, ch as _);
720             if idx != 0 {
721                 Some(idx)
722             } else {
723                 None
724             }
725         }
726     }
727 
get_glyph_dimensions( &mut self, font: &FontInstance, key: &GlyphKey, ) -> Option<GlyphDimensions>728     pub fn get_glyph_dimensions(
729         &mut self,
730         font: &FontInstance,
731         key: &GlyphKey,
732     ) -> Option<GlyphDimensions> {
733         let slot = self.load_glyph(font, key);
734         slot.and_then(|(slot, scale)| self.get_glyph_dimensions_impl(slot, &font, key, scale, true))
735     }
736 
choose_bitmap_size(&self, face: FT_Face, requested_size: f64) -> FT_Error737     fn choose_bitmap_size(&self, face: FT_Face, requested_size: f64) -> FT_Error {
738         let mut best_dist = unsafe { *(*face).available_sizes.offset(0) }.y_ppem as f64 / 64.0 - requested_size;
739         let mut best_size = 0;
740         let num_fixed_sizes = unsafe { (*face).num_fixed_sizes };
741         for i in 1 .. num_fixed_sizes {
742             // Distance is positive if strike is larger than desired size,
743             // or negative if smaller. If previously a found smaller strike,
744             // then prefer a larger strike. Otherwise, minimize distance.
745             let dist = unsafe { *(*face).available_sizes.offset(i as isize) }.y_ppem as f64 / 64.0 - requested_size;
746             if (best_dist < 0.0 && dist >= best_dist) || dist.abs() <= best_dist {
747                 best_dist = dist;
748                 best_size = i;
749             }
750         }
751         unsafe { FT_Select_Size(face, best_size) }
752     }
753 
prepare_font(font: &mut FontInstance)754     pub fn prepare_font(font: &mut FontInstance) {
755         match font.render_mode {
756             FontRenderMode::Mono => {
757                 // In mono mode the color of the font is irrelevant.
758                 font.color = ColorU::new(0xFF, 0xFF, 0xFF, 0xFF);
759                 // Subpixel positioning is disabled in mono mode.
760                 font.disable_subpixel_position();
761             }
762             FontRenderMode::Alpha | FontRenderMode::Subpixel => {
763                 // We don't do any preblending with FreeType currently, so the color is not used.
764                 font.color = ColorU::new(0xFF, 0xFF, 0xFF, 0xFF);
765             }
766         }
767     }
768 
rasterize_glyph_outline( &mut self, slot: FT_GlyphSlot, font: &FontInstance, key: &GlyphKey, scale: f32, ) -> bool769     fn rasterize_glyph_outline(
770         &mut self,
771         slot: FT_GlyphSlot,
772         font: &FontInstance,
773         key: &GlyphKey,
774         scale: f32,
775     ) -> bool {
776         // Get the subpixel offsets in FT 26.6 format.
777         let (dx, dy) = font.get_subpx_offset(key);
778         let (dx, dy) = (
779             (dx / scale as f64 * 64.0 + 0.5) as FT_Pos,
780             -(dy / scale as f64 * 64.0 + 0.5) as FT_Pos,
781         );
782 
783         // Move the outline curves to be at the origin, taking
784         // into account the subpixel positioning.
785         unsafe {
786             let outline = &(*slot).outline;
787             let mut cbox = FT_BBox { xMin: 0, yMin: 0, xMax: 0, yMax: 0 };
788             FT_Outline_Get_CBox(outline, &mut cbox);
789             self.pad_bounding_box(font, &mut cbox);
790             FT_Outline_Translate(
791                 outline,
792                 dx - ((cbox.xMin + dx) & !63),
793                 dy - ((cbox.yMin + dy) & !63),
794             );
795         }
796 
797         if font.render_mode == FontRenderMode::Subpixel {
798             let FontInstancePlatformOptions { lcd_filter, .. } = font.platform_options.unwrap_or_default();
799             let filter = match lcd_filter {
800                 FontLCDFilter::None => FT_LcdFilter::FT_LCD_FILTER_NONE,
801                 FontLCDFilter::Default => FT_LcdFilter::FT_LCD_FILTER_DEFAULT,
802                 FontLCDFilter::Light => FT_LcdFilter::FT_LCD_FILTER_LIGHT,
803                 FontLCDFilter::Legacy => FT_LcdFilter::FT_LCD_FILTER_LEGACY,
804             };
805             unsafe { FT_Library_SetLcdFilter(self.lib, filter) };
806         }
807         let render_mode = match font.render_mode {
808             FontRenderMode::Mono => FT_Render_Mode::FT_RENDER_MODE_MONO,
809             FontRenderMode::Alpha => FT_Render_Mode::FT_RENDER_MODE_NORMAL,
810             FontRenderMode::Subpixel => if font.flags.contains(FontInstanceFlags::LCD_VERTICAL) {
811                 FT_Render_Mode::FT_RENDER_MODE_LCD_V
812             } else {
813                 FT_Render_Mode::FT_RENDER_MODE_LCD
814             },
815         };
816         let result = unsafe { FT_Render_Glyph(slot, render_mode) };
817         if !succeeded(result) {
818             error!("Unable to rasterize");
819             debug!(
820                 "{:?} with {:?}, {:?}",
821                 key,
822                 render_mode,
823                 result
824             );
825             false
826         } else {
827             true
828         }
829     }
830 
rasterize_glyph(&mut self, font: &FontInstance, key: &GlyphKey) -> GlyphRasterResult831     pub fn rasterize_glyph(&mut self, font: &FontInstance, key: &GlyphKey) -> GlyphRasterResult {
832         let (slot, scale) = self.load_glyph(font, key).ok_or(GlyphRasterError::LoadFailed)?;
833 
834         // Get dimensions of the glyph, to see if we need to rasterize it.
835         // Don't apply scaling to the dimensions, as the glyph cache needs to know the actual
836         // footprint of the glyph.
837         let dimensions = self.get_glyph_dimensions_impl(slot, font, key, scale, false)
838                              .ok_or(GlyphRasterError::LoadFailed)?;
839         let GlyphDimensions { mut left, mut top, width, height, .. } = dimensions;
840 
841         // For spaces and other non-printable characters, early out.
842         if width == 0 || height == 0 {
843             return Err(GlyphRasterError::LoadFailed);
844         }
845 
846         let format = unsafe { (*slot).format };
847         match format {
848             FT_Glyph_Format::FT_GLYPH_FORMAT_BITMAP => {}
849             FT_Glyph_Format::FT_GLYPH_FORMAT_OUTLINE => {
850                 if !self.rasterize_glyph_outline(slot, font, key, scale) {
851                     return Err(GlyphRasterError::LoadFailed);
852                 }
853             }
854             _ => {
855                 error!("Unsupported format");
856                 debug!("format={:?}", format);
857                 return Err(GlyphRasterError::LoadFailed);
858             }
859         };
860 
861         debug!(
862             "Rasterizing {:?} as {:?} with dimensions {:?}",
863             key,
864             font.render_mode,
865             dimensions
866         );
867 
868         let bitmap = unsafe { &(*slot).bitmap };
869         let pixel_mode = unsafe { mem::transmute(bitmap.pixel_mode as u32) };
870         let (mut actual_width, mut actual_height) = match pixel_mode {
871             FT_Pixel_Mode::FT_PIXEL_MODE_LCD => {
872                 assert!(bitmap.width % 3 == 0);
873                 ((bitmap.width / 3) as usize, bitmap.rows as usize)
874             }
875             FT_Pixel_Mode::FT_PIXEL_MODE_LCD_V => {
876                 assert!(bitmap.rows % 3 == 0);
877                 (bitmap.width as usize, (bitmap.rows / 3) as usize)
878             }
879             FT_Pixel_Mode::FT_PIXEL_MODE_MONO |
880             FT_Pixel_Mode::FT_PIXEL_MODE_GRAY |
881             FT_Pixel_Mode::FT_PIXEL_MODE_BGRA => {
882                 (bitmap.width as usize, bitmap.rows as usize)
883             }
884             _ => panic!("Unsupported mode"),
885         };
886 
887         // If we need padding, we will need to expand the buffer size.
888         let (buffer_width, buffer_height, padding) = if font.use_texture_padding() {
889             (actual_width + 2, actual_height + 2, 1)
890         } else {
891             (actual_width, actual_height, 0)
892         };
893 
894         let mut final_buffer = vec![0u8; buffer_width * buffer_height * 4];
895 
896         // Extract the final glyph from FT format into BGRA8 format, which is
897         // what WR expects.
898         let subpixel_bgr = font.flags.contains(FontInstanceFlags::SUBPIXEL_BGR);
899         let mut src_row = bitmap.buffer;
900         let mut dest = 4 * padding * (padding + buffer_width);
901         let actual_end = final_buffer.len() - 4 * padding * (buffer_width + 1);
902         while dest < actual_end {
903             let mut src = src_row;
904             let row_end = dest + actual_width * 4;
905             match pixel_mode {
906                 FT_Pixel_Mode::FT_PIXEL_MODE_MONO => {
907                     while dest < row_end {
908                         // Cast the byte to signed so that we can left shift each bit into
909                         // the top bit, then right shift to fill out the bits with 0s or 1s.
910                         let mut byte: i8 = unsafe { *src as i8 };
911                         src = unsafe { src.offset(1) };
912                         let byte_end = cmp::min(row_end, dest + 8 * 4);
913                         while dest < byte_end {
914                             let alpha = (byte >> 7) as u8;
915                             final_buffer[dest + 0] = alpha;
916                             final_buffer[dest + 1] = alpha;
917                             final_buffer[dest + 2] = alpha;
918                             final_buffer[dest + 3] = alpha;
919                             dest += 4;
920                             byte <<= 1;
921                         }
922                     }
923                 }
924                 FT_Pixel_Mode::FT_PIXEL_MODE_GRAY => {
925                     while dest < row_end {
926                         let alpha = unsafe { *src };
927                         final_buffer[dest + 0] = alpha;
928                         final_buffer[dest + 1] = alpha;
929                         final_buffer[dest + 2] = alpha;
930                         final_buffer[dest + 3] = alpha;
931                         src = unsafe { src.offset(1) };
932                         dest += 4;
933                     }
934                 }
935                 FT_Pixel_Mode::FT_PIXEL_MODE_LCD => {
936                     while dest < row_end {
937                         let (mut r, g, mut b) = unsafe { (*src, *src.offset(1), *src.offset(2)) };
938                         if subpixel_bgr {
939                             mem::swap(&mut r, &mut b);
940                         }
941                         final_buffer[dest + 0] = b;
942                         final_buffer[dest + 1] = g;
943                         final_buffer[dest + 2] = r;
944                         final_buffer[dest + 3] = max(max(b, g), r);
945                         src = unsafe { src.offset(3) };
946                         dest += 4;
947                     }
948                 }
949                 FT_Pixel_Mode::FT_PIXEL_MODE_LCD_V => {
950                     while dest < row_end {
951                         let (mut r, g, mut b) =
952                             unsafe { (*src, *src.offset(bitmap.pitch as isize), *src.offset((2 * bitmap.pitch) as isize)) };
953                         if subpixel_bgr {
954                             mem::swap(&mut r, &mut b);
955                         }
956                         final_buffer[dest + 0] = b;
957                         final_buffer[dest + 1] = g;
958                         final_buffer[dest + 2] = r;
959                         final_buffer[dest + 3] = max(max(b, g), r);
960                         src = unsafe { src.offset(1) };
961                         dest += 4;
962                     }
963                     src_row = unsafe { src_row.offset((2 * bitmap.pitch) as isize) };
964                 }
965                 FT_Pixel_Mode::FT_PIXEL_MODE_BGRA => {
966                     // The source is premultiplied BGRA data.
967                     let dest_slice = &mut final_buffer[dest .. row_end];
968                     let src_slice = unsafe { slice::from_raw_parts(src, dest_slice.len()) };
969                     dest_slice.copy_from_slice(src_slice);
970                 }
971                 _ => panic!("Unsupported mode"),
972             }
973             src_row = unsafe { src_row.offset(bitmap.pitch as isize) };
974             dest = row_end + 8 * padding;
975         }
976 
977         if font.use_texture_padding() {
978             left -= padding as i32;
979             top += padding as i32;
980             actual_width = buffer_width;
981             actual_height = buffer_height;
982         }
983 
984         match format {
985             FT_Glyph_Format::FT_GLYPH_FORMAT_BITMAP => {
986                 if font.synthetic_italics.is_enabled() {
987                     let (skew_buffer, skew_width, skew_left) = skew_bitmap(
988                         &final_buffer,
989                         actual_width,
990                         actual_height,
991                         left,
992                         top,
993                         font.synthetic_italics.to_skew(),
994                         font.flags.contains(FontInstanceFlags::VERTICAL),
995                     );
996                     final_buffer = skew_buffer;
997                     actual_width = skew_width;
998                     left = skew_left;
999                 }
1000                 if font.flags.contains(FontInstanceFlags::TRANSPOSE) {
1001                     final_buffer = transpose_bitmap(&final_buffer, actual_width, actual_height);
1002                     mem::swap(&mut actual_width, &mut actual_height);
1003                     mem::swap(&mut left, &mut top);
1004                     left -= actual_width as i32;
1005                     top += actual_height as i32;
1006                 }
1007                 if font.flags.contains(FontInstanceFlags::FLIP_X) {
1008                     flip_bitmap_x(&mut final_buffer, actual_width, actual_height);
1009                     left = -(left + actual_width as i32);
1010                 }
1011                 if font.flags.contains(FontInstanceFlags::FLIP_Y) {
1012                     flip_bitmap_y(&mut final_buffer, actual_width, actual_height);
1013                     top = -(top - actual_height as i32);
1014                 }
1015             }
1016             FT_Glyph_Format::FT_GLYPH_FORMAT_OUTLINE => {
1017                 unsafe {
1018                     left += (*slot).bitmap_left;
1019                     top += (*slot).bitmap_top - height as i32;
1020                 }
1021             }
1022             _ => {}
1023         }
1024 
1025         let glyph_format = match (pixel_mode, format) {
1026             (FT_Pixel_Mode::FT_PIXEL_MODE_LCD, _) |
1027             (FT_Pixel_Mode::FT_PIXEL_MODE_LCD_V, _) => font.get_subpixel_glyph_format(),
1028             (FT_Pixel_Mode::FT_PIXEL_MODE_BGRA, _) => GlyphFormat::ColorBitmap,
1029             (_, FT_Glyph_Format::FT_GLYPH_FORMAT_BITMAP) => GlyphFormat::Bitmap,
1030             _ => font.get_alpha_glyph_format(),
1031         };
1032 
1033         Ok(RasterizedGlyph {
1034             left: left as f32,
1035             top: top as f32,
1036             width: actual_width as i32,
1037             height: actual_height as i32,
1038             scale,
1039             format: glyph_format,
1040             bytes: final_buffer,
1041         })
1042     }
1043 }
1044 
1045 impl Drop for FontContext {
drop(&mut self)1046     fn drop(&mut self) {
1047         self.variations.clear();
1048         self.faces.clear();
1049         unsafe {
1050             FT_Done_FreeType(self.lib);
1051         }
1052     }
1053 }
1054