* alloc.c: Do not define struct catchtag.
[bpt/emacs.git] / src / ftfont.c
index d6fabf8..ed9cb6f 100644 (file)
@@ -1,6 +1,6 @@
 /* ftfont.c -- FreeType font driver.
-   Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc.
-   Copyright (C) 2006, 2007, 2008
+   Copyright (C) 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
+   Copyright (C) 2006, 2007, 2008, 2009
      National Institute of Advanced Industrial Science and Technology (AIST)
      Registration Number H13PRO009
 
@@ -21,6 +21,7 @@ along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
 
 #include <config.h>
 #include <stdio.h>
+#include <setjmp.h>
 
 #include <fontconfig/fontconfig.h>
 #include <fontconfig/fcfreetype.h>
@@ -62,7 +63,7 @@ struct ftfont_info
 {
   struct font font;
 #ifdef HAVE_LIBOTF
-  /* The following three members must be here in this order to be
+  /* The following four members must be here in this order to be
      compatible with struct xftfont_info (in xftfont.c).  */
   int maybe_otf;       /* Flag to tell if this may be OTF or not.  */
   OTF *otf;
@@ -71,11 +72,19 @@ struct ftfont_info
   int index;
 };
 
+enum ftfont_cache_for
+  {
+    FTFONT_CACHE_FOR_FACE,
+    FTFONT_CACHE_FOR_CHARSET,
+    FTFONT_CACHE_FOR_ENTITY
+  };
+
 static Lisp_Object ftfont_pattern_entity P_ ((FcPattern *, Lisp_Object));
 
 static Lisp_Object ftfont_resolve_generic_family P_ ((Lisp_Object,
                                                      FcPattern *));
-static Lisp_Object ftfont_lookup_cache P_ ((Lisp_Object, int));
+static Lisp_Object ftfont_lookup_cache P_ ((Lisp_Object,
+                                           enum ftfont_cache_for));
 
 Lisp_Object ftfont_font_format P_ ((FcPattern *, Lisp_Object));
 
@@ -128,17 +137,59 @@ static struct
     { "windows-1251", { 0x0401, 0x0490 }, "ru"},
     { "koi8-r", { 0x0401, 0x2219 }, "ru"},
     { "mulelao-1", { 0x0E81 }, "lo"},
+    { "unicode-sip", { 0x20000 }},
     { NULL }
   };
 
 extern Lisp_Object Qc, Qm, Qp, Qd;
 
+/* Dirty hack for handing ADSTYLE property.
+
+   Fontconfig (actually the underlying FreeType) gives such ADSTYLE
+   font property of PCF/BDF fonts in FC_STYLE.  And, "Bold",
+   "Oblique", "Italic", or any non-normal SWIDTH property names
+   (e.g. SemiCondensed) are appended.  In addition, if there's no
+   ADSTYLE property nor non-normal WEIGHT/SLANT/SWIDTH properties,
+   "Regular" is used for FC_STYLE (see the function
+   pcf_interpret_style in src/pcf/pcfread.c of FreeType).
+
+   Unfortunately this behavior is not documented, so the following
+   code may fail if FreeType changes the behavior in the future.  */
+
+static Lisp_Object
+get_adstyle_property (FcPattern *p)
+{
+  char *str, *end;
+  Lisp_Object adstyle;
+
+  if (FcPatternGetString (p, FC_STYLE, 0, (FcChar8 **) &str) != FcResultMatch)
+    return Qnil;
+  for (end = str; *end && *end != ' '; end++);
+  if (*end)
+    {
+      char *p = alloca (end - str + 1);
+      memcpy (p, str, end - str);
+      p[end - str] = '\0';
+      end = p + (end - str);
+      str = p;
+    }
+  if (xstrcasecmp (str, "Regular") == 0
+      || xstrcasecmp (str, "Bold") == 0
+      || xstrcasecmp (str, "Oblique") == 0
+      || xstrcasecmp (str, "Italic") == 0)
+    return Qnil;
+  adstyle = font_intern_prop (str, end - str, 1);
+  if (font_style_to_value (FONT_WIDTH_INDEX, adstyle, 0) >= 0)
+    return Qnil;
+  return adstyle;
+}
+
 static Lisp_Object
 ftfont_pattern_entity (p, extra)
      FcPattern *p;
      Lisp_Object extra;
 {
-  Lisp_Object entity;
+  Lisp_Object key, cache, entity;
   char *file, *str;
   int index;
   int numeric;
@@ -150,7 +201,21 @@ ftfont_pattern_entity (p, extra)
   if (FcPatternGetInteger (p, FC_INDEX, 0, &index) != FcResultMatch)
     return Qnil;
 
+  key = Fcons (make_unibyte_string ((char *) file, strlen ((char *) file)),
+              make_number (index));
+  cache = ftfont_lookup_cache (key, FTFONT_CACHE_FOR_ENTITY);
+  entity = XCAR (cache);
+  if (! NILP (entity))
+    {
+      Lisp_Object val = font_make_entity ();
+      int i;
+
+      for (i = 0; i < FONT_OBJLIST_INDEX; i++)
+       ASET (val, i, AREF (entity, i));
+      return val;
+    }
   entity = font_make_entity ();
+  XSETCAR (cache, entity);
 
   ASET (entity, FONT_TYPE_INDEX, Qfreetype);
   ASET (entity, FONT_REGISTRY_INDEX, Qiso10646_1);
@@ -175,7 +240,9 @@ ftfont_pattern_entity (p, extra)
       FONT_SET_STYLE (entity, FONT_WIDTH_INDEX, make_number (numeric));
     }
   if (FcPatternGetDouble (p, FC_PIXEL_SIZE, 0, &dbl) == FcResultMatch)
