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