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