-    ASET (entity, FONT_SIZE_INDEX, make_number (dbl));
+    {
+      ASET (entity, FONT_SIZE_INDEX, make_number (dbl));
+    }
   else
     ASET (entity, FONT_SIZE_INDEX, make_number (0));
   if (FcPatternGetInteger (p, FC_SPACING, 0, &numeric) == FcResultMatch)
@@ -187,13 +254,31 @@ ftfont_pattern_entity (p, extra)
     }
   if (FcPatternGetBool (p, FC_SCALABLE, 0, &b) == FcResultMatch
       && b == FcTrue)
-    ASET (entity, FONT_AVGWIDTH_INDEX, make_number (0));
+    {
+      ASET (entity, FONT_SIZE_INDEX, make_number (0));
+      ASET (entity, FONT_AVGWIDTH_INDEX, make_number (0));
+    }
+  else
+    {
+      /* As this font is not scalable, parhaps this is a BDF or PCF
+        font. */ 
+      FT_Face ft_face;
+
+      ASET (entity, FONT_ADSTYLE_INDEX, get_adstyle_property (p));
+      if ((ft_library || FT_Init_FreeType (&ft_library) == 0)
+         && FT_New_Face (ft_library, file, index, &ft_face) == 0)
+       {
+         BDF_PropertyRec rec;
+
+         if (FT_Get_BDF_Property (ft_face, "AVERAGE_WIDTH", &rec) == 0
+             && rec.type == BDF_PROPERTY_TYPE_INTEGER)
+           ASET (entity, FONT_AVGWIDTH_INDEX, make_number (rec.u.integer));
+         FT_Done_Face (ft_face);
+       }
+    }
 
   ASET (entity, FONT_EXTRA_INDEX, Fcopy_sequence (extra));
-  font_put_extra (entity, QCfont_entity,
-                 Fcons (make_unibyte_string ((char *) file,
-                                             strlen ((char *) file)),
-                        make_number (index)));
+  font_put_extra (entity, QCfont_entity, key);
   return entity;
 }
 
@@ -247,8 +332,8 @@ ftfont_resolve_generic_family (family, pattern)
   else
     family = Qnil;
   XSETCDR (slot, family);
- err:
   if (match) FcPatternDestroy (match);
+ err:
   if (pattern) FcPatternDestroy (pattern);
   return family;
 }
@@ -260,36 +345,62 @@ struct ftfont_cache_data
 };
 
 static Lisp_Object
-ftfont_lookup_cache (key, for_face)
+ftfont_lookup_cache (key, cache_for)
      Lisp_Object key;
