1 /* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
2 /* cairo - a vector graphics library with display and print output
3  *
4  * Copyright © 2000 Keith Packard
5  * Copyright © 2005 Red Hat, Inc
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it either under the terms of the GNU Lesser General Public
9  * License version 2.1 as published by the Free Software Foundation
10  * (the "LGPL") or, at your option, under the terms of the Mozilla
11  * Public License Version 1.1 (the "MPL"). If you do not alter this
12  * notice, a recipient may use your version of this file under either
13  * the MPL or the LGPL.
14  *
15  * You should have received a copy of the LGPL along with this library
16  * in the file COPYING-LGPL-2.1; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
18  * You should have received a copy of the MPL along with this library
19  * in the file COPYING-MPL-1.1
20  *
21  * The contents of this file are subject to the Mozilla Public License
22  * Version 1.1 (the "License"); you may not use this file except in
23  * compliance with the License. You may obtain a copy of the License at
24  * http://www.mozilla.org/MPL/
25  *
26  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
27  * OF ANY KIND, either express or implied. See the LGPL or the MPL for
28  * the specific language governing rights and limitations.
29  *
30  * The Original Code is the cairo graphics library.
31  *
32  * The Initial Developer of the Original Code is Red Hat, Inc.
33  *
34  * Contributor(s):
35  *      Graydon Hoare <graydon@redhat.com>
36  *	Owen Taylor <otaylor@redhat.com>
37  *      Keith Packard <keithp@keithp.com>
38  *      Carl Worth <cworth@cworth.org>
39  */
40 
41 #define _BSD_SOURCE /* for strdup() */
42 #include "cairoint.h"
43 
44 #include "cairo-error-private.h"
45 #include "cairo-ft-private.h"
46 
47 #include <float.h>
48 
49 #include "cairo-fontconfig-private.h"
50 
51 #include <ft2build.h>
52 #include FT_FREETYPE_H
53 #include FT_OUTLINE_H
54 #include FT_IMAGE_H
55 #include FT_BITMAP_H
56 #include FT_TRUETYPE_TABLES_H
57 #if HAVE_FT_GLYPHSLOT_EMBOLDEN
58 #include FT_SYNTHESIS_H
59 #endif
60 
61 #if HAVE_FT_LIBRARY_SETLCDFILTER
62 #include FT_LCD_FILTER_H
63 #endif
64 
65 #define _GNU_SOURCE /* for RTLD_DEFAULT */
66 #include <dlfcn.h>
67 
68 #ifndef RTLD_DEFAULT
69 #define RTLD_DEFAULT ((void *) 0)
70 #endif
71 
72 /* Fontconfig version older than 2.6 didn't have these options */
73 #ifndef FC_LCD_FILTER
74 #define FC_LCD_FILTER	"lcdfilter"
75 #endif
76 /* Some Ubuntu versions defined FC_LCD_FILTER without defining the following */
77 #ifndef FC_LCD_NONE
78 #define FC_LCD_NONE	0
79 #define FC_LCD_DEFAULT	1
80 #define FC_LCD_LIGHT	2
81 #define FC_LCD_LEGACY	3
82 #endif
83 
84 /* FreeType version older than 2.3.5(?) didn't have these options */
85 #ifndef FT_LCD_FILTER_NONE
86 #define FT_LCD_FILTER_NONE	0
87 #define FT_LCD_FILTER_DEFAULT	1
88 #define FT_LCD_FILTER_LIGHT	2
89 #define FT_LCD_FILTER_LEGACY	16
90 #endif
91 
92 typedef FT_Error (*setLcdFilterFunc)(FT_Library, int);
93 static setLcdFilterFunc setLcdFilter;
94 
95 #define DOUBLE_TO_26_6(d) ((FT_F26Dot6)((d) * 64.0))
96 #define DOUBLE_FROM_26_6(t) ((double)(t) / 64.0)
97 #define DOUBLE_TO_16_16(d) ((FT_Fixed)((d) * 65536.0))
98 #define DOUBLE_FROM_16_16(t) ((double)(t) / 65536.0)
99 
100 /* This is the max number of FT_face objects we keep open at once
101  */
102 #define MAX_OPEN_FACES 10
103 /* This is the maximum font size we allow to be passed to FT_Set_Char_Size
104  */
105 #define MAX_FONT_SIZE 1000
106 
107 /**
108  * SECTION:cairo-ft
109  * @Title: FreeType Fonts
110  * @Short_Description: Font support for FreeType
111  * @See_Also: #cairo_font_face_t
112  *
113  * The FreeType font backend is primarily used to render text on GNU/Linux
114  * systems, but can be used on other platforms too.
115  */
116 
117 /**
118  * CAIRO_HAS_FT_FONT:
119  *
120  * Defined if the FreeType font backend is available.
121  * This macro can be used to conditionally compile backend-specific code.
122  */
123 
124 /**
125  * CAIRO_HAS_FC_FONT:
126  *
127  * Defined if the Fontconfig-specific functions of the FreeType font backend
128  * are available.
129  * This macro can be used to conditionally compile backend-specific code.
130  */
131 
132 /*
133  * The simple 2x2 matrix is converted into separate scale and shape
134  * factors so that hinting works right
135  */
136 
137 typedef struct _cairo_ft_font_transform {
138     double  x_scale, y_scale;
139     double  shape[2][2];
140 } cairo_ft_font_transform_t;
141 
142 /*
143  * We create an object that corresponds to a single font on the disk;
144  * (identified by a filename/id pair) these are shared between all
145  * fonts using that file.  For cairo_ft_font_face_create_for_ft_face(), we
146  * just create a one-off version with a permanent face value.
147  */
148 
149 typedef struct _cairo_ft_font_face cairo_ft_font_face_t;
150 
151 struct _cairo_ft_unscaled_font {
152     cairo_unscaled_font_t base;
153 
154     cairo_bool_t from_face; /* was the FT_Face provided by user? */
155     FT_Face face;	    /* provided or cached face */
156 
157     /* only set if from_face is false */
158     char *filename;
159     int id;
160 
161     /* We temporarily scale the unscaled font as needed */
162     cairo_bool_t have_scale;
163     cairo_matrix_t current_scale;
164     double x_scale;		/* Extracted X scale factor */
165     double y_scale;             /* Extracted Y scale factor */
166     cairo_bool_t have_shape;	/* true if the current scale has a non-scale component*/
167     cairo_matrix_t current_shape;
168     FT_Matrix Current_Shape;
169 
170     cairo_mutex_t mutex;
171     int lock_count;
172 
173     cairo_ft_font_face_t *faces;	/* Linked list of faces for this font */
174 };
175 
176 static int
177 _cairo_ft_unscaled_font_keys_equal (const void *key_a,
178 				    const void *key_b);
179 
180 static void
181 _cairo_ft_unscaled_font_fini (cairo_ft_unscaled_font_t *unscaled);
182 
183 typedef enum _cairo_ft_extra_flags {
184     CAIRO_FT_OPTIONS_HINT_METRICS = (1 << 0),
185     CAIRO_FT_OPTIONS_EMBOLDEN = (1 << 1)
186 } cairo_ft_extra_flags_t;
187 
188 typedef struct _cairo_ft_options {
189     cairo_font_options_t    base;
190     int			    load_flags;	 /* flags for FT_Load_Glyph */
191     cairo_ft_extra_flags_t  extra_flags; /* other flags that affect results */
192 } cairo_ft_options_t;
193 
194 struct _cairo_ft_font_face {
195     cairo_font_face_t base;
196 
197     cairo_ft_unscaled_font_t *unscaled;
198     cairo_ft_options_t ft_options;
199     cairo_ft_font_face_t *next;
200 
201 #if CAIRO_HAS_FC_FONT
202     FcPattern *pattern; /* if pattern is set, the above fields will be NULL */
203     cairo_font_face_t *resolved_font_face;
204     FcConfig *resolved_config;
205 #endif
206 };
207 
208 static const cairo_unscaled_font_backend_t cairo_ft_unscaled_font_backend;
209 
210 #if CAIRO_HAS_FC_FONT
211 static cairo_status_t
212 _cairo_ft_font_options_substitute (const cairo_font_options_t *options,
213 				   FcPattern                  *pattern);
214 
215 static cairo_font_face_t *
216 _cairo_ft_resolve_pattern (FcPattern		      *pattern,
217 			   const cairo_matrix_t       *font_matrix,
218 			   const cairo_matrix_t       *ctm,
219 			   const cairo_font_options_t *options);
220 
221 #endif
222 
223 /*
224  * We maintain a hash table to map file/id => #cairo_ft_unscaled_font_t.
225  * The hash table itself isn't limited in size. However, we limit the
226  * number of FT_Face objects we keep around; when we've exceeded that
227  * limit and need to create a new FT_Face, we dump the FT_Face from a
228  * random #cairo_ft_unscaled_font_t which has an unlocked FT_Face, (if
229  * there are any).
230  */
231 
232 typedef struct _cairo_ft_unscaled_font_map {
233     cairo_hash_table_t *hash_table;
234     FT_Library ft_library;
235     int num_open_faces;
236 } cairo_ft_unscaled_font_map_t;
237 
238 static cairo_ft_unscaled_font_map_t *cairo_ft_unscaled_font_map = NULL;
239 
240 
241 static void
_font_map_release_face_lock_held(cairo_ft_unscaled_font_map_t * font_map,cairo_ft_unscaled_font_t * unscaled)242 _font_map_release_face_lock_held (cairo_ft_unscaled_font_map_t *font_map,
243 				  cairo_ft_unscaled_font_t *unscaled)
244 {
245     if (unscaled->face) {
246 	FT_Done_Face (unscaled->face);
247 	unscaled->face = NULL;
248 	unscaled->have_scale = FALSE;
249 
250 	font_map->num_open_faces--;
251     }
252 }
253 
254 static cairo_status_t
_cairo_ft_unscaled_font_map_create(void)255 _cairo_ft_unscaled_font_map_create (void)
256 {
257     cairo_ft_unscaled_font_map_t *font_map;
258 
259     /* This function is only intended to be called from
260      * _cairo_ft_unscaled_font_map_lock. So we'll crash if we can
261      * detect some other call path. */
262     assert (cairo_ft_unscaled_font_map == NULL);
263 
264     font_map = malloc (sizeof (cairo_ft_unscaled_font_map_t));
265     if (unlikely (font_map == NULL))
266 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
267 
268     font_map->hash_table =
269 	_cairo_hash_table_create (_cairo_ft_unscaled_font_keys_equal);
270 
271     if (unlikely (font_map->hash_table == NULL))
272 	goto FAIL;
273 
274     if (unlikely (FT_Init_FreeType (&font_map->ft_library)))
275 	goto FAIL;
276 
277     font_map->num_open_faces = 0;
278 
279     cairo_ft_unscaled_font_map = font_map;
280     return CAIRO_STATUS_SUCCESS;
281 
282 FAIL:
283     if (font_map->hash_table)
284 	_cairo_hash_table_destroy (font_map->hash_table);
285     free (font_map);
286 
287     return _cairo_error (CAIRO_STATUS_NO_MEMORY);
288 }
289 
290 
291 static void
_cairo_ft_unscaled_font_map_pluck_entry(void * entry,void * closure)292 _cairo_ft_unscaled_font_map_pluck_entry (void *entry, void *closure)
293 {
294     cairo_ft_unscaled_font_t *unscaled = entry;
295     cairo_ft_unscaled_font_map_t *font_map = closure;
296 
297     _cairo_hash_table_remove (font_map->hash_table,
298 			      &unscaled->base.hash_entry);
299 
300     if (! unscaled->from_face)
301 	_font_map_release_face_lock_held (font_map, unscaled);
302 
303     _cairo_ft_unscaled_font_fini (unscaled);
304     free (unscaled);
305 }
306 
307 static void
_cairo_ft_unscaled_font_map_destroy(void)308 _cairo_ft_unscaled_font_map_destroy (void)
309 {
310     cairo_ft_unscaled_font_map_t *font_map;
311 
312     CAIRO_MUTEX_LOCK (_cairo_ft_unscaled_font_map_mutex);
313     font_map = cairo_ft_unscaled_font_map;
314     cairo_ft_unscaled_font_map = NULL;
315     CAIRO_MUTEX_UNLOCK (_cairo_ft_unscaled_font_map_mutex);
316 
317     if (font_map != NULL) {
318 	_cairo_hash_table_foreach (font_map->hash_table,
319 				   _cairo_ft_unscaled_font_map_pluck_entry,
320 				   font_map);
321 	assert (font_map->num_open_faces == 0);
322 
323 	FT_Done_FreeType (font_map->ft_library);
324 
325 	_cairo_hash_table_destroy (font_map->hash_table);
326 
327 	free (font_map);
328     }
329 }
330 
331 static cairo_ft_unscaled_font_map_t *
_cairo_ft_unscaled_font_map_lock(void)332 _cairo_ft_unscaled_font_map_lock (void)
333 {
334     CAIRO_MUTEX_LOCK (_cairo_ft_unscaled_font_map_mutex);
335 
336     if (unlikely (cairo_ft_unscaled_font_map == NULL)) {
337 	if (unlikely (_cairo_ft_unscaled_font_map_create ())) {
338 	    CAIRO_MUTEX_UNLOCK (_cairo_ft_unscaled_font_map_mutex);
339 	    return NULL;
340 	}
341     }
342 
343     return cairo_ft_unscaled_font_map;
344 }
345 
346 static void
_cairo_ft_unscaled_font_map_unlock(void)347 _cairo_ft_unscaled_font_map_unlock (void)
348 {
349     CAIRO_MUTEX_UNLOCK (_cairo_ft_unscaled_font_map_mutex);
350 }
351 
352 static void
_cairo_ft_unscaled_font_init_key(cairo_ft_unscaled_font_t * key,cairo_bool_t from_face,char * filename,int id,FT_Face face)353 _cairo_ft_unscaled_font_init_key (cairo_ft_unscaled_font_t *key,
354 				  cairo_bool_t              from_face,
355 				  char			   *filename,
356 				  int			    id,
357 				  FT_Face		    face)
358 {
359     unsigned long hash;
360 
361     key->from_face = from_face;
362     key->filename = filename;
363     key->id = id;
364     key->face = face;
365 
366     hash = _cairo_hash_string (filename);
367     /* the constants are just arbitrary primes */
368     hash += ((unsigned long) id) * 1607;
369     hash += ((unsigned long) face) * 2137;
370 
371     key->base.hash_entry.hash = hash;
372 }
373 
374 /**
375  * _cairo_ft_unscaled_font_init:
376  *
377  * Initialize a #cairo_ft_unscaled_font_t.
378  *
379  * There are two basic flavors of #cairo_ft_unscaled_font_t, one
380  * created from an FT_Face and the other created from a filename/id
381  * pair. These two flavors are identified as from_face and !from_face.
382  *
383  * To initialize a from_face font, pass filename==%NULL, id=0 and the
384  * desired face.
385  *
386  * To initialize a !from_face font, pass the filename/id as desired
387  * and face==%NULL.
388  *
389  * Note that the code handles these two flavors in very distinct
390  * ways. For example there is a hash_table mapping
391  * filename/id->#cairo_unscaled_font_t in the !from_face case, but no
392  * parallel in the from_face case, (where the calling code would have
393  * to do its own mapping to ensure similar sharing).
394  **/
395 static cairo_status_t
_cairo_ft_unscaled_font_init(cairo_ft_unscaled_font_t * unscaled,cairo_bool_t from_face,const char * filename,int id,FT_Face face)396 _cairo_ft_unscaled_font_init (cairo_ft_unscaled_font_t *unscaled,
397 			      cairo_bool_t              from_face,
398 			      const char	       *filename,
399 			      int			id,
400 			      FT_Face			face)
401 {
402     _cairo_unscaled_font_init (&unscaled->base,
403 			       &cairo_ft_unscaled_font_backend);
404 
405     if (from_face) {
406 	unscaled->from_face = TRUE;
407 	_cairo_ft_unscaled_font_init_key (unscaled, TRUE, NULL, 0, face);
408     } else {
409 	char *filename_copy;
410 
411 	unscaled->from_face = FALSE;
412 	unscaled->face = NULL;
413 
414 	filename_copy = strdup (filename);
415 	if (unlikely (filename_copy == NULL))
416 	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
417 
418 	_cairo_ft_unscaled_font_init_key (unscaled, FALSE, filename_copy, id, NULL);
419     }
420 
421     unscaled->have_scale = FALSE;
422     CAIRO_MUTEX_INIT (unscaled->mutex);
423     unscaled->lock_count = 0;
424 
425     unscaled->faces = NULL;
426 
427     return CAIRO_STATUS_SUCCESS;
428 }
429 
430 /**
431  * _cairo_ft_unscaled_font_fini:
432  *
433  * Free all data associated with a #cairo_ft_unscaled_font_t.
434  *
435  * CAUTION: The unscaled->face field must be %NULL before calling this
436  * function. This is because the #cairo_ft_unscaled_font_t_map keeps a
437  * count of these faces (font_map->num_open_faces) so it maintains the
438  * unscaled->face field while it has its lock held. See
439  * _font_map_release_face_lock_held().
440  **/
441 static void
_cairo_ft_unscaled_font_fini(cairo_ft_unscaled_font_t * unscaled)442 _cairo_ft_unscaled_font_fini (cairo_ft_unscaled_font_t *unscaled)
443 {
444     assert (unscaled->face == NULL);
445 
446     if (unscaled->filename) {
447 	free (unscaled->filename);
448 	unscaled->filename = NULL;
449     }
450 
451     CAIRO_MUTEX_FINI (unscaled->mutex);
452 }
453 
454 static int
_cairo_ft_unscaled_font_keys_equal(const void * key_a,const void * key_b)455 _cairo_ft_unscaled_font_keys_equal (const void *key_a,
456 				    const void *key_b)
457 {
458     const cairo_ft_unscaled_font_t *unscaled_a = key_a;
459     const cairo_ft_unscaled_font_t *unscaled_b = key_b;
460 
461     if (unscaled_a->id == unscaled_b->id &&
462 	unscaled_a->from_face == unscaled_b->from_face)
463     {
464         if (unscaled_a->from_face)
465 	    return unscaled_a->face == unscaled_b->face;
466 
467 	if (unscaled_a->filename == NULL && unscaled_b->filename == NULL)
468 	    return TRUE;
469 	else if (unscaled_a->filename == NULL || unscaled_b->filename == NULL)
470 	    return FALSE;
471 	else
472 	    return (strcmp (unscaled_a->filename, unscaled_b->filename) == 0);
473     }
474 
475     return FALSE;
476 }
477 
478 /* Finds or creates a #cairo_ft_unscaled_font_t for the filename/id from
479  * pattern.  Returns a new reference to the unscaled font.
480  */
481 static cairo_status_t
_cairo_ft_unscaled_font_create_internal(cairo_bool_t from_face,char * filename,int id,FT_Face font_face,cairo_ft_unscaled_font_t ** out)482 _cairo_ft_unscaled_font_create_internal (cairo_bool_t from_face,
483 					 char *filename,
484 					 int id,
485 					 FT_Face font_face,
486 					 cairo_ft_unscaled_font_t **out)
487 {
488     cairo_ft_unscaled_font_t key, *unscaled;
489     cairo_ft_unscaled_font_map_t *font_map;
490     cairo_status_t status;
491 
492     font_map = _cairo_ft_unscaled_font_map_lock ();
493     if (unlikely (font_map == NULL))
494 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
495 
496     _cairo_ft_unscaled_font_init_key (&key, from_face, filename, id, font_face);
497 
498     /* Return existing unscaled font if it exists in the hash table. */
499     unscaled = _cairo_hash_table_lookup (font_map->hash_table,
500 					 &key.base.hash_entry);
501     if (unscaled != NULL) {
502 	_cairo_unscaled_font_reference (&unscaled->base);
503 	goto DONE;
504     }
505 
506     /* Otherwise create it and insert into hash table. */
507     unscaled = malloc (sizeof (cairo_ft_unscaled_font_t));
508     if (unlikely (unscaled == NULL)) {
509 	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
510 	goto UNWIND_FONT_MAP_LOCK;
511     }
512 
513     status = _cairo_ft_unscaled_font_init (unscaled, from_face, filename, id, font_face);
514     if (unlikely (status))
515 	goto UNWIND_UNSCALED_MALLOC;
516 
517     assert (unscaled->base.hash_entry.hash == key.base.hash_entry.hash);
518     status = _cairo_hash_table_insert (font_map->hash_table,
519 				       &unscaled->base.hash_entry);
520     if (unlikely (status))
521 	goto UNWIND_UNSCALED_FONT_INIT;
522 
523 DONE:
524     _cairo_ft_unscaled_font_map_unlock ();
525     *out = unscaled;
526     return CAIRO_STATUS_SUCCESS;
527 
528 UNWIND_UNSCALED_FONT_INIT:
529     _cairo_ft_unscaled_font_fini (unscaled);
530 UNWIND_UNSCALED_MALLOC:
531     free (unscaled);
532 UNWIND_FONT_MAP_LOCK:
533     _cairo_ft_unscaled_font_map_unlock ();
534     return status;
535 }
536 
537 
538 #if CAIRO_HAS_FC_FONT
539 static cairo_status_t
_cairo_ft_unscaled_font_create_for_pattern(FcPattern * pattern,cairo_ft_unscaled_font_t ** out)540 _cairo_ft_unscaled_font_create_for_pattern (FcPattern *pattern,
541 					    cairo_ft_unscaled_font_t **out)
542 {
543     FT_Face font_face = NULL;
544     char *filename = NULL;
545     int id = 0;
546     FcResult ret;
547 
548     ret = FcPatternGetFTFace (pattern, FC_FT_FACE, 0, &font_face);
549     if (ret == FcResultMatch)
550 	goto DONE;
551     if (ret == FcResultOutOfMemory)
552 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
553 
554     ret = FcPatternGetString (pattern, FC_FILE, 0, (FcChar8 **) &filename);
555     if (ret == FcResultOutOfMemory)
556 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
557     if (ret == FcResultMatch) {
558 	/* If FC_INDEX is not set, we just use 0 */
559 	ret = FcPatternGetInteger (pattern, FC_INDEX, 0, &id);
560 	if (ret == FcResultOutOfMemory)
561 	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
562 
563 	goto DONE;
564     }
565 
566     /* The pattern contains neither a face nor a filename, resolve it later. */
567     *out = NULL;
568     return CAIRO_STATUS_SUCCESS;
569 
570 DONE:
571     return _cairo_ft_unscaled_font_create_internal (font_face != NULL,
572 						    filename, id, font_face,
573 						    out);
574 }
575 #endif
576 
577 static cairo_status_t
_cairo_ft_unscaled_font_create_from_face(FT_Face face,cairo_ft_unscaled_font_t ** out)578 _cairo_ft_unscaled_font_create_from_face (FT_Face face,
579 					  cairo_ft_unscaled_font_t **out)
580 {
581     return _cairo_ft_unscaled_font_create_internal (TRUE, NULL, 0, face, out);
582 }
583 
584 static void
_cairo_ft_unscaled_font_destroy(void * abstract_font)585 _cairo_ft_unscaled_font_destroy (void *abstract_font)
586 {
587     cairo_ft_unscaled_font_t *unscaled  = abstract_font;
588     cairo_ft_unscaled_font_map_t *font_map;
589 
590     if (unscaled == NULL)
591 	return;
592 
593     font_map = _cairo_ft_unscaled_font_map_lock ();
594     /* All created objects must have been mapped in the font map. */
595     assert (font_map != NULL);
596 
597     if (CAIRO_REFERENCE_COUNT_HAS_REFERENCE (&unscaled->base.ref_count)) {
598 	/* somebody recreated the font whilst we waited for the lock */
599 	_cairo_ft_unscaled_font_map_unlock ();
600 	return;
601     }
602 
603     _cairo_hash_table_remove (font_map->hash_table,
604 			      &unscaled->base.hash_entry);
605 
606     if (unscaled->from_face) {
607 	/* See comments in _ft_font_face_destroy about the "zombie" state
608 	 * for a _ft_font_face.
609 	 */
610 	if (unscaled->faces && unscaled->faces->unscaled == NULL) {
611 	    assert (unscaled->faces->next == NULL);
612 	    cairo_font_face_destroy (&unscaled->faces->base);
613 	}
614     } else {
615 	_font_map_release_face_lock_held (font_map, unscaled);
616     }
617     unscaled->face = NULL;
618 
619     _cairo_ft_unscaled_font_map_unlock ();
620 
621     _cairo_ft_unscaled_font_fini (unscaled);
622 }
623 
624 static cairo_bool_t
_has_unlocked_face(const void * entry)625 _has_unlocked_face (const void *entry)
626 {
627     const cairo_ft_unscaled_font_t *unscaled = entry;
628 
629     return (!unscaled->from_face && unscaled->lock_count == 0 && unscaled->face);
630 }
631 
632 /* Ensures that an unscaled font has a face object. If we exceed
633  * MAX_OPEN_FACES, try to close some.
634  *
635  * This differs from _cairo_ft_scaled_font_lock_face in that it doesn't
636  * set the scale on the face, but just returns it at the last scale.
637  */
638 cairo_warn FT_Face
_cairo_ft_unscaled_font_lock_face(cairo_ft_unscaled_font_t * unscaled)639 _cairo_ft_unscaled_font_lock_face (cairo_ft_unscaled_font_t *unscaled)
640 {
641     cairo_ft_unscaled_font_map_t *font_map;
642     FT_Face face = NULL;
643 
644     CAIRO_MUTEX_LOCK (unscaled->mutex);
645     unscaled->lock_count++;
646 
647     if (unscaled->face)
648 	return unscaled->face;
649 
650     /* If this unscaled font was created from an FT_Face then we just
651      * returned it above. */
652     assert (!unscaled->from_face);
653 
654     font_map = _cairo_ft_unscaled_font_map_lock ();
655     {
656 	assert (font_map != NULL);
657 
658 	while (font_map->num_open_faces >= MAX_OPEN_FACES)
659 	{
660 	    cairo_ft_unscaled_font_t *entry;
661 
662 	    entry = _cairo_hash_table_random_entry (font_map->hash_table,
663 						    _has_unlocked_face);
664 	    if (entry == NULL)
665 		break;
666 
667 	    _font_map_release_face_lock_held (font_map, entry);
668 	}
669     }
670     _cairo_ft_unscaled_font_map_unlock ();
671 
672     if (FT_New_Face (font_map->ft_library,
673 		     unscaled->filename,
674 		     unscaled->id,
675 		     &face) != FT_Err_Ok)
676     {
677 	unscaled->lock_count--;
678 	CAIRO_MUTEX_UNLOCK (unscaled->mutex);
679 	_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
680 	return NULL;
681     }
682 
683     unscaled->face = face;
684 
685     font_map->num_open_faces++;
686 
687     return face;
688 }
689 
690 
691 /* Unlock unscaled font locked with _cairo_ft_unscaled_font_lock_face
692  */
693 void
_cairo_ft_unscaled_font_unlock_face(cairo_ft_unscaled_font_t * unscaled)694 _cairo_ft_unscaled_font_unlock_face (cairo_ft_unscaled_font_t *unscaled)
695 {
696     assert (unscaled->lock_count > 0);
697 
698     unscaled->lock_count--;
699 
700     CAIRO_MUTEX_UNLOCK (unscaled->mutex);
701 }
702 
703 
704 static cairo_status_t
_compute_transform(cairo_ft_font_transform_t * sf,cairo_matrix_t * scale,cairo_ft_unscaled_font_t * unscaled)705 _compute_transform (cairo_ft_font_transform_t *sf,
706 		    cairo_matrix_t      *scale,
707 		    cairo_ft_unscaled_font_t *unscaled)
708 {
709     cairo_status_t status;
710     double x_scale, y_scale;
711     cairo_matrix_t normalized = *scale;
712 
713     /* The font matrix has x and y "scale" components which we extract and
714      * use as character scale values. These influence the way freetype
715      * chooses hints, as well as selecting different bitmaps in
716      * hand-rendered fonts. We also copy the normalized matrix to
717      * freetype's transformation.
718      */
719 
720     status = _cairo_matrix_compute_basis_scale_factors (scale,
721 						  &x_scale, &y_scale,
722 						  1);
723     if (unlikely (status))
724 	return status;
725 
726     /* FreeType docs say this about x_scale and y_scale:
727      * "A character width or height smaller than 1pt is set to 1pt;"
728      * So, we cap them from below at 1.0 and let the FT transform
729      * take care of sub-1.0 scaling. */
730     if (x_scale < 1.0)
731       x_scale = 1.0;
732     if (y_scale < 1.0)
733       y_scale = 1.0;
734 
735     if (unscaled && (unscaled->face->face_flags & FT_FACE_FLAG_SCALABLE) == 0) {
736 	double min_distance = DBL_MAX;
737 	cairo_bool_t magnify = TRUE;
738 	int i;
739 	int best_i = 0;
740 	double best_x_size = 0;
741 	double best_y_size = 0;
742 
743 	for (i = 0; i < unscaled->face->num_fixed_sizes; i++) {
744 	    double x_size = unscaled->face->available_sizes[i].x_ppem / 64.;
745 	    double y_size = unscaled->face->available_sizes[i].y_ppem / 64.;
746 	    double distance = y_size - y_scale;
747 
748 	    /*
749 	     * distance is positive if current strike is larger than desired
750 	     * size, and negative if smaller.
751 	     *
752 	     * We like to prefer down-scaling to upscaling.
753 	     */
754 
755 	    if ((magnify && distance >= 0) || fabs (distance) <= min_distance) {
756 		magnify = distance < 0;
757 		min_distance = fabs (distance);
758 		best_i = i;
759 		best_x_size = x_size;
760 		best_y_size = y_size;
761 	    }
762 	}
763 
764 	x_scale = best_x_size;
765 	y_scale = best_y_size;
766     }
767 
768     sf->x_scale = x_scale;
769     sf->y_scale = y_scale;
770 
771     cairo_matrix_scale (&normalized, 1.0 / x_scale, 1.0 / y_scale);
772 
773     _cairo_matrix_get_affine (&normalized,
774 			      &sf->shape[0][0], &sf->shape[0][1],
775 			      &sf->shape[1][0], &sf->shape[1][1],
776 			      NULL, NULL);
777 
778     return CAIRO_STATUS_SUCCESS;
779 }
780 
781 /* Temporarily scales an unscaled font to the give scale. We catch
782  * scaling to the same size, since changing a FT_Face is expensive.
783  */
784 static cairo_status_t
_cairo_ft_unscaled_font_set_scale(cairo_ft_unscaled_font_t * unscaled,cairo_matrix_t * scale)785 _cairo_ft_unscaled_font_set_scale (cairo_ft_unscaled_font_t *unscaled,
786 				   cairo_matrix_t	      *scale)
787 {
788     cairo_status_t status;
789     cairo_ft_font_transform_t sf;
790     FT_Matrix mat;
791     FT_Error error;
792     double x_scale, y_scale;
793 
794     assert (unscaled->face != NULL);
795 
796     if (unscaled->have_scale &&
797 	scale->xx == unscaled->current_scale.xx &&
798 	scale->yx == unscaled->current_scale.yx &&
799 	scale->xy == unscaled->current_scale.xy &&
800 	scale->yy == unscaled->current_scale.yy)
801 	return CAIRO_STATUS_SUCCESS;
802 
803     unscaled->have_scale = TRUE;
804     unscaled->current_scale = *scale;
805 
806     status = _compute_transform (&sf, scale, unscaled);
807     if (unlikely (status))
808 	return status;
809 
810     unscaled->x_scale = sf.x_scale;
811     unscaled->y_scale = sf.y_scale;
812 
813     mat.xx = DOUBLE_TO_16_16(sf.shape[0][0]);
814     mat.yx = - DOUBLE_TO_16_16(sf.shape[0][1]);
815     mat.xy = - DOUBLE_TO_16_16(sf.shape[1][0]);
816     mat.yy = DOUBLE_TO_16_16(sf.shape[1][1]);
817 
818     unscaled->have_shape = (mat.xx != 0x10000 ||
819 			    mat.yx != 0x00000 ||
820 			    mat.xy != 0x00000 ||
821 			    mat.yy != 0x10000);
822 
823     unscaled->Current_Shape = mat;
824     cairo_matrix_init (&unscaled->current_shape,
825 		       sf.shape[0][0], sf.shape[0][1],
826 		       sf.shape[1][0], sf.shape[1][1],
827 		       0.0, 0.0);
828 
829     FT_Set_Transform(unscaled->face, &mat, NULL);
830 
831     x_scale = MIN(sf.x_scale, MAX_FONT_SIZE);
832     y_scale = MIN(sf.y_scale, MAX_FONT_SIZE);
833     error = FT_Set_Char_Size (unscaled->face,
834 			      x_scale * 64.0 + .5,
835 			      y_scale * 64.0 + .5,
836 			      0, 0);
837     if (error)
838       return _cairo_error (CAIRO_STATUS_NO_MEMORY);
839 
840     return CAIRO_STATUS_SUCCESS;
841 }
842 
843 /* we sometimes need to convert the glyph bitmap in a FT_GlyphSlot
844  * into a different format. For example, we want to convert a
845  * FT_PIXEL_MODE_LCD or FT_PIXEL_MODE_LCD_V bitmap into a 32-bit
846  * ARGB or ABGR bitmap.
847  *
848  * this function prepares a target descriptor for this operation.
849  *
850  * input :: target bitmap descriptor. The function will set its
851  *          'width', 'rows' and 'pitch' fields, and only these
852  *
853  * slot  :: the glyph slot containing the source bitmap. this
854  *          function assumes that slot->format == FT_GLYPH_FORMAT_BITMAP
855  *
856  * mode  :: the requested final rendering mode. supported values are
857  *          MONO, NORMAL (i.e. gray), LCD and LCD_V
858  *
859  * the function returns the size in bytes of the corresponding buffer,
860  * it's up to the caller to allocate the corresponding memory block
861  * before calling _fill_xrender_bitmap
862  *
863  * it also returns -1 in case of error (e.g. incompatible arguments,
864  * like trying to convert a gray bitmap into a monochrome one)
865  */
866 static int
_compute_xrender_bitmap_size(FT_Bitmap * target,FT_GlyphSlot slot,FT_Render_Mode mode)867 _compute_xrender_bitmap_size(FT_Bitmap      *target,
868 			     FT_GlyphSlot    slot,
869 			     FT_Render_Mode  mode)
870 {
871     FT_Bitmap *ftbit;
872     int width, height, pitch;
873 
874     if (slot->format != FT_GLYPH_FORMAT_BITMAP)
875 	return -1;
876 
877     /* compute the size of the final bitmap */
878     ftbit = &slot->bitmap;
879 
880     width = ftbit->width;
881     height = ftbit->rows;
882     pitch = (width + 3) & ~3;
883 
884     switch (ftbit->pixel_mode) {
885     case FT_PIXEL_MODE_MONO:
886 	if (mode == FT_RENDER_MODE_MONO) {
887 	    pitch = (((width + 31) & ~31) >> 3);
888 	    break;
889 	}
890 	/* fall-through */
891 
892     case FT_PIXEL_MODE_GRAY:
893 	if (mode == FT_RENDER_MODE_LCD ||
894 	    mode == FT_RENDER_MODE_LCD_V)
895 	{
896 	    /* each pixel is replicated into a 32-bit ARGB value */
897 	    pitch = width * 4;
898 	}
899 	break;
900 
901     case FT_PIXEL_MODE_LCD:
902 	if (mode != FT_RENDER_MODE_LCD)
903 	    return -1;
904 
905 	/* horz pixel triplets are packed into 32-bit ARGB values */
906 	width /= 3;
907 	pitch = width * 4;
908 	break;
909 
910     case FT_PIXEL_MODE_LCD_V:
911 	if (mode != FT_RENDER_MODE_LCD_V)
912 	    return -1;
913 
914 	/* vert pixel triplets are packed into 32-bit ARGB values */
915 	height /= 3;
916 	pitch = width * 4;
917 	break;
918 
919     default:  /* unsupported source format */
920 	return -1;
921     }
922 
923     target->width = width;
924     target->rows = height;
925     target->pitch = pitch;
926     target->buffer = NULL;
927 
928     return pitch * height;
929 }
930 
931 /* this functions converts the glyph bitmap found in a FT_GlyphSlot
932  * into a different format (see _compute_xrender_bitmap_size)
933  *
934  * you should call this function after _compute_xrender_bitmap_size
935  *
936  * target :: target bitmap descriptor. Note that its 'buffer' pointer
937  *           must point to memory allocated by the caller
938  *
939  * slot   :: the glyph slot containing the source bitmap
940  *
941  * mode   :: the requested final rendering mode
942  *
943  * bgr    :: boolean, set if BGR or VBGR pixel ordering is needed
944  */
945 static void
_fill_xrender_bitmap(FT_Bitmap * target,FT_GlyphSlot slot,FT_Render_Mode mode,int bgr)946 _fill_xrender_bitmap(FT_Bitmap      *target,
947 		     FT_GlyphSlot    slot,
948 		     FT_Render_Mode  mode,
949 		     int             bgr)
950 {
951     FT_Bitmap *ftbit = &slot->bitmap;
952     unsigned char *srcLine = ftbit->buffer;
953     unsigned char *dstLine = target->buffer;
954     int src_pitch = ftbit->pitch;
955     int width = target->width;
956     int height = target->rows;
957     int pitch = target->pitch;
958     int subpixel;
959     int h;
960 
961     subpixel = (mode == FT_RENDER_MODE_LCD ||
962 		mode == FT_RENDER_MODE_LCD_V);
963 
964     if (src_pitch < 0)
965 	srcLine -= src_pitch * (ftbit->rows - 1);
966 
967     target->pixel_mode = ftbit->pixel_mode;
968 
969     switch (ftbit->pixel_mode) {
970     case FT_PIXEL_MODE_MONO:
971 	if (subpixel) {
972 	    /* convert mono to ARGB32 values */
973 
974 	    for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
975 		int x;
976 
977 		for (x = 0; x < width; x++) {
978 		    if (srcLine[(x >> 3)] & (0x80 >> (x & 7)))
979 			((unsigned int *) dstLine)[x] = 0xffffffffU;
980 		}
981 	    }
982 	    target->pixel_mode = FT_PIXEL_MODE_LCD;
983 
984 	} else if (mode == FT_RENDER_MODE_NORMAL) {
985 	    /* convert mono to 8-bit gray */
986 
987 	    for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
988 		int x;
989 
990 		for (x = 0; x < width; x++) {
991 		    if (srcLine[(x >> 3)] & (0x80 >> (x & 7)))
992 			dstLine[x] = 0xff;
993 		}
994 	    }
995 	    target->pixel_mode = FT_PIXEL_MODE_GRAY;
996 
997 	} else {
998 	    /* copy mono to mono */
999 
1000 	    int  bytes = (width + 7) >> 3;
1001 
1002 	    for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch)
1003 		memcpy (dstLine, srcLine, bytes);
1004 	}
1005 	break;
1006 
1007     case FT_PIXEL_MODE_GRAY:
1008 	if (subpixel) {
1009 	    /* convert gray to ARGB32 values */
1010 
1011 	    for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
1012 		int x;
1013 		unsigned int *dst = (unsigned int *) dstLine;
1014 
1015 		for (x = 0; x < width; x++) {
1016 		    unsigned int pix = srcLine[x];
1017 
1018 		    pix |= (pix << 8);
1019 		    pix |= (pix << 16);
1020 
1021 		    dst[x] = pix;
1022 		}
1023 	    }
1024 	    target->pixel_mode = FT_PIXEL_MODE_LCD;
1025         } else {
1026             /* copy gray into gray */
1027 
1028             for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch)
1029                 memcpy (dstLine, srcLine, width);
1030         }
1031         break;
1032 
1033     case FT_PIXEL_MODE_LCD:
1034 	if (!bgr) {
1035 	    /* convert horizontal RGB into ARGB32 */
1036 
1037 	    for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
1038 		int x;
1039 		unsigned char *src = srcLine;
1040 		unsigned int *dst = (unsigned int *) dstLine;
1041 
1042 		for (x = 0; x < width; x++, src += 3) {
1043 		    unsigned int  pix;
1044 
1045 		    pix = ((unsigned int)src[0] << 16) |
1046 			  ((unsigned int)src[1] <<  8) |
1047 			  ((unsigned int)src[2]      ) |
1048 			  ((unsigned int)src[1] << 24) ;
1049 
1050 		    dst[x] = pix;
1051 		}
1052 	    }
1053 	} else {
1054 	    /* convert horizontal BGR into ARGB32 */
1055 
1056 	    for (h = height; h > 0; h--, srcLine += src_pitch, dstLine += pitch) {
1057 
1058 		int x;
1059 		unsigned char *src = srcLine;
1060 		unsigned int *dst = (unsigned int *) dstLine;
1061 
1062 		for (x = 0; x < width; x++, src += 3) {
1063 		    unsigned int  pix;
1064 
1065 		    pix = ((unsigned int)src[2] << 16) |
1066 			  ((unsigned int)src[1] <<  8) |
1067 			  ((unsigned int)src[0]      ) |
1068 			  ((unsigned int)src[1] << 24) ;
1069 
1070 		    dst[x] = pix;
1071 		}
1072 	    }
1073 	}
1074 	break;
1075 
1076     default:  /* FT_PIXEL_MODE_LCD_V */
1077 	/* convert vertical RGB into ARGB32 */
1078 	if (!bgr) {
1079 
1080 	    for (h = height; h > 0; h--, srcLine += 3 * src_pitch, dstLine += pitch) {
1081 		int x;
1082 		unsigned char* src = srcLine;
1083 		unsigned int*  dst = (unsigned int *) dstLine;
1084 
1085 		for (x = 0; x < width; x++, src += 1) {
1086 		    unsigned int pix;
1087 		    pix = ((unsigned int)src[0]           << 16) |
1088 			  ((unsigned int)src[src_pitch]   <<  8) |
1089 			  ((unsigned int)src[src_pitch*2]      ) |
1090 			  ((unsigned int)src[src_pitch]   << 24) ;
1091 		    dst[x] = pix;
1092 		}
1093 	    }
1094 	} else {
1095 
1096 	    for (h = height; h > 0; h--, srcLine += 3*src_pitch, dstLine += pitch) {
1097 		int x;
1098 		unsigned char *src = srcLine;
1099 		unsigned int *dst = (unsigned int *) dstLine;
1100 
1101 		for (x = 0; x < width; x++, src += 1) {
1102 		    unsigned int  pix;
1103 
1104 		    pix = ((unsigned int)src[src_pitch * 2] << 16) |
1105 			  ((unsigned int)src[src_pitch]     <<  8) |
1106 			  ((unsigned int)src[0]                  ) |
1107 			  ((unsigned int)src[src_pitch]     << 24) ;
1108 
1109 		    dst[x] = pix;
1110 		}
1111 	    }
1112 	}
1113     }
1114 }
1115 
1116 
1117 /* Fills in val->image with an image surface created from @bitmap
1118  */
1119 static cairo_status_t
_get_bitmap_surface(FT_Bitmap * bitmap,FT_Library library,cairo_bool_t own_buffer,cairo_font_options_t * font_options,cairo_image_surface_t ** surface)1120 _get_bitmap_surface (FT_Bitmap		     *bitmap,
1121 		     FT_Library		      library,
1122 		     cairo_bool_t	      own_buffer,
1123 		     cairo_font_options_t    *font_options,
1124 		     cairo_image_surface_t  **surface)
1125 {
1126     int width, height, stride;
1127     unsigned char *data;
1128     int format = CAIRO_FORMAT_A8;
1129     cairo_image_surface_t *image;
1130     cairo_bool_t component_alpha = FALSE;
1131 
1132     width = bitmap->width;
1133     height = bitmap->rows;
1134 
1135     if (width == 0 || height == 0) {
1136 	*surface = (cairo_image_surface_t *)
1137 	    cairo_image_surface_create_for_data (NULL, format, 0, 0, 0);
1138 	return (*surface)->base.status;
1139     }
1140 
1141     switch (bitmap->pixel_mode) {
1142     case FT_PIXEL_MODE_MONO:
1143 	stride = (((width + 31) & ~31) >> 3);
1144 	if (own_buffer) {
1145 	    data = bitmap->buffer;
1146 	    assert (stride == bitmap->pitch);
1147 	} else {
1148 	    data = _cairo_malloc_ab (height, stride);
1149 	    if (!data)
1150 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1151 
1152 	    if (stride == bitmap->pitch) {
1153 		memcpy (data, bitmap->buffer, stride * height);
1154 	    } else {
1155 		int i;
1156 		unsigned char *source, *dest;
1157 		int copy_len = MIN (stride, bitmap->pitch);
1158 		int pad_len = stride - bitmap->pitch;
1159 
1160 		source = bitmap->buffer;
1161 		dest = data;
1162 		for (i = height; i; i--) {
1163 		    memcpy (dest, source, copy_len);
1164 		    source += bitmap->pitch;
1165 		    dest += stride;
1166 		}
1167 		/* do we really care about zeroing any extra row padding in dest? */
1168 		if (pad_len > 0) {
1169 		    dest = data + copy_len;
1170 		    for (i = height; i; i--) {
1171 			memset (dest, '\0', pad_len);
1172 			dest += stride;
1173 		    }
1174 		}
1175 	    }
1176 	}
1177 
1178 #ifndef WORDS_BIGENDIAN
1179 	{
1180 	    uint8_t   *d = data;
1181 	    int		count = stride * height;
1182 
1183 	    while (count--) {
1184 		*d = CAIRO_BITSWAP8 (*d);
1185 		d++;
1186 	    }
1187 	}
1188 #endif
1189 	format = CAIRO_FORMAT_A1;
1190 	break;
1191 
1192     case FT_PIXEL_MODE_LCD:
1193     case FT_PIXEL_MODE_LCD_V:
1194     case FT_PIXEL_MODE_GRAY:
1195 	if (font_options->antialias != CAIRO_ANTIALIAS_SUBPIXEL ||
1196 	    bitmap->pixel_mode == FT_PIXEL_MODE_GRAY)
1197 	{
1198 	    stride = bitmap->pitch;
1199 
1200 	    /* We don't support stride not multiple of 4. */
1201 	    if (stride & 3)
1202 	    {
1203 		assert (!own_buffer);
1204 		goto convert;
1205 	    }
1206 
1207 	    if (own_buffer) {
1208 		data = bitmap->buffer;
1209 	    } else {
1210 		data = _cairo_malloc_ab (height, stride);
1211 		if (!data)
1212 		    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1213 
1214 		memcpy (data, bitmap->buffer, stride * height);
1215 	    }
1216 
1217 	    format = CAIRO_FORMAT_A8;
1218 	} else {
1219 	    data = bitmap->buffer;
1220 	    stride = bitmap->pitch;
1221 	    format = CAIRO_FORMAT_ARGB32;
1222 	    component_alpha = TRUE;
1223 	}
1224 	break;
1225 #ifdef FT_LOAD_COLOR
1226     case FT_PIXEL_MODE_BGRA:
1227 	stride = width * 4;
1228 	if (own_buffer) {
1229 	    data = bitmap->buffer;
1230 	} else {
1231 	    data = _cairo_malloc_ab (height, stride);
1232 	    if (!data)
1233 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1234 
1235 	    memcpy (data, bitmap->buffer, stride * height);
1236 	}
1237 	format = CAIRO_FORMAT_ARGB32;
1238 	break;
1239 #endif
1240     case FT_PIXEL_MODE_GRAY2:
1241     case FT_PIXEL_MODE_GRAY4:
1242     convert:
1243 	if (!own_buffer && library)
1244 	{
1245 	    /* This is pretty much the only case that we can get in here. */
1246 	    /* Convert to 8bit grayscale. */
1247 
1248 	    FT_Bitmap  tmp;
1249 	    FT_Int     align;
1250 
1251 	    format = CAIRO_FORMAT_A8;
1252 
1253 	    align = cairo_format_stride_for_width (format, bitmap->width);
1254 
1255 	    FT_Bitmap_New( &tmp );
1256 
1257 	    if (FT_Bitmap_Convert( library, bitmap, &tmp, align ))
1258 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1259 
1260 	    FT_Bitmap_Done( library, bitmap );
1261 	    *bitmap = tmp;
1262 
1263 	    stride = bitmap->pitch;
1264 	    data = _cairo_malloc_ab (height, stride);
1265 	    if (!data)
1266 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1267 
1268 	    if (bitmap->num_grays != 256)
1269 	    {
1270 	      unsigned int x, y;
1271 	      unsigned int mul = 255 / (bitmap->num_grays - 1);
1272 	      FT_Byte *p = bitmap->buffer;
1273 	      for (y = 0; y < height; y++) {
1274 	        for (x = 0; x < width; x++)
1275 		  p[x] *= mul;
1276 		p += bitmap->pitch;
1277 	      }
1278 	    }
1279 
1280 	    memcpy (data, bitmap->buffer, stride * height);
1281 	    break;
1282 	}
1283 	/* These could be triggered by very rare types of TrueType fonts */
1284     default:
1285 	if (own_buffer)
1286 	    free (bitmap->buffer);
1287 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1288     }
1289 
1290     /* XXX */
1291     *surface = image = (cairo_image_surface_t *)
1292 	cairo_image_surface_create_for_data (data,
1293 					     format,
1294 					     width, height, stride);
1295     if (image->base.status) {
1296 	free (data);
1297 	return (*surface)->base.status;
1298     }
1299 
1300     if (component_alpha)
1301 	pixman_image_set_component_alpha (image->pixman_image, TRUE);
1302 
1303     _cairo_image_surface_assume_ownership_of_data (image);
1304 
1305     _cairo_debug_check_image_surface_is_defined (&image->base);
1306 
1307     return CAIRO_STATUS_SUCCESS;
1308 }
1309 
1310 /* Converts an outline FT_GlyphSlot into an image
1311  *
1312  * This could go through _render_glyph_bitmap as well, letting
1313  * FreeType convert the outline to a bitmap, but doing it ourselves
1314  * has two minor advantages: first, we save a copy of the bitmap
1315  * buffer: we can directly use the buffer that FreeType renders
1316  * into.
1317  *
1318  * Second, it may help when we add support for subpixel
1319  * rendering: the Xft code does it this way. (Keith thinks that
1320  * it may also be possible to get the subpixel rendering with
1321  * FT_Render_Glyph: something worth looking into in more detail
1322  * when we add subpixel support. If so, we may want to eliminate
1323  * this version of the code path entirely.
1324  */
1325 static cairo_status_t
_render_glyph_outline(FT_Face face,cairo_font_options_t * font_options,cairo_image_surface_t ** surface)1326 _render_glyph_outline (FT_Face                    face,
1327 		       cairo_font_options_t	 *font_options,
1328 		       cairo_image_surface_t	**surface)
1329 {
1330     int rgba = FC_RGBA_UNKNOWN;
1331     int lcd_filter = FT_LCD_FILTER_LEGACY;
1332     FT_GlyphSlot glyphslot = face->glyph;
1333     FT_Outline *outline = &glyphslot->outline;
1334     FT_Bitmap bitmap;
1335     FT_BBox cbox;
1336     unsigned int width, height;
1337     cairo_status_t status;
1338     FT_Error fterror;
1339     FT_Library library = glyphslot->library;
1340     FT_Render_Mode render_mode = FT_RENDER_MODE_NORMAL;
1341 
1342     switch (font_options->antialias) {
1343     case CAIRO_ANTIALIAS_NONE:
1344 	render_mode = FT_RENDER_MODE_MONO;
1345 	break;
1346 
1347     case CAIRO_ANTIALIAS_SUBPIXEL:
1348 	switch (font_options->subpixel_order) {
1349 	    case CAIRO_SUBPIXEL_ORDER_DEFAULT:
1350 	    case CAIRO_SUBPIXEL_ORDER_RGB:
1351 	    case CAIRO_SUBPIXEL_ORDER_BGR:
1352 		render_mode = FT_RENDER_MODE_LCD;
1353 		break;
1354 
1355 	    case CAIRO_SUBPIXEL_ORDER_VRGB:
1356 	    case CAIRO_SUBPIXEL_ORDER_VBGR:
1357 		render_mode = FT_RENDER_MODE_LCD_V;
1358 		break;
1359 	}
1360 
1361 	switch (font_options->lcd_filter) {
1362 	case CAIRO_LCD_FILTER_NONE:
1363 	    lcd_filter = FT_LCD_FILTER_NONE;
1364 	    break;
1365 	case CAIRO_LCD_FILTER_DEFAULT:
1366 	case CAIRO_LCD_FILTER_INTRA_PIXEL:
1367 	    lcd_filter = FT_LCD_FILTER_LEGACY;
1368 	    break;
1369 	case CAIRO_LCD_FILTER_FIR3:
1370 	    lcd_filter = FT_LCD_FILTER_LIGHT;
1371 	    break;
1372 	case CAIRO_LCD_FILTER_FIR5:
1373 	    lcd_filter = FT_LCD_FILTER_DEFAULT;
1374 	    break;
1375 	}
1376 
1377 	break;
1378 
1379     case CAIRO_ANTIALIAS_DEFAULT:
1380     case CAIRO_ANTIALIAS_GRAY:
1381 	render_mode = FT_RENDER_MODE_NORMAL;
1382     }
1383 
1384     FT_Outline_Get_CBox (outline, &cbox);
1385 
1386     cbox.xMin &= -64;
1387     cbox.yMin &= -64;
1388     cbox.xMax = (cbox.xMax + 63) & -64;
1389     cbox.yMax = (cbox.yMax + 63) & -64;
1390 
1391     width = (unsigned int) ((cbox.xMax - cbox.xMin) >> 6);
1392     height = (unsigned int) ((cbox.yMax - cbox.yMin) >> 6);
1393 
1394     if (width * height == 0) {
1395 	cairo_format_t format;
1396 	/* Looks like fb handles zero-sized images just fine */
1397 	switch (render_mode) {
1398 	case FT_RENDER_MODE_MONO:
1399 	    format = CAIRO_FORMAT_A1;
1400 	    break;
1401 	case FT_RENDER_MODE_LCD:
1402 	case FT_RENDER_MODE_LCD_V:
1403 	    format= CAIRO_FORMAT_ARGB32;
1404 	    break;
1405 	case FT_RENDER_MODE_LIGHT:
1406 	case FT_RENDER_MODE_NORMAL:
1407 	case FT_RENDER_MODE_MAX:
1408 	default:
1409 	    format = CAIRO_FORMAT_A8;
1410 	    break;
1411 	}
1412 
1413 	(*surface) = (cairo_image_surface_t *)
1414 	    cairo_image_surface_create_for_data (NULL, format, 0, 0, 0);
1415 	if ((*surface)->base.status)
1416 	    return (*surface)->base.status;
1417     } else {
1418 
1419 	int bitmap_size;
1420         static int initialized_setLcdFilter = 0;
1421 
1422 	switch (render_mode) {
1423 	case FT_RENDER_MODE_LCD:
1424 	    if (font_options->subpixel_order == CAIRO_SUBPIXEL_ORDER_BGR) {
1425 		rgba = FC_RGBA_BGR;
1426 	    } else {
1427 		rgba = FC_RGBA_RGB;
1428 	    }
1429             break;
1430 	case FT_RENDER_MODE_LCD_V:
1431 	    if (font_options->subpixel_order == CAIRO_SUBPIXEL_ORDER_VBGR) {
1432 		rgba = FC_RGBA_VBGR;
1433 	    } else {
1434 		rgba = FC_RGBA_VRGB;
1435 		}
1436 	    break;
1437 	case FT_RENDER_MODE_MONO:
1438 	case FT_RENDER_MODE_LIGHT:
1439 	case FT_RENDER_MODE_NORMAL:
1440 	case FT_RENDER_MODE_MAX:
1441 	default:
1442 	    break;
1443 	    }
1444 
1445         if (!initialized_setLcdFilter) {
1446           initialized_setLcdFilter = 1;
1447 #ifdef HAVE_FT_LIBRARY_SETLCDFILTER
1448 	  setLcdFilter = &FT_Library_SetLcdFilter;
1449 #else
1450           setLcdFilter = (setLcdFilterFunc) dlsym(RTLD_DEFAULT, "FT_Library_SetLcdFilter");
1451 #endif
1452         }
1453 
1454 	if (setLcdFilter)
1455           setLcdFilter (library, lcd_filter);
1456 
1457 	fterror = FT_Render_Glyph (face->glyph, render_mode);
1458 
1459 	if (setLcdFilter)
1460           setLcdFilter (library, FT_LCD_FILTER_NONE);
1461 
1462 	if (fterror != 0)
1463 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1464 
1465 	bitmap_size = _compute_xrender_bitmap_size (&bitmap,
1466 						    face->glyph,
1467 						    render_mode);
1468 	if (bitmap_size < 0)
1469 	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1470 
1471 	bitmap.buffer = calloc (1, bitmap_size);
1472 	if (bitmap.buffer == NULL)
1473 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1474 
1475 	_fill_xrender_bitmap (&bitmap, face->glyph, render_mode,
1476 			      (rgba == FC_RGBA_BGR || rgba == FC_RGBA_VBGR));
1477 
1478 	/* Note:
1479 	 * _get_bitmap_surface will free bitmap.buffer if there is an error
1480 	 */
1481 	status = _get_bitmap_surface (&bitmap, NULL, TRUE, font_options, surface);
1482 	if (unlikely (status))
1483 	    return status;
1484 
1485 	/* Note: the font's coordinate system is upside down from ours, so the
1486 	 * Y coordinate of the control box needs to be negated.  Moreover, device
1487 	 * offsets are position of glyph origin relative to top left while xMin
1488 	 * and yMax are offsets of top left relative to origin.  Another negation.
1489 	 */
1490 	cairo_surface_set_device_offset (&(*surface)->base,
1491 					 (double)-glyphslot->bitmap_left,
1492 					 (double)+glyphslot->bitmap_top);
1493     }
1494 
1495     return CAIRO_STATUS_SUCCESS;
1496 }
1497 
1498 /* Converts a bitmap (or other) FT_GlyphSlot into an image */
1499 static cairo_status_t
_render_glyph_bitmap(FT_Face face,cairo_font_options_t * font_options,cairo_image_surface_t ** surface)1500 _render_glyph_bitmap (FT_Face		      face,
1501 		      cairo_font_options_t   *font_options,
1502 		      cairo_image_surface_t **surface)
1503 {
1504     FT_GlyphSlot glyphslot = face->glyph;
1505     cairo_status_t status;
1506     FT_Error error;
1507 
1508     /* According to the FreeType docs, glyphslot->format could be
1509      * something other than FT_GLYPH_FORMAT_OUTLINE or
1510      * FT_GLYPH_FORMAT_BITMAP. Calling FT_Render_Glyph gives FreeType
1511      * the opportunity to convert such to
1512      * bitmap. FT_GLYPH_FORMAT_COMPOSITE will not be encountered since
1513      * we avoid the FT_LOAD_NO_RECURSE flag.
1514      */
1515     error = FT_Render_Glyph (glyphslot, FT_RENDER_MODE_NORMAL);
1516     /* XXX ignoring all other errors for now.  They are not fatal, typically
1517      * just a glyph-not-found. */
1518     if (error == FT_Err_Out_Of_Memory)
1519 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1520 
1521     status = _get_bitmap_surface (&glyphslot->bitmap,
1522 				  glyphslot->library,
1523 				  FALSE, font_options,
1524 				  surface);
1525     if (unlikely (status))
1526 	return status;
1527 
1528     /*
1529      * Note: the font's coordinate system is upside down from ours, so the
1530      * Y coordinate of the control box needs to be negated.  Moreover, device
1531      * offsets are position of glyph origin relative to top left while
1532      * bitmap_left and bitmap_top are offsets of top left relative to origin.
1533      * Another negation.
1534      */
1535     cairo_surface_set_device_offset (&(*surface)->base,
1536 				     -glyphslot->bitmap_left,
1537 				     +glyphslot->bitmap_top);
1538 
1539     return CAIRO_STATUS_SUCCESS;
1540 }
1541 
1542 static cairo_status_t
_transform_glyph_bitmap(cairo_matrix_t * shape,cairo_image_surface_t ** surface)1543 _transform_glyph_bitmap (cairo_matrix_t         * shape,
1544 			 cairo_image_surface_t ** surface)
1545 {
1546     cairo_matrix_t original_to_transformed;
1547     cairo_matrix_t transformed_to_original;
1548     cairo_image_surface_t *old_image;
1549     cairo_surface_t *image;
1550     double x[4], y[4];
1551     double origin_x, origin_y;
1552     int orig_width, orig_height;
1553     int i;
1554     int x_min, y_min, x_max, y_max;
1555     int width, height;
1556     cairo_status_t status;
1557     cairo_surface_pattern_t pattern;
1558 
1559     /* We want to compute a transform that takes the origin
1560      * (device_x_offset, device_y_offset) to 0,0, then applies
1561      * the "shape" portion of the font transform
1562      */
1563     original_to_transformed = *shape;
1564 
1565     cairo_surface_get_device_offset (&(*surface)->base, &origin_x, &origin_y);
1566     orig_width = (*surface)->width;
1567     orig_height = (*surface)->height;
1568 
1569     cairo_matrix_translate (&original_to_transformed,
1570 			    -origin_x, -origin_y);
1571 
1572     /* Find the bounding box of the original bitmap under that
1573      * transform
1574      */
1575     x[0] = 0;          y[0] = 0;
1576     x[1] = orig_width; y[1] = 0;
1577     x[2] = orig_width; y[2] = orig_height;
1578     x[3] = 0;          y[3] = orig_height;
1579 
1580     for (i = 0; i < 4; i++)
1581       cairo_matrix_transform_point (&original_to_transformed,
1582 				    &x[i], &y[i]);
1583 
1584     x_min = floor (x[0]);   y_min = floor (y[0]);
1585     x_max =  ceil (x[0]);   y_max =  ceil (y[0]);
1586 
1587     for (i = 1; i < 4; i++) {
1588 	if (x[i] < x_min)
1589 	    x_min = floor (x[i]);
1590 	else if (x[i] > x_max)
1591 	    x_max = ceil (x[i]);
1592 	if (y[i] < y_min)
1593 	    y_min = floor (y[i]);
1594 	else if (y[i] > y_max)
1595 	    y_max = ceil (y[i]);
1596     }
1597 
1598     /* Adjust the transform so that the bounding box starts at 0,0 ...
1599      * this gives our final transform from original bitmap to transformed
1600      * bitmap.
1601      */
1602     original_to_transformed.x0 -= x_min;
1603     original_to_transformed.y0 -= y_min;
1604 
1605     /* Create the transformed bitmap */
1606     width  = x_max - x_min;
1607     height = y_max - y_min;
1608 
1609     transformed_to_original = original_to_transformed;
1610     status = cairo_matrix_invert (&transformed_to_original);
1611     if (unlikely (status))
1612 	return status;
1613 
1614     if (cairo_image_surface_get_format (*surface) == CAIRO_FORMAT_ARGB32 &&
1615         !pixman_image_get_component_alpha ((*surface)->pixman_image))
1616       image = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
1617     else
1618       image = cairo_image_surface_create (CAIRO_FORMAT_A8, width, height);
1619     if (unlikely (image->status))
1620 	return image->status;
1621 
1622     /* Draw the original bitmap transformed into the new bitmap
1623      */
1624     _cairo_pattern_init_for_surface (&pattern, &(*surface)->base);
1625     cairo_pattern_set_matrix (&pattern.base, &transformed_to_original);
1626 
1627     status = _cairo_surface_paint (image,
1628 				   CAIRO_OPERATOR_SOURCE,
1629 				   &pattern.base,
1630 				   NULL);
1631 
1632     _cairo_pattern_fini (&pattern.base);
1633 
1634     if (unlikely (status)) {
1635 	cairo_surface_destroy (image);
1636 	return status;
1637     }
1638 
1639     /* Now update the cache entry for the new bitmap, recomputing
1640      * the origin based on the final transform.
1641      */
1642     cairo_matrix_transform_point (&original_to_transformed,
1643 				  &origin_x, &origin_y);
1644 
1645     old_image = (*surface);
1646     (*surface) = (cairo_image_surface_t *)image;
1647     cairo_surface_destroy (&old_image->base);
1648 
1649     cairo_surface_set_device_offset (&(*surface)->base,
1650 				     _cairo_lround (origin_x),
1651 				     _cairo_lround (origin_y));
1652     return CAIRO_STATUS_SUCCESS;
1653 }
1654 
1655 static const cairo_unscaled_font_backend_t cairo_ft_unscaled_font_backend = {
1656     _cairo_ft_unscaled_font_destroy,
1657 #if 0
1658     _cairo_ft_unscaled_font_create_glyph
1659 #endif
1660 };
1661 
1662 /* #cairo_ft_scaled_font_t */
1663 
1664 typedef struct _cairo_ft_scaled_font {
1665     cairo_scaled_font_t base;
1666     cairo_ft_unscaled_font_t *unscaled;
1667     cairo_ft_options_t ft_options;
1668 } cairo_ft_scaled_font_t;
1669 
1670 static const cairo_scaled_font_backend_t _cairo_ft_scaled_font_backend;
1671 
1672 #if CAIRO_HAS_FC_FONT
1673 /* The load flags passed to FT_Load_Glyph control aspects like hinting and
1674  * antialiasing. Here we compute them from the fields of a FcPattern.
1675  */
1676 static void
_get_pattern_ft_options(FcPattern * pattern,cairo_ft_options_t * ret)1677 _get_pattern_ft_options (FcPattern *pattern, cairo_ft_options_t *ret)
1678 {
1679     FcBool antialias, vertical_layout, hinting, autohint, bitmap, embolden;
1680     cairo_ft_options_t ft_options;
1681     int rgba;
1682 #ifdef FC_HINT_STYLE
1683     int hintstyle;
1684 #endif
1685 
1686     _cairo_font_options_init_default (&ft_options.base);
1687     ft_options.load_flags = FT_LOAD_DEFAULT;
1688     ft_options.extra_flags = 0;
1689 
1690 #ifndef FC_EMBEDDED_BITMAP
1691 #define FC_EMBEDDED_BITMAP "embeddedbitmap"
1692 #endif
1693 
1694     /* Check whether to force use of embedded bitmaps */
1695     if (FcPatternGetBool (pattern,
1696 			  FC_EMBEDDED_BITMAP, 0, &bitmap) != FcResultMatch)
1697 	bitmap = FcFalse;
1698 
1699     /* disable antialiasing if requested */
1700     if (FcPatternGetBool (pattern,
1701 			  FC_ANTIALIAS, 0, &antialias) != FcResultMatch)
1702 	antialias = FcTrue;
1703 
1704     if (antialias) {
1705 	cairo_subpixel_order_t subpixel_order;
1706 	int lcd_filter;
1707 
1708 	/* disable hinting if requested */
1709 	if (FcPatternGetBool (pattern,
1710 			      FC_HINTING, 0, &hinting) != FcResultMatch)
1711 	    hinting = FcTrue;
1712 
1713 	if (FcPatternGetInteger (pattern,
1714 				 FC_RGBA, 0, &rgba) != FcResultMatch)
1715 	    rgba = FC_RGBA_UNKNOWN;
1716 
1717 	switch (rgba) {
1718 	case FC_RGBA_RGB:
1719 	    subpixel_order = CAIRO_SUBPIXEL_ORDER_RGB;
1720 	    break;
1721 	case FC_RGBA_BGR:
1722 	    subpixel_order = CAIRO_SUBPIXEL_ORDER_BGR;
1723 	    break;
1724 	case FC_RGBA_VRGB:
1725 	    subpixel_order = CAIRO_SUBPIXEL_ORDER_VRGB;
1726 	    break;
1727 	case FC_RGBA_VBGR:
1728 	    subpixel_order = CAIRO_SUBPIXEL_ORDER_VBGR;
1729 	    break;
1730 	case FC_RGBA_UNKNOWN:
1731 	case FC_RGBA_NONE:
1732 	default:
1733 	    subpixel_order = CAIRO_SUBPIXEL_ORDER_DEFAULT;
1734 	    break;
1735 	}
1736 
1737 	if (subpixel_order != CAIRO_SUBPIXEL_ORDER_DEFAULT) {
1738 	    ft_options.base.subpixel_order = subpixel_order;
1739 	    ft_options.base.antialias = CAIRO_ANTIALIAS_SUBPIXEL;
1740 	}
1741 
1742 	if (FcPatternGetInteger (pattern,
1743 				 FC_LCD_FILTER, 0, &lcd_filter) == FcResultMatch)
1744 	{
1745 	    switch (lcd_filter) {
1746 	    case FC_LCD_NONE:
1747 		ft_options.base.lcd_filter = CAIRO_LCD_FILTER_NONE;
1748 		break;
1749 	    case FC_LCD_DEFAULT:
1750 		ft_options.base.lcd_filter = CAIRO_LCD_FILTER_FIR5;
1751 		break;
1752 	    case FC_LCD_LIGHT:
1753 		ft_options.base.lcd_filter = CAIRO_LCD_FILTER_FIR3;
1754 		break;
1755 	    case FC_LCD_LEGACY:
1756 		ft_options.base.lcd_filter = CAIRO_LCD_FILTER_INTRA_PIXEL;
1757 		break;
1758 	    }
1759 	}
1760 
1761 #ifdef FC_HINT_STYLE
1762 	if (FcPatternGetInteger (pattern,
1763 				 FC_HINT_STYLE, 0, &hintstyle) != FcResultMatch)
1764 	    hintstyle = FC_HINT_FULL;
1765 
1766 	if (!hinting)
1767 	    hintstyle = FC_HINT_NONE;
1768 
1769 	switch (hintstyle) {
1770 	case FC_HINT_NONE:
1771 	    ft_options.base.hint_style = CAIRO_HINT_STYLE_NONE;
1772 	    break;
1773 	case FC_HINT_SLIGHT:
1774 	    ft_options.base.hint_style = CAIRO_HINT_STYLE_SLIGHT;
1775 	    break;
1776 	case FC_HINT_MEDIUM:
1777 	default:
1778 	    ft_options.base.hint_style = CAIRO_HINT_STYLE_MEDIUM;
1779 	    break;
1780 	case FC_HINT_FULL:
1781 	    ft_options.base.hint_style = CAIRO_HINT_STYLE_FULL;
1782 	    break;
1783 	}
1784 #else /* !FC_HINT_STYLE */
1785 	if (!hinting) {
1786 	    ft_options.base.hint_style = CAIRO_HINT_STYLE_NONE;
1787 	}
1788 #endif /* FC_HINT_STYLE */
1789 
1790 	/* Force embedded bitmaps off if no hinting requested */
1791 	if (ft_options.base.hint_style == CAIRO_HINT_STYLE_NONE)
1792 	  bitmap = FcFalse;
1793 
1794 	if (!bitmap)
1795 	    ft_options.load_flags |= FT_LOAD_NO_BITMAP;
1796 
1797     } else {
1798 	ft_options.base.antialias = CAIRO_ANTIALIAS_NONE;
1799     }
1800 
1801     /* force autohinting if requested */
1802     if (FcPatternGetBool (pattern,
1803 			  FC_AUTOHINT, 0, &autohint) != FcResultMatch)
1804 	autohint = FcFalse;
1805 
1806     if (autohint)
1807 	ft_options.load_flags |= FT_LOAD_FORCE_AUTOHINT;
1808 
1809     if (FcPatternGetBool (pattern,
1810 			  FC_VERTICAL_LAYOUT, 0, &vertical_layout) != FcResultMatch)
1811 	vertical_layout = FcFalse;
1812 
1813     if (vertical_layout)
1814 	ft_options.load_flags |= FT_LOAD_VERTICAL_LAYOUT;
1815 
1816 #ifndef FC_EMBOLDEN
1817 #define FC_EMBOLDEN "embolden"
1818 #endif
1819     if (FcPatternGetBool (pattern,
1820 			  FC_EMBOLDEN, 0, &embolden) != FcResultMatch)
1821 	embolden = FcFalse;
1822 
1823     if (embolden)
1824 	ft_options.extra_flags |= CAIRO_FT_OPTIONS_EMBOLDEN;
1825 
1826     *ret = ft_options;
1827 }
1828 #endif
1829 
1830 static void
_cairo_ft_options_merge(cairo_ft_options_t * options,cairo_ft_options_t * other)1831 _cairo_ft_options_merge (cairo_ft_options_t *options,
1832 			 cairo_ft_options_t *other)
1833 {
1834     int load_flags = other->load_flags;
1835     int load_target = FT_LOAD_TARGET_NORMAL;
1836 
1837     /* clear load target mode */
1838     load_flags &= ~(FT_LOAD_TARGET_(FT_LOAD_TARGET_MODE(other->load_flags)));
1839 
1840     if (load_flags & FT_LOAD_NO_HINTING)
1841 	other->base.hint_style = CAIRO_HINT_STYLE_NONE;
1842 
1843     if (other->base.antialias == CAIRO_ANTIALIAS_NONE ||
1844 	options->base.antialias == CAIRO_ANTIALIAS_NONE) {
1845 	options->base.antialias = CAIRO_ANTIALIAS_NONE;
1846 	options->base.subpixel_order = CAIRO_SUBPIXEL_ORDER_DEFAULT;
1847     } else if (options->base.antialias != CAIRO_ANTIALIAS_GRAY) {
1848 	/* The surface supports subpixel aa, so let the font face options
1849 	 * choose whether to use subpixel aa.  If the surface has
1850 	 * CAIRO_ANTIALIAS_GRAY (e.g. PS, PDF, SVG, translucent part of a
1851 	 * CONTENT_COLOR_ALPHA surface), then don't accept subpixel aa. */
1852 	if (other->base.antialias != CAIRO_ANTIALIAS_DEFAULT)
1853 	    options->base.antialias = other->base.antialias;
1854 	/* If the surface knows the subpixel order then use that. */
1855 	if (options->base.subpixel_order == CAIRO_SUBPIXEL_ORDER_DEFAULT)
1856 	    options->base.subpixel_order = other->base.subpixel_order;
1857     }
1858 
1859     if (options->base.hint_style == CAIRO_HINT_STYLE_DEFAULT)
1860 	options->base.hint_style = other->base.hint_style;
1861 
1862     if (other->base.hint_style == CAIRO_HINT_STYLE_NONE)
1863 	options->base.hint_style = CAIRO_HINT_STYLE_NONE;
1864 
1865     if (options->base.lcd_filter == CAIRO_LCD_FILTER_DEFAULT)
1866 	options->base.lcd_filter = other->base.lcd_filter;
1867 
1868     if (other->base.lcd_filter == CAIRO_LCD_FILTER_NONE)
1869 	options->base.lcd_filter = CAIRO_LCD_FILTER_NONE;
1870 
1871     if (options->base.antialias == CAIRO_ANTIALIAS_NONE) {
1872 	if (options->base.hint_style == CAIRO_HINT_STYLE_NONE)
1873 	    load_flags |= FT_LOAD_NO_HINTING;
1874 	else
1875 	    load_target = FT_LOAD_TARGET_MONO;
1876 	load_flags |= FT_LOAD_MONOCHROME;
1877     } else {
1878 	switch (options->base.hint_style) {
1879 	case CAIRO_HINT_STYLE_NONE:
1880 	    load_flags |= FT_LOAD_NO_HINTING;
1881 	    break;
1882 	case CAIRO_HINT_STYLE_SLIGHT:
1883 	    load_target = FT_LOAD_TARGET_LIGHT;
1884 	    break;
1885 	case CAIRO_HINT_STYLE_MEDIUM:
1886 	    break;
1887 	case CAIRO_HINT_STYLE_FULL:
1888 	case CAIRO_HINT_STYLE_DEFAULT:
1889 	    if (options->base.antialias == CAIRO_ANTIALIAS_SUBPIXEL) {
1890 		switch (options->base.subpixel_order) {
1891 		case CAIRO_SUBPIXEL_ORDER_DEFAULT:
1892 		case CAIRO_SUBPIXEL_ORDER_RGB:
1893 		case CAIRO_SUBPIXEL_ORDER_BGR:
1894 		    load_target = FT_LOAD_TARGET_LCD;
1895 		    break;
1896 		case CAIRO_SUBPIXEL_ORDER_VRGB:
1897 		case CAIRO_SUBPIXEL_ORDER_VBGR:
1898 		    load_target = FT_LOAD_TARGET_LCD_V;
1899 		break;
1900 		}
1901 	    }
1902 	    break;
1903 	}
1904     }
1905 
1906     options->load_flags = load_flags | load_target;
1907     options->extra_flags = other->extra_flags;
1908     if (options->base.hint_metrics != CAIRO_HINT_METRICS_OFF)
1909 	options->extra_flags |= CAIRO_FT_OPTIONS_HINT_METRICS;
1910 }
1911 
1912 static cairo_status_t
_cairo_ft_font_face_scaled_font_create(void * abstract_font_face,const cairo_matrix_t * font_matrix,const cairo_matrix_t * ctm,const cairo_font_options_t * options,cairo_scaled_font_t ** font_out)1913 _cairo_ft_font_face_scaled_font_create (void		    *abstract_font_face,
1914 					const cairo_matrix_t	 *font_matrix,
1915 					const cairo_matrix_t	 *ctm,
1916 					const cairo_font_options_t *options,
1917 					cairo_scaled_font_t       **font_out)
1918 {
1919     cairo_ft_font_face_t *font_face = abstract_font_face;
1920     cairo_ft_scaled_font_t *scaled_font;
1921     FT_Face face;
1922     FT_Size_Metrics *metrics;
1923     cairo_font_extents_t fs_metrics;
1924     cairo_status_t status;
1925     cairo_ft_unscaled_font_t *unscaled;
1926 
1927     assert (font_face->unscaled);
1928 
1929     face = _cairo_ft_unscaled_font_lock_face (font_face->unscaled);
1930     if (unlikely (face == NULL)) /* backend error */
1931 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
1932 
1933     scaled_font = malloc (sizeof (cairo_ft_scaled_font_t));
1934     if (unlikely (scaled_font == NULL)) {
1935 	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
1936 	goto FAIL;
1937     }
1938 
1939     scaled_font->unscaled = unscaled = font_face->unscaled;
1940     _cairo_unscaled_font_reference (&unscaled->base);
1941 
1942     _cairo_font_options_init_copy (&scaled_font->ft_options.base, options);
1943     _cairo_ft_options_merge (&scaled_font->ft_options, &font_face->ft_options);
1944 
1945     status = _cairo_scaled_font_init (&scaled_font->base,
1946 			              &font_face->base,
1947 				      font_matrix, ctm, options,
1948 				      &_cairo_ft_scaled_font_backend);
1949     if (unlikely (status))
1950 	goto CLEANUP_SCALED_FONT;
1951 
1952     status = _cairo_ft_unscaled_font_set_scale (unscaled,
1953 				                &scaled_font->base.scale);
1954     if (unlikely (status)) {
1955 	/* This can only fail if we encounter an error with the underlying
1956 	 * font, so propagate the error back to the font-face. */
1957 	_cairo_ft_unscaled_font_unlock_face (unscaled);
1958 	_cairo_unscaled_font_destroy (&unscaled->base);
1959 	free (scaled_font);
1960 	return status;
1961     }
1962 
1963 
1964     metrics = &face->size->metrics;
1965 
1966     /*
1967      * Get to unscaled metrics so that the upper level can get back to
1968      * user space
1969      *
1970      * Also use this path for bitmap-only fonts.  The other branch uses
1971      * face members that are only relevant for scalable fonts.  This is
1972      * detected by simply checking for units_per_EM==0.
1973      */
1974     if (scaled_font->base.options.hint_metrics != CAIRO_HINT_METRICS_OFF ||
1975 	face->units_per_EM == 0) {
1976 	double x_factor, y_factor;
1977 
1978 	if (unscaled->x_scale == 0)
1979 	    x_factor = 0;
1980 	else
1981 	    x_factor = 1 / unscaled->x_scale;
1982 
1983 	if (unscaled->y_scale == 0)
1984 	    y_factor = 0;
1985 	else
1986 	    y_factor = 1 / unscaled->y_scale;
1987 
1988 	fs_metrics.ascent =        DOUBLE_FROM_26_6(metrics->ascender) * y_factor;
1989 	fs_metrics.descent =       DOUBLE_FROM_26_6(- metrics->descender) * y_factor;
1990 	fs_metrics.height =        DOUBLE_FROM_26_6(metrics->height) * y_factor;
1991 	if (!_cairo_ft_scaled_font_is_vertical (&scaled_font->base)) {
1992 	    fs_metrics.max_x_advance = DOUBLE_FROM_26_6(metrics->max_advance) * x_factor;
1993 	    fs_metrics.max_y_advance = 0;
1994 	} else {
1995 	    fs_metrics.max_x_advance = 0;
1996 	    fs_metrics.max_y_advance = DOUBLE_FROM_26_6(metrics->max_advance) * y_factor;
1997 	}
1998     } else {
1999 	double scale = face->units_per_EM;
2000 
2001 	fs_metrics.ascent =        face->ascender / scale;
2002 	fs_metrics.descent =       - face->descender / scale;
2003 	fs_metrics.height =        face->height / scale;
2004 	if (!_cairo_ft_scaled_font_is_vertical (&scaled_font->base)) {
2005 	    fs_metrics.max_x_advance = face->max_advance_width / scale;
2006 	    fs_metrics.max_y_advance = 0;
2007 	} else {
2008 	    fs_metrics.max_x_advance = 0;
2009 	    fs_metrics.max_y_advance = face->max_advance_height / scale;
2010 	}
2011     }
2012 
2013     status = _cairo_scaled_font_set_metrics (&scaled_font->base, &fs_metrics);
2014     if (unlikely (status))
2015 	goto CLEANUP_SCALED_FONT;
2016 
2017     _cairo_ft_unscaled_font_unlock_face (unscaled);
2018 
2019     *font_out = &scaled_font->base;
2020     return CAIRO_STATUS_SUCCESS;
2021 
2022   CLEANUP_SCALED_FONT:
2023     _cairo_unscaled_font_destroy (&unscaled->base);
2024     free (scaled_font);
2025   FAIL:
2026     _cairo_ft_unscaled_font_unlock_face (font_face->unscaled);
2027     *font_out = _cairo_scaled_font_create_in_error (status);
2028     return CAIRO_STATUS_SUCCESS; /* non-backend error */
2029 }
2030 
2031 cairo_bool_t
_cairo_scaled_font_is_ft(cairo_scaled_font_t * scaled_font)2032 _cairo_scaled_font_is_ft (cairo_scaled_font_t *scaled_font)
2033 {
2034     return scaled_font->backend == &_cairo_ft_scaled_font_backend;
2035 }
2036 
2037 static void
_cairo_ft_scaled_font_fini(void * abstract_font)2038 _cairo_ft_scaled_font_fini (void *abstract_font)
2039 {
2040     cairo_ft_scaled_font_t *scaled_font = abstract_font;
2041 
2042     if (scaled_font == NULL)
2043         return;
2044 
2045     _cairo_unscaled_font_destroy (&scaled_font->unscaled->base);
2046 }
2047 
2048 static int
_move_to(FT_Vector * to,void * closure)2049 _move_to (FT_Vector *to, void *closure)
2050 {
2051     cairo_path_fixed_t *path = closure;
2052     cairo_fixed_t x, y;
2053 
2054     x = _cairo_fixed_from_26_6 (to->x);
2055     y = _cairo_fixed_from_26_6 (to->y);
2056 
2057     if (_cairo_path_fixed_close_path (path) != CAIRO_STATUS_SUCCESS)
2058 	return 1;
2059     if (_cairo_path_fixed_move_to (path, x, y) != CAIRO_STATUS_SUCCESS)
2060 	return 1;
2061 
2062     return 0;
2063 }
2064 
2065 static int
_line_to(FT_Vector * to,void * closure)2066 _line_to (FT_Vector *to, void *closure)
2067 {
2068     cairo_path_fixed_t *path = closure;
2069     cairo_fixed_t x, y;
2070 
2071     x = _cairo_fixed_from_26_6 (to->x);
2072     y = _cairo_fixed_from_26_6 (to->y);
2073 
2074     if (_cairo_path_fixed_line_to (path, x, y) != CAIRO_STATUS_SUCCESS)
2075 	return 1;
2076 
2077     return 0;
2078 }
2079 
2080 static int
_conic_to(FT_Vector * control,FT_Vector * to,void * closure)2081 _conic_to (FT_Vector *control, FT_Vector *to, void *closure)
2082 {
2083     cairo_path_fixed_t *path = closure;
2084 
2085     cairo_fixed_t x0, y0;
2086     cairo_fixed_t x1, y1;
2087     cairo_fixed_t x2, y2;
2088     cairo_fixed_t x3, y3;
2089     cairo_point_t conic;
2090 
2091     if (! _cairo_path_fixed_get_current_point (path, &x0, &y0))
2092 	return 1;
2093 
2094     conic.x = _cairo_fixed_from_26_6 (control->x);
2095     conic.y = _cairo_fixed_from_26_6 (control->y);
2096 
2097     x3 = _cairo_fixed_from_26_6 (to->x);
2098     y3 = _cairo_fixed_from_26_6 (to->y);
2099 
2100     x1 = x0 + 2.0/3.0 * (conic.x - x0);
2101     y1 = y0 + 2.0/3.0 * (conic.y - y0);
2102 
2103     x2 = x3 + 2.0/3.0 * (conic.x - x3);
2104     y2 = y3 + 2.0/3.0 * (conic.y - y3);
2105 
2106     if (_cairo_path_fixed_curve_to (path,
2107 				    x1, y1,
2108 				    x2, y2,
2109 				    x3, y3) != CAIRO_STATUS_SUCCESS)
2110 	return 1;
2111 
2112     return 0;
2113 }
2114 
2115 static int
_cubic_to(FT_Vector * control1,FT_Vector * control2,FT_Vector * to,void * closure)2116 _cubic_to (FT_Vector *control1, FT_Vector *control2,
2117 	   FT_Vector *to, void *closure)
2118 {
2119     cairo_path_fixed_t *path = closure;
2120     cairo_fixed_t x0, y0;
2121     cairo_fixed_t x1, y1;
2122     cairo_fixed_t x2, y2;
2123 
2124     x0 = _cairo_fixed_from_26_6 (control1->x);
2125     y0 = _cairo_fixed_from_26_6 (control1->y);
2126 
2127     x1 = _cairo_fixed_from_26_6 (control2->x);
2128     y1 = _cairo_fixed_from_26_6 (control2->y);
2129 
2130     x2 = _cairo_fixed_from_26_6 (to->x);
2131     y2 = _cairo_fixed_from_26_6 (to->y);
2132 
2133     if (_cairo_path_fixed_curve_to (path,
2134 				    x0, y0,
2135 				    x1, y1,
2136 				    x2, y2) != CAIRO_STATUS_SUCCESS)
2137 	return 1;
2138 
2139     return 0;
2140 }
2141 
2142 static cairo_status_t
_decompose_glyph_outline(FT_Face face,cairo_font_options_t * options,cairo_path_fixed_t ** pathp)2143 _decompose_glyph_outline (FT_Face		  face,
2144 			  cairo_font_options_t	 *options,
2145 			  cairo_path_fixed_t	**pathp)
2146 {
2147     static const FT_Outline_Funcs outline_funcs = {
2148 	(FT_Outline_MoveToFunc)_move_to,
2149 	(FT_Outline_LineToFunc)_line_to,
2150 	(FT_Outline_ConicToFunc)_conic_to,
2151 	(FT_Outline_CubicToFunc)_cubic_to,
2152 	0, /* shift */
2153 	0, /* delta */
2154     };
2155     static const FT_Matrix invert_y = {
2156 	DOUBLE_TO_16_16 (1.0), 0,
2157 	0, DOUBLE_TO_16_16 (-1.0),
2158     };
2159 
2160     FT_GlyphSlot glyph;
2161     cairo_path_fixed_t *path;
2162     cairo_status_t status;
2163 
2164     path = _cairo_path_fixed_create ();
2165     if (!path)
2166 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2167 
2168     glyph = face->glyph;
2169 
2170     /* Font glyphs have an inverted Y axis compared to cairo. */
2171     FT_Outline_Transform (&glyph->outline, &invert_y);
2172     if (FT_Outline_Decompose (&glyph->outline, &outline_funcs, path)) {
2173 	_cairo_path_fixed_destroy (path);
2174 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2175     }
2176 
2177     status = _cairo_path_fixed_close_path (path);
2178     if (unlikely (status)) {
2179 	_cairo_path_fixed_destroy (path);
2180 	return status;
2181     }
2182 
2183     *pathp = path;
2184 
2185     return CAIRO_STATUS_SUCCESS;
2186 }
2187 
2188 /*
2189  * Translate glyph to match its metrics.
2190  */
2191 static void
_cairo_ft_scaled_glyph_vertical_layout_bearing_fix(void * abstract_font,FT_GlyphSlot glyph)2192 _cairo_ft_scaled_glyph_vertical_layout_bearing_fix (void        *abstract_font,
2193 						    FT_GlyphSlot glyph)
2194 {
2195     cairo_ft_scaled_font_t *scaled_font = abstract_font;
2196     FT_Vector vector;
2197 
2198     vector.x = glyph->metrics.vertBearingX - glyph->metrics.horiBearingX;
2199     vector.y = -glyph->metrics.vertBearingY - glyph->metrics.horiBearingY;
2200 
2201     if (glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
2202 	FT_Vector_Transform (&vector, &scaled_font->unscaled->Current_Shape);
2203 	FT_Outline_Translate(&glyph->outline, vector.x, vector.y);
2204     } else if (glyph->format == FT_GLYPH_FORMAT_BITMAP) {
2205 	glyph->bitmap_left += vector.x / 64;
2206 	glyph->bitmap_top  += vector.y / 64;
2207     }
2208 }
2209 
2210 static cairo_int_status_t
_cairo_ft_scaled_glyph_init(void * abstract_font,cairo_scaled_glyph_t * scaled_glyph,cairo_scaled_glyph_info_t info)2211 _cairo_ft_scaled_glyph_init (void			*abstract_font,
2212 			     cairo_scaled_glyph_t	*scaled_glyph,
2213 			     cairo_scaled_glyph_info_t	 info)
2214 {
2215     cairo_text_extents_t    fs_metrics;
2216     cairo_ft_scaled_font_t *scaled_font = abstract_font;
2217     cairo_ft_unscaled_font_t *unscaled = scaled_font->unscaled;
2218     FT_GlyphSlot glyph;
2219     FT_Face face;
2220     FT_Error error;
2221     int load_flags = scaled_font->ft_options.load_flags;
2222     FT_Glyph_Metrics *metrics;
2223     double x_factor, y_factor;
2224     cairo_bool_t vertical_layout = FALSE;
2225     cairo_status_t status;
2226 
2227     face = _cairo_ft_unscaled_font_lock_face (unscaled);
2228     if (!face)
2229 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2230 
2231     status = _cairo_ft_unscaled_font_set_scale (scaled_font->unscaled,
2232 				                &scaled_font->base.scale);
2233     if (unlikely (status))
2234 	goto FAIL;
2235 
2236     /* Ignore global advance unconditionally */
2237     load_flags |= FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH;
2238 
2239     if ((info & CAIRO_SCALED_GLYPH_INFO_PATH) != 0 &&
2240 	(info & CAIRO_SCALED_GLYPH_INFO_SURFACE) == 0)
2241 	load_flags |= FT_LOAD_NO_BITMAP;
2242 
2243     /*
2244      * Don't pass FT_LOAD_VERTICAL_LAYOUT to FT_Load_Glyph here as
2245      * suggested by freetype people.
2246      */
2247     if (load_flags & FT_LOAD_VERTICAL_LAYOUT) {
2248 	load_flags &= ~FT_LOAD_VERTICAL_LAYOUT;
2249 	vertical_layout = TRUE;
2250     }
2251 
2252 #ifdef FT_LOAD_COLOR
2253     /* Color-glyph support:
2254      *
2255      * This flags needs plumbing through fontconfig (does it?), and
2256      * maybe we should cache color and grayscale bitmaps separately
2257      * such that users of the font (ie. the surface) can choose which
2258      * version to use based on target content type.
2259      */
2260 
2261     load_flags |= FT_LOAD_COLOR;
2262 #endif
2263 
2264     error = FT_Load_Glyph (scaled_font->unscaled->face,
2265 			   _cairo_scaled_glyph_index(scaled_glyph),
2266 			   load_flags);
2267     /* XXX ignoring all other errors for now.  They are not fatal, typically
2268      * just a glyph-not-found. */
2269     if (error == FT_Err_Out_Of_Memory) {
2270 	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2271 	goto FAIL;
2272     }
2273 
2274     glyph = face->glyph;
2275 
2276 #if HAVE_FT_GLYPHSLOT_EMBOLDEN
2277     /*
2278      * embolden glyphs if requested
2279      */
2280     if (scaled_font->ft_options.extra_flags & CAIRO_FT_OPTIONS_EMBOLDEN)
2281 	FT_GlyphSlot_Embolden (glyph);
2282 #endif
2283 
2284     if (vertical_layout)
2285 	_cairo_ft_scaled_glyph_vertical_layout_bearing_fix (scaled_font, glyph);
2286 
2287     if (info & CAIRO_SCALED_GLYPH_INFO_METRICS) {
2288 
2289 	cairo_bool_t hint_metrics = scaled_font->base.options.hint_metrics != CAIRO_HINT_METRICS_OFF;
2290 	/*
2291 	 * Compute font-space metrics
2292 	 */
2293 	metrics = &glyph->metrics;
2294 
2295 	if (unscaled->x_scale == 0)
2296 	    x_factor = 0;
2297 	else
2298 	    x_factor = 1 / unscaled->x_scale;
2299 
2300 	if (unscaled->y_scale == 0)
2301 	    y_factor = 0;
2302 	else
2303 	    y_factor = 1 / unscaled->y_scale;
2304 
2305 	/*
2306 	 * Note: Y coordinates of the horizontal bearing need to be negated.
2307 	 *
2308 	 * Scale metrics back to glyph space from the scaled glyph space returned
2309 	 * by FreeType
2310 	 *
2311 	 * If we want hinted metrics but aren't asking for hinted glyphs from
2312 	 * FreeType, then we need to do the metric hinting ourselves.
2313 	 */
2314 
2315 	if (hint_metrics && (load_flags & FT_LOAD_NO_HINTING))
2316 	{
2317 	    FT_Pos x1, x2;
2318 	    FT_Pos y1, y2;
2319 	    FT_Pos advance;
2320 
2321 	    if (!vertical_layout) {
2322 		x1 = (metrics->horiBearingX) & -64;
2323 		x2 = (metrics->horiBearingX + metrics->width + 63) & -64;
2324 		y1 = (-metrics->horiBearingY) & -64;
2325 		y2 = (-metrics->horiBearingY + metrics->height + 63) & -64;
2326 
2327 		advance = ((metrics->horiAdvance + 32) & -64);
2328 
2329 		fs_metrics.x_bearing = DOUBLE_FROM_26_6 (x1) * x_factor;
2330 		fs_metrics.y_bearing = DOUBLE_FROM_26_6 (y1) * y_factor;
2331 
2332 		fs_metrics.width  = DOUBLE_FROM_26_6 (x2 - x1) * x_factor;
2333 		fs_metrics.height  = DOUBLE_FROM_26_6 (y2 - y1) * y_factor;
2334 
2335 		fs_metrics.x_advance = DOUBLE_FROM_26_6 (advance) * x_factor;
2336 		fs_metrics.y_advance = 0;
2337 	    } else {
2338 		x1 = (metrics->vertBearingX) & -64;
2339 		x2 = (metrics->vertBearingX + metrics->width + 63) & -64;
2340 		y1 = (metrics->vertBearingY) & -64;
2341 		y2 = (metrics->vertBearingY + metrics->height + 63) & -64;
2342 
2343 		advance = ((metrics->vertAdvance + 32) & -64);
2344 
2345 		fs_metrics.x_bearing = DOUBLE_FROM_26_6 (x1) * x_factor;
2346 		fs_metrics.y_bearing = DOUBLE_FROM_26_6 (y1) * y_factor;
2347 
2348 		fs_metrics.width  = DOUBLE_FROM_26_6 (x2 - x1) * x_factor;
2349 		fs_metrics.height  = DOUBLE_FROM_26_6 (y2 - y1) * y_factor;
2350 
2351 		fs_metrics.x_advance = 0;
2352 		fs_metrics.y_advance = DOUBLE_FROM_26_6 (advance) * y_factor;
2353 	    }
2354 	 } else {
2355 	    fs_metrics.width  = DOUBLE_FROM_26_6 (metrics->width) * x_factor;
2356 	    fs_metrics.height = DOUBLE_FROM_26_6 (metrics->height) * y_factor;
2357 
2358 	    if (!vertical_layout) {
2359 		fs_metrics.x_bearing = DOUBLE_FROM_26_6 (metrics->horiBearingX) * x_factor;
2360 		fs_metrics.y_bearing = DOUBLE_FROM_26_6 (-metrics->horiBearingY) * y_factor;
2361 
2362 		if (hint_metrics || glyph->format != FT_GLYPH_FORMAT_OUTLINE)
2363 		    fs_metrics.x_advance = DOUBLE_FROM_26_6 (metrics->horiAdvance) * x_factor;
2364 		else
2365 		    fs_metrics.x_advance = DOUBLE_FROM_16_16 (glyph->linearHoriAdvance) * x_factor;
2366 		fs_metrics.y_advance = 0 * y_factor;
2367 	    } else {
2368 		fs_metrics.x_bearing = DOUBLE_FROM_26_6 (metrics->vertBearingX) * x_factor;
2369 		fs_metrics.y_bearing = DOUBLE_FROM_26_6 (metrics->vertBearingY) * y_factor;
2370 
2371 		fs_metrics.x_advance = 0 * x_factor;
2372 		if (hint_metrics || glyph->format != FT_GLYPH_FORMAT_OUTLINE)
2373 		    fs_metrics.y_advance = DOUBLE_FROM_26_6 (metrics->vertAdvance) * y_factor;
2374 		else
2375 		    fs_metrics.y_advance = DOUBLE_FROM_16_16 (glyph->linearVertAdvance) * y_factor;
2376 	    }
2377 	 }
2378 
2379 	_cairo_scaled_glyph_set_metrics (scaled_glyph,
2380 					 &scaled_font->base,
2381 					 &fs_metrics);
2382     }
2383 
2384     if ((info & CAIRO_SCALED_GLYPH_INFO_SURFACE) != 0) {
2385 	cairo_image_surface_t	*surface;
2386 
2387 	if (glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
2388 	    status = _render_glyph_outline (face, &scaled_font->ft_options.base,
2389 					    &surface);
2390 	} else {
2391 	    status = _render_glyph_bitmap (face, &scaled_font->ft_options.base,
2392 					   &surface);
2393 	    if (likely (status == CAIRO_STATUS_SUCCESS) &&
2394 		unscaled->have_shape)
2395 	    {
2396 		status = _transform_glyph_bitmap (&unscaled->current_shape,
2397 						  &surface);
2398 		if (unlikely (status))
2399 		    cairo_surface_destroy (&surface->base);
2400 	    }
2401 	}
2402 	if (unlikely (status))
2403 	    goto FAIL;
2404 
2405 	_cairo_scaled_glyph_set_surface (scaled_glyph,
2406 					 &scaled_font->base,
2407 					 surface);
2408     }
2409 
2410     if (info & CAIRO_SCALED_GLYPH_INFO_PATH) {
2411 	cairo_path_fixed_t *path = NULL; /* hide compiler warning */
2412 
2413 	/*
2414 	 * A kludge -- the above code will trash the outline,
2415 	 * so reload it. This will probably never occur though
2416 	 */
2417 	if ((info & CAIRO_SCALED_GLYPH_INFO_SURFACE) != 0) {
2418 	    error = FT_Load_Glyph (face,
2419 				   _cairo_scaled_glyph_index(scaled_glyph),
2420 				   load_flags | FT_LOAD_NO_BITMAP);
2421 	    /* XXX ignoring all other errors for now.  They are not fatal, typically
2422 	     * just a glyph-not-found. */
2423 	    if (error == FT_Err_Out_Of_Memory) {
2424 		status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2425 		goto FAIL;
2426 	    }
2427 #if HAVE_FT_GLYPHSLOT_EMBOLDEN
2428 	    /*
2429 	     * embolden glyphs if requested
2430 	     */
2431 	    if (scaled_font->ft_options.extra_flags & CAIRO_FT_OPTIONS_EMBOLDEN)
2432 		FT_GlyphSlot_Embolden (glyph);
2433 #endif
2434 	    if (vertical_layout)
2435 		_cairo_ft_scaled_glyph_vertical_layout_bearing_fix (scaled_font, glyph);
2436 
2437 	}
2438 	if (glyph->format == FT_GLYPH_FORMAT_OUTLINE)
2439 	    status = _decompose_glyph_outline (face, &scaled_font->ft_options.base,
2440 					       &path);
2441 	else
2442 	    status = CAIRO_INT_STATUS_UNSUPPORTED;
2443 
2444 	if (unlikely (status))
2445 	    goto FAIL;
2446 
2447 	_cairo_scaled_glyph_set_path (scaled_glyph,
2448 				      &scaled_font->base,
2449 				      path);
2450     }
2451  FAIL:
2452     _cairo_ft_unscaled_font_unlock_face (unscaled);
2453 
2454     return status;
2455 }
2456 
2457 static unsigned long
_cairo_ft_ucs4_to_index(void * abstract_font,uint32_t ucs4)2458 _cairo_ft_ucs4_to_index (void	    *abstract_font,
2459 			 uint32_t    ucs4)
2460 {
2461     cairo_ft_scaled_font_t *scaled_font = abstract_font;
2462     cairo_ft_unscaled_font_t *unscaled = scaled_font->unscaled;
2463     FT_Face face;
2464     FT_UInt index;
2465 
2466     face = _cairo_ft_unscaled_font_lock_face (unscaled);
2467     if (!face)
2468 	return 0;
2469 
2470 #if CAIRO_HAS_FC_FONT
2471     index = FcFreeTypeCharIndex (face, ucs4);
2472 #else
2473     index = FT_Get_Char_Index (face, ucs4);
2474 #endif
2475 
2476     _cairo_ft_unscaled_font_unlock_face (unscaled);
2477     return index;
2478 }
2479 
2480 static cairo_int_status_t
_cairo_ft_load_truetype_table(void * abstract_font,unsigned long tag,long offset,unsigned char * buffer,unsigned long * length)2481 _cairo_ft_load_truetype_table (void	       *abstract_font,
2482                               unsigned long     tag,
2483                               long              offset,
2484                               unsigned char    *buffer,
2485                               unsigned long    *length)
2486 {
2487     cairo_ft_scaled_font_t *scaled_font = abstract_font;
2488     cairo_ft_unscaled_font_t *unscaled = scaled_font->unscaled;
2489     FT_Face face;
2490     cairo_status_t status = CAIRO_INT_STATUS_UNSUPPORTED;
2491 
2492     if (_cairo_ft_scaled_font_is_vertical (&scaled_font->base))
2493         return CAIRO_INT_STATUS_UNSUPPORTED;
2494 
2495 #if HAVE_FT_LOAD_SFNT_TABLE
2496     face = _cairo_ft_unscaled_font_lock_face (unscaled);
2497     if (!face)
2498 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2499 
2500     if (FT_IS_SFNT (face) &&
2501 	FT_Load_Sfnt_Table (face, tag, offset, buffer, length) == 0)
2502         status = CAIRO_STATUS_SUCCESS;
2503 
2504     _cairo_ft_unscaled_font_unlock_face (unscaled);
2505 #endif
2506 
2507     return status;
2508 }
2509 
2510 static cairo_int_status_t
_cairo_ft_index_to_ucs4(void * abstract_font,unsigned long index,uint32_t * ucs4)2511 _cairo_ft_index_to_ucs4(void	        *abstract_font,
2512 			unsigned long    index,
2513 			uint32_t	*ucs4)
2514 {
2515     cairo_ft_scaled_font_t *scaled_font = abstract_font;
2516     cairo_ft_unscaled_font_t *unscaled = scaled_font->unscaled;
2517     FT_Face face;
2518     FT_ULong  charcode;
2519     FT_UInt   gindex;
2520 
2521     face = _cairo_ft_unscaled_font_lock_face (unscaled);
2522     if (!face)
2523 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2524 
2525     *ucs4 = (uint32_t) -1;
2526     charcode = FT_Get_First_Char(face, &gindex);
2527     while (gindex != 0) {
2528 	if (gindex == index) {
2529 	    *ucs4 = charcode;
2530 	    break;
2531 	}
2532 	charcode = FT_Get_Next_Char (face, charcode, &gindex);
2533     }
2534 
2535     _cairo_ft_unscaled_font_unlock_face (unscaled);
2536 
2537     return CAIRO_STATUS_SUCCESS;
2538 }
2539 
2540 static const cairo_scaled_font_backend_t _cairo_ft_scaled_font_backend = {
2541     CAIRO_FONT_TYPE_FT,
2542     _cairo_ft_scaled_font_fini,
2543     _cairo_ft_scaled_glyph_init,
2544     NULL,			/* text_to_glyphs */
2545     _cairo_ft_ucs4_to_index,
2546     NULL,			/* show_glyphs */
2547     _cairo_ft_load_truetype_table,
2548     _cairo_ft_index_to_ucs4
2549 };
2550 
2551 /* #cairo_ft_font_face_t */
2552 
2553 #if CAIRO_HAS_FC_FONT
2554 static cairo_status_t
2555 _cairo_ft_font_face_create_for_pattern (FcPattern *pattern,
2556 					cairo_font_face_t **out);
2557 
2558 static cairo_status_t
_cairo_ft_font_face_create_for_toy(cairo_toy_font_face_t * toy_face,cairo_font_face_t ** font_face)2559 _cairo_ft_font_face_create_for_toy (cairo_toy_font_face_t   *toy_face,
2560 				    cairo_font_face_t      **font_face)
2561 {
2562     FcPattern *pattern;
2563     int fcslant;
2564     int fcweight;
2565     cairo_status_t status = CAIRO_STATUS_SUCCESS;
2566 
2567     pattern = FcPatternCreate ();
2568     if (!pattern)
2569 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2570 
2571     if (!FcPatternAddString (pattern,
2572 		             FC_FAMILY, (unsigned char *) toy_face->family))
2573     {
2574 	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2575 	goto FREE_PATTERN;
2576     }
2577 
2578     switch (toy_face->slant)
2579     {
2580     case CAIRO_FONT_SLANT_ITALIC:
2581         fcslant = FC_SLANT_ITALIC;
2582         break;
2583     case CAIRO_FONT_SLANT_OBLIQUE:
2584 	fcslant = FC_SLANT_OBLIQUE;
2585         break;
2586     case CAIRO_FONT_SLANT_NORMAL:
2587     default:
2588         fcslant = FC_SLANT_ROMAN;
2589         break;
2590     }
2591 
2592     if (!FcPatternAddInteger (pattern, FC_SLANT, fcslant)) {
2593 	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2594 	goto FREE_PATTERN;
2595     }
2596 
2597     switch (toy_face->weight)
2598     {
2599     case CAIRO_FONT_WEIGHT_BOLD:
2600         fcweight = FC_WEIGHT_BOLD;
2601         break;
2602     case CAIRO_FONT_WEIGHT_NORMAL:
2603     default:
2604         fcweight = FC_WEIGHT_MEDIUM;
2605         break;
2606     }
2607 
2608     if (!FcPatternAddInteger (pattern, FC_WEIGHT, fcweight)) {
2609 	status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
2610 	goto FREE_PATTERN;
2611     }
2612 
2613     status = _cairo_ft_font_face_create_for_pattern (pattern, font_face);
2614 
2615  FREE_PATTERN:
2616     FcPatternDestroy (pattern);
2617 
2618     return status;
2619 }
2620 #endif
2621 
2622 static void
_cairo_ft_font_face_destroy(void * abstract_face)2623 _cairo_ft_font_face_destroy (void *abstract_face)
2624 {
2625     cairo_ft_font_face_t *font_face = abstract_face;
2626 
2627     /* When destroying a face created by cairo_ft_font_face_create_for_ft_face,
2628      * we have a special "zombie" state for the face when the unscaled font
2629      * is still alive but there are no other references to a font face with
2630      * the same FT_Face.
2631      *
2632      * We go from:
2633      *
2634      *   font_face ------> unscaled
2635      *        <-....weak....../
2636      *
2637      * To:
2638      *
2639      *    font_face <------- unscaled
2640      */
2641 
2642     if (font_face->unscaled &&
2643 	font_face->unscaled->from_face &&
2644 	font_face->next == NULL &&
2645 	font_face->unscaled->faces == font_face &&
2646 	CAIRO_REFERENCE_COUNT_GET_VALUE (&font_face->unscaled->base.ref_count) > 1)
2647     {
2648 	cairo_font_face_reference (&font_face->base);
2649 
2650 	_cairo_unscaled_font_destroy (&font_face->unscaled->base);
2651 	font_face->unscaled = NULL;
2652 
2653 	return;
2654     }
2655 
2656     if (font_face->unscaled) {
2657 	cairo_ft_font_face_t *tmp_face = NULL;
2658 	cairo_ft_font_face_t *last_face = NULL;
2659 
2660 	/* Remove face from linked list */
2661 	for (tmp_face = font_face->unscaled->faces;
2662 	     tmp_face;
2663 	     tmp_face = tmp_face->next)
2664 	{
2665 	    if (tmp_face == font_face) {
2666 		if (last_face)
2667 		    last_face->next = tmp_face->next;
2668 		else
2669 		    font_face->unscaled->faces = tmp_face->next;
2670 	    }
2671 
2672 	    last_face = tmp_face;
2673 	}
2674 
2675 	_cairo_unscaled_font_destroy (&font_face->unscaled->base);
2676 	font_face->unscaled = NULL;
2677     }
2678 
2679 #if CAIRO_HAS_FC_FONT
2680     if (font_face->pattern) {
2681 	FcPatternDestroy (font_face->pattern);
2682 	cairo_font_face_destroy (font_face->resolved_font_face);
2683     }
2684 #endif
2685 }
2686 
2687 static cairo_font_face_t *
_cairo_ft_font_face_get_implementation(void * abstract_face,const cairo_matrix_t * font_matrix,const cairo_matrix_t * ctm,const cairo_font_options_t * options)2688 _cairo_ft_font_face_get_implementation (void                     *abstract_face,
2689 					const cairo_matrix_t       *font_matrix,
2690 					const cairo_matrix_t       *ctm,
2691 					const cairo_font_options_t *options)
2692 {
2693     cairo_ft_font_face_t      *font_face = abstract_face;
2694 
2695     /* The handling of font options is different depending on how the
2696      * font face was created. When the user creates a font face with
2697      * cairo_ft_font_face_create_for_ft_face(), then the load flags
2698      * passed in augment the load flags for the options.  But for
2699      * cairo_ft_font_face_create_for_pattern(), the load flags are
2700      * derived from a pattern where the user has called
2701      * cairo_ft_font_options_substitute(), so *just* use those load
2702      * flags and ignore the options.
2703      */
2704 
2705 #if CAIRO_HAS_FC_FONT
2706     /* If we have an unresolved pattern, resolve it and create
2707      * unscaled font.  Otherwise, use the ones stored in font_face.
2708      */
2709     if (font_face->pattern) {
2710 	cairo_font_face_t *resolved;
2711 
2712 	/* Cache the resolved font whilst the FcConfig remains consistent. */
2713 	resolved = font_face->resolved_font_face;
2714 	if (resolved != NULL) {
2715 	    if (! FcInitBringUptoDate ()) {
2716 		_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
2717 		return (cairo_font_face_t *) &_cairo_font_face_nil;
2718 	    }
2719 
2720 	    if (font_face->resolved_config == FcConfigGetCurrent ())
2721 		return cairo_font_face_reference (resolved);
2722 
2723 	    cairo_font_face_destroy (resolved);
2724 	    font_face->resolved_font_face = NULL;
2725 	}
2726 
2727 	resolved = _cairo_ft_resolve_pattern (font_face->pattern,
2728 					      font_matrix,
2729 					      ctm,
2730 					      options);
2731 	if (unlikely (resolved->status))
2732 	    return resolved;
2733 
2734 	font_face->resolved_font_face = cairo_font_face_reference (resolved);
2735 	font_face->resolved_config = FcConfigGetCurrent ();
2736 
2737 	return resolved;
2738     }
2739 #endif
2740 
2741     return abstract_face;
2742 }
2743 
2744 const cairo_font_face_backend_t _cairo_ft_font_face_backend = {
2745     CAIRO_FONT_TYPE_FT,
2746 #if CAIRO_HAS_FC_FONT
2747     _cairo_ft_font_face_create_for_toy,
2748 #else
2749     NULL,
2750 #endif
2751     _cairo_ft_font_face_destroy,
2752     _cairo_ft_font_face_scaled_font_create,
2753     _cairo_ft_font_face_get_implementation
2754 };
2755 
2756 #if CAIRO_HAS_FC_FONT
2757 static cairo_status_t
_cairo_ft_font_face_create_for_pattern(FcPattern * pattern,cairo_font_face_t ** out)2758 _cairo_ft_font_face_create_for_pattern (FcPattern *pattern,
2759 					cairo_font_face_t **out)
2760 {
2761     cairo_ft_font_face_t *font_face;
2762 
2763     font_face = malloc (sizeof (cairo_ft_font_face_t));
2764     if (unlikely (font_face == NULL))
2765 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2766 
2767     font_face->unscaled = NULL;
2768     font_face->next = NULL;
2769 
2770     font_face->pattern = FcPatternDuplicate (pattern);
2771     if (unlikely (font_face->pattern == NULL)) {
2772 	free (font_face);
2773 	return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2774     }
2775 
2776     font_face->resolved_font_face = NULL;
2777     font_face->resolved_config = NULL;
2778 
2779     _cairo_font_face_init (&font_face->base, &_cairo_ft_font_face_backend);
2780 
2781     *out = &font_face->base;
2782     return CAIRO_STATUS_SUCCESS;
2783 }
2784 #endif
2785 
2786 static cairo_font_face_t *
_cairo_ft_font_face_create(cairo_ft_unscaled_font_t * unscaled,cairo_ft_options_t * ft_options)2787 _cairo_ft_font_face_create (cairo_ft_unscaled_font_t *unscaled,
2788 			    cairo_ft_options_t	     *ft_options)
2789 {
2790     cairo_ft_font_face_t *font_face, **prev_font_face;
2791 
2792     /* Looked for an existing matching font face */
2793     for (font_face = unscaled->faces, prev_font_face = &unscaled->faces;
2794 	 font_face;
2795 	 prev_font_face = &font_face->next, font_face = font_face->next)
2796     {
2797 	if (font_face->ft_options.load_flags == ft_options->load_flags &&
2798 	    font_face->ft_options.extra_flags == ft_options->extra_flags &&
2799 	    cairo_font_options_equal (&font_face->ft_options.base, &ft_options->base))
2800 	{
2801 	    if (font_face->base.status) {
2802 		/* The font_face has been left in an error state, abandon it. */
2803 		*prev_font_face = font_face->next;
2804 		break;
2805 	    }
2806 
2807 	    if (font_face->unscaled == NULL) {
2808 		/* Resurrect this "zombie" font_face (from
2809 		 * _cairo_ft_font_face_destroy), switching its unscaled_font
2810 		 * from owner to ownee. */
2811 		font_face->unscaled = unscaled;
2812 		_cairo_unscaled_font_reference (&unscaled->base);
2813 		return &font_face->base;
2814 	    } else
2815 		return cairo_font_face_reference (&font_face->base);
2816 	}
2817     }
2818 
2819     /* No match found, create a new one */
2820     font_face = malloc (sizeof (cairo_ft_font_face_t));
2821     if (unlikely (!font_face)) {
2822 	_cairo_error_throw (CAIRO_STATUS_NO_MEMORY);
2823 	return (cairo_font_face_t *)&_cairo_font_face_nil;
2824     }
2825 
2826     font_face->unscaled = unscaled;
2827     _cairo_unscaled_font_reference (&unscaled->base);
2828 
2829     font_face->ft_options = *ft_options;
2830 
2831     if (unscaled->faces && unscaled->faces->unscaled == NULL) {
2832 	/* This "zombie" font_face (from _cairo_ft_font_face_destroy)
2833 	 * is no longer needed. */
2834 	assert (unscaled->from_face && unscaled->faces->next == NULL);
2835 	cairo_font_face_destroy (&unscaled->faces->base);
2836 	unscaled->faces = NULL;
2837     }
2838 
2839     font_face->next = unscaled->faces;
2840     unscaled->faces = font_face;
2841 
2842 #if CAIRO_HAS_FC_FONT
2843     font_face->pattern = NULL;
2844 #endif
2845 
2846     _cairo_font_face_init (&font_face->base, &_cairo_ft_font_face_backend);
2847 
2848     return &font_face->base;
2849 }
2850 
2851 /* implement the platform-specific interface */
2852 
2853 #if CAIRO_HAS_FC_FONT
2854 static cairo_status_t
_cairo_ft_font_options_substitute(const cairo_font_options_t * options,FcPattern * pattern)2855 _cairo_ft_font_options_substitute (const cairo_font_options_t *options,
2856 				   FcPattern                  *pattern)
2857 {
2858     FcValue v;
2859 
2860     if (options->antialias != CAIRO_ANTIALIAS_DEFAULT)
2861     {
2862 	if (FcPatternGet (pattern, FC_ANTIALIAS, 0, &v) == FcResultNoMatch)
2863 	{
2864 	    if (! FcPatternAddBool (pattern,
2865 			            FC_ANTIALIAS,
2866 				    options->antialias != CAIRO_ANTIALIAS_NONE))
2867 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2868 
2869 	    if (options->antialias != CAIRO_ANTIALIAS_SUBPIXEL) {
2870 		FcPatternDel (pattern, FC_RGBA);
2871 		if (! FcPatternAddInteger (pattern, FC_RGBA, FC_RGBA_NONE))
2872 		    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2873 	    }
2874 	}
2875     }
2876 
2877     if (options->antialias != CAIRO_ANTIALIAS_DEFAULT)
2878     {
2879 	if (FcPatternGet (pattern, FC_RGBA, 0, &v) == FcResultNoMatch)
2880 	{
2881 	    int rgba;
2882 
2883 	    if (options->antialias == CAIRO_ANTIALIAS_SUBPIXEL) {
2884 		switch (options->subpixel_order) {
2885 		case CAIRO_SUBPIXEL_ORDER_DEFAULT:
2886 		case CAIRO_SUBPIXEL_ORDER_RGB:
2887 		default:
2888 		    rgba = FC_RGBA_RGB;
2889 		    break;
2890 		case CAIRO_SUBPIXEL_ORDER_BGR:
2891 		    rgba = FC_RGBA_BGR;
2892 		    break;
2893 		case CAIRO_SUBPIXEL_ORDER_VRGB:
2894 		    rgba = FC_RGBA_VRGB;
2895 		    break;
2896 		case CAIRO_SUBPIXEL_ORDER_VBGR:
2897 		    rgba = FC_RGBA_VBGR;
2898 		    break;
2899 		}
2900 	    } else {
2901 		rgba = FC_RGBA_NONE;
2902 	    }
2903 
2904 	    if (! FcPatternAddInteger (pattern, FC_RGBA, rgba))
2905 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2906 	}
2907     }
2908 
2909     if (options->lcd_filter != CAIRO_LCD_FILTER_DEFAULT)
2910     {
2911 	if (FcPatternGet (pattern, FC_LCD_FILTER, 0, &v) == FcResultNoMatch)
2912 	{
2913 	    int lcd_filter;
2914 
2915 	    switch (options->lcd_filter) {
2916 	    case CAIRO_LCD_FILTER_NONE:
2917 		lcd_filter = FT_LCD_FILTER_NONE;
2918 		break;
2919 	    case CAIRO_LCD_FILTER_DEFAULT:
2920 	    case CAIRO_LCD_FILTER_INTRA_PIXEL:
2921 		lcd_filter = FT_LCD_FILTER_LEGACY;
2922 		break;
2923 	    case CAIRO_LCD_FILTER_FIR3:
2924 		lcd_filter = FT_LCD_FILTER_LIGHT;
2925 		break;
2926 	    default:
2927 	    case CAIRO_LCD_FILTER_FIR5:
2928 		lcd_filter = FT_LCD_FILTER_DEFAULT;
2929 		break;
2930 	    }
2931 
2932 	    if (! FcPatternAddInteger (pattern, FC_LCD_FILTER, lcd_filter))
2933 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2934 	}
2935     }
2936 
2937     if (options->hint_style != CAIRO_HINT_STYLE_DEFAULT)
2938     {
2939 	if (FcPatternGet (pattern, FC_HINTING, 0, &v) == FcResultNoMatch)
2940 	{
2941 	    if (! FcPatternAddBool (pattern,
2942 			            FC_HINTING,
2943 				    options->hint_style != CAIRO_HINT_STYLE_NONE))
2944 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2945 	}
2946 
2947 #ifdef FC_HINT_STYLE
2948 	if (FcPatternGet (pattern, FC_HINT_STYLE, 0, &v) == FcResultNoMatch)
2949 	{
2950 	    int hint_style;
2951 
2952 	    switch (options->hint_style) {
2953 	    case CAIRO_HINT_STYLE_NONE:
2954 		hint_style = FC_HINT_NONE;
2955 		break;
2956 	    case CAIRO_HINT_STYLE_SLIGHT:
2957 		hint_style = FC_HINT_SLIGHT;
2958 		break;
2959 	    case CAIRO_HINT_STYLE_MEDIUM:
2960 		hint_style = FC_HINT_MEDIUM;
2961 		break;
2962 	    case CAIRO_HINT_STYLE_FULL:
2963 	    case CAIRO_HINT_STYLE_DEFAULT:
2964 	    default:
2965 		hint_style = FC_HINT_FULL;
2966 		break;
2967 	    }
2968 
2969 	    if (! FcPatternAddInteger (pattern, FC_HINT_STYLE, hint_style))
2970 		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
2971 	}
2972 #endif
2973     }
2974 
2975     return CAIRO_STATUS_SUCCESS;
2976 }
2977 
2978 /**
2979  * cairo_ft_font_options_substitute:
2980  * @options: a #cairo_font_options_t object
2981  * @pattern: an existing #FcPattern
2982  *
2983  * Add options to a #FcPattern based on a #cairo_font_options_t font
2984  * options object. Options that are already in the pattern, are not overridden,
2985  * so you should call this function after calling FcConfigSubstitute() (the
2986  * user's settings should override options based on the surface type), but
2987  * before calling FcDefaultSubstitute().
2988  **/
2989 void
cairo_ft_font_options_substitute(const cairo_font_options_t * options,FcPattern * pattern)2990 cairo_ft_font_options_substitute (const cairo_font_options_t *options,
2991 				  FcPattern                  *pattern)
2992 {
2993     if (cairo_font_options_status ((cairo_font_options_t *) options))
2994 	return;
2995 
2996     _cairo_ft_font_options_substitute (options, pattern);
2997 }
2998 
2999 static cairo_font_face_t *
_cairo_ft_resolve_pattern(FcPattern * pattern,const cairo_matrix_t * font_matrix,const cairo_matrix_t * ctm,const cairo_font_options_t * font_options)3000 _cairo_ft_resolve_pattern (FcPattern		      *pattern,
3001 			   const cairo_matrix_t       *font_matrix,
3002 			   const cairo_matrix_t       *ctm,
3003 			   const cairo_font_options_t *font_options)
3004 {
3005     cairo_status_t status;
3006 
3007     cairo_matrix_t scale;
3008     FcPattern *resolved;
3009     cairo_ft_font_transform_t sf;
3010     FcResult result;
3011     cairo_ft_unscaled_font_t *unscaled;
3012     cairo_ft_options_t ft_options;
3013     cairo_font_face_t *font_face;
3014 
3015     scale = *ctm;
3016     scale.x0 = scale.y0 = 0;
3017     cairo_matrix_multiply (&scale,
3018                            font_matrix,
3019                            &scale);
3020 
3021     status = _compute_transform (&sf, &scale, NULL);
3022     if (unlikely (status))
3023 	return (cairo_font_face_t *)&_cairo_font_face_nil;
3024 
3025     pattern = FcPatternDuplicate (pattern);
3026     if (pattern == NULL)
3027 	return (cairo_font_face_t *)&_cairo_font_face_nil;
3028 
3029     if (! FcPatternAddDouble (pattern, FC_PIXEL_SIZE, sf.y_scale)) {
3030 	font_face = (cairo_font_face_t *)&_cairo_font_face_nil;
3031 	goto FREE_PATTERN;
3032     }
3033 
3034     if (! FcConfigSubstitute (NULL, pattern, FcMatchPattern)) {
3035 	font_face = (cairo_font_face_t *)&_cairo_font_face_nil;
3036 	goto FREE_PATTERN;
3037     }
3038 
3039     status = _cairo_ft_font_options_substitute (font_options, pattern);
3040     if (status) {
3041 	font_face = (cairo_font_face_t *)&_cairo_font_face_nil;
3042 	goto FREE_PATTERN;
3043     }
3044 
3045     FcDefaultSubstitute (pattern);
3046 
3047     resolved = FcFontMatch (NULL, pattern, &result);
3048     if (!resolved) {
3049 	/* We failed to find any font. Substitute twin so that the user can
3050 	 * see something (and hopefully recognise that the font is missing)
3051 	 * and not just receive a NO_MEMORY error during rendering.
3052 	 */
3053 	font_face = _cairo_font_face_twin_create_fallback ();
3054 	goto FREE_PATTERN;
3055     }
3056 
3057     status = _cairo_ft_unscaled_font_create_for_pattern (resolved, &unscaled);
3058     if (unlikely (status || unscaled == NULL)) {
3059 	font_face = (cairo_font_face_t *)&_cairo_font_face_nil;
3060 	goto FREE_RESOLVED;
3061     }
3062 
3063     _get_pattern_ft_options (resolved, &ft_options);
3064     font_face = _cairo_ft_font_face_create (unscaled, &ft_options);
3065     _cairo_unscaled_font_destroy (&unscaled->base);
3066 
3067 FREE_RESOLVED:
3068     FcPatternDestroy (resolved);
3069 
3070 FREE_PATTERN:
3071     FcPatternDestroy (pattern);
3072 
3073     return font_face;
3074 }
3075 
3076 /**
3077  * cairo_ft_font_face_create_for_pattern:
3078  * @pattern: A fontconfig pattern.  Cairo makes a copy of the pattern
3079  * if it needs to.  You are free to modify or free @pattern after this call.
3080  *
3081  * Creates a new font face for the FreeType font backend based on a
3082  * fontconfig pattern. This font can then be used with
3083  * cairo_set_font_face() or cairo_scaled_font_create(). The
3084  * #cairo_scaled_font_t returned from cairo_scaled_font_create() is
3085  * also for the FreeType backend and can be used with functions such
3086  * as cairo_ft_scaled_font_lock_face().
3087  *
3088  * Font rendering options are represented both here and when you
3089  * call cairo_scaled_font_create(). Font options that have a representation
3090  * in a #FcPattern must be passed in here; to modify #FcPattern
3091  * appropriately to reflect the options in a #cairo_font_options_t, call
3092  * cairo_ft_font_options_substitute().
3093  *
3094  * The pattern's FC_FT_FACE element is inspected first and if that is set,
3095  * that will be the FreeType font face associated with the returned cairo
3096  * font face.  Otherwise the FC_FILE element is checked.  If it's set,
3097  * that and the value of the FC_INDEX element (defaults to zero) of @pattern
3098  * are used to load a font face from file.
3099  *
3100  * If both steps from the previous paragraph fails, @pattern will be passed
3101  * to FcConfigSubstitute, FcDefaultSubstitute, and finally FcFontMatch,
3102  * and the resulting font pattern is used.
3103  *
3104  * If the FC_FT_FACE element of @pattern is set, the user is responsible
3105  * for making sure that the referenced FT_Face remains valid for the life
3106  * time of the returned #cairo_font_face_t.  See
3107  * cairo_ft_font_face_create_for_ft_face() for an exmaple of how to couple
3108  * the life time of the FT_Face to that of the cairo font-face.
3109  *
3110  * Return value: a newly created #cairo_font_face_t. Free with
3111  *  cairo_font_face_destroy() when you are done using it.
3112  **/
3113 cairo_font_face_t *
cairo_ft_font_face_create_for_pattern(FcPattern * pattern)3114 cairo_ft_font_face_create_for_pattern (FcPattern *pattern)
3115 {
3116     cairo_ft_unscaled_font_t *unscaled;
3117     cairo_font_face_t *font_face;
3118     cairo_ft_options_t ft_options;
3119     cairo_status_t status;
3120 
3121     status = _cairo_ft_unscaled_font_create_for_pattern (pattern, &unscaled);
3122     if (unlikely (status))
3123 	return (cairo_font_face_t *) &_cairo_font_face_nil;
3124     if (unlikely (unscaled == NULL)) {
3125 	/* Store the pattern.  We will resolve it and create unscaled
3126 	 * font when creating scaled fonts */
3127 	status = _cairo_ft_font_face_create_for_pattern (pattern,
3128 							 &font_face);
3129 	if (unlikely (status))
3130 	    return (cairo_font_face_t *) &_cairo_font_face_nil;
3131 
3132 	return font_face;
3133     }
3134 
3135     _get_pattern_ft_options (pattern, &ft_options);
3136     font_face = _cairo_ft_font_face_create (unscaled, &ft_options);
3137     _cairo_unscaled_font_destroy (&unscaled->base);
3138 
3139     return font_face;
3140 }
3141 #endif
3142 
3143 /**
3144  * cairo_ft_font_face_create_for_ft_face:
3145  * @face: A FreeType face object, already opened. This must
3146  *   be kept around until the face's ref_count drops to
3147  *   zero and it is freed. Since the face may be referenced
3148  *   internally to Cairo, the best way to determine when it
3149  *   is safe to free the face is to pass a
3150  *   #cairo_destroy_func_t to cairo_font_face_set_user_data()
3151  * @load_flags: flags to pass to FT_Load_Glyph when loading
3152  *   glyphs from the font. These flags are OR'ed together with
3153  *   the flags derived from the #cairo_font_options_t passed
3154  *   to cairo_scaled_font_create(), so only a few values such
3155  *   as %FT_LOAD_VERTICAL_LAYOUT, and %FT_LOAD_FORCE_AUTOHINT
3156  *   are useful. You should not pass any of the flags affecting
3157  *   the load target, such as %FT_LOAD_TARGET_LIGHT.
3158  *
3159  * Creates a new font face for the FreeType font backend from a
3160  * pre-opened FreeType face. This font can then be used with
3161  * cairo_set_font_face() or cairo_scaled_font_create(). The
3162  * #cairo_scaled_font_t returned from cairo_scaled_font_create() is
3163  * also for the FreeType backend and can be used with functions such
3164  * as cairo_ft_scaled_font_lock_face(). Note that Cairo may keep a reference
3165  * to the FT_Face alive in a font-cache and the exact lifetime of the reference
3166  * depends highly upon the exact usage pattern and is subject to external
3167  * factors. You must not call FT_Done_Face() before the last reference to the
3168  * #cairo_font_face_t has been dropped.
3169  *
3170  * As an example, below is how one might correctly couple the lifetime of
3171  * the FreeType face object to the #cairo_font_face_t.
3172  *
3173  * <informalexample><programlisting>
3174  * static const cairo_user_data_key_t key;
3175  *
3176  * font_face = cairo_ft_font_face_create_for_ft_face (ft_face, 0);
3177  * status = cairo_font_face_set_user_data (font_face, &key,
3178  *                                ft_face, (cairo_destroy_func_t) FT_Done_Face);
3179  * if (status) {
3180  *    cairo_font_face_destroy (font_face);
3181  *    FT_Done_Face (ft_face);
3182  *    return ERROR;
3183  * }
3184  * </programlisting></informalexample>
3185  *
3186  * Return value: a newly created #cairo_font_face_t. Free with
3187  *  cairo_font_face_destroy() when you are done using it.
3188  **/
3189 cairo_font_face_t *
cairo_ft_font_face_create_for_ft_face(FT_Face face,int load_flags)3190 cairo_ft_font_face_create_for_ft_face (FT_Face         face,
3191 				       int             load_flags)
3192 {
3193     cairo_ft_unscaled_font_t *unscaled;
3194     cairo_font_face_t *font_face;
3195     cairo_ft_options_t ft_options;
3196     cairo_status_t status;
3197 
3198     status = _cairo_ft_unscaled_font_create_from_face (face, &unscaled);
3199     if (unlikely (status))
3200 	return (cairo_font_face_t *)&_cairo_font_face_nil;
3201 
3202     ft_options.load_flags = load_flags;
3203     ft_options.extra_flags = 0;
3204     _cairo_font_options_init_default (&ft_options.base);
3205 
3206     font_face = _cairo_ft_font_face_create (unscaled, &ft_options);
3207     _cairo_unscaled_font_destroy (&unscaled->base);
3208 
3209     return font_face;
3210 }
3211 
3212 /**
3213  * cairo_ft_scaled_font_lock_face:
3214  * @scaled_font: A #cairo_scaled_font_t from the FreeType font backend. Such an
3215  *   object can be created by calling cairo_scaled_font_create() on a
3216  *   FreeType backend font face (see cairo_ft_font_face_create_for_pattern(),
3217  *   cairo_ft_font_face_create_for_ft_face()).
3218  *
3219  * cairo_ft_scaled_font_lock_face() gets the #FT_Face object from a FreeType
3220  * backend font and scales it appropriately for the font. You must
3221  * release the face with cairo_ft_scaled_font_unlock_face()
3222  * when you are done using it.  Since the #FT_Face object can be
3223  * shared between multiple #cairo_scaled_font_t objects, you must not
3224  * lock any other font objects until you unlock this one. A count is
3225  * kept of the number of times cairo_ft_scaled_font_lock_face() is
3226  * called. cairo_ft_scaled_font_unlock_face() must be called the same number
3227  * of times.
3228  *
3229  * You must be careful when using this function in a library or in a
3230  * threaded application, because freetype's design makes it unsafe to
3231  * call freetype functions simultaneously from multiple threads, (even
3232  * if using distinct FT_Face objects). Because of this, application
3233  * code that acquires an FT_Face object with this call must add its
3234  * own locking to protect any use of that object, (and which also must
3235  * protect any other calls into cairo as almost any cairo function
3236  * might result in a call into the freetype library).
3237  *
3238  * Return value: The #FT_Face object for @font, scaled appropriately,
3239  * or %NULL if @scaled_font is in an error state (see
3240  * cairo_scaled_font_status()) or there is insufficient memory.
3241  **/
3242 FT_Face
cairo_ft_scaled_font_lock_face(cairo_scaled_font_t * abstract_font)3243 cairo_ft_scaled_font_lock_face (cairo_scaled_font_t *abstract_font)
3244 {
3245     cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;
3246     FT_Face face;
3247     cairo_status_t status;
3248 
3249     if (! _cairo_scaled_font_is_ft (abstract_font)) {
3250 	_cairo_error_throw (CAIRO_STATUS_FONT_TYPE_MISMATCH);
3251 	return NULL;
3252     }
3253 
3254     if (scaled_font->base.status)
3255 	return NULL;
3256 
3257     face = _cairo_ft_unscaled_font_lock_face (scaled_font->unscaled);
3258     if (unlikely (face == NULL)) {
3259 	status = _cairo_scaled_font_set_error (&scaled_font->base, CAIRO_STATUS_NO_MEMORY);
3260 	return NULL;
3261     }
3262 
3263     status = _cairo_ft_unscaled_font_set_scale (scaled_font->unscaled,
3264 				                &scaled_font->base.scale);
3265     if (unlikely (status)) {
3266 	_cairo_ft_unscaled_font_unlock_face (scaled_font->unscaled);
3267 	status = _cairo_scaled_font_set_error (&scaled_font->base, status);
3268 	return NULL;
3269     }
3270 
3271     /* Note: We deliberately release the unscaled font's mutex here,
3272      * so that we are not holding a lock across two separate calls to
3273      * cairo function, (which would give the application some
3274      * opportunity for creating deadlock. This is obviously unsafe,
3275      * but as documented, the user must add manual locking when using
3276      * this function. */
3277      CAIRO_MUTEX_UNLOCK (scaled_font->unscaled->mutex);
3278 
3279     return face;
3280 }
3281 
3282 /**
3283  * cairo_ft_scaled_font_unlock_face:
3284  * @scaled_font: A #cairo_scaled_font_t from the FreeType font backend. Such an
3285  *   object can be created by calling cairo_scaled_font_create() on a
3286  *   FreeType backend font face (see cairo_ft_font_face_create_for_pattern(),
3287  *   cairo_ft_font_face_create_for_ft_face()).
3288  *
3289  * Releases a face obtained with cairo_ft_scaled_font_lock_face().
3290  **/
3291 void
cairo_ft_scaled_font_unlock_face(cairo_scaled_font_t * abstract_font)3292 cairo_ft_scaled_font_unlock_face (cairo_scaled_font_t *abstract_font)
3293 {
3294     cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;
3295 
3296     if (! _cairo_scaled_font_is_ft (abstract_font)) {
3297 	_cairo_error_throw (CAIRO_STATUS_FONT_TYPE_MISMATCH);
3298 	return;
3299     }
3300 
3301     if (scaled_font->base.status)
3302 	return;
3303 
3304     /* Note: We released the unscaled font's mutex at the end of
3305      * cairo_ft_scaled_font_lock_face, so we have to acquire it again
3306      * as _cairo_ft_unscaled_font_unlock_face expects it to be held
3307      * when we call into it. */
3308     CAIRO_MUTEX_LOCK (scaled_font->unscaled->mutex);
3309 
3310     _cairo_ft_unscaled_font_unlock_face (scaled_font->unscaled);
3311 }
3312 
3313 /* We expose our unscaled font implementation internally for the the
3314  * PDF backend, which needs to keep track of the the different
3315  * fonts-on-disk used by a document, so it can embed them.
3316  */
3317 cairo_unscaled_font_t *
_cairo_ft_scaled_font_get_unscaled_font(cairo_scaled_font_t * abstract_font)3318 _cairo_ft_scaled_font_get_unscaled_font (cairo_scaled_font_t *abstract_font)
3319 {
3320     cairo_ft_scaled_font_t *scaled_font = (cairo_ft_scaled_font_t *) abstract_font;
3321 
3322     return &scaled_font->unscaled->base;
3323 }
3324 
3325 cairo_bool_t
_cairo_ft_scaled_font_is_vertical(cairo_scaled_font_t * scaled_font)3326 _cairo_ft_scaled_font_is_vertical (cairo_scaled_font_t *scaled_font)
3327 {
3328     cairo_ft_scaled_font_t *ft_scaled_font;
3329 
3330     if (!_cairo_scaled_font_is_ft (scaled_font))
3331 	return FALSE;
3332 
3333     ft_scaled_font = (cairo_ft_scaled_font_t *) scaled_font;
3334     if (ft_scaled_font->ft_options.load_flags & FT_LOAD_VERTICAL_LAYOUT)
3335 	return TRUE;
3336     return FALSE;
3337 }
3338 
3339 unsigned int
_cairo_ft_scaled_font_get_load_flags(cairo_scaled_font_t * scaled_font)3340 _cairo_ft_scaled_font_get_load_flags (cairo_scaled_font_t *scaled_font)
3341 {
3342     cairo_ft_scaled_font_t *ft_scaled_font;
3343 
3344     if (! _cairo_scaled_font_is_ft (scaled_font))
3345 	return 0;
3346 
3347     ft_scaled_font = (cairo_ft_scaled_font_t *) scaled_font;
3348     return ft_scaled_font->ft_options.load_flags;
3349 }
3350 
3351 void
_cairo_ft_font_reset_static_data(void)3352 _cairo_ft_font_reset_static_data (void)
3353 {
3354     _cairo_ft_unscaled_font_map_destroy ();
3355 }
3356