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