-     int for_face;
+     enum ftfont_cache_for cache_for;
 {
-  Lisp_Object cache, val;
+  Lisp_Object cache, val, entity;
   struct ftfont_cache_data *cache_data;
 
-  cache = assoc_no_quit (key, ft_face_cache);
+  if (FONT_ENTITY_P (key))
+    {
+      entity = key;
+      val = assq_no_quit (QCfont_entity, AREF (entity, FONT_EXTRA_INDEX));
+      xassert (CONSP (val));
+      key = XCDR (val);
+    }
+  else
+    entity = Qnil;
+
+  if (NILP (ft_face_cache))
+    cache = Qnil;
+  else
+    cache = Fgethash (key, ft_face_cache, Qnil);
   if (NILP (cache))
     {
+      if (NILP (ft_face_cache))
+       {
+         Lisp_Object args[2];
+
+         args[0] = QCtest;
+         args[1] = Qequal;
+         ft_face_cache = Fmake_hash_table (2, args);
+       }
       cache_data = xmalloc (sizeof (struct ftfont_cache_data));
       cache_data->ft_face = NULL;
       cache_data->fc_charset = NULL;
       val = make_save_value (NULL, 0);
       XSAVE_VALUE (val)->integer = 0;
       XSAVE_VALUE (val)->pointer = cache_data;
-      cache = Fcons (key, val);
-      ft_face_cache = Fcons (cache, ft_face_cache);
+      cache = Fcons (Qnil, val);
+      Fputhash (key, cache, ft_face_cache);
     }
   else
     {
       val = XCDR (cache);
       cache_data = XSAVE_VALUE (val)->pointer;
     }
-  if (for_face ? ! cache_data->ft_face : ! cache_data->fc_charset)
+
+  if (cache_for == FTFONT_CACHE_FOR_ENTITY)
+    return cache;
+
+  if (cache_for == FTFONT_CACHE_FOR_FACE
+      ? ! cache_data->ft_face : ! cache_data->fc_charset)
     {
       char *filename = (char *) SDATA (XCAR (key));
       int index = XINT (XCDR (key));
 
-      if (for_face)
+      if (cache_for == FTFONT_CACHE_FOR_FACE)
        {
          if (! ft_library
              && FT_Init_FreeType (&ft_library) != 0)
@@ -300,24 +411,36 @@ ftfont_lookup_cache (key, for_face)
        }
       else
        {
-         FcPattern *pat;
-         FcFontSet *fontset;
-         FcObjectSet *objset;
-         FcCharSet *charset;
+         FcPattern *pat = NULL;
+         FcFontSet *fontset = NULL;
+         FcObjectSet *objset = NULL;
+         FcCharSet *charset = NULL;
 
          pat = FcPatternBuild (0, FC_FILE, FcTypeString, (FcChar8 *) filename,
                                FC_INDEX, FcTypeInteger, index, NULL);
-         objset = FcObjectSetBuild (FC_CHARSET, NULL);
+         if (! pat)
+           goto finish;
+         objset = FcObjectSetBuild (FC_CHARSET, FC_STYLE, NULL);
+         if (! objset)
+           goto finish;
          fontset = FcFontList (NULL, pat, objset);
-         xassert (fontset && fontset->nfont > 0);
-         if (FcPatternGetCharSet (fontset->fonts[0], FC_CHARSET, 0, &charset)
-             == FcResultMatch)
+         if (! fontset)
+           goto finish;
+         if (fontset && fontset->nfont > 0
+             && (FcPatternGetCharSet (fontset->fonts[0], FC_CHARSET, 0,
+                                      &charset)
+                 == FcResultMatch))
            cache_data->fc_charset = FcCharSetCopy (charset);
          else
            cache_data->fc_charset = FcCharSetCreate ();
-         FcFontSetDestroy (fontset);
-         FcObjectSetDestroy (objset);
-         FcPatternDestroy (pat);
+
+       finish:
+         if (fontset)
+           FcFontSetDestroy (fontset);
+         if (objset)
+           FcObjectSetDestroy (objset);
+         if (pat)
+           FcPatternDestroy (pat);
        }
     }
   return cache;
@@ -330,10 +453,7 @@ ftfont_get_fc_charset (entity)
   Lisp_Object val, cache;
   struct ftfont_cache_data *cache_data;
 
-  val = assq_no_quit (QCfont_entity, AREF (entity, FONT_EXTRA_INDEX));
-  xassert (CONSP (val));
-  val = XCDR (val);
-  cache = ftfont_lookup_cache (val, 0);
+  cache = ftfont_lookup_cache (entity, FTFONT_CACHE_FOR_CHARSET);
   val = XCDR (cache);
   cache_data = XSAVE_VALUE (val)->pointer;
   return cache_data->fc_charset;
@@ -380,6 +500,11 @@ static int ftfont_anchor_point P_ ((struct font *, unsigned, int,
 static Lisp_Object ftfont_otf_capability P_ ((struct font *));
 static Lisp_Object ftfont_shape P_ ((Lisp_Object));
 
+#ifdef HAVE_OTF_GET_VARIATION_GLYPHS
+static int ftfont_variation_glyphs P_ ((struct font *, int c,
+                                       unsigned variations[256]));
+#endif /* HAVE_OTF_GET_VARIATION_GLYPHS */
+
 struct font_driver ftfont_driver =
   {
     0,                         /* Qfreetype */
@@ -388,35 +513,42 @@ struct font_driver ftfont_driver =
     ftfont_list,
     ftfont_match,
     ftfont_list_family,
-    NULL,
+    NULL,                      /* free_entity */
     ftfont_open,
     ftfont_close,
     /* We can't draw a text without device dependent functions.  */
-    NULL,
-    NULL,
+    NULL,                      /* prepare_face */
+    NULL,                      /* done_face */
     ftfont_has_char,
     ftfont_encode_char,
     ftfont_text_extents,
     /* We can't draw a text without device dependent functions.  */
-    NULL,
+    NULL,                      /* draw */
     ftfont_get_bitmap,
-    NULL,
-    NULL,
-    NULL,
+    NULL,                      /* get_bitmap */
+    NULL,                      /* free_bitmap */
+    NULL,                      /* get_outline */
     ftfont_anchor_point,
 #ifdef HAVE_LIBOTF
     ftfont_otf_capability,
 #else  /* not HAVE_LIBOTF */
     NULL,
 #endif /* not HAVE_LIBOTF */
-    NULL,
-    NULL,
-    NULL,
+    NULL,                      /* otf_drive */
+    NULL,                      /* start_for_frame */
+    NULL,                      /* end_for_frame */
 #if defined (HAVE_M17N_FLT) && defined (HAVE_LIBOTF)
-    ftfont_shape
+    ftfont_shape,
 #else  /* not (HAVE_M17N_FLT && HAVE_LIBOTF) */
-    NULL
+    NULL,
 #endif /* not (HAVE_M17N_FLT && HAVE_LIBOTF) */
+    NULL,                      /* check */
+
+#ifdef HAVE_OTF_GET_VARIATION_GLYPHS
+    ftfont_variation_glyphs
+#else
+    NULL
+#endif
   };
 
 extern Lisp_Object QCname;
@@ -569,13 +701,15 @@ ftfont_get_open_type_spec (Lisp_Object otf_spec)
 }
 
 static FcPattern *ftfont_spec_pattern P_ ((Lisp_Object, char *,
-                                          struct OpenTypeSpec **));
+                                          struct OpenTypeSpec **,
+                                          char **langname));
 
 static FcPattern *
