use FT_FREETYPE_H if we have ft2build.h.
[swftools.git] / lib / modules / swffont.c
1 /* swffont.c
2
3    Functions for loading external fonts.
4
5    Extension module for the rfxswf library.
6    Part of the swftools package.
7
8    Copyright (c) 2003, 2004 Matthias Kramm
9  
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
23
24 static int loadfont_scale = 4;
25 static int skip_unused = 1;
26 static int full_unicode = 0;
27
28 void swf_SetLoadFontParameters(int _scale, int _skip_unused, int _full_unicode)
29 {
30     if(_scale) loadfont_scale = _scale;
31     skip_unused = _skip_unused;
32     full_unicode = _full_unicode;
33 }
34
35 #ifdef HAVE_FREETYPE
36
37 #ifdef HAVE_FREETYPE_FT2BUILD_H
38 #include <freetype/ft2build.h>
39 #include FT_FREETYPE_H
40 #else
41 #include <freetype/freetype.h>
42 #include <freetype/ftglyph.h>
43 #include <freetype/ftsizes.h>
44 #include <freetype/ftsnames.h>
45 #include <freetype/ttnameid.h>
46 #include <freetype/ftoutln.h>
47 #endif
48
49 #define FT_SCALE 1
50 #define FT_SUBPIXELS 64
51
52 static int ft_move_to(FT_Vector* _to, void* user) 
53 {
54     drawer_t* draw = (drawer_t*)user;
55     FPOINT to;
56     to.x = _to->x*FT_SCALE/(float)FT_SUBPIXELS;
57     to.y = -_to->y*FT_SCALE/(float)FT_SUBPIXELS;
58     draw->moveTo(draw, &to);
59     return 0;
60 }
61 static int ft_line_to(FT_Vector* _to, void* user) 
62 {
63     drawer_t* draw = (drawer_t*)user;
64     FPOINT to;
65     to.x = _to->x*FT_SCALE/(float)FT_SUBPIXELS;
66     to.y = -_to->y*FT_SCALE/(float)FT_SUBPIXELS;
67     draw->lineTo(draw, &to);
68     return 0;
69 }
70 static int ft_cubic_to(FT_Vector* _c1, FT_Vector* _c2, FT_Vector* _to, void* user)
71 {
72     drawer_t* draw = (drawer_t*)user;
73     FPOINT c1,c2,to;
74     to.x = _to->x*FT_SCALE/(float)FT_SUBPIXELS;
75     to.y = -_to->y*FT_SCALE/(float)FT_SUBPIXELS;
76     c1.x = _c1->x*FT_SCALE/(float)FT_SUBPIXELS;
77     c1.y = -_c1->y*FT_SCALE/(float)FT_SUBPIXELS;
78     c2.x = _c2->x*FT_SCALE/(float)FT_SUBPIXELS;
79     c2.y = -_c2->y*FT_SCALE/(float)FT_SUBPIXELS;
80     draw_cubicTo(draw, &c1, &c2, &to);
81     return 0;
82 }
83 static int ft_conic_to(FT_Vector* _c, FT_Vector* _to, void* user) 
84 {
85     drawer_t* draw = (drawer_t*)user;
86     FPOINT c,to;
87     to.x = _to->x*FT_SCALE/(float)FT_SUBPIXELS;
88     to.y = -_to->y*FT_SCALE/(float)FT_SUBPIXELS;
89     c.x = _c->x*FT_SCALE/(float)FT_SUBPIXELS;
90     c.y = -_c->y*FT_SCALE/(float)FT_SUBPIXELS;
91     draw_conicTo(draw, &c, &to);
92     return 0;
93 }
94 static FT_Outline_Funcs outline_functions =
95 {
96   ft_move_to,
97   ft_line_to,
98   ft_conic_to,
99   ft_cubic_to,
100   0,0
101 };
102
103 static FT_Library ftlibrary = 0;
104
105 SWFFONT* swf_LoadTrueTypeFont(char*filename)
106 {
107     FT_Face face;
108     FT_Error error;
109     const char* name = 0;
110     FT_ULong charcode;
111     FT_UInt gindex;
112     SWFFONT* font;
113     int t;
114     int*glyph2glyph;
115     FT_Size size;
116     int max_unicode = 0;
117     int charmap = -1;
118    
119     if(ftlibrary == 0) {
120         if(FT_Init_FreeType(&ftlibrary)) {
121             fprintf(stderr, "Couldn't init freetype library!\n");
122             exit(1);
123         }
124     }
125     error = FT_New_Face(ftlibrary, filename, 0, &face);
126     FT_Set_Pixel_Sizes (face, 16*loadfont_scale, 16*loadfont_scale);
127
128     if(error) {
129         fprintf(stderr, "Couldn't load file %s- not a TTF file?\n", filename);
130         return 0;
131     }
132     if(face->num_glyphs <= 0) {
133         fprintf(stderr, "File %s contains %d glyphs\n", face->num_glyphs);
134         return 0;
135     }
136
137     font = malloc(sizeof(SWFFONT));
138     memset(font, 0, sizeof(SWFFONT));
139     font->id = -1;
140     font->version = 2;
141     font->layout = malloc(sizeof(SWFLAYOUT));
142     memset(font->layout, 0, sizeof(SWFLAYOUT));
143     font->layout->bounds = malloc(face->num_glyphs*sizeof(SRECT));
144     font->style =  ((face->style_flags&FT_STYLE_FLAG_ITALIC)?FONT_STYLE_ITALIC:0)
145                   |((face->style_flags&FT_STYLE_FLAG_BOLD)?FONT_STYLE_BOLD:0);
146     font->encoding = FONT_ENCODING_UNICODE;
147     font->glyph2ascii = malloc(face->num_glyphs*sizeof(U16));
148     memset(font->glyph2ascii, 0, face->num_glyphs*sizeof(U16));
149     font->maxascii = 0;
150     font->glyph = malloc(face->num_glyphs*sizeof(SWFGLYPH));
151     memset(font->glyph, 0, face->num_glyphs*sizeof(SWFGLYPH));
152     if(FT_HAS_GLYPH_NAMES(face)) {
153         font->glyphnames = malloc(face->num_glyphs*sizeof(char*));
154         memset(font->glyphnames,0,face->num_glyphs*sizeof(char*));
155     }
156
157     font->layout->ascent = abs(face->ascender)*FT_SCALE*loadfont_scale*20/FT_SUBPIXELS/2; //face->bbox.xMin;
158     font->layout->descent = abs(face->descender)*FT_SCALE*loadfont_scale*20/FT_SUBPIXELS/2; //face->bbox.xMax;
159     font->layout->leading = font->layout->ascent + font->layout->descent;
160     font->layout->kerningcount = 0;
161     
162     name = FT_Get_Postscript_Name(face);
163     if(name && *name)
164         font->name = (U8*)strdup(name);
165
166     while(1) 
167     {
168     /*    // Map Glyphs to Unicode, version 1 (quick and dirty):
169         int t;
170         for(t=0;t<65536;t++) {
171             int index = FT_Get_Char_Index(face, t);
172             if(index>=0 && index<face->num_glyphs) {
173                 if(font->glyph2ascii[index]<0)
174                     font->glyph2ascii[index] = t;
175             }
176         }*/
177         
178         // Map Glyphs to Unicode, version 2 (much nicer):
179         // (The third way would be the AGL algorithm, as proposed
180         //  by Werner Lemberg on freetype@freetype.org)
181
182         charcode = FT_Get_First_Char(face, &gindex);
183         while(gindex != 0)
184         {
185             if(gindex >= 0 && gindex<face->num_glyphs) {
186                 if(!font->glyph2ascii[gindex]) {
187                     font->glyph2ascii[gindex] = charcode;
188                     if(charcode + 1 > font->maxascii) {
189                         font->maxascii = charcode + 1;
190                     }
191                 }
192             }
193             charcode = FT_Get_Next_Char(face, charcode, &gindex);
194         }
195
196         /* if we didn't find a single encoding character, try
197            the font's charmaps instead. That usually means that
198            the encoding is no longer unicode. 
199            TODO: find a way to convert the encoding to unicode
200          */
201         if(font->maxascii == 0 && charmap < face->num_charmaps - 1) {
202             charmap++;
203             FT_Set_Charmap(face, face->charmaps[charmap]);
204             font->encoding = 0;//anything but unicode FIXME
205         } else 
206             break;
207     }
208
209     if(full_unicode)
210         font->maxascii = 65535;
211     
212     font->ascii2glyph = malloc(font->maxascii*sizeof(int));
213     
214     for(t=0;t<font->maxascii;t++) {
215         int g = FT_Get_Char_Index(face, t);
216         if(!g || g>=face->num_glyphs)
217             g = -1;
218         font->ascii2glyph[t] = g;
219         if(g>=0) {
220             max_unicode = t+1;
221             if(!font->glyph2ascii[g]) {
222                 font->glyph2ascii[g] = t;
223             }
224         }
225     }
226     font->maxascii = max_unicode;
227
228     font->numchars = 0;
229
230     glyph2glyph = (int*)malloc(face->num_glyphs*sizeof(int));
231
232     for(t=0; t < face->num_glyphs; t++) {
233         FT_Glyph glyph;
234         FT_BBox bbox;
235         FT_Matrix matrix;
236         char name[128];
237         drawer_t draw;
238         int ret;
239         char hasname = 0;
240         name[0]=0;
241         if(FT_HAS_GLYPH_NAMES(face)) {
242             error = FT_Get_Glyph_Name(face, t, name, 127);
243             if(!error && name[0] && !strstr(name, "notdef")) {
244                 font->glyphnames[font->numchars] = strdup(name);
245                 hasname = 1;
246             }
247         }
248         if(!font->glyph2ascii[t] && !hasname && skip_unused) {
249             continue;
250         }
251         error = FT_Load_Glyph(face, t, FT_LOAD_NO_BITMAP);
252         if(error) {
253             fprintf(stderr, "Couldn't load glyph %d, error:%d\n", t, error);
254             continue;
255         }
256         error = FT_Get_Glyph(face->glyph, &glyph);
257         if(error) {
258             fprintf(stderr, "Couldn't get glyph %d, error:%d\n", t, error);
259             continue;
260         }
261
262         FT_Glyph_Get_CBox(glyph, ft_glyph_bbox_unscaled, &bbox);
263         bbox.yMin = -bbox.yMin;
264         bbox.yMax = -bbox.yMax;
265         if(bbox.xMax < bbox.xMin) {
266             // swap
267             bbox.xMax ^= bbox.xMin;
268             bbox.xMin ^= bbox.xMax;
269             bbox.xMax ^= bbox.xMin;
270         }
271         if(bbox.yMax < bbox.yMin) {
272             // swap
273             bbox.yMax ^= bbox.yMin;
274             bbox.yMin ^= bbox.yMax;
275             bbox.yMax ^= bbox.yMin;
276         }
277
278         swf_Shape01DrawerInit(&draw, 0);
279
280         //error = FT_Outline_Decompose(&face->glyph->outline, &outline_functions, &draw);
281         error = FT_Outline_Decompose(&face->glyph->outline, &outline_functions, &draw);
282         draw.finish(&draw);
283         
284         if(error) {
285             fprintf(stderr, "Couldn't decompose glyph %d\n", t);
286             draw.dealloc(&draw);
287             continue;
288         }
289
290 #if 0
291         if(bbox.xMin > 0) {
292             font->glyph[font->numchars].advance = (bbox.xMax*FT_SCALE)/FT_SUBPIXELS;
293         } else {
294             font->glyph[font->numchars].advance = ((bbox.xMax - bbox.xMin)*FT_SCALE)/FT_SUBPIXELS;
295         }
296 #else
297         font->glyph[font->numchars].advance = glyph->advance.x*20/65536;
298 #endif
299         
300         font->glyph[font->numchars].shape = swf_ShapeDrawerToShape(&draw);
301         
302         font->layout->bounds[font->numchars].xmin = (bbox.xMin*FT_SCALE*20)/FT_SUBPIXELS;
303         font->layout->bounds[font->numchars].ymin = (bbox.yMin*FT_SCALE*20)/FT_SUBPIXELS;
304         font->layout->bounds[font->numchars].xmax = (bbox.xMax*FT_SCALE*20)/FT_SUBPIXELS;
305         font->layout->bounds[font->numchars].ymax = (bbox.yMax*FT_SCALE*20)/FT_SUBPIXELS;
306
307         draw.dealloc(&draw);
308
309         FT_Done_Glyph(glyph);
310         font->glyph2ascii[font->numchars] = font->glyph2ascii[t];
311         glyph2glyph[t] = font->numchars;
312         font->numchars++;
313     }
314     /* notice: if skip_unused is true, font->glyph2ascii, font->glyphnames and font->layout->bounds will 
315                have more memory allocated than just font->numchars, but only the first font->numchars 
316                are used/valid */
317
318     for(t=0;t<font->maxascii;t++) {
319         if(font->ascii2glyph[t]>=0) {
320             font->ascii2glyph[t] = glyph2glyph[font->ascii2glyph[t]];
321         }
322     }
323     free(glyph2glyph);
324
325     FT_Done_Face(face);
326     FT_Done_FreeType(ftlibrary);ftlibrary=0;
327
328     return font;
329 }
330 #else  //HAVE_FREETYPE
331
332 SWFFONT* swf_LoadTrueTypeFont(char*filename)
333 {
334     fprintf(stderr, "Warning: no freetype library- not able to load %s\n", filename);
335     return 0;
336 }
337
338 #endif
339
340 #ifdef HAVE_T1LIB
341
342 #include <t1lib.h>
343
344 static int t1lib_initialized = 0;
345
346 static int counter = 0;
347
348 SWFFONT* swf_LoadT1Font(char*filename)
349 {
350     SWFFONT * font;
351     int nr;
352     float angle,underline;
353     char*fontname,*fullname,*familyname;
354     BBox bbox;
355     int s,num;
356     char**charnames;
357     char**charname;
358     char*encoding[256];
359     int c;
360     int t;
361
362     if(!t1lib_initialized) {
363         T1_SetBitmapPad(16);
364         if ((T1_InitLib(NO_LOGFILE)==NULL)){
365             fprintf(stderr, "Initialization of t1lib failed\n");
366             return 0;
367         }
368         t1lib_initialized = 1;
369     }
370     nr = T1_AddFont(filename);
371     T1_LoadFont(nr);
372
373     charnames = T1_GetAllCharNames(nr);
374     if(!charnames) {
375         fprintf(stderr, "No Charnames record- not a Type1 Font?\n");
376         return 0;
377     }
378
379     angle = T1_GetItalicAngle(nr);
380     fontname = T1_GetFontName(nr);
381     fullname = T1_GetFullName(nr);
382     familyname = T1_GetFamilyName(nr);
383     underline = T1_GetUnderlinePosition(nr);
384     bbox = T1_GetFontBBox(nr);
385
386     font = (SWFFONT*)malloc(sizeof(SWFFONT));
387     memset(font, 0, sizeof(SWFFONT));
388
389     font->version = 2;
390     if(fontname) 
391         font->name = (U8*)strdup(fontname);
392     else 
393         font->name = 0;
394     font->layout = (SWFLAYOUT*)malloc(sizeof(SWFLAYOUT));
395     memset(font->layout, 0, sizeof(SWFLAYOUT));
396
397     num = 0;
398     charname = charnames;
399     while(*charname) {
400         charname++;
401         if(num<256) {
402             if(*charname) encoding[num] = strdup(*charname);
403             else          encoding[num] = strdup(".notdef");
404         }
405         num++;
406     }
407     for(t=num;t<256;t++)
408         encoding[t] = strdup(".notdef");
409     
410     //T1_ReencodeFont(nr, encoding);
411
412     font->maxascii = num;
413     font->numchars = num;
414     
415     font->style = (/*bold*/0?FONT_STYLE_BOLD:0) + (angle>0.05?FONT_STYLE_ITALIC:0);
416
417     font->glyph = (SWFGLYPH*)malloc(num*sizeof(SWFGLYPH));
418     memset(font->glyph, 0, num*sizeof(SWFGLYPH));
419     font->glyph2ascii = (U16*)malloc(num*sizeof(U16));
420     memset(font->glyph2ascii, 0, num*sizeof(U16));
421     font->ascii2glyph = (int*)malloc(font->maxascii*sizeof(int));
422     memset(font->ascii2glyph, -1, font->maxascii*sizeof(int));
423     font->layout->ascent = (U16)(underline - bbox.lly);
424     font->layout->descent = (U16)(bbox.ury - underline);
425     font->layout->leading = (U16)(font->layout->ascent - 
426                              font->layout->descent -
427                              (bbox.lly - bbox.ury));
428     font->layout->bounds = (SRECT*)malloc(sizeof(SRECT)*num);
429     memset(font->layout->bounds, 0, sizeof(SRECT)*num);
430     font->layout->kerningcount = 0;
431     font->layout->kerning = 0;
432     font->glyphnames = malloc(num*sizeof(char*));
433     memset(font->glyphnames, 0, num*sizeof(char*));
434   
435     num = 0;
436
437     charname = charnames;
438     for(c=0;c<font->numchars;c++) {
439         drawer_t draw;
440         SRECT bbox;
441         T1_OUTLINE * outline;
442         FPOINT pos,last;
443         int firstx;
444         
445         outline = T1_GetCharOutline(nr, c, 100.0, 0);
446         firstx = outline->dest.x/0xffff;
447
448         pos.x = 0;
449         pos.y = 0;
450         last = pos;
451         
452         font->glyphnames[c] = strdup(*charname);
453
454         if(c<font->maxascii)
455             font->ascii2glyph[c] = c;
456         font->glyph2ascii[c] = c;
457         
458         swf_Shape01DrawerInit(&draw, 0);
459
460         while(outline) {
461             pos.x += (outline->dest.x/(float)0xffff);
462             pos.y += (outline->dest.y/(float)0xffff);
463
464             if(outline->type == T1_PATHTYPE_MOVE) {
465                 draw.moveTo(&draw,&pos);
466             } else if(outline->type == T1_PATHTYPE_LINE) {
467                 draw.lineTo(&draw,&pos);
468             } else if(outline->type == T1_PATHTYPE_BEZIER) {
469                 T1_BEZIERSEGMENT*o2 = (T1_BEZIERSEGMENT*)outline;
470                 FPOINT b,c;
471                 b.x = o2->B.x/(float)0xffff+last.x;
472                 b.y = o2->B.y/(float)0xffff+last.y;
473                 c.x = o2->C.x/(float)0xffff+last.x;
474                 c.y = o2->C.y/(float)0xffff+last.y;
475                 draw_cubicTo(&draw,&b,&c,&pos);
476             } else {
477                 fprintf(stderr, "loadT1Font: unknown outline type:%d\n", outline->type);
478             }
479             last = pos;
480             outline = outline->link;
481             printf("(%f,%f) ", pos.x, pos.y);
482         }
483         printf("\n");
484         
485         draw.finish(&draw);
486
487         font->glyph[c].shape = swf_ShapeDrawerToShape(&draw);
488         bbox = swf_ShapeDrawerGetBBox(&draw);
489         draw.dealloc(&draw);
490             
491         font->layout->bounds[c] = bbox;
492         font->glyph[c].advance = bbox.xmax;
493         if(!font->glyph[c].advance) {
494             font->glyph[c].advance = firstx;
495         }
496         charname++;
497     }
498     T1_DeleteFont(nr);
499
500     for(t=0;t<256;t++)
501         free(encoding[t]);
502     return font;
503 }
504
505 #else
506
507 SWFFONT* swf_LoadT1Font(char*filename)
508 {
509     fprintf(stderr, "Warning: no t1lib- not able to load %s\n", filename);
510     return 0;
511 }
512
513 #endif
514
515 SWFFONT* swf_DummyFont()
516 {
517     SWFFONT*font = (SWFFONT*)malloc(sizeof(SWFFONT));
518     memset(font, 0, sizeof(SWFFONT));
519     return font;
520 }
521
522 static int isSWF(const char*filename)
523 {
524     FILE*fi = fopen(filename, "rb");
525     char a[8];
526     if(!fi) {
527         perror(filename);
528         return -1;
529     }
530     memset(a, 0, sizeof(a));
531     fread(a, 4, 1, fi);
532     fclose(fi);
533
534     if(!strncmp(a, "FWS", 3) || !strncmp(a, "CWS", 3)) {
535         return 1;
536     }
537     return 0;
538 }
539
540 SWFFONT* swf_LoadFont(char*filename)
541 {
542     int is_swf;
543     if(filename == 0)
544         return swf_DummyFont();
545     is_swf = isSWF(filename);
546     if(is_swf<0)
547         return 0;
548     if(is_swf) {
549         return swf_ReadFont(filename);
550     }
551
552 #if defined(HAVE_FREETYPE)
553     return swf_LoadTrueTypeFont(filename);
554 #elif defined(HAVE_T1LIB)
555     return swf_LoadT1Font(filename);
556 #else
557     fprintf(stderr, "Error: Neither T1lib nor FreeType support compiled in. Could not load %s\n", filename);
558     return 0;
559 #endif
560 }
561