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