-ftfont_spec_pattern (spec, otlayout, otspec)
+ftfont_spec_pattern (spec, otlayout, otspec, langname)
      Lisp_Object spec;
      char *otlayout;
      struct OpenTypeSpec **otspec;
+     char **langname;
 {
   Lisp_Object tmp, extra;
   FcPattern *pattern = NULL;
@@ -588,10 +722,6 @@ ftfont_spec_pattern (spec, otlayout, otspec)
   Lisp_Object registry;
   int fc_charset_idx;
 
-  if (! NILP (AREF (spec, FONT_ADSTYLE_INDEX))
-      && SBYTES (SYMBOL_NAME (AREF (spec, FONT_ADSTYLE_INDEX))) > 0)
-    /* Fontconfig doesn't support adstyle property.  */
-    return NULL;
   if ((n = FONT_SLANT_NUMERIC (spec)) >= 0
       && n < 100)
     /* Fontconfig doesn't support reverse-italic/obligue.  */
@@ -607,8 +737,7 @@ ftfont_spec_pattern (spec, otlayout, otspec)
   if (NILP (registry)
       || EQ (registry, Qascii_0)
       || EQ (registry, Qiso10646_1)
-      || EQ (registry, Qunicode_bmp)
-      || EQ (registry, Qunicode_sip))
+      || EQ (registry, Qunicode_bmp))
     fc_charset_idx = -1;
   else
     {
@@ -618,7 +747,8 @@ ftfont_spec_pattern (spec, otlayout, otspec)
       if (fc_charset_idx < 0)
        return NULL;
       charset = fc_charset_table[fc_charset_idx].fc_charset;
-      lang = (FcChar8 *) fc_charset_table[fc_charset_idx].lang;
+      *langname = fc_charset_table[fc_charset_idx].lang;
+      lang = (FcChar8 *) *langname;
       if (lang)
        {
          langset = FcLangSetCreate ();
@@ -739,7 +869,7 @@ static Lisp_Object
 ftfont_list (frame, spec)
      Lisp_Object frame, spec;
 {
-  Lisp_Object val = Qnil, family;
+  Lisp_Object val = Qnil, family, adstyle;
   int i;
   FcPattern *pattern;
   FcFontSet *fontset = NULL;
@@ -750,6 +880,7 @@ ftfont_list (frame, spec)
   char otlayout[15];           /* For "otlayout:XXXX" */
   struct OpenTypeSpec *otspec = NULL;
   int spacing = -1;
+  char *langname = NULL;
 
   if (! fc_initialized)
     {
@@ -757,7 +888,7 @@ ftfont_list (frame, spec)
       fc_initialized = 1;
     }
 
-  pattern = ftfont_spec_pattern (spec, otlayout, &otspec);
+  pattern = ftfont_spec_pattern (spec, otlayout, &otspec, &langname);
   if (! pattern)
     return Qnil;
   if (FcPatternGetCharSet (pattern, FC_CHARSET, 0, &charset) != FcResultMatch)
@@ -787,10 +918,12 @@ ftfont_list (frame, spec)
            goto err;
        }
     }
-
+  adstyle = AREF (spec, FONT_ADSTYLE_INDEX);
+  if (! NILP (adstyle) && SBYTES (SYMBOL_NAME (adstyle)) == 0)
+    adstyle = Qnil;
   objset = FcObjectSetBuild (FC_FOUNDRY, FC_FAMILY, FC_WEIGHT, FC_SLANT,
                             FC_WIDTH, FC_PIXEL_SIZE, FC_SPACING, FC_SCALABLE,
-                            FC_FILE, FC_INDEX,
+                            FC_STYLE, FC_FILE, FC_INDEX,
 #ifdef FC_CAPABILITY
                             FC_CAPABILITY,
 #endif /* FC_CAPABILITY */
@@ -827,7 +960,7 @@ ftfont_list (frame, spec)
              FcPatternAddString (pattern, FC_FAMILY, fam);
              FcFontSetDestroy (fontset);
              fontset = FcFontList (NULL, pattern, objset);
-             if (fontset->nfont > 0)
+             if (fontset && fontset->nfont > 0)
                break;
            }
        }
