added kerning to fonts
[swftools.git] / lib / pdf / InfoOutputDev.cc
1 #include "config.h"
2 #include "Object.h"
3 #include "InfoOutputDev.h"
4 #include "SplashOutputDev.h"
5 #ifdef HAVE_POPPLER
6 #include <splash/SplashTypes.h>
7 #include <splash/SplashPath.h>
8 #include <splash/SplashFont.h>
9 #include <splash/SplashFontFile.h>
10 #else
11 #include "SplashTypes.h"
12 #include "SplashPath.h"
13 #include "SplashFont.h"
14 #include "SplashFontFile.h"
15 #endif
16 #include "GfxState.h"
17 #include "../log.h"
18 #include "../types.h"
19 #include "../q.h"
20 #include <math.h>
21 #include <assert.h>
22
23 int config_addspace = 1;
24 int config_fontquality = 10;
25 int config_bigchar = 0;
26
27 InfoOutputDev::InfoOutputDev(XRef*xref) 
28 {
29     num_links = 0;
30     num_jpeg_images = 0;
31     num_ppm_images = 0;
32     num_textfields = 0;
33     num_fonts = 0;
34     num_polygons= 0;
35     currentfont = 0;
36     currentglyph = 0;
37     id2font = new GHash(1);
38     SplashColor white = {255,255,255};
39     splash = new SplashOutputDev(splashModeRGB8,320,0,white,0,0);
40     splash->startDoc(xref);
41 }
42 InfoOutputDev::~InfoOutputDev() 
43 {
44     GHashIter*i;
45     id2font->startIter(&i);
46     GString*key;
47     FontInfo*fontinfo;
48     while(id2font->getNext(&i, &key, (void**)&fontinfo)) {
49         delete fontinfo;
50     }
51     id2font->killIter(&i);
52
53     delete id2font;id2font=0;
54     delete splash;splash=0;
55 }
56
57 void FontInfo::grow(int size)
58 {
59     if(size >= this->num_glyphs) {
60         this->glyphs = (GlyphInfo**)realloc(this->glyphs, sizeof(GlyphInfo*)*(size));
61         this->kerning = (dict_t**)realloc(this->kerning, sizeof(dict_t*)*(size));
62         memset(&this->glyphs[this->num_glyphs], 0, sizeof(SplashPath*)*((size)-this->num_glyphs));
63         memset(&this->kerning[this->num_glyphs], 0, sizeof(dict_t*)*((size)-this->num_glyphs));
64         this->num_glyphs = size;
65     }
66 }
67 FontInfo::FontInfo(char*id)
68 {
69     this->id = strdup(id);
70     this->charid2glyph = 0;
71     this->seen = 0;
72     this->num_glyphs = 0;
73     this->glyphs = 0;
74     this->kerning = 0;
75     this->splash_font = 0;
76     this->lastchar = -1;
77     this->lastx = 0;
78     this->lasty = 0;
79     this->gfxfont = 0;
80     this->space_char = -1;
81 }
82 FontInfo::~FontInfo()
83 {
84     if(this->id) {free(this->id);this->id=0;}
85     this->font = 0;
86     if(this->charid2glyph) {
87         free(this->charid2glyph);
88         this->charid2glyph = 0;
89     }
90     int t;
91     for(t=0;t<num_glyphs;t++) {
92         if(glyphs[t]) {
93             delete glyphs[t]->path;glyphs[t]->path = 0;
94             delete glyphs[t];
95             glyphs[t]=0;
96         }
97     }
98     free(glyphs);glyphs=0;
99     if(this->gfxfont)
100         gfxfont_free(this->gfxfont);
101    
102     if(kerning) {
103         for(t=0;t<num_glyphs;t++) {
104             dict_t* d = kerning[t];
105             if(!d) continue;
106             DICT_ITERATE_ITEMS(d,void*,key,mtf_t*,m) {
107                 mtf_destroy(m);
108             }
109             dict_destroy(d);
110         }
111     }
112 }
113
114 static int findSpace(gfxfont_t*font)
115 {
116     int first_space = -1;
117     int t;
118     for(t=0;t<font->num_glyphs;t++) {
119         gfxglyph_t*g = &font->glyphs[t];
120         if(GLYPH_IS_SPACE(g)) {
121             if(g->unicode == 32) return t;
122             if(first_space<0)
123                 first_space = t;
124         }
125     }
126     if(font->num_glyphs>32 && GLYPH_IS_SPACE(&font->glyphs[32])) {
127         return 32;
128     }
129     return first_space;
130 }
131
132 static int addSpace(gfxfont_t*font)
133 {
134     font->num_glyphs++;
135     font->glyphs = (gfxglyph_t*)realloc(font->glyphs, sizeof(gfxglyph_t)*font->num_glyphs);
136     gfxglyph_t*g = &font->glyphs[font->num_glyphs-1];
137     memset(g, 0, sizeof(*g));
138     g->unicode = 32;
139     //g->advance = font->ascent;
140     g->advance = fabs(font->ascent - font->descent)*2 / 3;
141     if(font->max_unicode > 32)
142         font->unicode2glyph[32] = font->num_glyphs-1;
143 #if 0
144     g->line = gfxline_makerectangle(0, -font->ascent, g->advance, font->descent);
145 #endif
146     return font->num_glyphs-1;
147 }
148
149 static gfxfont_t* createGfxFont(FontInfo*src)
150 {
151     gfxfont_t*font = (gfxfont_t*)malloc(sizeof(gfxfont_t));
152     memset(font, 0, sizeof(gfxfont_t));
153
154     font->glyphs = (gfxglyph_t*)malloc(sizeof(gfxglyph_t)*src->num_glyphs);
155     memset(font->glyphs, 0, sizeof(gfxglyph_t)*src->num_glyphs);
156     font->id = 0;
157     int t;
158
159     double quality = (INTERNAL_FONT_SIZE * 200 / config_fontquality) / src->max_size;
160     double scale = 1;
161     //printf("%d glyphs\n", font->num_glyphs);
162     font->num_glyphs = 0;
163     font->ascent = fabs(src->ascender);
164     font->descent = fabs(src->descender);
165     
166     for(t=0;t<src->num_glyphs;t++) {
167         if(src->glyphs[t]) {
168             SplashPath*path = src->glyphs[t]->path;
169             int len = path?path->getLength():0;
170             //printf("glyph %d) %08x (%d line segments)\n", t, path, len);
171             gfxglyph_t*glyph = &font->glyphs[font->num_glyphs];
172             src->glyphs[t]->glyphid = font->num_glyphs;
173             glyph->unicode = src->glyphs[t]->unicode;
174             if(glyph->unicode >= font->max_unicode)
175                 font->max_unicode = glyph->unicode+1;
176             gfxdrawer_t drawer;
177             gfxdrawer_target_gfxline(&drawer);
178             int s;
179             int count = 0;
180             double xmax = 0;
181             for(s=0;s<len;s++) {
182                 Guchar f;
183                 double x, y;
184                 path->getPoint(s, &x, &y, &f);
185                 if(!s || x > xmax)
186                     xmax = x;
187                 if(f&splashPathFirst) {
188                     drawer.moveTo(&drawer, x*scale, y*scale);
189                 }
190                 if(f&splashPathCurve) {
191                     double x2,y2;
192                     path->getPoint(++s, &x2, &y2, &f);
193                     if(f&splashPathCurve) {
194                         double x3,y3;
195                         path->getPoint(++s, &x3, &y3, &f);
196                         gfxdraw_cubicTo(&drawer, x*scale, y*scale, x2*scale, y2*scale, x3*scale, y3*scale, quality);
197                     } else {
198                         drawer.splineTo(&drawer, x*scale, y*scale, x2*scale, y2*scale);
199                     }
200                 } else {
201                     drawer.lineTo(&drawer, x*scale, y*scale);
202                 }
203              //   printf("%f %f %s %s\n", x, y, (f&splashPathCurve)?"curve":"",
204              //                           (f&splashPathFirst)?"first":"",
205              //                           (f&splashPathLast)?"last":"");
206             }
207
208             glyph->line = (gfxline_t*)drawer.result(&drawer);
209             if(src->glyphs[t]->advance>0) {
210                 glyph->advance = src->glyphs[t]->advance;
211             } else {
212                 msg("<warning> Approximating advance value for glyph %d", t);
213                 glyph->advance = xmax*scale;
214             }
215             if(config_bigchar) {
216                 double max = src->glyphs[t]->advance_max;
217                 if(max>0 && max > glyph->advance) {
218                     glyph->advance = max;
219                 }
220             }
221
222             font->num_glyphs++;
223         }
224     }
225     font->unicode2glyph = (int*)malloc(sizeof(int)*font->max_unicode);
226     memset(font->unicode2glyph, -1, sizeof(int)*font->max_unicode);
227     for(t=0;t<font->num_glyphs;t++) {
228         if(font->glyphs[t].unicode>0 && font->glyphs[t].unicode<font->max_unicode) {
229             font->unicode2glyph[font->glyphs[t].unicode] = t;
230         }
231
232     }
233
234     int kerning_size = 0;
235     for(t=0;t<font->num_glyphs;t++) {
236         dict_t* d = src->kerning[t];
237         if(!d) continue;
238         DICT_ITERATE_ITEMS(d,void*,key,mtf_t*,m) {
239             if(m) {
240                 kerning_size++;
241             }
242         }
243     }
244     font->kerning_size = kerning_size;
245     font->kerning = (gfxkerning_t*)malloc(sizeof(gfxkerning_t)*kerning_size);
246     int pos = 0;
247     for(t=0;t<font->num_glyphs;t++) {
248         dict_t* d = src->kerning[t];
249         if(!d) continue;
250         DICT_ITERATE_ITEMS(d,void*,key,mtf_t*,m) {
251             if(m) {
252                 font->kerning[pos].c1 = t;
253                 font->kerning[pos].c2 = (int)(ptroff_t)key;
254                 font->kerning[pos].advance = (int)(ptroff_t)m->first->key;
255                 pos++;
256             }
257         }
258     }
259     //int advance = (int)(ptroff_t)m->first->key;
260
261     return font;
262 }
263
264 static float find_average_glyph_advance(gfxfont_t*f)
265 {
266     if(!f->num_glyphs)
267         return 0.0;
268
269     float*values = (float*)malloc(sizeof(float)*f->num_glyphs);
270     int t;
271     for(t=0;t<f->num_glyphs;t++) {
272         values[t] = f->glyphs[t].advance;
273     }
274     float m = medianf(values, f->num_glyphs);
275     free(values);
276     return m;
277 }
278
279 gfxfont_t* FontInfo::getGfxFont()
280 {
281     if(!this->gfxfont) {
282         this->gfxfont = createGfxFont(this);
283         this->gfxfont->id = strdup(this->id);
284         this->space_char = findSpace(this->gfxfont);
285         this->average_advance = find_average_glyph_advance(this->gfxfont);
286
287         if(this->space_char>=0) {
288             msg("<debug> Font %s has space char %d (unicode=%d)", 
289                     this->id, this->space_char, 
290                     this->gfxfont->glyphs[this->space_char].unicode);
291         } else if(config_addspace) {
292             this->space_char = addSpace(this->gfxfont);
293             msg("<debug> Appending space char to font %s, position %d", this->gfxfont->id, this->space_char);
294         }
295     }
296     return this->gfxfont;
297 }
298
299 GBool InfoOutputDev::upsideDown() {return gTrue;}
300 GBool InfoOutputDev::useDrawChar() {return gTrue;}
301 GBool InfoOutputDev::interpretType3Chars() {return gTrue;}
302 GBool InfoOutputDev::useTilingPatternFill() {return gTrue;}
303
304 void InfoOutputDev::startPage(int pageNum, GfxState *state, double crop_x1, double crop_y1, double crop_x2, double crop_y2)
305 {
306     double x1,y1,x2,y2;
307     state->transform(crop_x1,crop_y1,&x1,&y1);
308     state->transform(crop_x2,crop_y2,&x2,&y2);
309     if(x2<x1) {double x3=x1;x1=x2;x2=x3;}
310     if(y2<y1) {double y3=y1;y1=y2;y2=y3;}
311     this->x1 = (int)x1;
312     this->y1 = (int)y1;
313     this->x2 = (int)x2;
314     this->y2 = (int)y2;
315     msg("<verbose> Generating info structure for page %d", pageNum);
316 }
317 void InfoOutputDev::endPage()
318 {
319 }
320 void InfoOutputDev::drawLink(Link *link, Catalog *catalog) 
321 {
322     num_links++;
323 }
324    
325 /*  } else if(!strcmp(key,"fontquality")) {
326         this->config_fontquality = atof(value);
327         if(this->config_fontquality<=1)
328             this->config_fontquality=1;
329     } else if(!strcmp(key,"bigchar")) {
330         this->config_bigchar = atoi(value);
331     }
332  */
333
334 double InfoOutputDev::getMaximumFontSize(char*id)
335 {
336     FontInfo*info = (FontInfo*)id2font->lookup(id);
337     if(!info) {
338         msg("<error> Unknown font id: %s", id);
339         return 0.0;
340     }
341     return info->max_size;
342 }
343
344 char*getFontID(GfxFont*font)
345 {
346     Ref*ref = font->getID();
347     GString*gstr = font->getName();
348     char* fname = gstr==0?0:gstr->getCString();
349     char buf[128];
350     if(fname==0) {
351         if(font->getType() == fontType3) {
352             sprintf(buf, "t3font-%d-%d", ref->num, ref->gen);
353         } else {
354             sprintf(buf, "font-%d-%d", ref->num, ref->gen);
355         }
356     } else {
357         sprintf(buf, "%s-%d-%d", fname, ref->num, ref->gen);
358     }
359     return strdup(buf);
360 }
361
362 void InfoOutputDev::updateFont(GfxState *state) 
363 {
364     GfxFont*font = state->getFont();
365     if(!font) {
366         currentfont = 0;
367         return;
368     }
369     if(font->getType() == fontType3) {
370         currentfont = 0;
371         return;
372     }
373     char*id = getFontID(font);
374
375     if(currentfont)
376         currentfont->splash_font = 0;
377
378     currentfont = (FontInfo*)id2font->lookup(id);
379     if(!currentfont) {
380         currentfont = new FontInfo(id);
381         currentfont->font = font;
382         currentfont->max_size = 0;
383         GString* idStr = new GString(id);
384         id2font->add(idStr, (void*)currentfont);
385         num_fonts++;
386     }
387
388     state->setCTM(1.0,0,0,1.0,0,0);
389     splash->updateCTM(state, 0,0,0,0,0,0);
390     state->setTextMat(1.0,0,0,1.0,0,0);
391     state->setFont(font, 1024.0);
392     splash->doUpdateFont(state);
393     currentfont->splash_font = splash->getCurrentFont();
394     if(currentfont->splash_font) {
395         currentfont->ascender = currentfont->splash_font->ascender;
396         currentfont->descender = currentfont->splash_font->descender;
397     } else {
398         currentfont->ascender = currentfont->descender = 0;
399     }
400
401     free(id);
402 }
403
404 void InfoOutputDev::fill(GfxState *state)
405 {
406     num_polygons++;
407 }
408
409 void InfoOutputDev::eoFill(GfxState *state)
410 {
411     num_polygons++;
412 }
413
414 FontInfo* InfoOutputDev::getFont(char*id)
415 {
416     return (FontInfo*)id2font->lookup(id);
417 }
418
419 void InfoOutputDev::drawChar(GfxState *state, double x, double y,
420                       double dx, double dy,
421                       double originX, double originY,
422                       CharCode code, int nBytes, Unicode *u, int uLen)
423 {
424     double m11,m21,m12,m22;
425     state->getFontTransMat(&m11, &m12, &m21, &m22);
426     m11 *= state->getHorizScaling();
427     m21 *= state->getHorizScaling();
428     double lenx = sqrt(m11*m11 + m12*m12);
429     double leny = sqrt(m21*m21 + m22*m22);
430     double len = lenx>leny?lenx:leny;
431     if(!currentfont || !currentfont->splash_font) {
432         return; //error
433     }
434     if(currentfont && currentfont->max_size < len) {
435         currentfont->max_size = len;
436     }
437     
438     num_textfields++;
439
440     currentfont->grow(code+1);
441     GlyphInfo*g = currentfont->glyphs[code];
442     if(!g) {
443         g = currentfont->glyphs[code] = new GlyphInfo();
444         g->advance_max = 0;
445         currentfont->splash_font->last_advance = -1;
446         g->path = currentfont->splash_font->getGlyphPath(code);
447         g->advance = currentfont->splash_font->last_advance;
448         g->unicode = 0;
449     }
450     if(uLen && ((u[0]>=32 && u[0]<g->unicode) || !g->unicode)) {
451         g->unicode = u[0];
452     }
453     if(currentfont->lastchar>=0 && currentfont->lasty == y) {
454         double xshift = (x - currentfont->lastx);
455         if(xshift>=0 && xshift > g->advance_max) {
456             g->advance_max = xshift;
457         }
458         int advance = (int)xshift;
459         if(advance>=0 && advance<g->advance*4 && advance!=currentfont->lastadvance) {
460             int c1 = currentfont->lastchar;
461             int c2 = code;
462             dict_t*d = currentfont->kerning[c1];
463             if(!d) {
464                 d = currentfont->kerning[c1] = dict_new2(&int_type);
465             }
466             mtf_t*k = (mtf_t*)dict_lookup(d, (void*)(ptroff_t)c2);
467             if(!k) {
468                 k = mtf_new(&int_type);
469                 dict_put(d, (void*)(ptroff_t)c2, k);
470             }
471             mtf_increase(k, (void*)(ptroff_t)advance);
472         }
473     }
474
475     currentfont->lastx = x;
476     currentfont->lasty = y;
477     currentfont->lastchar = code;
478     currentfont->lastadvance = (int)(g->advance+0.5);
479 }
480
481 GBool InfoOutputDev::beginType3Char(GfxState *state, double x, double y, double dx, double dy, CharCode code, Unicode *u, int uLen)
482 {
483     GfxFont*font = state->getFont();
484     if(!font)
485         return gTrue;
486     if(font->getType() != fontType3)
487         return gTrue;
488
489     char*id = getFontID(font);
490     currentfont = (FontInfo*)id2font->lookup(id);
491     if(!currentfont) {
492         currentfont = new FontInfo(id);
493         currentfont->font = font;
494         GString* idStr = new GString(id);
495         id2font->add(idStr, (void*)currentfont);
496         num_fonts++;
497     }
498     currentfont = currentfont;
499     free(id);
500
501     currentfont->grow(code+1);
502     if(!currentfont->glyphs[code]) {
503         currentglyph = currentfont->glyphs[code] = new GlyphInfo();
504         currentglyph->unicode = uLen?u[0]:0;
505         currentglyph->path = new SplashPath();
506         currentglyph->x1=0;
507         currentglyph->y1=0;
508         currentglyph->x2=dx;
509         currentglyph->y2=dy;
510         return gFalse;
511     } else {
512         return gTrue;
513     }
514 }
515
516 void InfoOutputDev::type3D0(GfxState *state, double wx, double wy)
517 {
518     currentglyph->x1=0;
519     currentglyph->y1=0;
520     currentglyph->x2=wx;
521     currentglyph->y2=wy;
522 }
523
524 void InfoOutputDev::type3D1(GfxState *state, double wx, double wy, double llx, double lly, double urx, double ury)
525 {
526     currentglyph->x1=llx;
527     currentglyph->y1=lly;
528     currentglyph->x2=urx;
529     currentglyph->y2=ury;
530 }
531
532 void InfoOutputDev::endType3Char(GfxState *state)
533 {
534     double x1 = currentglyph->x1;
535     double y1 = currentglyph->y1;
536     double x2 = currentglyph->x2;
537     double y2 = currentglyph->y2;
538     currentglyph->path->moveTo(x1,y1);
539     currentglyph->path->lineTo(x2,y1);
540     currentglyph->path->lineTo(x2,y2);
541     currentglyph->path->lineTo(x1,y2);
542     currentglyph->path->close();
543 }
544
545 void InfoOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
546                            int width, int height, GBool invert,
547                            GBool inlineImg) 
548 {
549     if(str->getKind()==strDCT) num_jpeg_images++; else num_ppm_images++;
550
551     OutputDev::drawImageMask(state,ref,str,width,height,invert,inlineImg);
552 }
553 void InfoOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
554                        int width, int height, GfxImageColorMap *colorMap,
555                        int *maskColors, GBool inlineImg)
556 {
557     if(str->getKind()==strDCT) num_jpeg_images++; else num_ppm_images++;
558
559     OutputDev::drawImage(state,ref,str,width,height,colorMap,maskColors,inlineImg);
560 }
561 void InfoOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str,
562                                 int width, int height,
563                                 GfxImageColorMap *colorMap,
564                                 Stream *maskStr,
565                                 int maskWidth, int maskHeight,
566                                 GBool maskInvert) 
567 {
568     if(str->getKind()==strDCT) num_jpeg_images++; else num_ppm_images++;
569
570     OutputDev::drawMaskedImage(state,ref,str,width,height,colorMap,maskStr,maskWidth,maskHeight,maskInvert);
571 }
572
573 void InfoOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
574                                     int width, int height,
575                                     GfxImageColorMap *colorMap,
576                                     Stream *maskStr,
577                                     int maskWidth, int maskHeight,
578                                     GfxImageColorMap *maskColorMap) 
579 {
580     if(str->getKind()==strDCT) num_jpeg_images++; else num_ppm_images++;
581
582     OutputDev::drawSoftMaskedImage(state,ref,str,width,height,colorMap,maskStr,maskWidth,maskHeight,maskColorMap);
583 }
584     
585 void InfoOutputDev::dumpfonts(gfxdevice_t*dev)
586 {
587     GHashIter*i;
588     GString*key;
589     FontInfo*font;
590     id2font->startIter(&i);
591     while(id2font->getNext(&i, &key, (void**)&font)) {
592         dev->addfont(dev, font->getGfxFont());
593     }
594 }