changed from malloc to rfx_alloc.
[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_FT2BUILD_H
38 #include <ft2build.h>
39 #include FT_FREETYPE_H
40 #include FT_GLYPH_H
41 #include FT_SIZES_H
42 #include FT_SFNT_NAMES_H
43 #include FT_TRUETYPE_IDS_H
44 #include FT_OUTLINE_H
45 #else
46 #include <freetype/freetype.h>
47 #include <freetype/ftglyph.h>
48 #include <freetype/ftsizes.h>
49 #include <freetype/ftsnames.h>
50 #include <freetype/ttnameid.h>
51 #include <freetype/ftoutln.h>
52 #endif
53
54 #define FT_SCALE 1
55 #define FT_SUBPIXELS 64
56
57 static int ft_move_to(FT_Vector* _to, void* user) 
58 {
59     drawer_t* draw = (drawer_t*)user;
60     FPOINT to;
61     to.x = _to->x*FT_SCALE/(float)FT_SUBPIXELS;
62     to.y = -_to->y*FT_SCALE/(float)FT_SUBPIXELS;
63     draw->moveTo(draw, &to);
64     return 0;
65 }
66 static int ft_line_to(FT_Vector* _to, void* user) 
67 {
68     drawer_t* draw = (drawer_t*)user;
69     FPOINT to;
70     to.x = _to->x*FT_SCALE/(float)FT_SUBPIXELS;
71     to.y = -_to->y*FT_SCALE/(float)FT_SUBPIXELS;
72     draw->lineTo(draw, &to);
73     return 0;
74 }
75 static int ft_cubic_to(FT_Vector* _c1, FT_Vector* _c2, FT_Vector* _to, void* user)
76 {
77     drawer_t* draw = (drawer_t*)user;
78     FPOINT c1,c2,to;
79     to.x = _to->x*FT_SCALE/(float)FT_SUBPIXELS;
80     to.y = -_to->y*FT_SCALE/(float)FT_SUBPIXELS;
81     c1.x = _c1->x*FT_SCALE/(float)FT_SUBPIXELS;
82     c1.y = -_c1->y*FT_SCALE/(float)FT_SUBPIXELS;
83     c2.x = _c2->x*FT_SCALE/(float)FT_SUBPIXELS;
84     c2.y = -_c2->y*FT_SCALE/(float)FT_SUBPIXELS;
85     draw_cubicTo(draw, &c1, &c2, &to);
86     return 0;
87 }
88 static int ft_conic_to(FT_Vector* _c, FT_Vector* _to, void* user) 
89 {
90     drawer_t* draw = (drawer_t*)user;
91     FPOINT c,to;
92     to.x = _to->x*FT_SCALE/(float)FT_SUBPIXELS;
93     to.y = -_to->y*FT_SCALE/(float)FT_SUBPIXELS;
94     c.x = _c->x*FT_SCALE/(float)FT_SUBPIXELS;
95     c.y = -_c->y*FT_SCALE/(float)FT_SUBPIXELS;
96     draw_conicTo(draw, &c, &to);
97     return 0;
98 }
99 static FT_Outline_Funcs outline_functions =
100 {
101   ft_move_to,
102   ft_line_to,
103   ft_conic_to,
104   ft_cubic_to,
105   0,0
106 };
107
108 static FT_Library ftlibrary = 0;
109
110 SWFFONT* swf_LoadTrueTypeFont(char*filename)
111 {
112     FT_Face face;
113     FT_Error error;
114     const char* name = 0;
115     FT_ULong charcode;
116     FT_UInt gindex;
117     SWFFONT* font;
118     int t;
119     int*glyph2glyph;
120     FT_Size size;
121     int max_unicode = 0;
122     int charmap = -1;
123    
124     if(ftlibrary == 0) {
125         if(FT_Init_FreeType(&ftlibrary)) {
126             fprintf(stderr, "Couldn't init freetype library!\n");
127             exit(1);
128         }
129     }
130     error = FT_New_Face(ftlibrary, filename, 0, &face);
131     FT_Set_Pixel_Sizes (face, 16*loadfont_scale, 16*loadfont_scale);
132
133     if(error) {
134         fprintf(stderr, "Couldn't load file %s- not a TTF file?\n", filename);
135         return 0;
136     }
137     if(face->num_glyphs <= 0) {
138         fprintf(stderr, "File %s contains %d glyphs\n", face->num_glyphs);
139         return 0;
140     }
141
142     font = rfx_calloc(sizeof(SWFFONT));
143     font->id = -1;
144     font->version = 2;
145     font->layout = rfx_calloc(sizeof(SWFLAYOUT));
146     font->layout->bounds = rfx_calloc(face->num_glyphs*sizeof(SRECT));
147     font->style =  ((face->style_flags&FT_STYLE_FLAG_ITALIC)?FONT_STYLE_ITALIC:0)
148                   |((face->style_flags&FT_STYLE_FLAG_BOLD)?FONT_STYLE_BOLD:0);
149     font->encoding = FONT_ENCODING_UNICODE;
150     font->glyph2ascii = rfx_calloc(face->num_glyphs*sizeof(U16));
151     font->maxascii = 0;
152     font->glyph = rfx_calloc(face->num_glyphs*sizeof(SWFGLYPH));
153     if(FT_HAS_GLYPH_NAMES(face)) {
154         font->glyphnames = rfx_calloc(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 = rfx_calloc(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*)rfx_calloc(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     rfx_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*)rfx_calloc(sizeof(SWFFONT));
387
388     font->version = 2;
389     if(fontname) 
390         font->name = (U8*)strdup(fontname);
391     else 
392         font->name = 0;
393     font->layout = (SWFLAYOUT*)rfx_calloc(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*)rfx_calloc(num*sizeof(SWFGLYPH));
416     font->glyph2ascii = (U16*)rfx_calloc(num*sizeof(U16));
417     font->ascii2glyph = (int*)rfx_calloc(font->maxascii*sizeof(int));
418     font->layout->ascent = (U16)(underline - bbox.lly);
419     font->layout->descent = (U16)(bbox.ury - underline);
420     font->layout->leading = (U16)(font->layout->ascent - 
421                              font->layout->descent -
422                              (bbox.lly - bbox.ury));
423     font->layout->bounds = (SRECT*)rfx_calloc(sizeof(SRECT)*num);
424     font->layout->kerningcount = 0;
425     font->layout->kerning = 0;
426     font->glyphnames = rfx_calloc(num*sizeof(char*));
427   
428     num = 0;
429
430     charname = charnames;
431     for(c=0;c<font->numchars;c++) {
432         drawer_t draw;
433         SRECT bbox;
434         T1_OUTLINE * outline;
435         FPOINT pos,last;
436         int firstx;
437         
438         outline = T1_GetCharOutline(nr, c, 100.0, 0);
439         firstx = outline->dest.x/0xffff;
440
441         pos.x = 0;
442         pos.y = 0;
443         last = pos;
444         
445         font->glyphnames[c] = strdup(*charname);
446
447         if(c<font->maxascii)
448             font->ascii2glyph[c] = c;
449         font->glyph2ascii[c] = c;
450         
451         swf_Shape01DrawerInit(&draw, 0);
452
453         while(outline) {
454             pos.x += (outline->dest.x/(float)0xffff);
455             pos.y += (outline->dest.y/(float)0xffff);
456
457             if(outline->type == T1_PATHTYPE_MOVE) {
458                 draw.moveTo(&draw,&pos);
459             } else if(outline->type == T1_PATHTYPE_LINE) {
460                 draw.lineTo(&draw,&pos);
461             } else if(outline->type == T1_PATHTYPE_BEZIER) {
462                 T1_BEZIERSEGMENT*o2 = (T1_BEZIERSEGMENT*)outline;
463                 FPOINT b,c;
464                 b.x = o2->B.x/(float)0xffff+last.x;
465                 b.y = o2->B.y/(float)0xffff+last.y;
466                 c.x = o2->C.x/(float)0xffff+last.x;
467                 c.y = o2->C.y/(float)0xffff+last.y;
468                 draw_cubicTo(&draw,&b,&c,&pos);
469             } else {
470                 fprintf(stderr, "loadT1Font: unknown outline type:%d\n", outline->type);
471             }
472             last = pos;
473             outline = outline->link;
474             printf("(%f,%f) ", pos.x, pos.y);
475         }
476         printf("\n");
477         
478         draw.finish(&draw);
479
480         font->glyph[c].shape = swf_ShapeDrawerToShape(&draw);
481         bbox = swf_ShapeDrawerGetBBox(&draw);
482         draw.dealloc(&draw);
483             
484         font->layout->bounds[c] = bbox;
485         font->glyph[c].advance = bbox.xmax;
486         if(!font->glyph[c].advance) {
487             font->glyph[c].advance = firstx;
488         }
489         charname++;
490     }
491     T1_DeleteFont(nr);
492
493     for(t=0;t<256;t++)
494         rfx_free(encoding[t]);
495     return font;
496 }
497
498 #else
499
500 SWFFONT* swf_LoadT1Font(char*filename)
501 {
502     fprintf(stderr, "Warning: no t1lib- not able to load %s\n", filename);
503     return 0;
504 }
505
506 #endif
507
508 SWFFONT* swf_DummyFont()
509 {
510     SWFFONT*font = (SWFFONT*)rfx_calloc(sizeof(SWFFONT));
511     return font;
512 }
513
514 static int isSWF(const char*filename)
515 {
516     FILE*fi = fopen(filename, "rb");
517     char a[8];
518     if(!fi) {
519         perror(filename);
520         return -1;
521     }
522     memset(a, 0, sizeof(a));
523     fread(a, 4, 1, fi);
524     fclose(fi);
525
526     if(!strncmp(a, "FWS", 3) || !strncmp(a, "CWS", 3)) {
527         return 1;
528     }
529     return 0;
530 }
531
532 SWFFONT* swf_LoadFont(char*filename)
533 {
534     int is_swf;
535     if(filename == 0)
536         return swf_DummyFont();
537     is_swf = isSWF(filename);
538     if(is_swf<0)
539         return 0;
540     if(is_swf) {
541         return swf_ReadFont(filename);
542     }
543
544 #if defined(HAVE_FREETYPE)
545     return swf_LoadTrueTypeFont(filename);
546 #elif defined(HAVE_T1LIB)
547     return swf_LoadT1Font(filename);
548 #else
549     fprintf(stderr, "Error: Neither T1lib nor FreeType support compiled in. Could not load %s\n", filename);
550     return 0;
551 #endif
552 }
553