@@ -895,6 +1028,20 @@ ftfont_list (frame, spec)
          if (j == ASIZE (chars))
            continue;
        }
+      if (! NILP (adstyle) || langname)
+       {
+         Lisp_Object this_adstyle = get_adstyle_property (fontset->fonts[i]);
+
+         if (! NILP (adstyle)
+             && (NILP (this_adstyle)
+                 || xstrcasecmp (SDATA (SYMBOL_NAME (adstyle)),
+                                 SDATA (SYMBOL_NAME (this_adstyle))) != 0))
+           continue;
+         if (langname
+             && ! NILP (this_adstyle)
+             && xstrcasecmp (langname, SDATA (SYMBOL_NAME (this_adstyle))))
+           continue;
+       }
       entity = ftfont_pattern_entity (fontset->fonts[i],
                                      AREF (spec, FONT_EXTRA_INDEX));
       if (! NILP (entity))
@@ -909,7 +1056,7 @@ ftfont_list (frame, spec)
   val = Qnil;
 
  finish:
-  font_add_log ("ftfont-list", spec, val);
+  FONT_ADD_LOG ("ftfont-list", spec, val);
   if (objset) FcObjectSetDestroy (objset);
   if (fontset) FcFontSetDestroy (fontset);
   if (pattern) FcPatternDestroy (pattern);
@@ -920,11 +1067,12 @@ static Lisp_Object
 ftfont_match (frame, spec)
      Lisp_Object frame, spec;
 {
-  Lisp_Object entity;
+  Lisp_Object entity = Qnil;
   FcPattern *pattern, *match = NULL;
   FcResult result;
   char otlayout[15];           /* For "otlayout:XXXX" */
   struct OpenTypeSpec *otspec = NULL;
+  char *langname = NULL;
 
   if (! fc_initialized)
     {
@@ -932,7 +1080,7 @@ ftfont_match (frame, spec)
       fc_initialized = 1;
     }
 
-  pattern = ftfont_spec_pattern (spec, otlayout, &otspec);
+  pattern = ftfont_spec_pattern (spec, otlayout, &otspec, &langname);
   if (! pattern)
     return Qnil;
 
@@ -962,7 +1110,7 @@ ftfont_match (frame, spec)
     }
   FcPatternDestroy (pattern);
 
-  font_add_log ("ftfont-match", spec, entity);
+  FONT_ADD_LOG ("ftfont-match", spec, entity);
   return entity;
 }
 
