*** empty log message ***
[m17n/m17n-test.git] / flt.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <ft2build.h>
4 #include FT_FREETYPE_H
5 #include FT_TRUETYPE_TABLES_H
6 #include <fontconfig/fontconfig.h>
7 #include <fontconfig/fcfreetype.h>
8
9 #if defined (FLT_GUI)
10
11 #include <m17n-gui.h>
12 #define PROGNAME "flt-gui"
13
14 #elif defined (FLT_OTF)
15
16 #include <m17n-flt.h>
17 #include <otf.h>
18 #define PROGNAME "flt-otf"
19
20 #elif defined (FLT_HB)
21
22 #include <m17n-flt.h>
23 #include <harfbuzz.h>
24 #define PROGNAME "flt-hb"
25
26 #else  /* (defined (FLT_PANGO)) */
27
28 #include <m17n-flt.h>
29 #define PANGO_ENABLE_ENGINE
30 #define PANGO_ENABLE_BACKEND
31 #include <pango/pango.h>
32 #include <pango/pango-ot.h>
33 #include <pango/pangoft2.h>
34 #include <pango/pangofc-font.h>
35 #endif
36
37 static FT_Library ft_library;
38
39 int
40 parse_font_name (char *fontname, char **family, int *size, char **err)
41 {
42   FcPattern *pat;
43   FcChar8 *fam;
44   double pixelsize;
45
46   pat = FcNameParse ((FcChar8 *) fontname);
47   if (! pat)
48     {
49       *err = "invalid name format";
50       return -1;
51     }
52   if (FcPatternGetString (pat, FC_FAMILY, 0, &fam) != FcResultMatch)
53     {
54       FcPatternDestroy (pat);
55       *err = "no family name";
56       return -1;
57     }
58   if (FcPatternGetDouble (pat, FC_PIXEL_SIZE, 0, &pixelsize) != FcResultMatch)
59     pixelsize = 20;
60   *family = strdup ((char *) fam);
61   *size = pixelsize;
62   FcPatternDestroy (pat);
63   return 0;
64 }
65
66 FT_Face
67 new_face (char *fontname, char **err)
68 {
69   FcPattern *pat;
70   FcChar8 *fam, *file;
71   int size;
72   double pixelsize;
73   FcFontSet *fs;
74   FcObjectSet *os;
75   FT_Face face;
76
77   if (parse_font_name (fontname, (char **) &fam, &size, err) < 0)
78     return NULL;
79   pixelsize = size;
80   pat = FcPatternBuild (0,
81                         FC_FAMILY, FcTypeString, fam,
82                         FC_SCALABLE, FcTypeBool, FcTrue,
83                         NULL);
84   free (fam);
85   os = FcObjectSetBuild (FC_FILE, NULL);
86   fs = FcFontList (NULL, pat, os);
87   if (fs->nfont == 0)
88     {
89       *err = "no matching font";
90       return NULL;
91     }
92   FcPatternGetString (fs->fonts[0], FC_FILE, 0, &file);
93
94   if (FT_New_Face (ft_library, (char *) file, 0, &face))
95     {
96       FcFontSetDestroy (fs);
97       FcObjectSetDestroy (os);
98       FcPatternDestroy (pat);
99       *err = "font open fail";
100       return NULL;
101     }
102   FcFontSetDestroy (fs);
103   FcObjectSetDestroy (os);
104   FcPatternDestroy (pat);
105   if (FT_Set_Pixel_Sizes (face, pixelsize, pixelsize))
106     {
107       *err = "set pixelsize fail";
108       FT_Done_Face (face);
109       return NULL;
110     }
111   return face;
112 }
113
114 #ifdef FLT_GUI
115
116 typedef struct
117 {
118   MFont *font;
119   FT_Face face;
120 } MFLTFont;
121
122 MFrame *frame;
123
124 MFLTFont *
125 open_font (char *fontname, char **err)
126 {
127   FT_Face ft_face = new_face (fontname, err);
128   MFLTFont *font;
129   MFace *face;
130   MPlist *plist;
131   MFontset *fontset;
132
133   if (! ft_face)
134     return NULL;
135   face = mface ();
136   plist = mplist ();
137   fontset = mfontset ("generic");
138   mface_put_prop (face, Mfontset, fontset);
139   mplist_add (plist, Mface, face);
140   mplist_add (plist, Mdevice, Mnil);
141   frame = mframe (plist);
142   m17n_object_unref (plist);
143   m17n_object_unref (face);
144   m17n_object_unref (fontset);
145
146   font = calloc (1, sizeof (MFLTFont));
147   font->font = mfont_encapsulate (frame, Mfreetype, ft_face);
148   font->face = ft_face;
149   return font;
150 }
151
152 void
153 close_font (MFLTFont *font)
154 {
155   FT_Done_Face (font->face);
156   free (font);
157   m17n_object_unref (frame);
158 }
159
160 int
161 flt (MText *mt, int from, int to, MFLTFont *font, char *flt_name)
162 {
163   MDrawControl control;
164
165   memset (&control, 0, sizeof (MDrawControl));
166   control.two_dimensional = 1;
167   control.enable_bidi = 1;
168   control.anti_alias = 1;
169   /*control.disable_caching = 1;*/
170   mtext_put_prop (mt, from, to, Mfont, font->font);
171   mdraw_text_extents (frame, mt, from, to, &control, NULL, NULL, NULL);
172   return 0;
173 }
174
175 #elif defined (FLT_OTF) || defined (FLT_HB)
176
177 typedef struct {
178   MFLTFont font;
179   FT_Face face;
180 } FontInfo;
181
182 int
183 get_glyph_id (MFLTFont *font, MFLTGlyph *g)
184 {
185   FT_Face face = ((FontInfo *) font)->face;
186
187   g->code = FT_Get_Char_Index (face, g->code);
188
189   return (g->code ? 0 : -1);
190 }
191
192 int 
193 get_metric (MFLTFont *font, MFLTGlyphString *gstring, int from, int to)
194 {
195   FT_Face face = ((FontInfo *) font)->face;
196
197   for (; from < to; from++)
198     {
199       MFLTGlyph *g = gstring->glyphs + from;
200       FT_Glyph_Metrics *metrics;
201
202       if (FT_Load_Glyph (face, g->code, FT_LOAD_DEFAULT))
203         return -1;
204       metrics = &face->glyph->metrics;
205       g->lbearing = metrics->horiBearingX;
206       g->rbearing = metrics->horiBearingX + metrics->width;
207       g->xadv = metrics->horiAdvance;
208       g->yadv = metrics->vertAdvance;
209       g->ascent = metrics->horiBearingY;
210       g->descent = metrics->height - metrics->horiBearingY;
211     }
212   return 0;
213 }
214
215 int
216 flt (MText *mt, int from, int to, MFLTFont *font, char *flt_name)
217 {
218   MFLTGlyphString gstring;
219   int len = to - from;
220   int i;
221
222   memset (&gstring, 0, sizeof (MFLTGlyphString));
223   gstring.glyph_size = sizeof (MFLTGlyph);
224   gstring.allocated = len * 2;
225   gstring.glyphs = alloca (sizeof (MFLTGlyph) * gstring.allocated);
226   for (i = 0; i < len; i++)
227     gstring.glyphs[i].c = mtext_ref_char (mt, from + i);
228   gstring.used = len;
229   return mflt_run (&gstring, 0, len, font, msymbol (flt_name));
230 }
231
232 #ifdef FLT_OTF
233
234 typedef struct {
235   MFLTFont font;
236   FT_Face face;
237   OTF *otf;
238 } FontInfoOTF;
239
240 #define DEVICE_DELTA(table, size)                               \
241   (((size) >= (table).StartSize && (size) <= (table).EndSize)   \
242    ? ((table).DeltaValue[(size) - (table).StartSize] << 6)      \
243    : 0)
244
245 static void
246 adjust_anchor (OTF_Anchor *anchor, FT_Face face,
247                unsigned code, unsigned x_ppem, unsigned y_ppem, int *x, int *y)
248 {
249   if (anchor->AnchorFormat == 2)
250     {
251       FT_Outline *outline;
252       int ap = anchor->f.f1.AnchorPoint;
253
254       FT_Load_Glyph (face, (FT_UInt) code, FT_LOAD_MONOCHROME);
255       outline = &face->glyph->outline;
256       if (ap < outline->n_points)
257         {
258           *x = outline->points[ap].x;
259           *y = outline->points[ap].y;
260         }
261     }
262   else if (anchor->AnchorFormat == 3)
263     {
264       if (anchor->f.f2.XDeviceTable.offset)
265         *x += DEVICE_DELTA (anchor->f.f2.XDeviceTable, x_ppem);
266       if (anchor->f.f2.YDeviceTable.offset)
267         *y += DEVICE_DELTA (anchor->f.f2.YDeviceTable, y_ppem);
268     }
269 }
270
271 char *
272 tag_name (char *str, unsigned tag)
273 {
274   *str++ = tag >> 24;
275   *str++ = (tag >> 16) & 0xFF;
276   *str++ = (tag >> 8) & 0xFF;
277   *str++ = tag & 0xFF;
278   return str;
279 }
280
281 void
282 encode_features (char *str, int count, unsigned *features)
283 {
284   int all = 0;
285   int i;
286
287   for (i = 0; i < count; i++)
288     {
289       unsigned tag = features[i];
290
291       if (tag == 0)
292         all = 1;
293       else
294         {
295           if (i > 0)
296             *str++ = ',';
297           if (all)
298             *str++ = '~';
299           str = tag_name (str, tag);
300         }
301     }
302   if (all)
303     {
304       if (i > 1)
305         *str++ = ',';
306       *str++ = '*';
307     }
308   *str = '\0';
309 }
310
311 int
312 drive_otf (MFLTFont *font, MFLTOtfSpec *spec,
313            MFLTGlyphString *in, int from, int to,
314            MFLTGlyphString *out, MFLTGlyphAdjustment *adjustment)
315 {
316   int len = to - from;
317   int i, gidx;
318   OTF *otf = ((FontInfoOTF *) font)->otf;
319   OTF_GlyphString otf_gstring;
320   OTF_Glyph *otfg;
321   char script[4], langsys[4];
322   char *gsub_features = NULL, *gpos_features = NULL;
323
324   if (len == 0)
325     return from;
326
327   if (! otf)
328     goto simple_copy;
329   otf_gstring.glyphs = NULL;
330   if (OTF_get_table (otf, "head") < 0)
331     {
332       OTF_close (otf);
333       ((FontInfoOTF *) font)->otf = NULL;
334       goto simple_copy;
335     }
336
337   tag_name (script, spec->script);
338   tag_name (langsys, spec->langsys);
339
340   if (spec->gsub_count > 0)
341     {
342       gsub_features = alloca (6 * spec->gsub_count);
343       if (gsub_features)
344         {
345           if (OTF_check_table (otf, "GSUB") < 0)
346             gsub_features = NULL;
347           else
348             encode_features (gsub_features, spec->gsub_count, spec->gsub);
349         }
350     }
351   if (spec->gpos_count)
352     {
353       gpos_features = alloca (6 * spec->gpos_count);
354       if (gpos_features)
355         {
356           if (OTF_check_table (otf, "GPOS") < 0)
357             gpos_features = NULL;
358           else
359             encode_features (gpos_features, spec->gpos_count, spec->gpos);
360         }
361     }
362
363   otf_gstring.size = otf_gstring.used = len;
364   otf_gstring.glyphs = (OTF_Glyph *) malloc (sizeof (OTF_Glyph) * len);
365   memset (otf_gstring.glyphs, 0, sizeof (OTF_Glyph) * len);
366   for (i = 0; i < len; i++)
367     {
368       otf_gstring.glyphs[i].c = in->glyphs[from + i].c;
369       otf_gstring.glyphs[i].glyph_id = in->glyphs[from + i].code;
370     }
371
372   OTF_drive_gdef (otf, &otf_gstring);
373   gidx = out->used;
374
375   if (gsub_features)
376     {
377       if (OTF_drive_gsub (otf, &otf_gstring, script, langsys, gsub_features)
378           < 0)
379         goto simple_copy;
380       if (out->allocated < out->used + otf_gstring.used)
381         return -2;
382       for (i = 0, otfg = otf_gstring.glyphs; i < otf_gstring.used; i++, otfg++)
383         {
384           MFLTGlyph *g = out->glyphs + out->used;
385           int j;
386
387           *g = in->glyphs[from + otfg->f.index.from];
388           g->c = 0;
389           for (j = from + otfg->f.index.from; j <= from + otfg->f.index.to; j++)
390             if (in->glyphs[j].code == otfg->glyph_id)
391               {
392                 g->c = in->glyphs[j].c;
393                 break;
394               }
395           g->code = otfg->glyph_id;
396           out->used++;
397         }
398     }
399   else
400     {
401       if (out->allocated < out->used + len)
402         return -2;
403       for (i = 0; i < len; i++)
404         out->glyphs[out->used++] = in->glyphs[from + i];
405     }
406
407   font->get_metric (font, out, gidx, out->used);
408
409   if (gpos_features)
410     {
411       FT_Face face;
412       MFLTGlyph *base = NULL, *mark = NULL, *g;
413       int x_ppem, y_ppem, x_scale, y_scale;
414
415       if (OTF_drive_gpos (otf, &otf_gstring, script, langsys, gpos_features)
416           < 0)
417         return to;
418
419       face = ((FontInfo *) font)->face;
420       x_ppem = face->size->metrics.x_ppem;
421       y_ppem = face->size->metrics.y_ppem;
422       x_scale = face->size->metrics.x_scale;
423       y_scale = face->size->metrics.y_scale;
424
425       for (i = 0, otfg = otf_gstring.glyphs, g = out->glyphs + gidx;
426            i < otf_gstring.used; i++, otfg++, g++)
427         {
428           MFLTGlyph *prev;
429
430           if (! otfg->glyph_id)
431             continue;
432           switch (otfg->positioning_type)
433             {
434             case 0:
435               break;
436             case 1: case 2:
437               {
438                 int format = otfg->f.f1.format;
439
440                 if (format & OTF_XPlacement)
441                   adjustment[i].xoff
442                     = otfg->f.f1.value->XPlacement * x_scale / 0x10000;
443                 if (format & OTF_XPlaDevice)
444                   adjustment[i].xoff
445                     += DEVICE_DELTA (otfg->f.f1.value->XPlaDevice, x_ppem);
446                 if (format & OTF_YPlacement)
447                   adjustment[i].yoff
448                     = - (otfg->f.f1.value->YPlacement * y_scale / 0x10000);
449                 if (format & OTF_YPlaDevice)
450                   adjustment[i].yoff
451                     -= DEVICE_DELTA (otfg->f.f1.value->YPlaDevice, y_ppem);
452                 if (format & OTF_XAdvance)
453                   adjustment[i].xadv
454                     += otfg->f.f1.value->XAdvance * x_scale / 0x10000;
455                 if (format & OTF_XAdvDevice)
456                   adjustment[i].xadv
457                     += DEVICE_DELTA (otfg->f.f1.value->XAdvDevice, x_ppem);
458                 if (format & OTF_YAdvance)
459                   adjustment[i].yadv
460                     += otfg->f.f1.value->YAdvance * y_scale / 0x10000;
461                 if (format & OTF_YAdvDevice)
462                   adjustment[i].yadv
463                     += DEVICE_DELTA (otfg->f.f1.value->YAdvDevice, y_ppem);
464                 adjustment[i].set = 1;
465               }
466               break;
467             case 3:
468               /* Not yet supported.  */
469               break;
470             case 4: case 5:
471               if (! base)
472                 break;
473               prev = base;
474               goto label_adjust_anchor;
475             default:            /* i.e. case 6 */
476               if (! mark)
477                 break;
478               prev = mark;
479
480             label_adjust_anchor:
481               {
482                 int base_x, base_y, mark_x, mark_y;
483
484                 base_x = otfg->f.f4.base_anchor->XCoordinate * x_scale / 0x10000;
485                 base_y = otfg->f.f4.base_anchor->YCoordinate * y_scale / 0x10000;
486                 mark_x = otfg->f.f4.mark_anchor->XCoordinate * x_scale / 0x10000;
487                 mark_y = otfg->f.f4.mark_anchor->YCoordinate * y_scale / 0x10000;;
488
489                 if (otfg->f.f4.base_anchor->AnchorFormat != 1)
490                   adjust_anchor (otfg->f.f4.base_anchor, face, prev->code,
491                                  x_ppem, y_ppem, &base_x, &base_y);
492                 if (otfg->f.f4.mark_anchor->AnchorFormat != 1)
493                   adjust_anchor (otfg->f.f4.mark_anchor, face, g->code,
494                                  x_ppem, y_ppem, &mark_x, &mark_y);
495                 adjustment[i].xoff = (base_x - mark_x);
496                 adjustment[i].yoff = - (base_y - mark_y);
497                 adjustment[i].back = (g - prev);
498                 adjustment[i].set = 1;
499               }
500             }
501           if (otfg->GlyphClass == OTF_GlyphClass0)
502             base = mark = g;
503           else if (otfg->GlyphClass == OTF_GlyphClassMark)
504             mark = g;
505           else
506             base = g;
507         }
508     }
509   free (otf_gstring.glyphs);
510   return to;
511
512  simple_copy:
513   font->get_metric (font, in, from, to);
514   for (i = 0; i < len; i++)
515     {
516       MFLTGlyph *g = in->glyphs + (from + i);
517
518       out->glyphs[out->used++] = *g;
519     }
520   if (otf_gstring.glyphs)
521     free (otf_gstring.glyphs);
522   return to;
523 }
524
525 MFLTFont *
526 open_font (char *fontname, char **err)
527 {
528   FT_Face face = new_face (fontname, err);
529   FontInfoOTF *font_info;
530
531   if (! face)
532     return NULL;
533   font_info = malloc (sizeof (FontInfoOTF));
534   font_info->font.get_glyph_id = get_glyph_id;
535   font_info->font.get_metric = get_metric;
536   font_info->font.drive_otf = drive_otf;
537   font_info->face = face;
538   font_info->otf = OTF_open_ft_face (face);
539   return ((MFLTFont *) font_info);
540 }
541
542 void
543 close_font (MFLTFont *font)
544 {
545   FontInfoOTF *font_info = (FontInfoOTF *) font;
546
547   OTF_close (font_info->otf);
548   FT_Done_Face (font_info->face);
549   free (font_info);
550 }
551
552 #else  /* FLT_HB */
553
554 typedef struct {
555   HB_UShort count;
556   HB_UShort *indices;
557 } FeatureInfo;
558
559 typedef struct {
560   FeatureInfo gsub;
561   FeatureInfo gpos;
562 } GsubGposInfo;
563
564 typedef struct {
565   MFLTFont font;
566   FT_Face face;
567   HB_FontRec hb_font;
568   HB_StreamRec gdef_stream;
569   HB_GDEF gdef;
570   HB_GSUB gsub;
571   HB_GPOS gpos;
572   MPlist *otf_spec_cache;
573 } FontInfoHB;
574
575 HB_Bool
576 convertStringToGlyphIndices (HB_Font font, const HB_UChar16 *string,
577                              hb_uint32 length, HB_Glyph *glyphs,
578                              hb_uint32 *numGlyphs, HB_Bool rightToLeft)
579 {
580   return TRUE;
581 }
582
583 void
584 getGlyphAdvances (HB_Font font, const HB_Glyph *glyphs, hb_uint32 numGlyphs,
585                   HB_Fixed *advances, int flags /*HB_ShaperFlag*/)
586 {
587   hb_uint32 i;
588
589   for (i = 0; i < numGlyphs; i++)
590     advances[i] =0;
591 }
592
593 HB_Bool
594 canRender (HB_Font font, const HB_UChar16 *string, hb_uint32 length)
595 {
596   return TRUE;
597 }
598
599 HB_Error
600 getPointInOutline (HB_Font font, HB_Glyph glyph, int flags /*HB_ShaperFlag*/,
601                    hb_uint32 point, HB_Fixed *xpos, HB_Fixed *ypos,
602                    hb_uint32 *nPoints)
603 {
604   FT_Face face = font->faceData;
605   HB_Error error;
606
607   if ((error = (HB_Error) FT_Load_Glyph (face, glyph, flags)))
608     return error;
609   if (face->glyph->format != ft_glyph_format_outline)
610     return (HB_Error) HB_Err_Invalid_GPOS_SubTable;
611   *nPoints = face->glyph->outline.n_points;
612   if (! *nPoints)
613     return HB_Err_Ok;
614   if (point > *nPoints)
615     return (HB_Error) HB_Err_Invalid_GPOS_SubTable;
616
617   *xpos = face->glyph->outline.points[point].x;
618   *ypos = face->glyph->outline.points[point].y;
619
620   return HB_Err_Ok;
621 }
622
623 void
624 getGlyphMetrics (HB_Font font, HB_Glyph glyph, HB_GlyphMetrics *metrics)
625 {
626 }
627
628 HB_Fixed
629 getFontMetric (HB_Font font, HB_FontMetric metric)
630 {
631   return 0;
632 }
633
634 #define MAKE_TAG(name) ((((FT_ULong) (name)[0]) << 24)          \
635                         | (((FT_ULong) (name)[1]) << 16)        \
636                         | (((FT_ULong) (name)[2]) << 8)         \
637                         | (name)[3])
638
639 HB_Error
640 new_stream (FT_Face face, char *tagname, HB_Stream stream)
641 {
642   FT_ULong tag = MAKE_TAG (tagname);
643   FT_ULong len;
644   FT_Byte *buf;
645
646   if (! FT_IS_SFNT (face))
647     return HB_Err_Invalid_Argument;
648   len = 0;
649   if (FT_Load_Sfnt_Table (face, tag, 0, NULL, &len))
650     return HB_Err_Table_Missing;
651   buf = malloc (len);
652   if (! buf)
653     return HB_Err_Out_Of_Memory;
654   if (FT_Load_Sfnt_Table (face, tag, 0, buf, &len))
655     {
656       free (buf);
657       return HB_Err_Table_Missing;
658     }
659   stream->base = (HB_Byte *) buf;
660   stream->size = len;
661   stream->pos = 0;
662   stream->cursor = NULL;
663
664   return HB_Err_Ok;
665 }
666
667 HB_Error
668 load_gdef (FontInfoHB *font_info)
669 {
670   HB_Error err;
671
672   if (! font_info->gdef_stream.base)
673     {
674       err = new_stream ((FT_Face) font_info->hb_font.faceData, "GDEF",
675                         &font_info->gdef_stream);
676       if (err != HB_Err_Ok)
677         return err;
678     }
679   return HB_Load_GDEF_Table (&font_info->gdef_stream, &font_info->gdef);
680 }
681
682 HB_Error
683 load_gsub (FontInfoHB *font_info)
684 {
685   HB_Error err;
686   HB_StreamRec stream;
687   HB_LookupList *lookup_list;
688   int i;
689
690   if (! font_info->gdef)
691     {
692       if ((err = load_gdef (font_info)) != HB_Err_Ok)
693         return err;
694     }
695   err = new_stream ((FT_Face) font_info->hb_font.faceData, "GSUB", &stream);
696   if (err != HB_Err_Ok)
697     return err;
698   err = HB_Load_GSUB_Table (&stream, &font_info->gsub,
699                             font_info->gdef, &font_info->gdef_stream);
700   free (stream.base);
701   lookup_list = &font_info->gsub->LookupList;
702   for (i = 0; i < lookup_list->LookupCount; i++)
703     lookup_list->Properties[i] = HB_GLYPH_PROPERTIES_UNKNOWN;
704   return err;
705 }
706
707 HB_Error
708 load_gpos (FontInfoHB *font_info)
709 {
710   HB_Error err;
711   HB_StreamRec stream;
712   HB_LookupList *lookup_list;
713   int i;
714
715   if (! font_info->gdef)
716     {
717       if ((err = load_gdef (font_info)) != HB_Err_Ok)
718         return err;
719     }
720   err = new_stream ((FT_Face) font_info->hb_font.faceData, "GPOS", &stream);
721   if (err != HB_Err_Ok)
722     return err;
723   err = HB_Load_GPOS_Table (&stream, &font_info->gpos,
724                             font_info->gdef, &font_info->gdef_stream);
725   free (stream.base);
726   lookup_list = &font_info->gpos->LookupList;
727   for (i = 0; i < lookup_list->LookupCount; i++)
728     lookup_list->Properties[i] = HB_GLYPH_PROPERTIES_UNKNOWN;
729   return err;
730 }
731
732 const HB_FontClass hb_fontClass = {
733     convertStringToGlyphIndices, getGlyphAdvances, canRender,
734     getPointInOutline, getGlyphMetrics, getFontMetric
735 };
736
737 void
738 setup_features (int gsubp, FontInfoHB *font_info, MFLTOtfSpec *spec,
739                 FeatureInfo *info)
740 {
741   int count, preordered;
742   unsigned int *features;
743   FT_UShort script, langsys;
744   FT_UShort req_feature, index;
745   FT_UInt *feature_list;
746   int i, j, k;
747   HB_Error err;
748
749   if (gsubp)
750     {
751       if (! font_info->gsub)
752         {
753           if (load_gsub (font_info) != HB_Err_Ok)
754             return;
755         }
756       if (HB_GSUB_Select_Script (font_info->gsub, spec->script, &script)
757           != HB_Err_Ok)
758         return;
759       if (spec->langsys)
760         {
761           if (HB_GSUB_Select_Language (font_info->gsub, spec->langsys,
762                                        script, &langsys, &req_feature)
763               != HB_Err_Ok)
764             return;
765         }
766       else
767         langsys = req_feature = 0xFFFF;
768       count = spec->gsub_count;
769       features = spec->gsub;
770     }
771   else
772     {
773       if (! font_info->gpos)
774         {
775           if (load_gpos (font_info) != HB_Err_Ok)
776             return;
777         }
778       if (HB_GPOS_Select_Script (font_info->gpos, spec->script, &script)
779           != HB_Err_Ok)
780         return;
781       if (spec->langsys)
782         {
783           if (HB_GPOS_Select_Language (font_info->gpos, spec->langsys,
784                                        script, &langsys, &req_feature)
785               != HB_Err_Ok)
786             return;
787         }
788       else
789         langsys = req_feature = 0xFFFF;
790       count = spec->gpos_count;
791       features = spec->gpos;
792     }
793   feature_list = NULL;
794   for (preordered = 0; preordered < count; preordered++)
795     if (features[preordered] == 0)
796       {
797         if ((gsubp ? HB_GSUB_Query_Features (font_info->gsub, script, langsys,
798                                              &feature_list)
799              : HB_GPOS_Query_Features (font_info->gpos, script, langsys,
800                                        &feature_list))
801             != HB_Err_Ok)
802           return;
803         break;
804       }
805   if (feature_list)
806     for (i = 0; feature_list[i]; i++);
807   else
808     i = preordered;
809   info->indices = malloc (sizeof (FT_UShort) * ((req_feature != 0xFFFF) + i));
810   i = 0;
811   if (req_feature != 0xFFFF)
812     info->indices[i++] = req_feature;
813   for (j = 0; j < preordered; j++)
814     if ((gsubp ? HB_GSUB_Select_Feature (font_info->gsub, features[j],
815                                          script, langsys, &index)
816          : HB_GPOS_Select_Feature (font_info->gpos, features[j],
817                                    script, langsys, &index))
818         == HB_Err_Ok)
819       info->indices[i++] = index;
820   if (feature_list)
821     for (j = 0; feature_list[j]; j++)
822       {
823         for (k = preordered + 1; k < count; k++)
824           if (feature_list[j] == features[k])
825             break;
826         if (k == count
827             && ((gsubp
828                  ? HB_GSUB_Select_Feature (font_info->gsub, feature_list[j],
829                                            script, langsys, &index)
830                  : HB_GPOS_Select_Feature (font_info->gpos, feature_list[j],
831                                            script, langsys, &index))
832                 == HB_Err_Ok))
833           info->indices[i++] = index;
834       }
835   info->count = i;
836 }
837
838 GsubGposInfo *
839 setup_otf_spec (MFLTFont *font, MFLTOtfSpec *spec)
840 {
841   FontInfoHB *font_info = (FontInfoHB *) font;
842   GsubGposInfo *ginfo;
843
844   if (spec->gsub_count + spec->gpos_count == 0)
845     return NULL;
846   ginfo = mplist_get (font_info->otf_spec_cache, spec->sym);
847   if (ginfo)
848     return (ginfo->gsub.count + ginfo->gpos.count > 0 ? ginfo : NULL);
849   ginfo = calloc (1, sizeof (GsubGposInfo));
850   mplist_push (font_info->otf_spec_cache, spec->sym, ginfo);
851   setup_features (1, font_info, spec, &(ginfo->gsub));
852   setup_features (0, font_info, spec, &(ginfo->gpos));
853   return ginfo;
854 }
855
856 int
857 drive_otf (MFLTFont *font, MFLTOtfSpec *spec,
858            MFLTGlyphString *in, int from, int to,
859            MFLTGlyphString *out, MFLTGlyphAdjustment *adjustment)
860 {
861   FontInfoHB *font_info = (FontInfoHB *) font;
862   int len = to - from;
863   int i;
864   HB_Buffer buf;
865   GsubGposInfo *ginfo;
866   HB_UShort *apply_order_save;
867   HB_UShort apply_count_save;
868   int gpos_applied = 0;
869   HB_Error err;
870
871   if (len == 0)
872     return from;
873
874   buf = NULL;
875   if (hb_buffer_new (&buf) != FT_Err_Ok)
876     goto simple_copy;
877   for (i = from; i < to; i++)
878     {
879       if (hb_buffer_add_glyph (buf, in->glyphs[i].code, 0, i) != FT_Err_Ok)
880         goto simple_copy;
881     }
882   ginfo = setup_otf_spec (font, spec);
883   if (! ginfo)
884     goto simple_copy;
885   if (ginfo->gsub.count > 0)
886     {
887       if (! font_info->gdef
888           && load_gdef (font_info) != HB_Err_Ok)
889         goto simple_copy;
890       apply_order_save = font_info->gsub->FeatureList.ApplyOrder;
891       apply_count_save = font_info->gsub->FeatureList.ApplyCount;
892       font_info->gsub->FeatureList.ApplyOrder = ginfo->gsub.indices;
893       font_info->gsub->FeatureList.ApplyCount = ginfo->gsub.count;
894       err = HB_GSUB_Apply_String (font_info->gsub, buf);
895       font_info->gsub->FeatureList.ApplyOrder = apply_order_save;
896       font_info->gsub->FeatureList.ApplyCount = apply_count_save;
897       if (err != HB_Err_Ok && err != HB_Err_Not_Covered)
898         goto simple_copy;
899       if (out->used + buf->in_length > out->allocated)
900         return -2;
901     }
902
903   if (ginfo->gpos.count > 0
904       && (font_info->gpos || load_gpos (font_info) == HB_Err_Ok))
905     {
906       apply_order_save = font_info->gpos->FeatureList.ApplyOrder;
907       apply_count_save = font_info->gpos->FeatureList.ApplyCount;
908       font_info->gpos->FeatureList.ApplyOrder = ginfo->gpos.indices;
909       font_info->gpos->FeatureList.ApplyCount = ginfo->gpos.count;
910       err = HB_GPOS_Apply_String (&font_info->hb_font, font_info->gpos,
911                                   FT_LOAD_DEFAULT, buf, FALSE, FALSE);
912       font_info->gpos->FeatureList.ApplyOrder = apply_order_save;
913       font_info->gpos->FeatureList.ApplyCount = apply_count_save;
914       if (err == HB_Err_Ok)
915         gpos_applied = 1;
916     }
917
918   for (i = 0; i < buf->in_length; i++)
919     {
920       HB_GlyphItem hg = buf->in_string + i;
921       HB_Position pos = buf->positions + i;
922       MFLTGlyph *g;
923
924       out->glyphs[out->used] = in->glyphs[hg->cluster];
925       g = out->glyphs + out->used++;
926       if (g->code != hg->gindex)
927         g->c = 0, g->code = hg->gindex;
928       adjustment[i].set = gpos_applied;
929       if (gpos_applied)
930         {
931           adjustment[i].xadv = pos->x_advance;
932           adjustment[i].yadv = pos->y_advance;
933           adjustment[i].xoff = pos->x_pos;
934           adjustment[i].yoff = - pos->y_pos;
935           adjustment[i].back = pos->back;
936           adjustment[i].advance_is_absolute = pos->new_advance;
937         }
938     }
939   return to;
940
941  simple_copy:
942   if (buf)
943     hb_buffer_free (buf);
944   for (i = 0; i < len; i++)
945     out->glyphs[out->used++] = in->glyphs[from + i];
946   return to;
947 }
948
949 MFLTFont *
950 open_font (char *fontname, char **err)
951 {
952   FT_Face face = new_face (fontname, err);
953   FontInfoHB *font_info;
954
955   if (! face)
956     return NULL;
957   font_info = calloc (1, sizeof (FontInfoHB));
958   font_info->font.get_glyph_id = get_glyph_id;
959   font_info->font.get_metric = get_metric;
960   font_info->font.drive_otf = drive_otf;
961   font_info->face = face;
962   font_info->hb_font.klass = &hb_fontClass;
963   font_info->hb_font.faceData = face;
964   font_info->hb_font.userData = NULL;
965   font_info->hb_font.x_ppem = face->size->metrics.x_ppem;
966   font_info->hb_font.x_scale = face->size->metrics.x_scale;
967   font_info->hb_font.y_scale = face->size->metrics.y_scale;
968   font_info->hb_font.y_ppem = face->size->metrics.y_ppem;
969   font_info->otf_spec_cache = mplist ();
970   return ((MFLTFont *) font_info);
971 }
972
973 void
974 close_font (MFLTFont *font)
975 {
976   FontInfoHB *font_info = (FontInfoHB *) font;
977   MPlist *p;
978
979   if (font_info->gdef)
980     {
981       HB_Done_GDEF_Table (font_info->gdef);
982       free (font_info->gdef_stream.base);
983     }
984   if (font_info->gsub)
985     HB_Done_GSUB_Table (font_info->gsub);
986   if (font_info->gpos)
987     HB_Done_GPOS_Table (font_info->gpos);
988   FT_Done_Face ((FT_Face) (font_info->hb_font.faceData));
989   for (p = font_info->otf_spec_cache; mplist_key (p) != Mnil;
990        p = mplist_next (p))
991     {
992       GsubGposInfo *ginfo = mplist_value (p);
993
994       if (ginfo->gsub.count > 0)
995         free (ginfo->gsub.indices);
996       if (ginfo->gpos.count > 0)
997         free (ginfo->gpos.indices);
998     }
999   m17n_object_unref (font_info->otf_spec_cache);
1000   free (font_info);
1001 }
1002
1003 #endif
1004
1005 #else  /* (defined (FLT_PANGO) */
1006
1007 typedef struct {
1008   int count;
1009   guint *indices;
1010   PangoOTRuleset *ruleset;
1011 } FeatureInfo;
1012
1013 typedef struct {
1014   FeatureInfo gsub;
1015   FeatureInfo gpos;
1016 } GsubGposInfo;
1017
1018 typedef struct {
1019   MFLTFont font;
1020   PangoFontMap *fontmap;
1021   PangoContext *context;
1022   PangoFcFont *pango_font;
1023   MPlist *otf_spec_cache;
1024 } FontInfoPango;
1025
1026 int
1027 get_glyph_id (MFLTFont *font, MFLTGlyph *g)
1028 {
1029   FontInfoPango *font_info = (FontInfoPango *) font;
1030   PangoGlyph glyph = pango_fc_font_get_glyph (font_info->pango_font, g->c);
1031
1032   return (glyph ? (int) glyph : -1);
1033 }
1034
1035 int
1036 get_metric (MFLTFont *font, MFLTGlyphString *gstring, int from, int to)
1037 {
1038   FontInfoPango *font_info = (FontInfoPango *) font;
1039   int i;
1040
1041   for (i = from; i < to; i++)
1042     {
1043       MFLTGlyph *g = gstring->glyphs + from;
1044       PangoRectangle inc, logical;
1045
1046       pango_font_get_glyph_extents (PANGO_FONT (font_info->pango_font),
1047                                     gstring->glyphs[i].code, &inc, &logical);
1048       g->lbearing = inc.x;
1049       g->rbearing = inc.x + inc.width;
1050       g->xadv = logical.width;
1051       g->yadv = 0;
1052       g->ascent = - inc.y;
1053       g->descent = inc.height + inc.y;
1054     }
1055 }
1056
1057 void
1058 setup_features (PangoOTTableType type, FontInfoPango *font_info,
1059                 MFLTOtfSpec *spec, FeatureInfo *info)
1060 {
1061   int count, preordered;
1062   unsigned int *features;
1063   guint script, langsys;
1064   guint req_feature, index;
1065   guint *feature_list;
1066   int i, j, k;
1067   int err;
1068   FT_Face face;
1069   PangoOTInfo *ot_info; 
1070
1071   face = pango_fc_font_lock_face (font_info->pango_font);
1072   ot_info = pango_ot_info_get (face);
1073   pango_fc_font_unlock_face (font_info->pango_font);
1074
1075   if (! pango_ot_info_find_script (ot_info, type, spec->script, &script))
1076     return;
1077   if (spec->langsys)
1078     {
1079       if (! pango_ot_info_find_language (ot_info, type, script,
1080                                          spec->langsys,
1081                                          &langsys, &req_feature))
1082         return;
1083     }
1084   else
1085     {
1086       langsys = PANGO_OT_DEFAULT_LANGUAGE;
1087       req_feature = 0xFFFF;
1088     }
1089   if (type == PANGO_OT_TABLE_GSUB)
1090     {
1091       count = spec->gsub_count;
1092       features = spec->gsub;
1093     }
1094   else
1095     {
1096       count = spec->gpos_count;
1097       features = spec->gpos;
1098     }
1099   feature_list = NULL;
1100   for (preordered = 0; preordered < count; preordered++)
1101     if (features[preordered] == 0)
1102       {
1103         feature_list = pango_ot_info_list_features (ot_info, type, 0,
1104                                                     script, langsys);
1105         if (! feature_list)
1106           return;
1107         break;
1108       }
1109   if (feature_list)
1110     for (i = 0; feature_list[i]; i++);
1111   else
1112     i = preordered;
1113   info->indices = malloc (sizeof (guint) * ((req_feature != 0xFFFF) + i));
1114   i = 0;
1115   if (req_feature != 0xFFFF)
1116     info->indices[i++] = req_feature;
1117   for (j = 0; j < preordered; j++)
1118     if (pango_ot_info_find_feature (ot_info, type, features[j],
1119                                     script, langsys, &index))
1120       info->indices[i++] = index;
1121   if (feature_list)
1122     for (j = 0; feature_list[j]; j++)
1123       {
1124         for (k = preordered + 1; k < count; k++)
1125           if (feature_list[j] == features[k])
1126             break;
1127         if (k == count
1128             && pango_ot_info_find_feature (ot_info, type, feature_list[j],
1129                                            script, langsys, &index))
1130           info->indices[i++] = index;
1131       }
1132   info->count = i;
1133   info->ruleset = pango_ot_ruleset_new (ot_info);
1134   for (i = 0; i < info->count; i++)
1135     pango_ot_ruleset_add_feature (info->ruleset, type, info->indices[i],
1136                                   PANGO_OT_ALL_GLYPHS);
1137 }
1138
1139 GsubGposInfo *
1140 setup_otf_spec (FontInfoPango *font_info, MFLTOtfSpec *spec)
1141 {
1142   GsubGposInfo *ginfo;
1143
1144   if (spec->gsub_count + spec->gpos_count == 0)
1145     return NULL;
1146   ginfo = mplist_get (font_info->otf_spec_cache, spec->sym);
1147   if (ginfo)
1148     return (ginfo->gsub.count + ginfo->gpos.count > 0 ? ginfo : NULL);
1149   ginfo = calloc (1, sizeof (GsubGposInfo));
1150   mplist_push (font_info->otf_spec_cache, spec->sym, ginfo);
1151   setup_features (PANGO_OT_TABLE_GSUB, font_info, spec, &(ginfo->gsub));
1152   setup_features (PANGO_OT_TABLE_GPOS, font_info, spec, &(ginfo->gpos));
1153   return ginfo;
1154 }
1155
1156 int
1157 drive_otf (MFLTFont *font, MFLTOtfSpec *spec,
1158            MFLTGlyphString *in, int from, int to,
1159            MFLTGlyphString *out, MFLTGlyphAdjustment *adjustment)
1160 {
1161   FontInfoPango *font_info = (FontInfoPango *) font;
1162   PangoOTBuffer *buffer;
1163   GsubGposInfo *ginfo;
1164   PangoGlyphString *glyphs;
1165   int i;
1166
1167   buffer = pango_ot_buffer_new (font_info->pango_font);
1168   for (i = from; i < to; i++)
1169     pango_ot_buffer_add_glyph (buffer, in->glyphs[i].code, 0, i);
1170   ginfo = setup_otf_spec (font_info, spec);
1171   if (! ginfo)
1172     goto simple_copy;
1173   if (ginfo->gsub.count > 0)
1174     pango_ot_ruleset_substitute (ginfo->gsub.ruleset, buffer);
1175   if (ginfo->gpos.count > 0)
1176     pango_ot_ruleset_position (ginfo->gpos.ruleset, buffer);
1177   glyphs = pango_glyph_string_new ();
1178   pango_ot_buffer_output (buffer, glyphs);
1179   for (i = 0; i < glyphs->num_glyphs; i++)
1180     {
1181       PangoGlyphInfo *glyph_info = glyphs->glyphs + i;
1182       MFLTGlyph *g;
1183
1184       out->glyphs[out->used] = in->glyphs[glyphs->log_clusters[i]];
1185       g = out->glyphs + out->used++;
1186       if (g->code != glyph_info->glyph)
1187         g->c = 0, g->code = glyph_info->glyph;
1188       g->xoff = glyph_info->geometry.x_offset;
1189       g->yoff = glyph_info->geometry.y_offset;
1190       g->xadv = glyph_info->geometry.width;
1191       g->yadv = 0;
1192       adjustment[i].set = 0;
1193     }
1194   pango_ot_buffer_destroy (buffer);
1195   pango_glyph_string_free (glyphs);
1196   return to;
1197
1198  simple_copy:
1199   pango_ot_buffer_destroy (buffer);
1200   for (i = from; i < to; i++)
1201     out->glyphs[out->used++] = in->glyphs[i];
1202   return to;
1203 }
1204
1205
1206 MFLTFont *
1207 open_font (char *fontname, char **err)
1208 {
1209   FontInfoPango *font_info = NULL;
1210   PangoFontMap *fontmap;
1211   PangoContext *context;
1212   PangoFontDescription *desc;
1213   PangoFont *pango_font;
1214   char *family;
1215   int size;
1216   double pango_size;
1217   
1218   if (parse_font_name (fontname, &family, &size, err) < 0)
1219     return NULL;
1220   desc = pango_font_description_new ();
1221   pango_font_description_set_family (desc, family);
1222   free (family);
1223   pango_size = size * PANGO_SCALE;
1224   pango_font_description_set_absolute_size (desc, pango_size);
1225
1226   fontmap = pango_ft2_font_map_new ();
1227   context = pango_context_new ();
1228   pango_context_set_font_map (context, fontmap);
1229   pango_font = pango_context_load_font (context, desc);
1230   pango_font_description_free (desc);
1231   if (pango_font)
1232     {
1233       font_info = calloc (1, sizeof (FontInfoPango));
1234       font_info->fontmap = fontmap;
1235       font_info->context = context;
1236       font_info->pango_font = PANGO_FC_FONT (pango_font);
1237     }
1238   else
1239     {
1240       g_object_unref (context);
1241       g_object_unref (fontmap);
1242     }
1243   return (MFLTFont *) font_info;
1244 }
1245
1246 void
1247 close_font (MFLTFont *font)
1248 {
1249   FontInfoPango *font_info = (FontInfoPango *) font;
1250
1251   g_object_unref (font_info->context);
1252   g_object_unref (font_info->fontmap);
1253 }
1254
1255 int
1256 flt (MText *mt, int from, int to, MFLTFont *font, char *flt_name)
1257 {
1258   MFLTGlyphString gstring;
1259   int len = to - from;
1260   int i;
1261
1262   memset (&gstring, 0, sizeof (MFLTGlyphString));
1263   gstring.glyph_size = sizeof (MFLTGlyph);
1264   gstring.allocated = len * 2;
1265   gstring.glyphs = alloca (sizeof (MFLTGlyph) * gstring.allocated);
1266   for (i = 0; i < len; i++)
1267     gstring.glyphs[i].c = mtext_ref_char (mt, from + i);
1268   gstring.used = len;
1269   return mflt_run (&gstring, 0, len, font, msymbol (flt_name));
1270 }
1271
1272 #endif
1273
1274 int
1275 main (int argc, char **argv)
1276 {
1277   char *font_name, *flt_name;
1278   char *err;
1279   MText *mt;
1280   MFLTFont *font;
1281   int len, i, j;
1282
1283   if (argc < 3)
1284     {
1285       fprintf (stderr, "Usage: flt FONT-NAME FLT-NAME < TEXT-FILE\n");
1286       exit (1);
1287     }
1288
1289   font_name = argv[1];
1290   flt_name = argv[2];
1291
1292   FT_Init_FreeType (&ft_library);
1293   M17N_INIT ();
1294   font = open_font (font_name, &err);
1295   if (! font)
1296     {
1297       fprintf (stderr, "Font error: %s: %s\n", argv[1], err);
1298       exit (1);
1299     }
1300
1301   mt = mconv_decode_stream (msymbol ("utf-8"), stdin);
1302   len = mtext_len (mt);
1303   for (i = 0, j = mtext_character (mt, i, len, '\n'); i < len;
1304        i = j + 1, j = mtext_character (mt, i, len, '\n'))
1305     {
1306       if (j < 0)
1307         j = len;
1308       if (flt (mt, i, j, font, flt_name) < 0)
1309         {
1310           fprintf (stderr, "Error in FLT processing.\n");
1311           exit (1);
1312         }
1313     }
1314   m17n_object_unref (mt);
1315   close_font (font);
1316   M17N_FINI ();
1317   return 0;
1318 }