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 *     FreeType works in 26.6 mode.  Clients can decide to use that mode, and everything
55 *     would work fine.  However, we also abuse this API for performing in font-space,
56 *     but don't pass the correct flags to FreeType.  We just abuse the no-hinting mode
57 *     for that, such that no rounding etc happens.  As such, we don't set ppem, and
58 *     pass NO_HINTING around.  This seems to work best, until we go ahead and add a full
59 *     load_flags API.
60 *
61 *   - We don't handle / allow for emboldening / obliqueing.
62 *
63 *   - In the future, we should add constructors to create fonts in font space?
64 *
65 *   - FT_Load_Glyph() is exteremely costly.  Do something about it?
66 */
67
68
69static hb_bool_t
70hb_ft_get_glyph (hb_font_t *font HB_UNUSED,
71		 void *font_data,
72		 hb_codepoint_t unicode,
73		 hb_codepoint_t variation_selector,
74		 hb_codepoint_t *glyph,
75		 void *user_data HB_UNUSED)
76
77{
78  FT_Face ft_face = (FT_Face) font_data;
79
80  if (unlikely (variation_selector)) {
81    *glyph = FT_Face_GetCharVariantIndex (ft_face, unicode, variation_selector);
82    return *glyph != 0;
83  }
84
85  *glyph = FT_Get_Char_Index (ft_face, unicode);
86  return *glyph != 0;
87}
88
89static hb_position_t
90hb_ft_get_glyph_h_advance (hb_font_t *font HB_UNUSED,
91			   void *font_data,
92			   hb_codepoint_t glyph,
93			   void *user_data HB_UNUSED)
94{
95  FT_Face ft_face = (FT_Face) font_data;
96  int load_flags = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING;
97  FT_Fixed v;
98
99  if (unlikely (FT_Get_Advance (ft_face, glyph, load_flags, &v)))
100    return 0;
101
102  if (font->x_scale < 0)
103    v = -v;
104
105  return (v + (1<<9)) >> 10;
106}
107
108static hb_position_t
109hb_ft_get_glyph_v_advance (hb_font_t *font HB_UNUSED,
110			   void *font_data,
111			   hb_codepoint_t glyph,
112			   void *user_data HB_UNUSED)
113{
114  FT_Face ft_face = (FT_Face) font_data;
115  int load_flags = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING | FT_LOAD_VERTICAL_LAYOUT;
116  FT_Fixed v;
117
118  if (unlikely (FT_Get_Advance (ft_face, glyph, load_flags, &v)))
119    return 0;
120
121  /* Note: FreeType's vertical metrics grows downward while other FreeType coordinates
122   * have a Y growing upward.  Hence the extra negation. */
123  return (-v + (1<<9)) >> 10;
124}
125
126static hb_bool_t
127hb_ft_get_glyph_h_origin (hb_font_t *font HB_UNUSED,
128			  void *font_data HB_UNUSED,
129			  hb_codepoint_t glyph HB_UNUSED,
130			  hb_position_t *x HB_UNUSED,
131			  hb_position_t *y HB_UNUSED,
132			  void *user_data HB_UNUSED)
133{
134  /* We always work in the horizontal coordinates. */
135  return true;
136}
137
138static hb_bool_t
139hb_ft_get_glyph_v_origin (hb_font_t *font HB_UNUSED,
140			  void *font_data,
141			  hb_codepoint_t glyph,
142			  hb_position_t *x,
143			  hb_position_t *y,
144			  void *user_data HB_UNUSED)
145{
146  FT_Face ft_face = (FT_Face) font_data;
147  int load_flags = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING;
148
149  if (unlikely (FT_Load_Glyph (ft_face, glyph, load_flags)))
150    return false;
151
152  /* Note: FreeType's vertical metrics grows downward while other FreeType coordinates
153   * have a Y growing upward.  Hence the extra negation. */
154  *x = ft_face->glyph->metrics.horiBearingX -   ft_face->glyph->metrics.vertBearingX;
155  *y = ft_face->glyph->metrics.horiBearingY - (-ft_face->glyph->metrics.vertBearingY);
156
157  return true;
158}
159
160static hb_position_t
161hb_ft_get_glyph_h_kerning (hb_font_t *font,
162			   void *font_data,
163			   hb_codepoint_t left_glyph,
164			   hb_codepoint_t right_glyph,
165			   void *user_data HB_UNUSED)
166{
167  FT_Face ft_face = (FT_Face) font_data;
168  FT_Vector kerningv;
169
170  FT_Kerning_Mode mode = font->x_ppem ? FT_KERNING_DEFAULT : FT_KERNING_UNFITTED;
171  if (FT_Get_Kerning (ft_face, left_glyph, right_glyph, mode, &kerningv))
172    return 0;
173
174  return kerningv.x;
175}
176
177static hb_position_t
178hb_ft_get_glyph_v_kerning (hb_font_t *font HB_UNUSED,
179			   void *font_data HB_UNUSED,
180			   hb_codepoint_t top_glyph HB_UNUSED,
181			   hb_codepoint_t bottom_glyph HB_UNUSED,
182			   void *user_data HB_UNUSED)
183{
184  /* FreeType API doesn't support vertical kerning */
185  return 0;
186}
187
188static hb_bool_t
189hb_ft_get_glyph_extents (hb_font_t *font HB_UNUSED,
190			 void *font_data,
191			 hb_codepoint_t glyph,
192			 hb_glyph_extents_t *extents,
193			 void *user_data HB_UNUSED)
194{
195  FT_Face ft_face = (FT_Face) font_data;
196  int load_flags = FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING;
197
198  if (unlikely (FT_Load_Glyph (ft_face, glyph, load_flags)))
199    return false;
200
201  extents->x_bearing = ft_face->glyph->metrics.horiBearingX;
202  extents->y_bearing = ft_face->glyph->metrics.horiBearingY;
203  extents->width = ft_face->glyph->metrics.width;
204  extents->height = -ft_face->glyph->metrics.height;
205  return true;
206}
207
208static hb_bool_t
209hb_ft_get_glyph_contour_point (hb_font_t *font HB_UNUSED,
210			       void *font_data,
211			       hb_codepoint_t glyph,
212			       unsigned int point_index,
213			       hb_position_t *x,
214			       hb_position_t *y,
215			       void *user_data HB_UNUSED)
216{
217  FT_Face ft_face = (FT_Face) font_data;
218  int load_flags = FT_LOAD_DEFAULT;
219
220  if (unlikely (FT_Load_Glyph (ft_face, glyph, load_flags)))
221      return false;
222
223  if (unlikely (ft_face->glyph->format != FT_GLYPH_FORMAT_OUTLINE))
224      return false;
225
226  if (unlikely (point_index >= (unsigned int) ft_face->glyph->outline.n_points))
227      return false;
228
229  *x = ft_face->glyph->outline.points[point_index].x;
230  *y = ft_face->glyph->outline.points[point_index].y;
231
232  return true;
233}
234
235static hb_bool_t
236hb_ft_get_glyph_name (hb_font_t *font HB_UNUSED,
237		      void *font_data,
238		      hb_codepoint_t glyph,
239		      char *name, unsigned int size,
240		      void *user_data HB_UNUSED)
241{
242  FT_Face ft_face = (FT_Face) font_data;
243
244  hb_bool_t ret = !FT_Get_Glyph_Name (ft_face, glyph, name, size);
245  if (ret && (size && !*name))
246    ret = false;
247
248  return ret;
249}
250
251static hb_bool_t
252hb_ft_get_glyph_from_name (hb_font_t *font HB_UNUSED,
253			   void *font_data,
254			   const char *name, int len, /* -1 means nul-terminated */
255			   hb_codepoint_t *glyph,
256			   void *user_data HB_UNUSED)
257{
258  FT_Face ft_face = (FT_Face) font_data;
259
260  if (len < 0)
261    *glyph = FT_Get_Name_Index (ft_face, (FT_String *) name);
262  else {
263    /* Make a nul-terminated version. */
264    char buf[128];
265    len = MIN (len, (int) sizeof (buf) - 1);
266    strncpy (buf, name, len);
267    buf[len] = '\0';
268    *glyph = FT_Get_Name_Index (ft_face, buf);
269  }
270
271  if (*glyph == 0)
272  {
273    /* Check whether the given name was actually the name of glyph 0. */
274    char buf[128];
275    if (!FT_Get_Glyph_Name(ft_face, 0, buf, sizeof (buf)) &&
276        len < 0 ? !strcmp (buf, name) : !strncmp (buf, name, len))
277      return true;
278  }
279
280  return *glyph != 0;
281}
282
283
284static hb_font_funcs_t *
285_hb_ft_get_font_funcs (void)
286{
287  static const hb_font_funcs_t ft_ffuncs = {
288    HB_OBJECT_HEADER_STATIC,
289
290    true, /* immutable */
291
292    {
293#define HB_FONT_FUNC_IMPLEMENT(name) hb_ft_get_##name,
294      HB_FONT_FUNCS_IMPLEMENT_CALLBACKS
295#undef HB_FONT_FUNC_IMPLEMENT
296    }
297  };
298
299  return const_cast<hb_font_funcs_t *> (&ft_ffuncs);
300}
301
302
303static hb_blob_t *
304reference_table  (hb_face_t *face HB_UNUSED, hb_tag_t tag, void *user_data)
305{
306  FT_Face ft_face = (FT_Face) user_data;
307  FT_Byte *buffer;
308  FT_ULong  length = 0;
309  FT_Error error;
310
311  /* Note: FreeType like HarfBuzz uses the NONE tag for fetching the entire blob */
312
313  error = FT_Load_Sfnt_Table (ft_face, tag, 0, NULL, &length);
314  if (error)
315    return NULL;
316
317  buffer = (FT_Byte *) malloc (length);
318  if (buffer == NULL)
319    return NULL;
320
321  error = FT_Load_Sfnt_Table (ft_face, tag, 0, buffer, &length);
322  if (error)
323    return NULL;
324
325  return hb_blob_create ((const char *) buffer, length,
326			 HB_MEMORY_MODE_WRITABLE,
327			 buffer, free);
328}
329
330/**
331 * hb_ft_face_create:
332 * @ft_face: (destroy destroy) (scope notified):
333 * @destroy:
334 *
335 *
336 *
337 * Return value: (transfer full):
338 * Since: 1.0
339 **/
340hb_face_t *
341hb_ft_face_create (FT_Face           ft_face,
342		   hb_destroy_func_t destroy)
343{
344  hb_face_t *face;
345
346  if (ft_face->stream->read == NULL) {
347    hb_blob_t *blob;
348
349    blob = hb_blob_create ((const char *) ft_face->stream->base,
350			   (unsigned int) ft_face->stream->size,
351			   HB_MEMORY_MODE_READONLY,
352			   ft_face, destroy);
353    face = hb_face_create (blob, ft_face->face_index);
354    hb_blob_destroy (blob);
355  } else {
356    face = hb_face_create_for_tables (reference_table, ft_face, destroy);
357  }
358
359  hb_face_set_index (face, ft_face->face_index);
360  hb_face_set_upem (face, ft_face->units_per_EM);
361
362  return face;
363}
364
365/**
366 * hb_ft_face_create_referenced:
367 * @ft_face:
368 *
369 *
370 *
371 * Return value: (transfer full):
372 * Since: 1.0
373 **/
374hb_face_t *
375hb_ft_face_create_referenced (FT_Face ft_face)
376{
377  FT_Reference_Face (ft_face);
378  return hb_ft_face_create (ft_face, (hb_destroy_func_t) FT_Done_Face);
379}
380
381static void
382hb_ft_face_finalize (FT_Face ft_face)
383{
384  hb_face_destroy ((hb_face_t *) ft_face->generic.data);
385}
386
387/**
388 * hb_ft_face_create_cached:
389 * @ft_face:
390 *
391 *
392 *
393 * Return value: (transfer full):
394 * Since: 1.0
395 **/
396hb_face_t *
397hb_ft_face_create_cached (FT_Face ft_face)
398{
399  if (unlikely (!ft_face->generic.data || ft_face->generic.finalizer != (FT_Generic_Finalizer) hb_ft_face_finalize))
400  {
401    if (ft_face->generic.finalizer)
402      ft_face->generic.finalizer (ft_face);
403
404    ft_face->generic.data = hb_ft_face_create (ft_face, NULL);
405    ft_face->generic.finalizer = (FT_Generic_Finalizer) hb_ft_face_finalize;
406  }
407
408  return hb_face_reference ((hb_face_t *) ft_face->generic.data);
409}
410
411static void
412_do_nothing (void)
413{
414}
415
416
417/**
418 * hb_ft_font_create:
419 * @ft_face: (destroy destroy) (scope notified):
420 * @destroy:
421 *
422 *
423 *
424 * Return value: (transfer full):
425 * Since: 1.0
426 **/
427hb_font_t *
428hb_ft_font_create (FT_Face           ft_face,
429		   hb_destroy_func_t destroy)
430{
431  hb_font_t *font;
432  hb_face_t *face;
433
434  face = hb_ft_face_create (ft_face, destroy);
435  font = hb_font_create (face);
436  hb_face_destroy (face);
437  hb_font_set_funcs (font,
438		     _hb_ft_get_font_funcs (),
439		     ft_face, (hb_destroy_func_t) _do_nothing);
440  hb_font_set_scale (font,
441		     (int) (((uint64_t) ft_face->size->metrics.x_scale * (uint64_t) ft_face->units_per_EM + (1<<15)) >> 16),
442		     (int) (((uint64_t) ft_face->size->metrics.y_scale * (uint64_t) ft_face->units_per_EM + (1<<15)) >> 16));
443#if 0 /* hb-ft works in no-hinting model */
444  hb_font_set_ppem (font,
445		    ft_face->size->metrics.x_ppem,
446		    ft_face->size->metrics.y_ppem);
447#endif
448
449  return font;
450}
451
452/**
453 * hb_ft_font_create_referenced:
454 * @ft_face:
455 *
456 *
457 *
458 * Return value: (transfer full):
459 * Since: 1.0
460 **/
461hb_font_t *
462hb_ft_font_create_referenced (FT_Face ft_face)
463{
464  FT_Reference_Face (ft_face);
465  return hb_ft_font_create (ft_face, (hb_destroy_func_t) FT_Done_Face);
466}
467
468
469/* Thread-safe, lock-free, FT_Library */
470
471static FT_Library ft_library;
472
473#ifdef HB_USE_ATEXIT
474static
475void free_ft_library (void)
476{
477  FT_Done_FreeType (ft_library);
478}
479#endif
480
481static FT_Library
482get_ft_library (void)
483{
484retry:
485  FT_Library library = (FT_Library) hb_atomic_ptr_get (&ft_library);
486
487  if (unlikely (!library))
488  {
489    /* Not found; allocate one. */
490    if (FT_Init_FreeType (&library))
491      return NULL;
492
493    if (!hb_atomic_ptr_cmpexch (&ft_library, NULL, library)) {
494      FT_Done_FreeType (library);
495      goto retry;
496    }
497
498#ifdef HB_USE_ATEXIT
499    atexit (free_ft_library); /* First person registers atexit() callback. */
500#endif
501  }
502
503  return library;
504}
505
506static void
507_release_blob (FT_Face ft_face)
508{
509  hb_blob_destroy ((hb_blob_t *) ft_face->generic.data);
510}
511
512void
513hb_ft_font_set_funcs (hb_font_t *font)
514{
515  hb_blob_t *blob = hb_face_reference_blob (font->face);
516  unsigned int blob_length;
517  const char *blob_data = hb_blob_get_data (blob, &blob_length);
518  if (unlikely (!blob_length))
519    DEBUG_MSG (FT, font, "Font face has empty blob");
520
521  FT_Face ft_face = NULL;
522  FT_Error err = FT_New_Memory_Face (get_ft_library (),
523				     (const FT_Byte *) blob_data,
524				     blob_length,
525				     hb_face_get_index (font->face),
526				     &ft_face);
527
528  if (unlikely (err)) {
529    hb_blob_destroy (blob);
530    DEBUG_MSG (FT, font, "Font face FT_New_Memory_Face() failed");
531    return;
532  }
533
534  FT_Select_Charmap (ft_face, FT_ENCODING_UNICODE);
535
536  FT_Set_Char_Size (ft_face,
537		    abs (font->x_scale), abs (font->y_scale),
538		    0, 0);
539#if 0
540		    font->x_ppem * 72 * 64 / font->x_scale,
541		    font->y_ppem * 72 * 64 / font->y_scale);
542#endif
543  if (font->x_scale < 0 || font->y_scale < 0)
544  {
545    FT_Matrix matrix = { font->x_scale < 0 ? -1 : +1, 0,
546			  0, font->y_scale < 0 ? -1 : +1};
547    FT_Set_Transform (ft_face, &matrix, NULL);
548  }
549
550  ft_face->generic.data = blob;
551  ft_face->generic.finalizer = (FT_Generic_Finalizer) _release_blob;
552
553  hb_font_set_funcs (font,
554		     _hb_ft_get_font_funcs (),
555		     ft_face,
556		     (hb_destroy_func_t) FT_Done_Face);
557}
558
559FT_Face
560hb_ft_font_get_face (hb_font_t *font)
561{
562  if (font->destroy == (hb_destroy_func_t) FT_Done_Face ||
563      font->destroy == (hb_destroy_func_t) _do_nothing)
564    return (FT_Face) font->user_data;
565
566  return NULL;
567}
568