@@ -970,7 +1118,7 @@ static Lisp_Object
 ftfont_list_family (frame)
      Lisp_Object frame;
 {
-  Lisp_Object list;
+  Lisp_Object list = Qnil;
   FcPattern *pattern = NULL;
   FcFontSet *fontset = NULL;
   FcObjectSet *objset = NULL;
@@ -992,7 +1140,6 @@ ftfont_list_family (frame)
   if (! fontset)
     goto finish;
 
-  list = Qnil;
   for (i = 0; i < fontset->nfont; i++)
     {
       FcPattern *pat = fontset->fonts[i];
@@ -1034,7 +1181,7 @@ ftfont_open (f, entity, pixel_size)
   if (! CONSP (val))
     return Qnil;
   val = XCDR (val);
-  cache = ftfont_lookup_cache (val, 1);
+  cache = ftfont_lookup_cache (entity, FTFONT_CACHE_FOR_FACE);
   if (NILP (cache))
     return Qnil;
   filename = XCAR (val);
@@ -1068,10 +1215,10 @@ ftfont_open (f, entity, pixel_size)
   ASET (font_object, FONT_TYPE_INDEX, Qfreetype);
   len = font_unparse_xlfd (entity, size, name, 256);
   if (len > 0)
-    ASET (font_object, FONT_NAME_INDEX, make_unibyte_string (name, len));
+    ASET (font_object, FONT_NAME_INDEX, make_string (name, len));
   len = font_unparse_fcname (entity, size, name, 256);
   if (len > 0)
-    ASET (font_object, FONT_FULLNAME_INDEX, make_unibyte_string (name, len));
+    ASET (font_object, FONT_FULLNAME_INDEX, make_string (name, len));
   else
     ASET (font_object, FONT_FULLNAME_INDEX,
          AREF (font_object, FONT_NAME_INDEX));
@@ -1118,7 +1265,7 @@ ftfont_open (f, entity, pixel_size)
 
       font->min_width = font->average_width = font->space_width = 0;
       for (i = 32, n = 0; i < 127; i++)
-       if (FT_Load_Char (ft_face, i, FT_LOAD_DEFAULT) != 0)
+       if (FT_Load_Char (ft_face, i, FT_LOAD_DEFAULT) == 0)
          {
            int this_width = ft_face->glyph->metrics.horiAdvance >> 6;
 
@@ -1141,7 +1288,7 @@ ftfont_open (f, entity, pixel_size)
   if (scalable)
     {
       font->underline_position = -ft_face->underline_position * size / upEM;
-      font->underline_thickness = -ft_face->underline_thickness * size / upEM;
+      font->underline_thickness = ft_face->underline_thickness * size / upEM;
     }
   else
     {
@@ -1161,7 +1308,7 @@ ftfont_close (f, font)
   Lisp_Object val, cache;
 
   val = Fcons (font->props[FONT_FILE_INDEX], make_number (ftfont_info->index));
-  cache = ftfont_lookup_cache (val, 1);
+  cache = ftfont_lookup_cache (val, FTFONT_CACHE_FOR_FACE);
   xassert (CONSP (cache));
   val = XCDR (cache);
   (XSAVE_VALUE (val)->integer)--;
@@ -1181,13 +1328,35 @@ ftfont_close (f, font)
 }
 
 static int
-ftfont_has_char (entity, c)
-     Lisp_Object entity;
+ftfont_has_char (font, c)
+     Lisp_Object font;
      int c;
 {
-  FcCharSet *charset = ftfont_get_fc_charset (entity);
+  struct charset *cs = NULL;
+
+  if (EQ (AREF (font, FONT_ADSTYLE_INDEX), Qja)
+      && charset_jisx0208 >= 0)
+    cs = CHARSET_FROM_ID (charset_jisx0208);
+  else if (EQ (AREF (font, FONT_ADSTYLE_INDEX), Qko)
+      && charset_ksc5601 >= 0)
+    cs = CHARSET_FROM_ID (charset_ksc5601);
+  if (cs)
+    return (ENCODE_CHAR (cs, c) != CHARSET_INVALID_CODE (cs));
+
+  if (FONT_ENTITY_P (font))
+    {
+      FcCharSet *charset = ftfont_get_fc_charset (font);
+
+      return (FcCharSetHasChar (charset, c) == FcTrue);
+    }
+  else
+    {
+      struct ftfont_info *ftfont_info;
 
-  return (FcCharSetHasChar (charset, c) == FcTrue);
+      ftfont_info = (struct ftfont_info *) XFONT_OBJECT (font);
+      return (FT_Get_Char_Index (ftfont_info->ft_size->face, (FT_ULong) c)
+             != 0);
+    }
 }
 
 static unsigned
@@ -1232,7 +1401,7 @@ ftfont_text_extents (font, code, nglyphs, metrics)
                  metrics->lbearing = m->horiBearingX >> 6;
                  metrics->rbearing = (m->horiBearingX + m->width) >> 6;
                  metrics->ascent = m->horiBearingY >> 6;
-                 metrics->descent = (m->horiBearingY + m->height) >> 6;
+                 metrics->descent = (m->height - m->horiBearingY) >> 6;
                }
              first = 0;
            }
@@ -1246,8 +1415,8 @@ ftfont_text_extents (font, code, nglyphs, metrics)
                  = width + ((m->horiBearingX + m->width) >> 6);
              if (metrics->ascent < (m->horiBearingY >> 6))
                metrics->ascent = m->horiBearingY >> 6;
-             if (metrics->descent > ((m->horiBearingY + m->height) >> 6))
-               metrics->descent = (m->horiBearingY + m->height) >> 6;
+             if (metrics->descent > ((m->height - m->horiBearingY) >> 6))
+               metrics->descent = (m->height - m->horiBearingY) >> 6;
            }
          width += m->horiAdvance >> 6;
        }
@@ -1340,7 +1509,7 @@ ftfont_otf_features (gsub_gpos)
      OTF_GSUB_GPOS *gsub_gpos;
 {
   Lisp_Object scripts, langsyses, features, sym;
-  int i, j, k;
+  int i, j, k, l;
 
   for (scripts = Qnil, i = gsub_gpos->ScriptList.ScriptCount - 1; i >= 0; i--)
     {
@@ -1359,7 +1528,10 @@ ftfont_otf_features (gsub_gpos)
 
          for (features = Qnil, k = otf_langsys->FeatureCount - 1; k >= 0; k--)
            {
-             OTF_TAG_SYM (sym, gsub_gpos->FeatureList.Feature[k].FeatureTag);
+             l = otf_langsys->FeatureIndex[k];
+             if (l >= gsub_gpos->FeatureList.FeatureCount)
+               continue;
+             OTF_TAG_SYM (sym, gsub_gpos->FeatureList.Feature[l].FeatureTag);
              features = Fcons (sym, features);
            }
          if (j >= 0)
@@ -1368,7 +1540,7 @@ ftfont_otf_features (gsub_gpos)
            sym = Qnil;
          langsyses = Fcons (Fcons (sym, features), langsyses);
        }
-      
+
       OTF_TAG_SYM (sym, gsub_gpos->ScriptList.Script[i].ScriptTag);
       scripts = Fcons (Fcons (sym, langsyses), scripts);
     }
