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