1/*
2 * Copyright © 2009  Red Hat, Inc.
3 * Copyright © 2009  Keith Stribley
4 *
5 *  This is part of HarfBuzz, a text shaping library.
6 *
7 * Permission is hereby granted, without written agreement and without
8 * license or royalty fees, to use, copy, modify, and distribute this
9 * software and its documentation for any purpose, provided that the
10 * above copyright notice and the following two paragraphs appear in
11 * all copies of this software.
12 *
13 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
14 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
15 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
16 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
17 * DAMAGE.
18 *
19 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
20 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21 * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
22 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
23 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24 *
25 * Red Hat Author(s): Behdad Esfahbod
26 */
27
28#include "hb-private.hh"
29
30#include "hb-ft.h"
31
32#include "hb-font-private.hh"
33
34#include FT_ADVANCES_H
35#include FT_TRUETYPE_TABLES_H
36
37
38
39#ifndef HB_DEBUG_FT
40#define HB_DEBUG_FT (HB_DEBUG+0)
41#endif
42
43
44/* TODO:
45 *
46 * In general, this file does a fine job of what it's supposed to do.
47 * There are, however, things that need more work:
48 *
49 *   - We don't handle any load_flags.  That definitely has API implications. :(
50 *     I believe hb_ft_font_create() should take load_flags input.
51 *     In particular, FT_Get_Advance() without the NO_HINTING flag seems to be
52 *     buggy.
53 *
54 *   - We don't handle / allow for emboldening / obliqueing.
55 *
56 *   - In the future, we should add constructors to create fonts in font space?
57 *
58 *   - FT_Load_Glyph() is exteremely costly.  Do something about it?
59 */
60
61
62static hb_bool_t
63hb_ft_get_glyph (hb_font_t *font HB_UNUSED,
64		 void *font_data,
65		 hb_codepoint_t unicode,
66		 hb_codepoint_t variation_selector,
67		 hb_codepoint_t *glyph,
68		 void *user_data HB_UNUSED)
69
70{
71  FT_Face ft_face = (FT_Face) font_data;
72
73#ifdef HAVE_FT_FACE_GETCHARVARIANTINDEX
74  if (unlikely (variation_selector)) {
75    *glyph = FT_Face_GetCharVariantIndex (ft_face, unicode, variation_selector);
76    return *glyph != 0;
77  }
78#endif
79
80  *glyph = FT_Get_Char_Index (ft_face, unicode);
81  return *glyph != 0;
82}
83
84static hb_position_t
85hb_ft_get_glyph_h_advance (hb_font_t *font HB_UNUSED,
86			   void *font_data,
87			   hb_codepoint_t glyph,
88			   void *user_data HB_UNUSED)
89{
90  FT_Face ft_face = (FT_Face) font_data;
91  int load_flags = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING;
92  FT_Fixed v;
93
94  if (unlikely (FT_Get_Advance (ft_face, glyph, load_flags, &v)))
95    return 0;
96
97  return (v + (1<<9)) >> 10;
98}
99
100static hb_position_t
101hb_ft_get_glyph_v_advance (hb_font_t *font HB_UNUSED,
102			   void *font_data,
103			   hb_codepoint_t glyph,
104			   void *user_data HB_UNUSED)
105{
106  FT_Face ft_face = (FT_Face) font_data;
107  int load_flags = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING | FT_LOAD_VERTICAL_LAYOUT;
108  FT_Fixed v;
109
110  if (unlikely (FT_Get_Advance (ft_face, glyph, load_flags, &v)))
111    return 0;
112
113  /* Note: FreeType's vertical metrics grows downward while other FreeType coordinates
114   * have a Y growing upward.  Hence the extra negation. */
115  return (-v + (1<<9)) >> 10;
116}
117
118static hb_bool_t
119hb_ft_get_glyph_h_origin (hb_font_t *font HB_UNUSED,
120			  void *font_data HB_UNUSED,
121			  hb_codepoint_t glyph HB_UNUSED,
122			  hb_position_t *x HB_UNUSED,
123			  hb_position_t *y HB_UNUSED,
124			  void *user_data HB_UNUSED)
125{
126  /* We always work in the horizontal coordinates. */
127  return true;
128}
129
130static hb_bool_t
131hb_ft_get_glyph_v_origin (hb_font_t *font HB_UNUSED,
132			  void *font_data,
133			  hb_codepoint_t glyph,
134			  hb_position_t *x,
135			  hb_position_t *y,
136			  void *user_data HB_UNUSED)
137{
138  FT_Face ft_face = (FT_Face) font_data;
139  int load_flags = FT_LOAD_DEFAULT;
140
141  if (unlikely (FT_Load_Glyph (ft_face, glyph, load_flags)))
142    return false;
143
144  /* Note: FreeType's vertical metrics grows downward while other FreeType coordinates
145   * have a Y growing upward.  Hence the extra negation. */
146  *x = ft_face->glyph->metrics.horiBearingX -   ft_face->glyph->metrics.vertBearingX;
147  *y = ft_face->glyph->metrics.horiBearingY - (-ft_face->glyph->metrics.vertBearingY);
148
149  return true;
150}
151
152static hb_position_t
153hb_ft_get_glyph_h_kerning (hb_font_t *font,
154			   void *font_data,
155			   hb_codepoint_t left_glyph,
156			   hb_codepoint_t right_glyph,
157			   void *user_data HB_UNUSED)
158{
159  FT_Face ft_face = (FT_Face) font_data;
160  FT_Vector kerningv;
161
162  FT_Kerning_Mode mode = font->x_ppem ? FT_KERNING_DEFAULT : FT_KERNING_UNFITTED;
163  if (FT_Get_Kerning (ft_face, left_glyph, right_glyph, mode, &kerningv))
164    return 0;
165
166  return kerningv.x;
167}
168
169static hb_position_t
170hb_ft_get_glyph_v_kerning (hb_font_t *font HB_UNUSED,
171			   void *font_data HB_UNUSED,
172			   hb_codepoint_t top_glyph HB_UNUSED,
173			   hb_codepoint_t bottom_glyph HB_UNUSED,
174			   void *user_data HB_UNUSED)
175{
176  /* FreeType API doesn't support vertical kerning */
177  return 0;
178}
179
180static hb_bool_t
181hb_ft_get_glyph_extents (hb_font_t *font HB_UNUSED,
182			 void *font_data,
183			 hb_codepoint_t glyph,
184			 hb_glyph_extents_t *extents,
185			 void *user_data HB_UNUSED)
186{
187  FT_Face ft_face = (FT_Face) font_data;
188  int load_flags = FT_LOAD_DEFAULT;
189
190  if (unlikely (FT_Load_Glyph (ft_face, glyph, load_flags)))
191    return false;
192
193  extents->x_bearing = ft_face->glyph->metrics.horiBearingX;
194  extents->y_bearing = ft_face->glyph->metrics.horiBearingY;
195  extents->width = ft_face->glyph->metrics.width;
196  extents->height = -ft_face->glyph->metrics.height;
197  return true;
198}
199
200static hb_bool_t
201hb_ft_get_glyph_contour_point (hb_font_t *font HB_UNUSED,
202			       void *font_data,
203			       hb_codepoint_t glyph,
204			       unsigned int point_index,
205			       hb_position_t *x,
206			       hb_position_t *y,
207			       void *user_data HB_UNUSED)
208{
209  FT_Face ft_face = (FT_Face) font_data;
210  int load_flags = FT_LOAD_DEFAULT;
211
212  if (unlikely (FT_Load_Glyph (ft_face, glyph, load_flags)))
213      return false;
214
215  if (unlikely (ft_face->glyph->format != FT_GLYPH_FORMAT_OUTLINE))
216      return false;
217
218  if (unlikely (point_index >= (unsigned int) ft_face->glyph->outline.n_points))
219      return false;
220
221  *x = ft_face->glyph->outline.points[point_index].x;
222  *y = ft_face->glyph->outline.points[point_index].y;
223
224  return true;
225}
226
227static hb_bool_t
228hb_ft_get_glyph_name (hb_font_t *font HB_UNUSED,
229		      void *font_data,
230		      hb_codepoint_t glyph,
231		      char *name, unsigned int size,
232		      void *user_data HB_UNUSED)
233{
234  FT_Face ft_face = (FT_Face) font_data;
235
236  hb_bool_t ret = !FT_Get_Glyph_Name (ft_face, glyph, name, size);
237  if (ret && (size && !*name))
238    ret = false;
239
240  return ret;
241}
242
243static hb_bool_t
244hb_ft_get_glyph_from_name (hb_font_t *font HB_UNUSED,
245			   void *font_data,
246			   const char *name, int len, /* -1 means nul-terminated */
247			   hb_codepoint_t *glyph,
248			   void *user_data HB_UNUSED)
249{
250  FT_Face ft_face = (FT_Face) font_data;
251
252  if (len < 0)
253    *glyph = FT_Get_Name_Index (ft_face, (FT_String *) name);
254  else {
255    /* Make a nul-terminated version. */
256    char buf[128];
257    len = MIN (len, (int) sizeof (buf) - 1);
258    strncpy (buf, name, len);
259    buf[len] = '\0';
260    *glyph = FT_Get_Name_Index (ft_face, buf);
261  }
262
263  if (*glyph == 0)
264  {
265    /* Check whether the given name was actually the name of glyph 0. */
266    char buf[128];
267    if (!FT_Get_Glyph_Name(ft_face, 0, buf, sizeof (buf)) &&
268        len < 0 ? !strcmp (buf, name) : !strncmp (buf, name, len))
269      return true;
270  }
271
272  return *glyph != 0;
273}
274
275
276static hb_font_funcs_t *
277_hb_ft_get_font_funcs (void)
278{
279  static const hb_font_funcs_t ft_ffuncs = {
280    HB_OBJECT_HEADER_STATIC,
281
282    true, /* immutable */
283
284    {
285#define HB_FONT_FUNC_IMPLEMENT(name) hb_ft_get_##name,
286      HB_FONT_FUNCS_IMPLEMENT_CALLBACKS
287#undef HB_FONT_FUNC_IMPLEMENT
288    }
289  };
290
291  return const_cast<hb_font_funcs_t *> (&ft_ffuncs);
292}
293
294
295static hb_blob_t *
296reference_table  (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
297{
298  FT_Face ft_face = (FT_Face) user_data;
299  FT_Byte *buffer;
300  FT_ULong  length = 0;
301  FT_Error error;
302
303  /* Note: FreeType like HarfBuzz uses the NONE tag for fetching the entire blob */
304
305  error = FT_Load_Sfnt_Table (ft_face, tag, 0, NULL, &length);
306  if (error)
307    return NULL;
308
309  buffer = (FT_Byte *) malloc (length);
310  if (buffer == NULL)
311    return NULL;
312
313  error = FT_Load_Sfnt_Table (ft_face, tag, 0, buffer, &length);
314  if (error)
315    return NULL;
316
317  return hb_blob_create ((const char *) buffer, length,
318			 HB_MEMORY_MODE_WRITABLE,
319			 buffer, free);
320}
321
322/**
323 * hb_ft_face_create:
324 * @ft_face: (destroy destroy) (scope notified):
325 * @destroy:
326 *
327 *
328 *
329 * Return value: (transfer full):
330 * Since: 1.0
331 **/
332hb_face_t *
333hb_ft_face_create (FT_Face           ft_face,
334		   hb_destroy_func_t destroy)
335{
336  hb_face_t *face;
337
338  if (ft_face->stream->read == NULL) {
339    hb_blob_t *blob;
340
341    blob = hb_blob_create ((const char *) ft_face->stream->base,
342			   (unsigned int) ft_face->stream->size,
343			   /* TODO: We assume that it's mmap()'ed, but FreeType code
344			    * suggests that there are cases we reach here but font is
345			    * not mmapped.  For example, when mmap() fails.  No idea
346			    * how to deal with it better here. */
347			   HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE,
348			   ft_face, destroy);
349    face = hb_face_create (blob, ft_face->face_index);
350    hb_blob_destroy (blob);
351  } else {
352    face = hb_face_create_for_tables (reference_table, ft_face, destroy);
353  }
354
355  hb_face_set_index (face, ft_face->face_index);
356  hb_face_set_upem (face, ft_face->units_per_EM);
357
358  return face;
359}
360
361static void
362hb_ft_face_finalize (FT_Face ft_face)
363{
364  hb_face_destroy ((hb_face_t *) ft_face->generic.data);
365}
366
367/**
368 * hb_ft_face_create_cached:
369 * @ft_face:
370 *
371 *
372 *
373 * Return value: (transfer full):
374 * Since: 1.0
375 **/
376hb_face_t *
377hb_ft_face_create_cached (FT_Face ft_face)
378{
379  if (unlikely (!ft_face->generic.data || ft_face->generic.finalizer != (FT_Generic_Finalizer) hb_ft_face_finalize))
380  {
381    if (ft_face->generic.finalizer)
382      ft_face->generic.finalizer (ft_face);
383
384    ft_face->generic.data = hb_ft_face_create (ft_face, NULL);
385    ft_face->generic.finalizer = (FT_Generic_Finalizer) hb_ft_face_finalize;
386  }
387
388  return hb_face_reference ((hb_face_t *) ft_face->generic.data);
389}
390
391static void
392_do_nothing (void)
393{
394}
395
396
397/**
398 * hb_ft_font_create:
399 * @ft_face: (destroy destroy) (scope notified):
400 * @destroy:
401 *
402 *
403 *
404 * Return value: (transfer full):
405 * Since: 1.0
406 **/
407hb_font_t *
408hb_ft_font_create (FT_Face           ft_face,
409		   hb_destroy_func_t destroy)
410{
411  hb_font_t *font;
412  hb_face_t *face;
413
414  face = hb_ft_face_create (ft_face, destroy);
415  font = hb_font_create (face);
416  hb_face_destroy (face);
417  hb_font_set_funcs (font,
418		     _hb_ft_get_font_funcs (),
419		     ft_face, (hb_destroy_func_t) _do_nothing);
420  hb_font_set_scale (font,
421		     (int) (((uint64_t) ft_face->size->metrics.x_scale * (uint64_t) ft_face->units_per_EM + (1<<15)) >> 16),
422		     (int) (((uint64_t) ft_face->size->metrics.y_scale * (uint64_t) ft_face->units_per_EM + (1<<15)) >> 16));
423  hb_font_set_ppem (font,
424		    ft_face->size->metrics.x_ppem,
425		    ft_face->size->metrics.y_ppem);
426
427  return font;
428}
429
430
431/* Thread-safe, lock-free, FT_Library */
432
433static FT_Library ft_library;
434
435static inline
436void free_ft_library (void)
437{
438  FT_Done_FreeType (ft_library);
439}
440
441static FT_Library
442get_ft_library (void)
443{
444retry:
445  FT_Library library = (FT_Library) hb_atomic_ptr_get (&ft_library);
446
447  if (unlikely (!library))
448  {
449    /* Not found; allocate one. */
450    if (FT_Init_FreeType (&library))
451      return NULL;
452
453    if (!hb_atomic_ptr_cmpexch (&ft_library, NULL, library)) {
454      FT_Done_FreeType (library);
455      goto retry;
456    }
457
458#ifdef HAVE_ATEXIT
459    atexit (free_ft_library); /* First person registers atexit() callback. */
460#endif
461  }
462
463  return library;
464}
465
466static void
467_release_blob (FT_Face ft_face)
468{
469  hb_blob_destroy ((hb_blob_t *) ft_face->generic.data);
470}
471
472void
473hb_ft_font_set_funcs (hb_font_t *font)
474{
475  hb_blob_t *blob = hb_face_reference_blob (font->face);
476  unsigned int blob_length;
477  const char *blob_data = hb_blob_get_data (blob, &blob_length);
478  if (unlikely (!blob_length))
479    DEBUG_MSG (FT, font, "Font face has empty blob");
480
481  FT_Face ft_face = NULL;
482  FT_Error err = FT_New_Memory_Face (get_ft_library (),
483				     (const FT_Byte *) blob_data,
484				     blob_length,
485				     hb_face_get_index (font->face),
486				     &ft_face);
487
488  if (unlikely (err)) {
489    hb_blob_destroy (blob);
490    DEBUG_MSG (FT, font, "Font face FT_New_Memory_Face() failed");
491    return;
492  }
493
494  FT_Select_Charmap (ft_face, FT_ENCODING_UNICODE);
495
496  assert (font->y_scale >= 0);
497  FT_Set_Char_Size (ft_face,
498		    font->x_scale, font->y_scale,
499		    0, 0);
500#if 0
501		    font->x_ppem * 72 * 64 / font->x_scale,
502		    font->y_ppem * 72 * 64 / font->y_scale);
503#endif
504
505  ft_face->generic.data = blob;
506  ft_face->generic.finalizer = (FT_Generic_Finalizer) _release_blob;
507
508  hb_font_set_funcs (font,
509		     _hb_ft_get_font_funcs (),
510		     ft_face,
511		     (hb_destroy_func_t) FT_Done_Face);
512}
513
514FT_Face
515hb_ft_font_get_face (hb_font_t *font)
516{
517  if (font->destroy == (hb_destroy_func_t) FT_Done_Face ||
518      font->destroy == (hb_destroy_func_t) _do_nothing)
519    return (FT_Face) font->user_data;
520
521  return NULL;
522}
523