@@ -1388,9 +1560,11 @@ ftfont_otf_capability (font)
   if (! otf)
     return Qnil;
   gsub_gpos = Fcons (Qnil, Qnil);
-  if (OTF_get_table (otf, "GSUB") == 0)
+  if (OTF_get_table (otf, "GSUB") == 0
+      && otf->gsub->FeatureList.FeatureCount > 0)
     XSETCAR (gsub_gpos, ftfont_otf_features (otf->gsub));
-  if (OTF_get_table (otf, "GPOS") == 0)
+  if (OTF_get_table (otf, "GPOS") == 0
+      && otf->gpos->FeatureList.FeatureCount > 0)
     XSETCDR (gsub_gpos, ftfont_otf_features (otf->gpos));
   return gsub_gpos;
 }
@@ -1532,6 +1706,25 @@ adjust_anchor (FT_Face ft_face, OTF_Anchor *anchor,
 
 static OTF_GlyphString otf_gstring;
 
+static void
+setup_otf_gstring (int size)
+{
+  if (otf_gstring.size == 0)
+    {
+      otf_gstring.glyphs = (OTF_Glyph *) xmalloc (sizeof (OTF_Glyph) * size);
+      otf_gstring.size = size;
+    }
+  else if (otf_gstring.size < size)
+    {
+      otf_gstring.glyphs = xrealloc (otf_gstring.glyphs,
+                                    sizeof (OTF_Glyph) * size);
+      otf_gstring.size = size;
+    }
+  otf_gstring.used = size;
+  memset (otf_gstring.glyphs, 0, sizeof (OTF_Glyph) * size);
+}
+
+
 static int
 ftfont_drive_otf (font, spec, in, from, to, out, adjustment)
      MFLTFont *font;
@@ -1584,19 +1777,7 @@ ftfont_drive_otf (font, spec, in, from, to, out, adjustment)
        }
     }
 
