Imported Upstream version 2.6.7
[platform/upstream/harfbuzz.git] / src / hb-ft.cc
1 /*
2  * Copyright © 2009  Red Hat, Inc.
3  * Copyright © 2009  Keith Stribley
4  * Copyright © 2015  Google, Inc.
5  *
6  *  This is part of HarfBuzz, a text shaping library.
7  *
8  * Permission is hereby granted, without written agreement and without
9  * license or royalty fees, to use, copy, modify, and distribute this
10  * software and its documentation for any purpose, provided that the
11  * above copyright notice and the following two paragraphs appear in
12  * all copies of this software.
13  *
14  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
15  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
16  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
17  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
18  * DAMAGE.
19  *
20  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
21  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
22  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
23  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
24  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
25  *
26  * Red Hat Author(s): Behdad Esfahbod
27  * Google Author(s): Behdad Esfahbod
28  */
29
30 #include "hb.hh"
31
32 #ifdef HAVE_FREETYPE
33
34 #include "hb-ft.h"
35
36 #include "hb-font.hh"
37 #include "hb-machinery.hh"
38 #include "hb-cache.hh"
39
40 #include FT_ADVANCES_H
41 #include FT_MULTIPLE_MASTERS_H
42 #include FT_TRUETYPE_TABLES_H
43
44
45 /**
46  * SECTION:hb-ft
47  * @title: hb-ft
48  * @short_description: FreeType integration
49  * @include: hb-ft.h
50  *
51  * Functions for using HarfBuzz with the FreeType library.
52  *
53  * HarfBuzz supports using FreeType to provide face and
54  * font data.
55  *
56  * <note>Note that FreeType is not thread-safe, therefore these
57  * functions are not thread-safe either.</note>
58  **/
59
60
61 /* TODO:
62  *
63  * In general, this file does a fine job of what it's supposed to do.
64  * There are, however, things that need more work:
65  *
66  *   - FreeType works in 26.6 mode.  Clients can decide to use that mode, and everything
67  *     would work fine.  However, we also abuse this API for performing in font-space,
68  *     but don't pass the correct flags to FreeType.  We just abuse the no-hinting mode
69  *     for that, such that no rounding etc happens.  As such, we don't set ppem, and
70  *     pass NO_HINTING as load_flags.  Would be much better to use NO_SCALE, and scale
71  *     ourselves.
72  *
73  *   - We don't handle / allow for emboldening / obliqueing.
74  *
75  *   - In the future, we should add constructors to create fonts in font space?
76  */
77
78
79 struct hb_ft_font_t
80 {
81   mutable hb_mutex_t lock;
82   FT_Face ft_face;
83   int load_flags;
84   bool symbol; /* Whether selected cmap is symbol cmap. */
85   bool unref; /* Whether to destroy ft_face when done. */
86
87   mutable hb_atomic_int_t cached_x_scale;
88   mutable hb_advance_cache_t advance_cache;
89 };
90
91 static hb_ft_font_t *
92 _hb_ft_font_create (FT_Face ft_face, bool symbol, bool unref)
93 {
94   hb_ft_font_t *ft_font = (hb_ft_font_t *) calloc (1, sizeof (hb_ft_font_t));
95
96   if (unlikely (!ft_font))
97     return nullptr;
98
99   ft_font->lock.init ();
100   ft_font->ft_face = ft_face;
101   ft_font->symbol = symbol;
102   ft_font->unref = unref;
103
104   ft_font->load_flags = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING;
105
106   ft_font->cached_x_scale.set_relaxed (0);
107   ft_font->advance_cache.init ();
108
109   return ft_font;
110 }
111
112 static void
113 _hb_ft_face_destroy (void *data)
114 {
115   FT_Done_Face ((FT_Face) data);
116 }
117
118 static void
119 _hb_ft_font_destroy (void *data)
120 {
121   hb_ft_font_t *ft_font = (hb_ft_font_t *) data;
122
123   ft_font->advance_cache.fini ();
124
125   if (ft_font->unref)
126     _hb_ft_face_destroy (ft_font->ft_face);
127
128   ft_font->lock.fini ();
129
130   free (ft_font);
131 }
132
133 /**
134  * hb_ft_font_set_load_flags:
135  * @font: #hb_font_t to work upon
136  * @load_flags: The FreeType load flags to set
137  *
138  * Sets the FT_Load_Glyph load flags for the specified #hb_font_t.
139  *
140  * For more information, see 
141  * https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#ft_load_xxx
142  *
143  * Since: 1.0.5
144  **/
145 void
146 hb_ft_font_set_load_flags (hb_font_t *font, int load_flags)
147 {
148   if (hb_object_is_immutable (font))
149     return;
150
151   if (unlikely (font->destroy != (hb_destroy_func_t) _hb_ft_font_destroy))
152     return;
153
154   hb_ft_font_t *ft_font = (hb_ft_font_t *) font->user_data;
155
156   ft_font->load_flags = load_flags;
157 }
158
159 /**
160  * hb_ft_font_get_load_flags:
161  * @font: #hb_font_t to work upon
162  *
163  * Fetches the FT_Load_Glyph load flags of the specified #hb_font_t.
164  *
165  * For more information, see 
166  * https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#ft_load_xxx
167  *
168  * Return value: FT_Load_Glyph flags found
169  *
170  * Since: 1.0.5
171  **/
172 int
173 hb_ft_font_get_load_flags (hb_font_t *font)
174 {
175   if (unlikely (font->destroy != (hb_destroy_func_t) _hb_ft_font_destroy))
176     return 0;
177
178   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font->user_data;
179
180   return ft_font->load_flags;
181 }
182
183 /**
184  * hb_ft_get_face:
185  * @font: #hb_font_t to work upon
186  *
187  * Fetches the FT_Face associated with the specified #hb_font_t
188  * font object.
189  *
190  * Return value: the FT_Face found
191  *
192  * Since: 0.9.2
193  **/
194 FT_Face
195 hb_ft_font_get_face (hb_font_t *font)
196 {
197   if (unlikely (font->destroy != (hb_destroy_func_t) _hb_ft_font_destroy))
198     return nullptr;
199
200   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font->user_data;
201
202   return ft_font->ft_face;
203 }
204
205 /**
206  * hb_ft_font_lock_face:
207  * @font:
208  *
209  *
210  *
211  * Return value:
212  * Since: 2.6.5
213  **/
214 FT_Face
215 hb_ft_font_lock_face (hb_font_t *font)
216 {
217   if (unlikely (font->destroy != (hb_destroy_func_t) _hb_ft_font_destroy))
218     return nullptr;
219
220   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font->user_data;
221
222   ft_font->lock.lock ();
223
224   return ft_font->ft_face;
225 }
226
227 /**
228  * hb_ft_font_unlock_face:
229  * @font:
230  *
231  *
232  *
233  * Return value:
234  * Since: 2.6.5
235  **/
236 void
237 hb_ft_font_unlock_face (hb_font_t *font)
238 {
239   if (unlikely (font->destroy != (hb_destroy_func_t) _hb_ft_font_destroy))
240     return;
241
242   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font->user_data;
243
244   ft_font->lock.unlock ();
245 }
246
247
248 static hb_bool_t
249 hb_ft_get_nominal_glyph (hb_font_t *font HB_UNUSED,
250                          void *font_data,
251                          hb_codepoint_t unicode,
252                          hb_codepoint_t *glyph,
253                          void *user_data HB_UNUSED)
254 {
255   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
256   hb_lock_t lock (ft_font->lock);
257   unsigned int g = FT_Get_Char_Index (ft_font->ft_face, unicode);
258
259   if (unlikely (!g))
260   {
261     if (unlikely (ft_font->symbol) && unicode <= 0x00FFu)
262     {
263       /* For symbol-encoded OpenType fonts, we duplicate the
264        * U+F000..F0FF range at U+0000..U+00FF.  That's what
265        * Windows seems to do, and that's hinted about at:
266        * https://docs.microsoft.com/en-us/typography/opentype/spec/recom
267        * under "Non-Standard (Symbol) Fonts". */
268       g = FT_Get_Char_Index (ft_font->ft_face, 0xF000u + unicode);
269       if (!g)
270         return false;
271     }
272     else
273       return false;
274   }
275
276   *glyph = g;
277   return true;
278 }
279
280 static unsigned int
281 hb_ft_get_nominal_glyphs (hb_font_t *font HB_UNUSED,
282                           void *font_data,
283                           unsigned int count,
284                           const hb_codepoint_t *first_unicode,
285                           unsigned int unicode_stride,
286                           hb_codepoint_t *first_glyph,
287                           unsigned int glyph_stride,
288                           void *user_data HB_UNUSED)
289 {
290   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
291   hb_lock_t lock (ft_font->lock);
292   unsigned int done;
293   for (done = 0;
294        done < count && (*first_glyph = FT_Get_Char_Index (ft_font->ft_face, *first_unicode));
295        done++)
296   {
297     first_unicode = &StructAtOffsetUnaligned<hb_codepoint_t> (first_unicode, unicode_stride);
298     first_glyph = &StructAtOffsetUnaligned<hb_codepoint_t> (first_glyph, glyph_stride);
299   }
300   /* We don't need to do ft_font->symbol dance here, since HB calls the singular
301    * nominal_glyph() for what we don't handle here. */
302   return done;
303 }
304
305
306 static hb_bool_t
307 hb_ft_get_variation_glyph (hb_font_t *font HB_UNUSED,
308                            void *font_data,
309                            hb_codepoint_t unicode,
310                            hb_codepoint_t variation_selector,
311                            hb_codepoint_t *glyph,
312                            void *user_data HB_UNUSED)
313 {
314   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
315   hb_lock_t lock (ft_font->lock);
316   unsigned int g = FT_Face_GetCharVariantIndex (ft_font->ft_face, unicode, variation_selector);
317
318   if (unlikely (!g))
319     return false;
320
321   *glyph = g;
322   return true;
323 }
324
325 static void
326 hb_ft_get_glyph_h_advances (hb_font_t* font, void* font_data,
327                             unsigned count,
328                             const hb_codepoint_t *first_glyph,
329                             unsigned glyph_stride,
330                             hb_position_t *first_advance,
331                             unsigned advance_stride,
332                             void *user_data HB_UNUSED)
333 {
334   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
335   hb_lock_t lock (ft_font->lock);
336   FT_Face ft_face = ft_font->ft_face;
337   int load_flags = ft_font->load_flags;
338   int mult = font->x_scale < 0 ? -1 : +1;
339
340   if (font->x_scale != ft_font->cached_x_scale.get ())
341   {
342     ft_font->advance_cache.clear ();
343     ft_font->cached_x_scale.set (font->x_scale);
344   }
345
346   for (unsigned int i = 0; i < count; i++)
347   {
348     FT_Fixed v = 0;
349     hb_codepoint_t glyph = *first_glyph;
350
351     unsigned int cv;
352     if (ft_font->advance_cache.get (glyph, &cv))
353       v = cv;
354     else
355     {
356       FT_Get_Advance (ft_face, glyph, load_flags, &v);
357       ft_font->advance_cache.set (glyph, v);
358     }
359
360     *first_advance = (v * mult + (1<<9)) >> 10;
361     first_glyph = &StructAtOffsetUnaligned<hb_codepoint_t> (first_glyph, glyph_stride);
362     first_advance = &StructAtOffsetUnaligned<hb_position_t> (first_advance, advance_stride);
363   }
364 }
365
366 static hb_position_t
367 hb_ft_get_glyph_v_advance (hb_font_t *font,
368                            void *font_data,
369                            hb_codepoint_t glyph,
370                            void *user_data HB_UNUSED)
371 {
372   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
373   hb_lock_t lock (ft_font->lock);
374   FT_Fixed v;
375
376   if (unlikely (FT_Get_Advance (ft_font->ft_face, glyph, ft_font->load_flags | FT_LOAD_VERTICAL_LAYOUT, &v)))
377     return 0;
378
379   if (font->y_scale < 0)
380     v = -v;
381
382   /* Note: FreeType's vertical metrics grows downward while other FreeType coordinates
383    * have a Y growing upward.  Hence the extra negation. */
384   return (-v + (1<<9)) >> 10;
385 }
386
387 static hb_bool_t
388 hb_ft_get_glyph_v_origin (hb_font_t *font,
389                           void *font_data,
390                           hb_codepoint_t glyph,
391                           hb_position_t *x,
392                           hb_position_t *y,
393                           void *user_data HB_UNUSED)
394 {
395   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
396   hb_lock_t lock (ft_font->lock);
397   FT_Face ft_face = ft_font->ft_face;
398
399   if (unlikely (FT_Load_Glyph (ft_face, glyph, ft_font->load_flags)))
400     return false;
401
402   /* Note: FreeType's vertical metrics grows downward while other FreeType coordinates
403    * have a Y growing upward.  Hence the extra negation. */
404   *x = ft_face->glyph->metrics.horiBearingX -   ft_face->glyph->metrics.vertBearingX;
405   *y = ft_face->glyph->metrics.horiBearingY - (-ft_face->glyph->metrics.vertBearingY);
406
407   if (font->x_scale < 0)
408     *x = -*x;
409   if (font->y_scale < 0)
410     *y = -*y;
411
412   return true;
413 }
414
415 #ifndef HB_NO_OT_SHAPE_FALLBACK
416 static hb_position_t
417 hb_ft_get_glyph_h_kerning (hb_font_t *font,
418                            void *font_data,
419                            hb_codepoint_t left_glyph,
420                            hb_codepoint_t right_glyph,
421                            void *user_data HB_UNUSED)
422 {
423   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
424   FT_Vector kerningv;
425
426   FT_Kerning_Mode mode = font->x_ppem ? FT_KERNING_DEFAULT : FT_KERNING_UNFITTED;
427   if (FT_Get_Kerning (ft_font->ft_face, left_glyph, right_glyph, mode, &kerningv))
428     return 0;
429
430   return kerningv.x;
431 }
432 #endif
433
434 static hb_bool_t
435 hb_ft_get_glyph_extents (hb_font_t *font,
436                          void *font_data,
437                          hb_codepoint_t glyph,
438                          hb_glyph_extents_t *extents,
439                          void *user_data HB_UNUSED)
440 {
441   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
442   hb_lock_t lock (ft_font->lock);
443   FT_Face ft_face = ft_font->ft_face;
444
445   if (unlikely (FT_Load_Glyph (ft_face, glyph, ft_font->load_flags)))
446     return false;
447
448   extents->x_bearing = ft_face->glyph->metrics.horiBearingX;
449   extents->y_bearing = ft_face->glyph->metrics.horiBearingY;
450   extents->width = ft_face->glyph->metrics.width;
451   extents->height = -ft_face->glyph->metrics.height;
452   if (font->x_scale < 0)
453   {
454     extents->x_bearing = -extents->x_bearing;
455     extents->width = -extents->width;
456   }
457   if (font->y_scale < 0)
458   {
459     extents->y_bearing = -extents->y_bearing;
460     extents->height = -extents->height;
461   }
462   return true;
463 }
464
465 static hb_bool_t
466 hb_ft_get_glyph_contour_point (hb_font_t *font HB_UNUSED,
467                                void *font_data,
468                                hb_codepoint_t glyph,
469                                unsigned int point_index,
470                                hb_position_t *x,
471                                hb_position_t *y,
472                                void *user_data HB_UNUSED)
473 {
474   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
475   hb_lock_t lock (ft_font->lock);
476   FT_Face ft_face = ft_font->ft_face;
477
478   if (unlikely (FT_Load_Glyph (ft_face, glyph, ft_font->load_flags)))
479       return false;
480
481   if (unlikely (ft_face->glyph->format != FT_GLYPH_FORMAT_OUTLINE))
482       return false;
483
484   if (unlikely (point_index >= (unsigned int) ft_face->glyph->outline.n_points))
485       return false;
486
487   *x = ft_face->glyph->outline.points[point_index].x;
488   *y = ft_face->glyph->outline.points[point_index].y;
489
490   return true;
491 }
492
493 static hb_bool_t
494 hb_ft_get_glyph_name (hb_font_t *font HB_UNUSED,
495                       void *font_data,
496                       hb_codepoint_t glyph,
497                       char *name, unsigned int size,
498                       void *user_data HB_UNUSED)
499 {
500   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
501   hb_lock_t lock (ft_font->lock);
502   FT_Face ft_face = ft_font->ft_face;
503
504   hb_bool_t ret = !FT_Get_Glyph_Name (ft_face, glyph, name, size);
505   if (ret && (size && !*name))
506     ret = false;
507
508   return ret;
509 }
510
511 static hb_bool_t
512 hb_ft_get_glyph_from_name (hb_font_t *font HB_UNUSED,
513                            void *font_data,
514                            const char *name, int len, /* -1 means nul-terminated */
515                            hb_codepoint_t *glyph,
516                            void *user_data HB_UNUSED)
517 {
518   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
519   hb_lock_t lock (ft_font->lock);
520   FT_Face ft_face = ft_font->ft_face;
521
522   if (len < 0)
523     *glyph = FT_Get_Name_Index (ft_face, (FT_String *) name);
524   else {
525     /* Make a nul-terminated version. */
526     char buf[128];
527     len = hb_min (len, (int) sizeof (buf) - 1);
528     strncpy (buf, name, len);
529     buf[len] = '\0';
530     *glyph = FT_Get_Name_Index (ft_face, buf);
531   }
532
533   if (*glyph == 0)
534   {
535     /* Check whether the given name was actually the name of glyph 0. */
536     char buf[128];
537     if (!FT_Get_Glyph_Name(ft_face, 0, buf, sizeof (buf)) &&
538         len < 0 ? !strcmp (buf, name) : !strncmp (buf, name, len))
539       return true;
540   }
541
542   return *glyph != 0;
543 }
544
545 static hb_bool_t
546 hb_ft_get_font_h_extents (hb_font_t *font HB_UNUSED,
547                           void *font_data,
548                           hb_font_extents_t *metrics,
549                           void *user_data HB_UNUSED)
550 {
551   const hb_ft_font_t *ft_font = (const hb_ft_font_t *) font_data;
552   hb_lock_t lock (ft_font->lock);
553   FT_Face ft_face = ft_font->ft_face;
554   metrics->ascender = FT_MulFix(ft_face->ascender, ft_face->size->metrics.y_scale);
555   metrics->descender = FT_MulFix(ft_face->descender, ft_face->size->metrics.y_scale);
556   metrics->line_gap = FT_MulFix( ft_face->height, ft_face->size->metrics.y_scale ) - (metrics->ascender - metrics->descender);
557   if (font->y_scale < 0)
558   {
559     metrics->ascender = -metrics->ascender;
560     metrics->descender = -metrics->descender;
561     metrics->line_gap = -metrics->line_gap;
562   }
563   return true;
564 }
565
566 #if HB_USE_ATEXIT
567 static void free_static_ft_funcs ();
568 #endif
569
570 static struct hb_ft_font_funcs_lazy_loader_t : hb_font_funcs_lazy_loader_t<hb_ft_font_funcs_lazy_loader_t>
571 {
572   static hb_font_funcs_t *create ()
573   {
574     hb_font_funcs_t *funcs = hb_font_funcs_create ();
575
576     hb_font_funcs_set_font_h_extents_func (funcs, hb_ft_get_font_h_extents, nullptr, nullptr);
577     //hb_font_funcs_set_font_v_extents_func (funcs, hb_ft_get_font_v_extents, nullptr, nullptr);
578     hb_font_funcs_set_nominal_glyph_func (funcs, hb_ft_get_nominal_glyph, nullptr, nullptr);
579     hb_font_funcs_set_nominal_glyphs_func (funcs, hb_ft_get_nominal_glyphs, nullptr, nullptr);
580     hb_font_funcs_set_variation_glyph_func (funcs, hb_ft_get_variation_glyph, nullptr, nullptr);
581     hb_font_funcs_set_glyph_h_advances_func (funcs, hb_ft_get_glyph_h_advances, nullptr, nullptr);
582     hb_font_funcs_set_glyph_v_advance_func (funcs, hb_ft_get_glyph_v_advance, nullptr, nullptr);
583     //hb_font_funcs_set_glyph_h_origin_func (funcs, hb_ft_get_glyph_h_origin, nullptr, nullptr);
584     hb_font_funcs_set_glyph_v_origin_func (funcs, hb_ft_get_glyph_v_origin, nullptr, nullptr);
585 #ifndef HB_NO_OT_SHAPE_FALLBACK
586     hb_font_funcs_set_glyph_h_kerning_func (funcs, hb_ft_get_glyph_h_kerning, nullptr, nullptr);
587 #endif
588     //hb_font_funcs_set_glyph_v_kerning_func (funcs, hb_ft_get_glyph_v_kerning, nullptr, nullptr);
589     hb_font_funcs_set_glyph_extents_func (funcs, hb_ft_get_glyph_extents, nullptr, nullptr);
590     hb_font_funcs_set_glyph_contour_point_func (funcs, hb_ft_get_glyph_contour_point, nullptr, nullptr);
591     hb_font_funcs_set_glyph_name_func (funcs, hb_ft_get_glyph_name, nullptr, nullptr);
592     hb_font_funcs_set_glyph_from_name_func (funcs, hb_ft_get_glyph_from_name, nullptr, nullptr);
593
594     hb_font_funcs_make_immutable (funcs);
595
596 #if HB_USE_ATEXIT
597     atexit (free_static_ft_funcs);
598 #endif
599
600     return funcs;
601   }
602 } static_ft_funcs;
603
604 #if HB_USE_ATEXIT
605 static
606 void free_static_ft_funcs ()
607 {
608   static_ft_funcs.free_instance ();
609 }
610 #endif
611
612 static hb_font_funcs_t *
613 _hb_ft_get_font_funcs ()
614 {
615   return static_ft_funcs.get_unconst ();
616 }
617
618 static void
619 _hb_ft_font_set_funcs (hb_font_t *font, FT_Face ft_face, bool unref)
620 {
621   bool symbol = ft_face->charmap && ft_face->charmap->encoding == FT_ENCODING_MS_SYMBOL;
622
623   hb_font_set_funcs (font,
624                      _hb_ft_get_font_funcs (),
625                      _hb_ft_font_create (ft_face, symbol, unref),
626                      _hb_ft_font_destroy);
627 }
628
629
630 static hb_blob_t *
631 _hb_ft_reference_table (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
632 {
633   FT_Face ft_face = (FT_Face) user_data;
634   FT_Byte *buffer;
635   FT_ULong  length = 0;
636   FT_Error error;
637
638   /* Note: FreeType like HarfBuzz uses the NONE tag for fetching the entire blob */
639
640   error = FT_Load_Sfnt_Table (ft_face, tag, 0, nullptr, &length);
641   if (error)
642     return nullptr;
643
644   buffer = (FT_Byte *) malloc (length);
645   if (!buffer)
646     return nullptr;
647
648   error = FT_Load_Sfnt_Table (ft_face, tag, 0, buffer, &length);
649   if (error)
650   {
651     free (buffer);
652     return nullptr;
653   }
654
655   return hb_blob_create ((const char *) buffer, length,
656                          HB_MEMORY_MODE_WRITABLE,
657                          buffer, free);
658 }
659
660 /**
661  * hb_ft_face_create:
662  * @ft_face: (destroy destroy) (scope notified): FT_Face to work upon
663  * @destroy: A callback to call when the face object is not needed anymore
664  *
665  * Creates an #hb_face_t face object from the specified FT_Face.
666  *
667  * This variant of the function does not provide any life-cycle management.
668  *
669  * Most client programs should use hb_ft_face_create_referenced()
670  * (or, perhaps, hb_ft_face_create_cached()) instead. 
671  *
672  * If you know you have valid reasons not to use hb_ft_face_create_referenced(),
673  * then it is the client program's responsibility to destroy @ft_face 
674  * after the #hb_face_t face object has been destroyed.
675  *
676  * Return value: (transfer full): the new #hb_face_t face object
677  *
678  * Since: 0.9.2
679  **/
680 hb_face_t *
681 hb_ft_face_create (FT_Face           ft_face,
682                    hb_destroy_func_t destroy)
683 {
684   hb_face_t *face;
685
686   if (!ft_face->stream->read) {
687     hb_blob_t *blob;
688
689     blob = hb_blob_create ((const char *) ft_face->stream->base,
690                            (unsigned int) ft_face->stream->size,
691                            HB_MEMORY_MODE_READONLY,
692                            ft_face, destroy);
693     face = hb_face_create (blob, ft_face->face_index);
694     hb_blob_destroy (blob);
695   } else {
696     face = hb_face_create_for_tables (_hb_ft_reference_table, ft_face, destroy);
697   }
698
699   hb_face_set_index (face, ft_face->face_index);
700   hb_face_set_upem (face, ft_face->units_per_EM);
701
702   return face;
703 }
704
705 /**
706  * hb_ft_face_create_referenced:
707  * @ft_face: FT_Face to work upon
708  *
709  * Creates an #hb_face_t face object from the specified FT_Face.
710  *
711  * This is the preferred variant of the hb_ft_face_create*
712  * function family, because it calls FT_Reference_Face() on @ft_face,
713  * ensuring that @ft_face remains alive as long as the resulting
714  * #hb_face_t face object remains alive. Also calls FT_Done_Face()
715  * when the #hb_face_t face object is destroyed.
716  *
717  * Use this version unless you know you have good reasons not to.
718  *
719  * Return value: (transfer full): the new #hb_face_t face object
720  *
721  * Since: 0.9.38
722  **/
723 hb_face_t *
724 hb_ft_face_create_referenced (FT_Face ft_face)
725 {
726   FT_Reference_Face (ft_face);
727   return hb_ft_face_create (ft_face, _hb_ft_face_destroy);
728 }
729
730 static void
731 hb_ft_face_finalize (FT_Face ft_face)
732 {
733   hb_face_destroy ((hb_face_t *) ft_face->generic.data);
734 }
735
736 /**
737  * hb_ft_face_create_cached:
738  * @ft_face: FT_Face to work upon
739  *
740  * Creates an #hb_face_t face object from the specified FT_Face.
741  *
742  * This variant of the function caches the newly created #hb_face_t
743  * face object, using the @generic pointer of @ft_face. Subsequent function
744  * calls that are passed the same @ft_face parameter will have the same
745  * #hb_face_t returned to them, and that #hb_face_t will be correctly
746  * reference counted.
747  *
748  * However, client programs are still responsible for destroying
749  * @ft_face after the last #hb_face_t face object has been destroyed.
750  *
751  * Return value: (transfer full): the new #hb_face_t face object
752  *
753  * Since: 0.9.2
754  **/
755 hb_face_t *
756 hb_ft_face_create_cached (FT_Face ft_face)
757 {
758   if (unlikely (!ft_face->generic.data || ft_face->generic.finalizer != (FT_Generic_Finalizer) hb_ft_face_finalize))
759   {
760     if (ft_face->generic.finalizer)
761       ft_face->generic.finalizer (ft_face);
762
763     ft_face->generic.data = hb_ft_face_create (ft_face, nullptr);
764     ft_face->generic.finalizer = (FT_Generic_Finalizer) hb_ft_face_finalize;
765   }
766
767   return hb_face_reference ((hb_face_t *) ft_face->generic.data);
768 }
769
770 /**
771  * hb_ft_font_create:
772  * @ft_face: (destroy destroy) (scope notified): FT_Face to work upon
773  * @destroy: (optional): A callback to call when the font object is not needed anymore
774  *
775  * Creates an #hb_font_t font object from the specified FT_Face.
776  *
777  * <note>Note: You must set the face size on @ft_face before calling
778  * hb_ft_font_create() on it. Otherwise, HarfBuzz will not pick up
779  * the face size.</note>
780  *
781  * This variant of the function does not provide any life-cycle management.
782  *
783  * Most client programs should use hb_ft_font_create_referenced()
784  * instead. 
785  *
786  * If you know you have valid reasons not to use hb_ft_font_create_referenced(),
787  * then it is the client program's responsibility to destroy @ft_face 
788  * after the #hb_font_t font object has been destroyed.
789  *
790  * HarfBuzz will use the @destroy callback on the #hb_font_t font object 
791  * if it is supplied when you use this function. However, even if @destroy
792  * is provided, it is the client program's responsibility to destroy @ft_face,
793  * and it is the client program's responsibility to ensure that @ft_face is
794  * destroyed only after the #hb_font_t font object has been destroyed.
795  *
796  * Return value: (transfer full): the new #hb_font_t font object
797  *
798  * Since: 0.9.2
799  **/
800 hb_font_t *
801 hb_ft_font_create (FT_Face           ft_face,
802                    hb_destroy_func_t destroy)
803 {
804   hb_font_t *font;
805   hb_face_t *face;
806
807   face = hb_ft_face_create (ft_face, destroy);
808   font = hb_font_create (face);
809   hb_face_destroy (face);
810   _hb_ft_font_set_funcs (font, ft_face, false);
811   hb_ft_font_changed (font);
812   return font;
813 }
814
815 /**
816  * hb_ft_font_has_changed:
817  * @font: #hb_font_t to work upon
818  *
819  * Refreshes the state of @font when the underlying FT_Face has changed.
820  * This function should be called after changing the size or
821  * variation-axis settings on the FT_Face.
822  *
823  * Since: 1.0.5
824  **/
825 void
826 hb_ft_font_changed (hb_font_t *font)
827 {
828   if (font->destroy != (hb_destroy_func_t) _hb_ft_font_destroy)
829     return;
830
831   hb_ft_font_t *ft_font = (hb_ft_font_t *) font->user_data;
832   FT_Face ft_face = ft_font->ft_face;
833
834   hb_font_set_scale (font,
835                      (int) (((uint64_t) ft_face->size->metrics.x_scale * (uint64_t) ft_face->units_per_EM + (1u<<15)) >> 16),
836                      (int) (((uint64_t) ft_face->size->metrics.y_scale * (uint64_t) ft_face->units_per_EM + (1u<<15)) >> 16));
837 #if 0 /* hb-ft works in no-hinting model */
838   hb_font_set_ppem (font,
839                     ft_face->size->metrics.x_ppem,
840                     ft_face->size->metrics.y_ppem);
841 #endif
842
843 #if defined(HAVE_FT_GET_VAR_BLEND_COORDINATES) && !defined(HB_NO_VAR)
844   FT_MM_Var *mm_var = nullptr;
845   if (!FT_Get_MM_Var (ft_face, &mm_var))
846   {
847     FT_Fixed *ft_coords = (FT_Fixed *) calloc (mm_var->num_axis, sizeof (FT_Fixed));
848     int *coords = (int *) calloc (mm_var->num_axis, sizeof (int));
849     if (coords && ft_coords)
850     {
851       if (!FT_Get_Var_Blend_Coordinates (ft_face, mm_var->num_axis, ft_coords))
852       {
853         bool nonzero = false;
854
855         for (unsigned int i = 0; i < mm_var->num_axis; ++i)
856          {
857           coords[i] = ft_coords[i] >>= 2;
858           nonzero = nonzero || coords[i];
859          }
860
861         if (nonzero)
862           hb_font_set_var_coords_normalized (font, coords, mm_var->num_axis);
863         else
864           hb_font_set_var_coords_normalized (font, nullptr, 0);
865       }
866     }
867     free (coords);
868     free (ft_coords);
869 #ifdef HAVE_FT_DONE_MM_VAR
870     FT_Done_MM_Var (ft_face->glyph->library, mm_var);
871 #else
872     free (mm_var);
873 #endif
874   }
875 #endif
876 }
877
878 /**
879  * hb_ft_font_create_referenced:
880  * @ft_face: FT_Face to work upon
881  *
882  * Creates an #hb_font_t font object from the specified FT_Face.
883  *
884  * <note>Note: You must set the face size on @ft_face before calling
885  * hb_ft_font_create_references() on it. Otherwise, HarfBuzz will not pick up
886  * the face size.</note>
887  *
888  * This is the preferred variant of the hb_ft_font_create*
889  * function family, because it calls FT_Reference_Face() on @ft_face,
890  * ensuring that @ft_face remains alive as long as the resulting
891  * #hb_font_t font object remains alive.
892  *
893  * Use this version unless you know you have good reasons not to.
894  *
895  * Return value: (transfer full): the new #hb_font_t font object
896  *
897  * Since: 0.9.38
898  **/
899 hb_font_t *
900 hb_ft_font_create_referenced (FT_Face ft_face)
901 {
902   FT_Reference_Face (ft_face);
903   return hb_ft_font_create (ft_face, _hb_ft_face_destroy);
904 }
905
906 #if HB_USE_ATEXIT
907 static void free_static_ft_library ();
908 #endif
909
910 static struct hb_ft_library_lazy_loader_t : hb_lazy_loader_t<hb_remove_pointer<FT_Library>,
911                                                              hb_ft_library_lazy_loader_t>
912 {
913   static FT_Library create ()
914   {
915     FT_Library l;
916     if (FT_Init_FreeType (&l))
917       return nullptr;
918
919 #if HB_USE_ATEXIT
920     atexit (free_static_ft_library);
921 #endif
922
923     return l;
924   }
925   static void destroy (FT_Library l)
926   {
927     FT_Done_FreeType (l);
928   }
929   static FT_Library get_null ()
930   {
931     return nullptr;
932   }
933 } static_ft_library;
934
935 #if HB_USE_ATEXIT
936 static
937 void free_static_ft_library ()
938 {
939   static_ft_library.free_instance ();
940 }
941 #endif
942
943 static FT_Library
944 get_ft_library ()
945 {
946   return static_ft_library.get_unconst ();
947 }
948
949 static void
950 _release_blob (FT_Face ft_face)
951 {
952   hb_blob_destroy ((hb_blob_t *) ft_face->generic.data);
953 }
954
955 /**
956  * hb_ft_font_set_funcs:
957  * @font: #hb_font_t to work upon
958  *
959  * Configures the font-functions structure of the specified
960  * #hb_font_t font object to use FreeType font functions.
961  *
962  * In particular, you can use this function to configure an
963  * existing #hb_face_t face object for use with FreeType font
964  * functions even if that #hb_face_t face object was initially
965  * created with hb_face_create(), and therefore was not
966  * initially configured to use FreeType font functions.
967  *
968  * An #hb_face_t face object created with hb_ft_face_create()
969  * is preconfigured for FreeType font functions and does not
970  * require this function to be used.
971  *
972  * <note>Note: Internally, this function creates an FT_Face.
973 * </note>
974  *
975  * Since: 1.0.5
976  **/
977 void
978 hb_ft_font_set_funcs (hb_font_t *font)
979 {
980   hb_blob_t *blob = hb_face_reference_blob (font->face);
981   unsigned int blob_length;
982   const char *blob_data = hb_blob_get_data (blob, &blob_length);
983   if (unlikely (!blob_length))
984     DEBUG_MSG (FT, font, "Font face has empty blob");
985
986   FT_Face ft_face = nullptr;
987   FT_Error err = FT_New_Memory_Face (get_ft_library (),
988                                      (const FT_Byte *) blob_data,
989                                      blob_length,
990                                      hb_face_get_index (font->face),
991                                      &ft_face);
992
993   if (unlikely (err)) {
994     hb_blob_destroy (blob);
995     DEBUG_MSG (FT, font, "Font face FT_New_Memory_Face() failed");
996     return;
997   }
998
999   if (FT_Select_Charmap (ft_face, FT_ENCODING_MS_SYMBOL))
1000     FT_Select_Charmap (ft_face, FT_ENCODING_UNICODE);
1001
1002   FT_Set_Char_Size (ft_face,
1003                     abs (font->x_scale), abs (font->y_scale),
1004                     0, 0);
1005 #if 0
1006                     font->x_ppem * 72 * 64 / font->x_scale,
1007                     font->y_ppem * 72 * 64 / font->y_scale);
1008 #endif
1009   if (font->x_scale < 0 || font->y_scale < 0)
1010   {
1011     FT_Matrix matrix = { font->x_scale < 0 ? -1 : +1, 0,
1012                           0, font->y_scale < 0 ? -1 : +1};
1013     FT_Set_Transform (ft_face, &matrix, nullptr);
1014   }
1015
1016 #if defined(HAVE_FT_GET_VAR_BLEND_COORDINATES) && !defined(HB_NO_VAR)
1017   unsigned int num_coords;
1018   const int *coords = hb_font_get_var_coords_normalized (font, &num_coords);
1019   if (num_coords)
1020   {
1021     FT_Fixed *ft_coords = (FT_Fixed *) calloc (num_coords, sizeof (FT_Fixed));
1022     if (ft_coords)
1023     {
1024       for (unsigned int i = 0; i < num_coords; i++)
1025         ft_coords[i] = coords[i] * 4;
1026       FT_Set_Var_Blend_Coordinates (ft_face, num_coords, ft_coords);
1027       free (ft_coords);
1028     }
1029   }
1030 #endif
1031
1032   ft_face->generic.data = blob;
1033   ft_face->generic.finalizer = (FT_Generic_Finalizer) _release_blob;
1034
1035   _hb_ft_font_set_funcs (font, ft_face, true);
1036   hb_ft_font_set_load_flags (font, FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING);
1037 }
1038
1039
1040 #endif