-  if (otf_gstring.size == 0)
-    {
-      otf_gstring.glyphs = (OTF_Glyph *) malloc (sizeof (OTF_Glyph) * len);
-      otf_gstring.size = len;
-    }
-  else if (otf_gstring.size < len)
-    {
-      otf_gstring.glyphs = (OTF_Glyph *) realloc (otf_gstring.glyphs,
-                                                 sizeof (OTF_Glyph) * len);
-      otf_gstring.size = len;
-    }
-  otf_gstring.used = len;
-  memset (otf_gstring.glyphs, 0, sizeof (OTF_Glyph) * len);
+  setup_otf_gstring (len);
   for (i = 0; i < len; i++)
     {
       otf_gstring.glyphs[i].c = in->glyphs[from + i].c;
@@ -1747,7 +1928,7 @@ ftfont_drive_otf (font, spec, in, from, to, out, adjustment)
                base_x = otfg->f.f4.base_anchor->XCoordinate * x_scale / 0x10000;
                base_y = otfg->f.f4.base_anchor->YCoordinate * y_scale / 0x10000;
                mark_x = otfg->f.f4.mark_anchor->XCoordinate * x_scale / 0x10000;
-               mark_y = otfg->f.f4.mark_anchor->YCoordinate * y_scale / 0x10000;;
+               mark_y = otfg->f.f4.mark_anchor->YCoordinate * y_scale / 0x10000;
 
                if (otfg->f.f4.base_anchor->AnchorFormat != 1)
                  adjust_anchor (ft_face, otfg->f.f4.base_anchor,
@@ -1803,7 +1984,7 @@ static int m17n_flt_initialized;
 
 extern Lisp_Object QCfamily;
 
-Lisp_Object
+static Lisp_Object
 ftfont_shape_by_flt (lgstring, font, ft_face, otf)
      Lisp_Object lgstring;
      struct font *font;
@@ -1814,6 +1995,7 @@ ftfont_shape_by_flt (lgstring, font, ft_face, otf)
   EMACS_UINT i;
   struct MFLTFontFT flt_font_ft;
   MFLT *flt = NULL;
+  int with_variation_selector = 0;
 
   if (! m17n_flt_initialized)
     {
@@ -1822,24 +2004,71 @@ ftfont_shape_by_flt (lgstring, font, ft_face, otf)
     }
 
   for (i = 0; i < len; i++)
-    if (NILP (LGSTRING_GLYPH (lgstring, i)))
-      break;
+    {
+      Lisp_Object g = LGSTRING_GLYPH (lgstring, i);
+      int c;
+
+      if (NILP (g))
+       break;
+      c = LGLYPH_CHAR (g);
+      if (CHAR_VARIATION_SELECTOR_P (c))
+       with_variation_selector++;
+    }
   len = i;
+  if (with_variation_selector)
+    {
+      setup_otf_gstring (len);
+      for (i = 0; i < len; i++)
+       {
+         Lisp_Object g = LGSTRING_GLYPH (lgstring, i);
+
+         otf_gstring.glyphs[i].c = LGLYPH_CHAR (g);
+         otf_gstring.glyphs[i].f.index.from = LGLYPH_FROM (g);
+         otf_gstring.glyphs[i].f.index.to = LGLYPH_TO (g);
+       }
+      OTF_drive_cmap (otf, &otf_gstring);
+      for (i = 0; i < otf_gstring.used; i++)
+       {
+         OTF_Glyph *otfg = otf_gstring.glyphs + i;
+         Lisp_Object g0 = LGSTRING_GLYPH (lgstring, otfg->f.index.from);
+         Lisp_Object g1 = LGSTRING_GLYPH (lgstring, otfg->f.index.to);
+
+         LGLYPH_SET_CODE (g0, otfg->glyph_id);
+         LGLYPH_SET_TO (g0, LGLYPH_TO (g1));
+         LGSTRING_SET_GLYPH (lgstring, i, g0);
+       }
+      if (len > otf_gstring.used)
+       {
+         len = otf_gstring.used;
+         LGSTRING_SET_GLYPH (lgstring, len, Qnil);
+       }
+    }
 
   if (gstring.allocated == 0)
     {
       gstring.allocated = len * 2;
       gstring.glyph_size = sizeof (MFLTGlyph);
-      gstring.glyphs = malloc (sizeof (MFLTGlyph) * gstring.allocated);
+      gstring.glyphs = xmalloc (sizeof (MFLTGlyph) * gstring.allocated);
     }
   else if (gstring.allocated < len * 2)
     {
       gstring.allocated = len * 2;
-      gstring.glyphs = realloc (gstring.glyphs,
-                               sizeof (MFLTGlyph) * gstring.allocated);
+      gstring.glyphs = xrealloc (gstring.glyphs,
+                                sizeof (MFLTGlyph) * gstring.allocated);
     }
+  memset (gstring.glyphs, 0, sizeof (MFLTGlyph) * len);
   for (i = 0; i < len; i++)
-    gstring.glyphs[i].c = LGLYPH_CHAR (LGSTRING_GLYPH (lgstring, i));
+    {
+      Lisp_Object g = LGSTRING_GLYPH (lgstring, i);
+
+      gstring.glyphs[i].c = LGLYPH_CHAR (g);
+      if (with_variation_selector)
+       {
+         gstring.glyphs[i].code = LGLYPH_CODE (g);
+         gstring.glyphs[i].encoded = 1;
+       }
+    }
+
   gstring.used = len;
   gstring.r2l = 0;
 
@@ -1850,7 +2079,7 @@ ftfont_shape_by_flt (lgstring, font, ft_face, otf)
       flt_font_ft.flt_font.family = Mnil;
     else
       flt_font_ft.flt_font.family
-       = msymbol ((char *) SDATA (SYMBOL_NAME (family)));
+       = msymbol ((char *) SDATA (Fdowncase (SYMBOL_NAME (family))));
   }
   flt_font_ft.flt_font.x_ppem = ft_face->size->metrics.x_ppem;
   flt_font_ft.flt_font.y_ppem = ft_face->size->metrics.y_ppem;
@@ -1862,7 +2091,8 @@ ftfont_shape_by_flt (lgstring, font, ft_face, otf)
   flt_font_ft.font = font;
   flt_font_ft.ft_face = ft_face;
   flt_font_ft.otf = otf;
-  if (ASCII_CHAR_P (gstring.glyphs[0].c))
+  if (len > 1
+      && gstring.glyphs[1].c >= 0x300 && gstring.glyphs[1].c <= 0x36F)
     /* A little bit ad hoc.  Perhaps, shaper must get script and
        language information, and select a proper flt for them
        here.  */
@@ -1873,8 +2103,8 @@ ftfont_shape_by_flt (lgstring, font, ft_face, otf)
       if (result != -2)
        break;
       gstring.allocated += gstring.allocated;
-      gstring.glyphs = realloc (gstring.glyphs,
-                               sizeof (MFLTGlyph) * gstring.allocated);
+      gstring.glyphs = xrealloc (gstring.glyphs,
+                                sizeof (MFLTGlyph) * gstring.allocated);
     }
   if (gstring.used > LGSTRING_GLYPH_LEN (lgstring))
     return Qnil;
@@ -1936,6 +2166,24 @@ ftfont_shape (lgstring)
 }
 
 #endif /* HAVE_M17N_FLT */
+
+#ifdef HAVE_OTF_GET_VARIATION_GLYPHS
+
+static int
+ftfont_variation_glyphs (font, c, variations)
+     struct font *font;
+     int c;
+     unsigned variations[256];
+{
+  struct ftfont_info *ftfont_info = (struct ftfont_info *) font;
+  OTF *otf = ftfont_get_otf (ftfont_info);
+
+  if (! otf)
+    return 0;
+  return OTF_get_variation_glyphs (otf, c, variations);
+}
+
+#endif /* HAVE_OTF_GET_VARIATION_GLYPHS */
 #endif /* HAVE_LIBOTF */
 
 Lisp_Object