Applied Moriyoshi Koizumi's CID Type 2 patch.
[swftools.git] / pdf2swf / SWFOutputDev.cc
1 /* pdfswf.cc
2    implements a pdf output device (OutputDev).
3
4    This file is part of swftools.
5
6    Swftools is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    Swftools is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with swftools; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stddef.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include "../config.h"
26 #ifdef HAVE_DIRENT_H
27 #include <dirent.h>
28 #endif
29 #ifdef HAVE_SYS_STAT_H
30 #include <sys/stat.h>
31 #endif
32 #ifdef HAVE_FONTCONFIG_H
33 #include <fontconfig.h>
34 #endif
35 //xpdf header files
36 #include "config.h"
37 #include "gfile.h"
38 #include "GString.h"
39 #include "gmem.h"
40 #include "Object.h"
41 #include "Stream.h"
42 #include "Array.h"
43 #include "Dict.h"
44 #include "XRef.h"
45 #include "Catalog.h"
46 #include "Page.h"
47 #include "PDFDoc.h"
48 #include "Error.h"
49 #include "OutputDev.h"
50 #include "GfxState.h"
51 #include "GfxFont.h"
52 #include "CharCodeToUnicode.h"
53 #include "NameToUnicodeTable.h"
54 #include "GlobalParams.h"
55 //#define XPDF_101
56 #ifdef XPDF_101
57 #include "FontFile.h"
58 #else
59 #include "FoFiType1C.h"
60 #include "FoFiTrueType.h"
61 #endif
62 #include "SWFOutputDev.h"
63
64 //swftools header files
65 #include "swfoutput.h"
66 #include "../lib/log.h"
67
68 #include <math.h>
69
70 typedef struct _fontfile
71 {
72     char*filename;
73     int used;
74 } fontfile_t;
75
76 // for pdfswf_addfont
77 static fontfile_t fonts[2048];
78 static int fontnum = 0;
79
80 static int config_use_fontconfig = 1;
81
82 // swf <-> pdf pages
83 // TODO: move into pdf_doc_t
84 static int*pages = 0;
85 static int pagebuflen = 0;
86 static int pagepos = 0;
87
88 /* config */
89 static double caplinewidth = 3.0;
90 static int zoom = 72; /* xpdf: 86 */
91
92 static void printInfoString(Dict *infoDict, char *key, char *fmt);
93 static void printInfoDate(Dict *infoDict, char *key, char *fmt);
94
95 struct mapping {
96     char*pdffont;
97     char*filename;
98 } pdf2t1map[] ={
99 {"Times-Roman",           "n021003l"},
100 {"Times-Italic",          "n021023l"},
101 {"Times-Bold",            "n021004l"},
102 {"Times-BoldItalic",      "n021024l"},
103 {"Helvetica",             "n019003l"},
104 {"Helvetica-Oblique",     "n019023l"},
105 {"Helvetica-Bold",        "n019004l"},
106 {"Helvetica-BoldOblique", "n019024l"},
107 {"Courier",               "n022003l"},
108 {"Courier-Oblique",       "n022023l"},
109 {"Courier-Bold",          "n022004l"},
110 {"Courier-BoldOblique",   "n022024l"},
111 {"Symbol",                "s050000l"},
112 {"ZapfDingbats",          "d050000l"}};
113
114 class SWFOutputDev:  public OutputDev {
115   int outputstarted;
116   struct swfoutput output;
117 public:
118
119   // Constructor.
120   SWFOutputDev();
121
122   // Destructor.
123   virtual ~SWFOutputDev() ;
124
125   void setMove(int x,int y);
126   void setClip(int x1,int y1,int x2,int y2);
127   
128   int save(char*filename);
129
130   void getDimensions(int*x1,int*y1,int*x2,int*y2);
131
132   //----- get info about output device
133
134   // Does this device use upside-down coordinates?
135   // (Upside-down means (0,0) is the top left corner of the page.)
136   virtual GBool upsideDown();
137
138   // Does this device use drawChar() or drawString()?
139   virtual GBool useDrawChar();
140   
141   // Can this device draw gradients?
142   virtual GBool useGradients();
143   
144   virtual GBool interpretType3Chars() {return gTrue;}
145
146   //----- initialization and control
147
148   void setXRef(PDFDoc*doc, XRef *xref);
149
150   // Start a page.
151   virtual void startPage(int pageNum, GfxState *state, double x1, double y1, double x2, double y2) ;
152
153   //----- link borders
154   virtual void drawLink(Link *link, Catalog *catalog) ;
155
156   //----- save/restore graphics state
157   virtual void saveState(GfxState *state) ;
158   virtual void restoreState(GfxState *state) ;
159
160   //----- update graphics state
161
162   virtual void updateFont(GfxState *state);
163   virtual void updateFillColor(GfxState *state);
164   virtual void updateStrokeColor(GfxState *state);
165   virtual void updateLineWidth(GfxState *state);
166   virtual void updateLineJoin(GfxState *state);
167   virtual void updateLineCap(GfxState *state);
168   
169   virtual void updateAll(GfxState *state) 
170   {
171       updateFont(state);
172       updateFillColor(state);
173       updateStrokeColor(state);
174       updateLineWidth(state);
175       updateLineJoin(state);
176       updateLineCap(state);
177   };
178
179   //----- path painting
180   virtual void stroke(GfxState *state) ;
181   virtual void fill(GfxState *state) ;
182   virtual void eoFill(GfxState *state) ;
183
184   //----- path clipping
185   virtual void clip(GfxState *state) ;
186   virtual void eoClip(GfxState *state) ;
187
188   //----- text drawing
189   virtual void beginString(GfxState *state, GString *s) ;
190   virtual void endString(GfxState *state) ;
191   virtual void drawChar(GfxState *state, double x, double y,
192                         double dx, double dy,
193                         double originX, double originY,
194                         CharCode code, Unicode *u, int uLen);
195
196   //----- image drawing
197   virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
198                              int width, int height, GBool invert,
199                              GBool inlineImg);
200   virtual void drawImage(GfxState *state, Object *ref, Stream *str,
201                          int width, int height, GfxImageColorMap *colorMap,
202                          int *maskColors, GBool inlineImg);
203   
204   virtual GBool beginType3Char(GfxState *state,
205                                CharCode code, Unicode *u, int uLen);
206   virtual void endType3Char(GfxState *state);
207
208   private:
209   void drawGeneralImage(GfxState *state, Object *ref, Stream *str,
210                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
211                                    GBool inlineImg, int mask);
212   int clipping[64];
213   int clippos;
214
215   int currentpage;
216
217   PDFDoc*doc;
218   XRef*xref;
219
220   char* searchFont(char*name);
221   char* substituteFont(GfxFont*gfxFont, char*oldname);
222   char* writeEmbeddedFontToFile(XRef*ref, GfxFont*font);
223   int t1id;
224   int jpeginfo; // did we write "File contains jpegs" yet?
225   int pbminfo; // did we write "File contains jpegs" yet?
226   int linkinfo; // did we write "File contains links" yet?
227   int ttfinfo; // did we write "File contains TrueType Fonts" yet?
228   int gradientinfo; // did we write "File contains Gradients yet?
229
230   int type3active; // are we between beginType3()/endType3()?
231
232   GfxState *laststate;
233
234   int pic_xids[1024];
235   int pic_yids[1024];
236   int pic_ids[1024];
237   int pic_width[1024];
238   int pic_height[1024];
239   int picpos;
240   int pic_id;
241   char type3Warning;
242
243   char* substitutetarget[256];
244   char* substitutesource[256];
245   int substitutepos;
246
247   int user_movex,user_movey;
248   int user_clipx1,user_clipx2,user_clipy1,user_clipy2;
249 };
250
251 static char*getFontID(GfxFont*font);
252
253 class InfoOutputDev:  public OutputDev 
254 {
255   public:
256   int x1,y1,x2,y2;
257   int num_links;
258   int num_images;
259   int num_fonts;
260
261   InfoOutputDev() 
262   {
263       num_links = 0;
264       num_images = 0;
265       num_fonts = 0;
266   }
267   virtual ~InfoOutputDev() 
268   {
269   }
270   virtual GBool upsideDown() {return gTrue;}
271   virtual GBool useDrawChar() {return gTrue;}
272   virtual GBool useGradients() {return gTrue;}
273   virtual GBool interpretType3Chars() {return gTrue;}
274   virtual void startPage(int pageNum, GfxState *state, double crop_x1, double crop_y1, double crop_x2, double crop_y2)
275   {
276       double x1,y1,x2,y2;
277       state->transform(crop_x1,crop_y1,&x1,&y1);
278       state->transform(crop_x2,crop_y2,&x2,&y2);
279       if(x2<x1) {double x3=x1;x1=x2;x2=x3;}
280       if(y2<y1) {double y3=y1;y1=y2;y2=y3;}
281       this->x1 = (int)x1;
282       this->y1 = (int)y1;
283       this->x2 = (int)x2;
284       this->y2 = (int)y2;
285   }
286   virtual void drawLink(Link *link, Catalog *catalog) 
287   {
288       num_links++;
289   }
290   virtual void updateFont(GfxState *state) 
291   {
292       GfxFont*font = state->getFont();
293       if(!font)
294           return;
295       char*id = getFontID(font);
296       /* FIXME*/
297       num_fonts++;
298   }
299   virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
300                              int width, int height, GBool invert,
301                              GBool inlineImg) 
302   {
303       num_images++;
304   }
305   virtual void drawImage(GfxState *state, Object *ref, Stream *str,
306                          int width, int height, GfxImageColorMap *colorMap,
307                          int *maskColors, GBool inlineImg)
308   {
309       num_images++;
310   }
311 };
312
313 SWFOutputDev::SWFOutputDev()
314 {
315     jpeginfo = 0;
316     ttfinfo = 0;
317     linkinfo = 0;
318     pbminfo = 0;
319     type3active = 0;
320     clippos = 0;
321     clipping[clippos] = 0;
322     outputstarted = 0;
323     xref = 0;
324     picpos = 0;
325     pic_id = 0;
326     substitutepos = 0;
327     type3Warning = 0;
328     user_movex = 0;
329     user_movey = 0;
330     user_clipx1 = 0;
331     user_clipy1 = 0;
332     user_clipx2 = 0;
333     user_clipy2 = 0;
334     memset(&output, 0, sizeof(output));
335 //    printf("SWFOutputDev::SWFOutputDev() \n");
336 };
337   
338 void SWFOutputDev::setMove(int x,int y)
339 {
340     this->user_movex = x;
341     this->user_movey = y;
342 }
343
344 void SWFOutputDev::setClip(int x1,int y1,int x2,int y2)
345 {
346     if(x2<x1) {int x3=x1;x1=x2;x2=x3;}
347     if(y2<y1) {int y3=y1;y1=y2;y2=y3;}
348
349     this->user_clipx1 = x1;
350     this->user_clipy1 = y1;
351     this->user_clipx2 = x2;
352     this->user_clipy2 = y2;
353 }
354 void SWFOutputDev::getDimensions(int*x1,int*y1,int*x2,int*y2)
355 {
356     if(x1) *x1 = output.swf.movieSize.xmin/20;
357     if(y1) *y1 = output.swf.movieSize.ymin/20;
358     if(x2) *x2 = output.swf.movieSize.xmax/20;
359     if(y2) *y2 = output.swf.movieSize.ymax/20;
360 }
361
362 static char*getFontID(GfxFont*font)
363 {
364     GString*gstr = font->getName();
365     char* fontname = gstr==0?0:gstr->getCString();
366     if(fontname==0) {
367         char buf[32];
368         Ref*r=font->getID();
369         sprintf(buf, "UFONT%d", r->num);
370         return strdup(buf);
371     }
372     return strdup(fontname);
373 }
374
375 static char*getFontName(GfxFont*font)
376 {
377     char*fontid = getFontID(font);
378     char*fontname= 0;
379     char* plus = strchr(fontid, '+');
380     if(plus && plus < &fontid[strlen(fontid)-1]) {
381         fontname = strdup(plus+1);
382     } else {
383         fontname = strdup(fontid);
384     }
385     free(fontid);
386     return fontname;
387 }
388
389 static char mybuf[1024];
390 static char* gfxstate2str(GfxState *state)
391 {
392   char*bufpos = mybuf;
393   GfxRGB rgb;
394   bufpos+=sprintf(bufpos,"CTM[%.3f/%.3f/%.3f/%.3f/%.3f/%.3f] ",
395                                     state->getCTM()[0],
396                                     state->getCTM()[1],
397                                     state->getCTM()[2],
398                                     state->getCTM()[3],
399                                     state->getCTM()[4],
400                                     state->getCTM()[5]);
401   if(state->getX1()!=0.0)
402   bufpos+=sprintf(bufpos,"X1-%.1f ",state->getX1());
403   if(state->getY1()!=0.0)
404   bufpos+=sprintf(bufpos,"Y1-%.1f ",state->getY1());
405   bufpos+=sprintf(bufpos,"X2-%.1f ",state->getX2());
406   bufpos+=sprintf(bufpos,"Y2-%.1f ",state->getY2());
407   bufpos+=sprintf(bufpos,"PW%.1f ",state->getPageWidth());
408   bufpos+=sprintf(bufpos,"PH%.1f ",state->getPageHeight());
409   /*bufpos+=sprintf(bufpos,"FC[%.1f/%.1f] ",
410           state->getFillColor()->c[0], state->getFillColor()->c[1]);
411   bufpos+=sprintf(bufpos,"SC[%.1f/%.1f] ",
412           state->getStrokeColor()->c[0], state->getFillColor()->c[1]);*/
413 /*  bufpos+=sprintf(bufpos,"FC[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f]",
414           state->getFillColor()->c[0], state->getFillColor()->c[1],
415           state->getFillColor()->c[2], state->getFillColor()->c[3],
416           state->getFillColor()->c[4], state->getFillColor()->c[5],
417           state->getFillColor()->c[6], state->getFillColor()->c[7]);
418   bufpos+=sprintf(bufpos,"SC[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f]",
419           state->getStrokeColor()->c[0], state->getFillColor()->c[1],
420           state->getStrokeColor()->c[2], state->getFillColor()->c[3],
421           state->getStrokeColor()->c[4], state->getFillColor()->c[5],
422           state->getStrokeColor()->c[6], state->getFillColor()->c[7]);*/
423   state->getFillRGB(&rgb);
424   if(rgb.r || rgb.g || rgb.b)
425   bufpos+=sprintf(bufpos,"FR[%.1f/%.1f/%.1f] ", rgb.r,rgb.g,rgb.b);
426   state->getStrokeRGB(&rgb);
427   if(rgb.r || rgb.g || rgb.b)
428   bufpos+=sprintf(bufpos,"SR[%.1f/%.1f/%.1f] ", rgb.r,rgb.g,rgb.b);
429   if(state->getFillColorSpace()->getNComps()>1)
430   bufpos+=sprintf(bufpos,"CS[[%d]] ",state->getFillColorSpace()->getNComps());
431   if(state->getStrokeColorSpace()->getNComps()>1)
432   bufpos+=sprintf(bufpos,"SS[[%d]] ",state->getStrokeColorSpace()->getNComps());
433   if(state->getFillPattern())
434   bufpos+=sprintf(bufpos,"FP%08x ", state->getFillPattern());
435   if(state->getStrokePattern())
436   bufpos+=sprintf(bufpos,"SP%08x ", state->getStrokePattern());
437  
438   if(state->getFillOpacity()!=1.0)
439   bufpos+=sprintf(bufpos,"FO%.1f ", state->getFillOpacity());
440   if(state->getStrokeOpacity()!=1.0)
441   bufpos+=sprintf(bufpos,"SO%.1f ", state->getStrokeOpacity());
442
443   bufpos+=sprintf(bufpos,"LW%.1f ", state->getLineWidth());
444  
445   double * dash;
446   int length;
447   double start;
448   state->getLineDash(&dash, &length, &start);
449   int t;
450   if(length)
451   {
452       bufpos+=sprintf(bufpos,"DASH%.1f[",start);
453       for(t=0;t<length;t++) {
454           bufpos+=sprintf(bufpos,"D%.1f",dash[t]);
455       }
456       bufpos+=sprintf(bufpos,"]");
457   }
458
459   if(state->getFlatness()!=1)
460   bufpos+=sprintf(bufpos,"F%d ", state->getFlatness());
461   if(state->getLineJoin()!=0)
462   bufpos+=sprintf(bufpos,"J%d ", state->getLineJoin());
463   if(state->getLineJoin()!=0)
464   bufpos+=sprintf(bufpos,"C%d ", state->getLineCap());
465   if(state->getLineJoin()!=0)
466   bufpos+=sprintf(bufpos,"ML%d ", state->getMiterLimit());
467
468   if(state->getFont() && getFontID(state->getFont()))
469   bufpos+=sprintf(bufpos,"F\"%s\" ",getFontID(state->getFont()));
470   bufpos+=sprintf(bufpos,"FS%.1f ", state->getFontSize());
471   bufpos+=sprintf(bufpos,"MAT[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f] ", state->getTextMat()[0],state->getTextMat()[1],state->getTextMat()[2],
472                                    state->getTextMat()[3],state->getTextMat()[4],state->getTextMat()[5]);
473   if(state->getCharSpace())
474   bufpos+=sprintf(bufpos,"CS%.5f ", state->getCharSpace());
475   if(state->getWordSpace())
476   bufpos+=sprintf(bufpos,"WS%.5f ", state->getWordSpace());
477   if(state->getHorizScaling()!=1.0)
478   bufpos+=sprintf(bufpos,"SC%.1f ", state->getHorizScaling());
479   if(state->getLeading())
480   bufpos+=sprintf(bufpos,"L%.1f ", state->getLeading());
481   if(state->getRise())
482   bufpos+=sprintf(bufpos,"R%.1f ", state->getRise());
483   if(state->getRender())
484   bufpos+=sprintf(bufpos,"R%d ", state->getRender());
485   bufpos+=sprintf(bufpos,"P%08x ", state->getPath());
486   bufpos+=sprintf(bufpos,"CX%.1f ", state->getCurX());
487   bufpos+=sprintf(bufpos,"CY%.1f ", state->getCurY());
488   if(state->getLineX())
489   bufpos+=sprintf(bufpos,"LX%.1f ", state->getLineX());
490   if(state->getLineY())
491   bufpos+=sprintf(bufpos,"LY%.1f ", state->getLineY());
492   bufpos+=sprintf(bufpos," ");
493   return mybuf;
494 }
495
496 static void dumpFontInfo(char*loglevel, GfxFont*font);
497 static int lastdumps[1024];
498 static int lastdumppos = 0;
499 /* nr = 0  unknown
500    nr = 1  substituting
501    nr = 2  type 3
502  */
503 static void showFontError(GfxFont*font, int nr) 
504 {  
505     Ref*r=font->getID();
506     int t;
507     for(t=0;t<lastdumppos;t++)
508         if(lastdumps[t] == r->num)
509             break;
510     if(t < lastdumppos)
511       return;
512     if(lastdumppos<sizeof(lastdumps)/sizeof(int))
513     lastdumps[lastdumppos++] = r->num;
514     if(nr == 0)
515       msg("<warning> The following font caused problems:");
516     else if(nr == 1)
517       msg("<warning> The following font caused problems (substituting):");
518     else if(nr == 2)
519       msg("<warning> The following Type 3 Font will be rendered as bitmap:");
520     dumpFontInfo("<warning>", font);
521 }
522
523 static void dumpFontInfo(char*loglevel, GfxFont*font)
524 {
525   char* name = getFontID(font);
526   Ref* r=font->getID();
527   msg("%s=========== %s (ID:%d,%d) ==========\n", loglevel, getFontName(font), r->num,r->gen);
528
529   GString*gstr  = font->getTag();
530    
531   msg("%s| Tag: %s\n", loglevel, name);
532   
533   if(font->isCIDFont()) msg("%s| is CID font\n", loglevel);
534
535   GfxFontType type=font->getType();
536   switch(type) {
537     case fontUnknownType:
538      msg("%s| Type: unknown\n",loglevel);
539     break;
540     case fontType1:
541      msg("%s| Type: 1\n",loglevel);
542     break;
543     case fontType1C:
544      msg("%s| Type: 1C\n",loglevel);
545     break;
546     case fontType3:
547      msg("%s| Type: 3\n",loglevel);
548     break;
549     case fontTrueType:
550      msg("%s| Type: TrueType\n",loglevel);
551     break;
552     case fontCIDType0:
553      msg("%s| Type: CIDType0\n",loglevel);
554     break;
555     case fontCIDType0C:
556      msg("%s| Type: CIDType0C\n",loglevel);
557     break;
558     case fontCIDType2:
559      msg("%s| Type: CIDType2\n",loglevel);
560     break;
561   }
562   
563   Ref embRef;
564   GBool embedded = font->getEmbeddedFontID(&embRef);
565   if(font->getEmbeddedFontName())
566     name = font->getEmbeddedFontName()->getCString();
567   if(embedded)
568    msg("%s| Embedded name: %s id: %d\n",loglevel, FIXNULL(name), embRef.num);
569
570   gstr = font->getExtFontFile();
571   if(gstr)
572    msg("%s| External Font file: %s\n", loglevel, FIXNULL(gstr->getCString()));
573
574   // Get font descriptor flags.
575   if(font->isFixedWidth()) msg("%s| is fixed width\n", loglevel);
576   if(font->isSerif()) msg("%s| is serif\n", loglevel);
577   if(font->isSymbolic()) msg("%s| is symbolic\n", loglevel);
578   if(font->isItalic()) msg("%s| is italic\n", loglevel);
579   if(font->isBold()) msg("%s| is bold\n", loglevel);
580 }
581
582 //void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str, int width, int height, GBool invert, GBool inlineImg) {printf("void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str, int width, int height, GBool invert, GBool inlineImg) \n");}
583 //void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, GBool inlineImg) {printf("void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, GBool inlineImg) \n");}
584
585 static void free_outline(SWF_OUTLINE*outline)
586 {
587     while(outline) {
588         SWF_OUTLINE*next = outline->link;
589         free(outline);
590         outline = next;
591     }
592 }
593
594 static void dump_outline(SWF_OUTLINE*outline)
595 {
596     double x=0,y=0;
597     while(outline) {
598         double lastx=x,lasty=y;
599         x += (outline->dest.x/(float)0xffff);
600         y += (outline->dest.y/(float)0xffff);
601         if(outline->type == SWF_PATHTYPE_MOVE) {
602             msg("<trace> | moveto %f,%f", x,y);
603         } else if(outline->type == SWF_PATHTYPE_LINE) {
604             msg("<trace> | lineto: %f,%f\n",x,y);
605         } else if(outline->type == SWF_PATHTYPE_BEZIER) {
606             SWF_BEZIERSEGMENT*o2 = (SWF_BEZIERSEGMENT*)outline;
607             float x1 = o2->C.x/(float)0xffff+lastx;
608             float y1 = o2->C.y/(float)0xffff+lasty;
609             float x2 = o2->B.x/(float)0xffff+lastx;
610             float y2 = o2->B.y/(float)0xffff+lasty;
611             msg("<trace> | spline: %f,%f -> %f,%f -> %f,%f\n",x1,y1,x2,y2,x,y);
612         } 
613         outline = outline->link;
614     }
615 }
616
617 SWF_OUTLINE* gfxPath_to_SWF_OUTLINE(GfxState*state, GfxPath*path)
618 {
619     int num = path->getNumSubpaths();
620     int s,t;
621     bezierpathsegment*start,*last=0;
622     bezierpathsegment*outline = start = (bezierpathsegment*)malloc(sizeof(bezierpathsegment));
623     int cpos = 0;
624     double lastx=0,lasty=0;
625     if(!num) {
626         msg("<warning> empty path");
627         outline->type = SWF_PATHTYPE_MOVE;
628         outline->dest.x = 0;
629         outline->dest.y = 0;
630         outline->link = 0;
631         return (SWF_OUTLINE*)outline;
632     }
633     for(t = 0; t < num; t++) {
634         GfxSubpath *subpath = path->getSubpath(t);
635         int subnum = subpath->getNumPoints();
636
637         for(s=0;s<subnum;s++) {
638            double nx,ny;
639            state->transform(subpath->getX(s),subpath->getY(s),&nx,&ny);
640            int x = (int)((nx-lastx)*0xffff);
641            int y = (int)((ny-lasty)*0xffff);
642            if(s==0) 
643            {
644                 last = outline;
645                 outline->type = SWF_PATHTYPE_MOVE;
646                 outline->dest.x = x;
647                 outline->dest.y = y;
648                 outline->link = (SWF_OUTLINE*)malloc(sizeof(bezierpathsegment));
649                 outline = (bezierpathsegment*)outline->link;
650                 cpos = 0;
651                 lastx = nx;
652                 lasty = ny;
653            }
654            else if(subpath->getCurve(s) && !cpos)
655            {
656                 outline->B.x = x;
657                 outline->B.y = y;
658                 cpos = 1;
659            } 
660            else if(subpath->getCurve(s) && cpos)
661            {
662                 outline->C.x = x;
663                 outline->C.y = y;
664                 cpos = 2;
665            }
666            else
667            {
668                 last = outline;
669                 outline->dest.x = x;
670                 outline->dest.y = y;
671                 outline->type = cpos?SWF_PATHTYPE_BEZIER:SWF_PATHTYPE_LINE;
672                 outline->link = (SWF_OUTLINE*)malloc(sizeof(bezierpathsegment));
673                 outline = (bezierpathsegment*)outline->link;
674                 cpos = 0;
675                 lastx = nx;
676                 lasty = ny;
677            }
678         }
679     }
680     if(last->link) {free(last->link);}
681     last->link = 0;
682
683     return (SWF_OUTLINE*)start;
684 }
685 /*----------------------------------------------------------------------------
686  * Primitive Graphic routines
687  *----------------------------------------------------------------------------*/
688
689 void SWFOutputDev::stroke(GfxState *state) 
690 {
691     GfxPath * path = state->getPath();
692     int lineCap = state->getLineCap(); // 0=butt, 1=round 2=square
693     int lineJoin = state->getLineJoin(); // 0=miter, 1=round 2=bevel
694     double miterLimit = state->getMiterLimit();
695     double width = state->getTransformedLineWidth();
696     struct swfmatrix m;
697     GfxRGB rgb;
698     double opaq = state->getStrokeOpacity();
699     state->getStrokeRGB(&rgb);
700
701     m.m11 = 1; m.m21 = 0; m.m22 = 1;
702     m.m12 = 0; m.m13 = 0; m.m23 = 0;
703     SWF_OUTLINE*outline = gfxPath_to_SWF_OUTLINE(state, path);
704     
705     if(getLogLevel() >= LOGLEVEL_TRACE)  {
706         msg("<trace> stroke\n");
707         dump_outline(outline);
708     }
709
710     lineJoin = 1; // other line joins are not yet supported by the swf encoder
711                   // TODO: support bevel joints
712
713     if(((lineCap==1) && (lineJoin==1)) || width<=caplinewidth) {
714         /* FIXME- if the path is smaller than 2 segments, we could ignore
715            lineJoin */
716         swfoutput_setdrawmode(&output, DRAWMODE_STROKE);
717         swfoutput_drawpath(&output, outline, &m);
718     } else {
719         swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
720                                         (char)(rgb.b*255), (char)(opaq*255));
721
722         //swfoutput_setlinewidth(&output, 1.0); //only for debugging
723         //swfoutput_setstrokecolor(&output, 0, 255, 0, 255); //likewise, see below
724         //swfoutput_setfillcolor(&output, 255, 0, 0, 255); //likewise, see below
725
726         swfoutput_drawpath2poly(&output, outline, &m, lineJoin, lineCap, width, miterLimit);
727         updateLineWidth(state);  //reset
728         updateStrokeColor(state); //reset
729         updateFillColor(state);  //reset
730     }
731     free_outline(outline);
732 }
733 void SWFOutputDev::fill(GfxState *state) 
734 {
735     GfxPath * path = state->getPath();
736     struct swfmatrix m;
737     m.m11 = 1; m.m21 = 0; m.m22 = 1;
738     m.m12 = 0; m.m13 = 0; m.m23 = 0;
739     SWF_OUTLINE*outline = gfxPath_to_SWF_OUTLINE(state, path);
740
741     if(getLogLevel() >= LOGLEVEL_TRACE)  {
742         msg("<trace> fill\n");
743         dump_outline(outline);
744     }
745
746     swfoutput_setdrawmode(&output, DRAWMODE_FILL);
747     swfoutput_drawpath(&output, outline, &m);
748     free_outline(outline);
749 }
750 void SWFOutputDev::eoFill(GfxState *state) 
751 {
752     GfxPath * path = state->getPath();
753     struct swfmatrix m;
754     m.m11 = 1; m.m21 = 0; m.m22 = 1;
755     m.m12 = 0; m.m13 = 0; m.m23 = 0;
756     SWF_OUTLINE*outline = gfxPath_to_SWF_OUTLINE(state, path);
757
758     if(getLogLevel() >= LOGLEVEL_TRACE)  {
759         msg("<trace> eofill\n");
760         dump_outline(outline);
761     }
762
763     swfoutput_setdrawmode(&output, DRAWMODE_EOFILL);
764     swfoutput_drawpath(&output, outline, &m);
765     free_outline(outline);
766 }
767 void SWFOutputDev::clip(GfxState *state) 
768 {
769     GfxPath * path = state->getPath();
770     struct swfmatrix m;
771     m.m11 = 1; m.m22 = 1;
772     m.m12 = 0; m.m21 = 0; 
773     m.m13 = 0; m.m23 = 0;
774     SWF_OUTLINE*outline = gfxPath_to_SWF_OUTLINE(state, path);
775
776     if(getLogLevel() >= LOGLEVEL_TRACE)  {
777         msg("<trace> clip\n");
778         dump_outline(outline);
779     }
780
781     swfoutput_startclip(&output, outline, &m);
782     clipping[clippos] ++;
783     free_outline(outline);
784 }
785 void SWFOutputDev::eoClip(GfxState *state) 
786 {
787     GfxPath * path = state->getPath();
788     struct swfmatrix m;
789     m.m11 = 1; m.m21 = 0; m.m22 = 1;
790     m.m12 = 0; m.m13 = 0; m.m23 = 0;
791     SWF_OUTLINE*outline = gfxPath_to_SWF_OUTLINE(state, path);
792
793     if(getLogLevel() >= LOGLEVEL_TRACE)  {
794         msg("<trace> eoclip\n");
795         dump_outline(outline);
796     }
797
798     swfoutput_startclip(&output, outline, &m);
799     clipping[clippos] ++;
800     free_outline(outline);
801 }
802 int SWFOutputDev::save(char*filename)
803 {
804     return swfoutput_save(&output, filename);
805 }
806
807 SWFOutputDev::~SWFOutputDev() 
808 {
809     swfoutput_destroy(&output);
810     outputstarted = 0;
811 };
812 GBool SWFOutputDev::upsideDown() 
813 {
814     msg("<debug> upsidedown? yes");
815     return gTrue;
816 };
817 GBool SWFOutputDev::useDrawChar() 
818 {
819     return gTrue;
820 }
821 GBool SWFOutputDev::useGradients()
822 {
823     if(!gradientinfo)
824     {
825         msg("<notice> File contains gradients");
826         gradientinfo = 1;
827     }
828     return gTrue;
829 }
830
831 void SWFOutputDev::beginString(GfxState *state, GString *s) 
832
833     double m11,m21,m12,m22;
834 //    msg("<debug> %s beginstring \"%s\"\n", gfxstate2str(state), s->getCString());
835     state->getFontTransMat(&m11, &m12, &m21, &m22);
836     m11 *= state->getHorizScaling();
837     m21 *= state->getHorizScaling();
838     swfoutput_setfontmatrix(&output, m11, -m21, m12, -m22);
839 }
840
841 void SWFOutputDev::drawChar(GfxState *state, double x, double y,
842                         double dx, double dy,
843                         double originX, double originY,
844                         CharCode c, Unicode *_u, int uLen)
845 {
846     // check for invisible text -- this is used by Acrobat Capture
847     if ((state->getRender() & 3) == 3)
848         return;
849     Gushort *CIDToGIDMap = 0;
850     GfxFont*font = state->getFont();
851
852     if(font->getType() == fontType3) {
853         /* type 3 chars are passed as graphics */
854         return;
855     }
856     double x1,y1;
857     x1 = x;
858     y1 = y;
859     state->transform(x, y, &x1, &y1);
860     
861     Unicode u=0;
862     char*name=0;
863
864     if(_u && uLen) {
865         u = *_u;
866         if (u) {
867             int t;
868             /* find out char name from unicode index 
869                TODO: should be precomputed
870              */
871             for(t=0;t<sizeof(nameToUnicodeTab)/sizeof(nameToUnicodeTab[0]);t++) {
872                 if(nameToUnicodeTab[t].u == u) {
873                     name = nameToUnicodeTab[t].name;
874                     break;
875                 }
876             }
877         }
878     }
879
880     if(font->isCIDFont()) {
881         GfxCIDFont*cfont = (GfxCIDFont*)font;
882
883         if(font->getType() == fontCIDType2) {
884             CIDToGIDMap = cfont->getCIDToGID();
885         }
886     } else {
887         Gfx8BitFont*font8;
888         font8 = (Gfx8BitFont*)font;
889         char**enc=font8->getEncoding();
890         if(enc && enc[c])
891            name = enc[c];
892     }
893  
894     if (CIDToGIDMap) {
895         msg("<debug> drawChar(%f, %f, c='%c' (%d), GID=%d, u=%d <%d>) CID=%d name=\"%s\"\n", x, y, (c&127)>=32?c:'?', c, CIDToGIDMap[c], u, uLen, font->isCIDFont(), FIXNULL(name));
896         swfoutput_drawchar(&output, x1, y1, name, CIDToGIDMap[c], u);
897     } else {
898         msg("<debug> drawChar(%f,%f,c='%c' (%d), u=%d <%d>) CID=%d name=\"%s\"\n",x,y,(c&127)>=32?c:'?',c,u, uLen, font->isCIDFont(), FIXNULL(name));
899         swfoutput_drawchar(&output, x1, y1, name, c, u);
900     }
901 }
902
903 void SWFOutputDev::endString(GfxState *state) { 
904 }    
905
906  
907 GBool SWFOutputDev::beginType3Char(GfxState *state,
908                                CharCode code, Unicode *u, int uLen)
909 {
910     msg("<debug> beginType3Char %d, %08x, %d", code, *u, uLen);
911     type3active = 1;
912     /* the character itself is going to be passed using
913        drawImageMask() */
914     return gFalse; /* gTrue= is_in_cache? */
915 }
916
917 void SWFOutputDev::endType3Char(GfxState *state)
918 {
919     type3active = 0;
920     msg("<debug> endType3Char");
921 }
922
923 void SWFOutputDev::startPage(int pageNum, GfxState *state, double crop_x1, double crop_y1, double crop_x2, double crop_y2) 
924 {
925     this->currentpage = pageNum;
926     double x1,y1,x2,y2;
927     int rot = doc->getPageRotate(1);
928     laststate = state;
929     msg("<verbose> startPage %d (%f,%f,%f,%f)\n", pageNum, crop_x1, crop_y1, crop_x2, crop_y2);
930     if(rot!=0)
931         msg("<verbose> page is rotated %d degrees\n", rot);
932
933     /* state->transform(state->getX1(),state->getY1(),&x1,&y1);
934     state->transform(state->getX2(),state->getY2(),&x2,&y2);
935     Use CropBox, not MediaBox, as page size
936     */
937     
938     /*x1 = crop_x1;
939     y1 = crop_y1;
940     x2 = crop_x2;
941     y2 = crop_y2;*/
942     state->transform(crop_x1,crop_y1,&x1,&y1);
943     state->transform(crop_x2,crop_y2,&x2,&y2);
944
945     if(x2<x1) {double x3=x1;x1=x2;x2=x3;}
946     if(y2<y1) {double y3=y1;y1=y2;y2=y3;}
947
948     /* apply user clip box */
949     if(user_clipx1|user_clipy1|user_clipx2|user_clipy2) {
950         if(user_clipx1 > x1) x1 = user_clipx1;
951         if(user_clipx2 < x2) x2 = user_clipx2;
952         if(user_clipy1 > y1) y1 = user_clipy1;
953         if(user_clipy2 < y2) y2 = user_clipy2;
954     }
955
956     if(!outputstarted) {
957         msg("<verbose> Bounding box is (%f,%f)-(%f,%f)", x1,y1,x2,y2);
958         swfoutput_init(&output);
959         outputstarted = 1;
960     }
961       
962     swfoutput_newpage(&output, pageNum, user_movex, user_movey, (int)x1, (int)y1, (int)x2, (int)y2);
963 }
964
965 void SWFOutputDev::drawLink(Link *link, Catalog *catalog) 
966 {
967     msg("<debug> drawlink\n");
968     double x1, y1, x2, y2, w;
969     GfxRGB rgb;
970     swfcoord points[5];
971     int x, y;
972
973 #ifdef XPDF_101
974     link->getBorder(&x1, &y1, &x2, &y2, &w);
975 #else
976     link->getRect(&x1, &y1, &x2, &y2);
977 #endif
978     rgb.r = 0;
979     rgb.g = 0;
980     rgb.b = 1;
981     cvtUserToDev(x1, y1, &x, &y);
982     points[0].x = points[4].x = (int)x;
983     points[0].y = points[4].y = (int)y;
984     cvtUserToDev(x2, y1, &x, &y);
985     points[1].x = (int)x;
986     points[1].y = (int)y;
987     cvtUserToDev(x2, y2, &x, &y);
988     points[2].x = (int)x;
989     points[2].y = (int)y;
990     cvtUserToDev(x1, y2, &x, &y);
991     points[3].x = (int)x;
992     points[3].y = (int)y;
993
994     LinkAction*action=link->getAction();
995     char buf[128];
996     char*s = 0;
997     char*type = "-?-";
998     char*url = 0;
999     char*named = 0;
1000     int page = -1;
1001     switch(action->getKind())
1002     {
1003         case actionGoTo: {
1004             type = "GoTo";
1005             LinkGoTo *ha=(LinkGoTo *)link->getAction();
1006             LinkDest *dest=NULL;
1007             if (ha->getDest()==NULL) 
1008                 dest=catalog->findDest(ha->getNamedDest());
1009             else dest=ha->getDest();
1010             if (dest){ 
1011               if (dest->isPageRef()){
1012                 Ref pageref=dest->getPageRef();
1013                 page=catalog->findPage(pageref.num,pageref.gen);
1014               }
1015               else  page=dest->getPageNum();
1016               sprintf(buf, "%d", page);
1017               s = strdup(buf);
1018             }
1019         }
1020         break;
1021         case actionGoToR: {
1022             type = "GoToR";
1023             LinkGoToR*l = (LinkGoToR*)action;
1024             GString*g = l->getNamedDest();
1025             if(g)
1026              s = strdup(g->getCString());
1027         }
1028         break;
1029         case actionNamed: {
1030             type = "Named";
1031             LinkNamed*l = (LinkNamed*)action;
1032             GString*name = l->getName();
1033             if(name) {
1034                 s = strdup(name->lowerCase()->getCString());
1035                 named = name->getCString();
1036                 if(!strchr(s,':')) 
1037                 {
1038                     if(strstr(s, "next") || strstr(s, "forward"))
1039                     {
1040                         page = currentpage + 1;
1041                     }
1042                     else if(strstr(s, "prev") || strstr(s, "back"))
1043                     {
1044                         page = currentpage - 1;
1045                     }
1046                     else if(strstr(s, "last") || strstr(s, "end"))
1047                     {
1048                         page = pagepos>0?pages[pagepos-1]:0;
1049                     }
1050                     else if(strstr(s, "first") || strstr(s, "top"))
1051                     {
1052                         page = 1;
1053                     }
1054                 }
1055             }
1056         }
1057         break;
1058         case actionLaunch: {
1059             type = "Launch";
1060             LinkLaunch*l = (LinkLaunch*)action;
1061             GString * str = new GString(l->getFileName());
1062             str->append(l->getParams());
1063             s = strdup(str->getCString());
1064             delete str;
1065         }
1066         break;
1067         case actionURI: {
1068             type = "URI";
1069             LinkURI*l = (LinkURI*)action;
1070             GString*g = l->getURI();
1071             if(g) {
1072              url = g->getCString();
1073              s = strdup(url);
1074             }
1075         }
1076         break;
1077         case actionUnknown: {
1078             type = "Unknown";
1079             LinkUnknown*l = (LinkUnknown*)action;
1080             s = strdup("");
1081         }
1082         break;
1083         default: {
1084             msg("<error> Unknown link type!\n");
1085             break;
1086         }
1087     }
1088     if(!s) s = strdup("-?-");
1089
1090     if(!linkinfo && (page || url))
1091     {
1092         msg("<notice> File contains links");
1093         linkinfo = 1;
1094     }
1095     if(page>0)
1096     {
1097         int t;
1098         for(t=0;t<pagepos;t++)
1099             if(pages[t]==page)
1100                 break;
1101         if(t!=pagepos)
1102             swfoutput_linktopage(&output, t, points);
1103     }
1104     else if(url)
1105     {
1106         swfoutput_linktourl(&output, url, points);
1107     }
1108     else if(named)
1109     {
1110         swfoutput_namedlink(&output, named, points);
1111     }
1112     msg("<verbose> \"%s\" link to \"%s\" (%d)\n", type, FIXNULL(s), page);
1113     free(s);s=0;
1114 }
1115
1116 void SWFOutputDev::saveState(GfxState *state) {
1117   msg("<debug> saveState\n");
1118   updateAll(state);
1119   if(clippos<64)
1120     clippos ++;
1121   else
1122     msg("<error> Too many nested states in pdf.");
1123   clipping[clippos] = 0;
1124 };
1125
1126 void SWFOutputDev::restoreState(GfxState *state) {
1127   msg("<debug> restoreState\n");
1128   updateAll(state);
1129   while(clipping[clippos]) {
1130       swfoutput_endclip(&output);
1131       clipping[clippos]--;
1132   }
1133   clippos--;
1134 }
1135
1136 char* SWFOutputDev::searchFont(char*name) 
1137 {       
1138     int i;
1139     char*filename=0;
1140     int is_standard_font = 0;
1141         
1142     msg("<verbose> SearchFont(%s)", name);
1143
1144     /* see if it is a pdf standard font */
1145     for(i=0;i<sizeof(pdf2t1map)/sizeof(mapping);i++) 
1146     {
1147         if(!strcmp(name, pdf2t1map[i].pdffont))
1148         {
1149             name = pdf2t1map[i].filename;
1150             is_standard_font = 1;
1151             break;
1152         }
1153     }
1154     /* look in all font files */
1155     for(i=0;i<fontnum;i++) 
1156     {
1157         if(strstr(fonts[i].filename, name))
1158         {
1159             if(!fonts[i].used) {
1160
1161                 fonts[i].used = 1;
1162                 if(!is_standard_font)
1163                     msg("<notice> Using %s for %s", fonts[i].filename, name);
1164             }
1165             return strdup(fonts[i].filename);
1166         }
1167     }
1168     return 0;
1169 }
1170
1171 void SWFOutputDev::updateLineWidth(GfxState *state)
1172 {
1173     double width = state->getTransformedLineWidth();
1174     swfoutput_setlinewidth(&output, width);
1175 }
1176
1177 void SWFOutputDev::updateLineCap(GfxState *state)
1178 {
1179     int c = state->getLineCap();
1180 }
1181
1182 void SWFOutputDev::updateLineJoin(GfxState *state)
1183 {
1184     int j = state->getLineJoin();
1185 }
1186
1187 void SWFOutputDev::updateFillColor(GfxState *state) 
1188 {
1189     GfxRGB rgb;
1190     double opaq = state->getFillOpacity();
1191     state->getFillRGB(&rgb);
1192
1193     swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
1194                                     (char)(rgb.b*255), (char)(opaq*255));
1195 }
1196
1197 void SWFOutputDev::updateStrokeColor(GfxState *state) 
1198 {
1199     GfxRGB rgb;
1200     double opaq = state->getStrokeOpacity();
1201     state->getStrokeRGB(&rgb);
1202
1203     swfoutput_setstrokecolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
1204                                       (char)(rgb.b*255), (char)(opaq*255));
1205 }
1206
1207 void FoFiWrite(void *stream, char *data, int len)
1208 {
1209    fwrite(data, len, 1, (FILE*)stream);
1210 }
1211
1212 char*SWFOutputDev::writeEmbeddedFontToFile(XRef*ref, GfxFont*font)
1213 {
1214     char*tmpFileName = NULL;
1215     FILE *f;
1216     int c;
1217     char *fontBuf;
1218     int fontLen;
1219     Ref embRef;
1220     Object refObj, strObj;
1221     char namebuf[512];
1222     tmpFileName = mktmpname(namebuf);
1223     int ret;
1224
1225     ret = font->getEmbeddedFontID(&embRef);
1226     if(!ret) {
1227         msg("<verbose> Didn't get embedded font id");
1228         /* not embedded- the caller should now search the font
1229            directories for this font */
1230         return 0;
1231     }
1232
1233     f = fopen(tmpFileName, "wb");
1234     if (!f) {
1235       msg("<error> Couldn't create temporary Type 1 font file");
1236         return 0;
1237     }
1238
1239     /*if(font->isCIDFont()) {
1240         GfxCIDFont* cidFont = (GfxCIDFont *)font;
1241         GString c = cidFont->getCollection();
1242         msg("<notice> Collection: %s", c.getCString());
1243     }*/
1244
1245     if (font->getType() == fontType1C ||
1246         font->getType() == fontCIDType0C) {
1247       if (!(fontBuf = font->readEmbFontFile(xref, &fontLen))) {
1248         fclose(f);
1249         msg("<error> Couldn't read embedded font file");
1250         return 0;
1251       }
1252 #ifdef XPDF_101
1253       Type1CFontFile *cvt = new Type1CFontFile(fontBuf, fontLen);
1254       cvt->convertToType1(f);
1255 #else
1256       FoFiType1C *cvt = FoFiType1C::make(fontBuf, fontLen);
1257       cvt->convertToType1(NULL, gTrue, FoFiWrite, f);
1258 #endif
1259       //cvt->convertToCIDType0("test", f);
1260       //cvt->convertToType0("test", f);
1261       delete cvt;
1262       gfree(fontBuf);
1263     } else if(font->getType() == fontTrueType) {
1264       msg("<verbose> writing font using TrueTypeFontFile::writeTTF");
1265       if (!(fontBuf = font->readEmbFontFile(xref, &fontLen))) {
1266         fclose(f);
1267         msg("<error> Couldn't read embedded font file");
1268         return 0;
1269       }
1270 #ifdef XPDF_101
1271       TrueTypeFontFile *cvt = new TrueTypeFontFile(fontBuf, fontLen);
1272       cvt->writeTTF(f);
1273 #else
1274       FoFiTrueType *cvt = FoFiTrueType::make(fontBuf, fontLen);
1275       cvt->writeTTF(FoFiWrite, f);
1276 #endif
1277       delete cvt;
1278       gfree(fontBuf);
1279     } else {
1280       font->getEmbeddedFontID(&embRef);
1281       refObj.initRef(embRef.num, embRef.gen);
1282       refObj.fetch(ref, &strObj);
1283       refObj.free();
1284       strObj.streamReset();
1285       int f4[4];
1286       char f4c[4];
1287       int t;
1288       for(t=0;t<4;t++) {
1289           f4[t] = strObj.streamGetChar();
1290           f4c[t] = (char)f4[t];
1291           if(f4[t] == EOF)
1292               break;
1293       }
1294       if(t==4) {
1295           if(!strncmp(f4c, "true", 4)) {
1296               /* some weird TTF fonts don't start with 0,1,0,0 but with "true".
1297                  Change this on the fly */
1298               f4[0] = f4[2] = f4[3] = 0;
1299               f4[1] = 1;
1300           }
1301           fputc(f4[0], f);
1302           fputc(f4[1], f);
1303           fputc(f4[2], f);
1304           fputc(f4[3], f);
1305
1306           while ((c = strObj.streamGetChar()) != EOF) {
1307             fputc(c, f);
1308           }
1309       }
1310       strObj.streamClose();
1311       strObj.free();
1312     }
1313     fclose(f);
1314
1315     return strdup(tmpFileName);
1316 }
1317     
1318 char* searchForSuitableFont(GfxFont*gfxFont)
1319 {
1320     char*name = getFontName(gfxFont);
1321     char*fontname = 0;
1322     char*filename = 0;
1323
1324     if(!config_use_fontconfig)
1325         return 0;
1326     
1327 #ifdef HAVE_FONTCONFIG
1328     FcPattern *pattern, *match;
1329     FcResult result;
1330     FcChar8 *v;
1331
1332     static int fcinitcalled = false; 
1333         
1334     msg("<debug> searchForSuitableFont(%s)", name);
1335     
1336     // call init ony once
1337     if (!fcinitcalled) {
1338         msg("<debug> Initializing FontConfig...");
1339         fcinitcalled = true;
1340         if(FcInit()) {
1341             msg("<debug> FontConfig Initialization failed. Disabling.");
1342             config_use_fontconfig = 0;
1343             return 0;
1344         }
1345         msg("<debug> ...initialized FontConfig");
1346     }
1347    
1348     msg("<debug> FontConfig: Create \"%s\" Family Pattern", name);
1349     pattern = FcPatternBuild(NULL, FC_FAMILY, FcTypeString, name, NULL);
1350     if (gfxFont->isItalic()) // check for italic
1351         msg("<debug> FontConfig: Adding Italic Slant");
1352         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1353     if (gfxFont->isBold()) // check for bold
1354         msg("<debug> FontConfig: Adding Bold Weight");
1355         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1356
1357     msg("<debug> FontConfig: Try to match...");
1358     // configure and match using the original font name 
1359     FcConfigSubstitute(0, pattern, FcMatchPattern); 
1360     FcDefaultSubstitute(pattern);
1361     match = FcFontMatch(0, pattern, &result);
1362     
1363     if (FcPatternGetString(match, "family", 0, &v) == FcResultMatch) {
1364         msg("<debug> FontConfig: family=%s", (char*)v);
1365         // if we get an exact match
1366         if (strcmp((char *)v, name) == 0) {
1367             if (FcPatternGetString(match, "file", 0, &v) == FcResultMatch) {
1368                 filename = strdup((char*)v);
1369                 char *nfn = strrchr(filename, '/');
1370                 if(nfn) fontname = strdup(nfn+1);
1371                 else    fontname = filename;
1372             }
1373             msg("<debug> FontConfig: Returning \"%s\"", fontname);
1374         } else {
1375             // initialize patterns
1376             FcPatternDestroy(pattern);
1377             FcPatternDestroy(match);
1378
1379             // now match against serif etc.
1380             if (gfxFont->isSerif()) {
1381                 msg("<debug> FontConfig: Create Serif Family Pattern");
1382                 pattern = FcPatternBuild (NULL, FC_FAMILY, FcTypeString, "serif", NULL);
1383             } else if (gfxFont->isFixedWidth()) {
1384                 msg("<debug> FontConfig: Create Monospace Family Pattern");
1385                 pattern = FcPatternBuild (NULL, FC_FAMILY, FcTypeString, "monospace", NULL);
1386             } else {
1387                 msg("<debug> FontConfig: Create Sans Family Pattern");
1388                 pattern = FcPatternBuild (NULL, FC_FAMILY, FcTypeString, "sans", NULL);
1389             }
1390
1391             // check for italic
1392             if (gfxFont->isItalic()) {
1393                 msg("<debug> FontConfig: Adding Italic Slant");
1394                 int bb = FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1395             }
1396             // check for bold
1397             if (gfxFont->isBold()) {
1398                 msg("<debug> FontConfig: Adding Bold Weight");
1399                 int bb = FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1400             }
1401
1402             msg("<debug> FontConfig: Try to match... (2)");
1403             // configure and match using serif etc
1404             FcConfigSubstitute (0, pattern, FcMatchPattern);
1405             FcDefaultSubstitute (pattern);
1406             match = FcFontMatch (0, pattern, &result);
1407             
1408             if (FcPatternGetString(match, "file", 0, &v) == FcResultMatch) {
1409                 filename = strdup((char*)v);
1410                 char *nfn = strrchr(filename, '/');
1411                 if(nfn) fontname = strdup(nfn+1);
1412                 else    fontname = filename;
1413             }
1414             msg("<debug> FontConfig: Returning \"%s\"", fontname);
1415         }        
1416     }
1417
1418     //printf("FONTCONFIG: pattern");
1419     //FcPatternPrint(pattern);
1420     //printf("FONTCONFIG: match");
1421     //FcPatternPrint(match);
1422  
1423     FcPatternDestroy(pattern);
1424     FcPatternDestroy(match);
1425
1426     pdfswf_addfont(filename);
1427     return fontname;
1428 #else
1429     return 0;
1430 #endif
1431 }
1432
1433 char* SWFOutputDev::substituteFont(GfxFont*gfxFont, char* oldname)
1434 {
1435     char*fontname = 0, *filename = 0;
1436     msg("<notice> subsituteFont(%s)", oldname);
1437
1438     if(!(fontname = searchForSuitableFont(gfxFont))) {
1439         fontname = "Times-Roman";
1440     }
1441     filename = searchFont(fontname);
1442
1443     if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
1444         msg("<fatal> Too many fonts in file.");
1445         exit(1);
1446     }
1447     if(oldname) {
1448         substitutesource[substitutepos] = oldname;
1449         substitutetarget[substitutepos] = fontname;
1450         msg("<notice> substituting %s -> %s", FIXNULL(oldname), FIXNULL(fontname));
1451         substitutepos ++;
1452     }
1453     return strdup(filename);
1454 }
1455
1456 void unlinkfont(char* filename)
1457 {
1458     int l;
1459     if(!filename)
1460         return;
1461     l=strlen(filename);
1462     unlink(filename);
1463     if(!strncmp(&filename[l-4],".afm",4)) {
1464         memcpy(&filename[l-4],".pfb",4);
1465         unlink(filename);
1466         memcpy(&filename[l-4],".pfa",4);
1467         unlink(filename);
1468         memcpy(&filename[l-4],".afm",4);
1469         return;
1470     } else 
1471     if(!strncmp(&filename[l-4],".pfa",4)) {
1472         memcpy(&filename[l-4],".afm",4);
1473         unlink(filename);
1474         memcpy(&filename[l-4],".pfa",4);
1475         return;
1476     } else 
1477     if(!strncmp(&filename[l-4],".pfb",4)) {
1478         memcpy(&filename[l-4],".afm",4);
1479         unlink(filename);
1480         memcpy(&filename[l-4],".pfb",4);
1481         return;
1482     }
1483 }
1484
1485 void SWFOutputDev::setXRef(PDFDoc*doc, XRef *xref) 
1486 {
1487     this->doc = doc;
1488     this->xref = xref;
1489 }
1490
1491
1492 void SWFOutputDev::updateFont(GfxState *state) 
1493 {
1494     GfxFont*gfxFont = state->getFont();
1495       
1496     if (!gfxFont) {
1497         return;
1498     }  
1499     char * fontid = getFontID(gfxFont);
1500     
1501     int t;
1502     /* first, look if we substituted this font before-
1503        this way, we don't initialize the T1 Fonts
1504        too often */
1505     for(t=0;t<substitutepos;t++) {
1506         if(!strcmp(fontid, substitutesource[t])) {
1507             fontid = substitutetarget[t];
1508             break;
1509         }
1510     }
1511
1512     /* second, see if swfoutput already has this font
1513        cached- if so, we are done */
1514     if(swfoutput_queryfont(&output, fontid))
1515     {
1516         swfoutput_setfont(&output, fontid, 0);
1517         
1518         msg("<debug> updateFont(%s) [cached]", fontid);
1519         return;
1520     }
1521
1522     // look for Type 3 font
1523     if (gfxFont->getType() == fontType3) {
1524         if(!type3Warning) {
1525             type3Warning = gTrue;
1526             showFontError(gfxFont, 2);
1527         }
1528         return;
1529     }
1530
1531     /* now either load the font, or find a substitution */
1532
1533     Ref embRef;
1534     GBool embedded = gfxFont->getEmbeddedFontID(&embRef);
1535
1536     char*fileName = 0;
1537     int del = 0;
1538     if(embedded &&
1539        (gfxFont->getType() == fontType1 ||
1540         gfxFont->getType() == fontType1C ||
1541         //gfxFont->getType() == fontCIDType0C ||
1542         gfxFont->getType() == fontTrueType ||
1543         gfxFont->getType() == fontCIDType2
1544        ))
1545     {
1546       fileName = writeEmbeddedFontToFile(xref, gfxFont);
1547       if(!fileName) showFontError(gfxFont,0);
1548       else del = 1;
1549     } else {
1550       char * fontname = getFontName(gfxFont);
1551       fileName = searchFont(fontname);
1552       if(!fileName) showFontError(gfxFont,0);
1553     }
1554     if(!fileName) {
1555         char * fontname = getFontName(gfxFont);
1556         msg("<warning> Font %s %scould not be loaded.", fontname, embedded?"":"(not embedded) ");
1557         msg("<warning> Try putting a TTF version of that font (named \"%s.ttf\") into /swftools/fonts", fontname);
1558         fileName = substituteFont(gfxFont, fontid);
1559         if(fontid) { fontid = substitutetarget[substitutepos-1]; /*ugly hack*/};
1560         msg("<notice> Font is now %s (%s)", fontid, fileName);
1561     }
1562
1563     if(!fileName) {
1564         msg("<error> Couldn't set font %s\n", fontid);
1565         return;
1566     }
1567         
1568     msg("<verbose> updateFont(%s) -> %s", fontid, fileName);
1569     dumpFontInfo("<verbose>", gfxFont);
1570
1571     swfoutput_setfont(&output, fontid, fileName);
1572    
1573     if(fileName && del)
1574         unlinkfont(fileName);
1575     if(fileName)
1576         free(fileName);
1577 }
1578
1579 #define SQR(x) ((x)*(x))
1580
1581 unsigned char* antialize(unsigned char*data, int width, int height, int newwidth, int newheight, int palettesize)
1582 {
1583     if((newwidth<2 || newheight<2) ||
1584        (width<=newwidth || height<=newheight))
1585         return 0;
1586     unsigned char*newdata;
1587     int x,y;
1588     newdata= (unsigned char*)malloc(newwidth*newheight);
1589     int t;
1590     double fx = (double)(width)/newwidth;
1591     double fy = (double)(height)/newheight;
1592     double px = 0;
1593     int blocksize = (int)(8192/(fx*fy));
1594     int r = 8192*256/palettesize;
1595     for(x=0;x<newwidth;x++) {
1596         double ex = px + fx;
1597         int fromx = (int)px;
1598         int tox = (int)ex;
1599         int xweight1 = (int)(((fromx+1)-px)*256);
1600         int xweight2 = (int)((ex-tox)*256);
1601         double py =0;
1602         for(y=0;y<newheight;y++) {
1603             double ey = py + fy;
1604             int fromy = (int)py;
1605             int toy = (int)ey;
1606             int yweight1 = (int)(((fromy+1)-py)*256);
1607             int yweight2 = (int)((ey-toy)*256);
1608             int a = 0;
1609             int xx,yy;
1610             for(xx=fromx;xx<=tox;xx++)
1611             for(yy=fromy;yy<=toy;yy++) {
1612                 int b = 1-data[width*yy+xx];
1613                 int weight=256;
1614                 if(xx==fromx) weight = (weight*xweight1)/256;
1615                 if(xx==tox) weight = (weight*xweight2)/256;
1616                 if(yy==fromy) weight = (weight*yweight1)/256;
1617                 if(yy==toy) weight = (weight*yweight2)/256;
1618                 a+=b*weight;
1619             }
1620             //if(a) a=(palettesize-1)*r/blocksize;
1621             newdata[y*newwidth+x] = (a*blocksize)/r;
1622             py = ey;
1623         }
1624         px = ex;
1625     }
1626     return newdata;
1627 }
1628
1629 void SWFOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
1630                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
1631                                    GBool inlineImg, int mask)
1632 {
1633   FILE *fi;
1634   int c;
1635   char fileName[128];
1636   double x1,y1,x2,y2,x3,y3,x4,y4;
1637   ImageStream *imgStr;
1638   Guchar pixBuf[4];
1639   GfxRGB rgb;
1640   int ncomps = 1;
1641   int bits = 1;
1642                                  
1643   if(colorMap) {
1644     ncomps = colorMap->getNumPixelComps();
1645     bits = colorMap->getBits();
1646   }
1647   imgStr = new ImageStream(str, width, ncomps,bits);
1648   imgStr->reset();
1649
1650   if(!width || !height || (height<=1 && width<=1))
1651   {
1652       msg("<verbose> Ignoring %d by %d image", width, height);
1653       unsigned char buf[8];
1654       int x,y;
1655       for (y = 0; y < height; ++y)
1656       for (x = 0; x < width; ++x) {
1657           imgStr->getPixel(buf);
1658       }
1659       delete imgStr;
1660       return;
1661   }
1662   
1663   state->transform(0, 1, &x1, &y1);
1664   state->transform(0, 0, &x2, &y2);
1665   state->transform(1, 0, &x3, &y3);
1666   state->transform(1, 1, &x4, &y4);
1667
1668   if(!pbminfo && !(str->getKind()==strDCT)) {
1669       if(!type3active) {
1670           msg("<notice> file contains pbm pictures %s",mask?"(masked)":"");
1671           pbminfo = 1;
1672       }
1673       if(mask)
1674       msg("<verbose> drawing %d by %d masked picture\n", width, height);
1675   }
1676   if(!jpeginfo && (str->getKind()==strDCT)) {
1677       msg("<notice> file contains jpeg pictures");
1678       jpeginfo = 1;
1679   }
1680
1681   if(mask) {
1682       int yes=0,i,j;
1683       unsigned char buf[8];
1684       int xid = 0;
1685       int yid = 0;
1686       int x,y;
1687       unsigned char*pic = new unsigned char[width*height];
1688       RGBA pal[256];
1689       GfxRGB rgb;
1690       state->getFillRGB(&rgb);
1691       memset(pal,255,sizeof(pal));
1692       pal[0].r = (int)(rgb.r*255); pal[0].g = (int)(rgb.g*255); 
1693       pal[0].b = (int)(rgb.b*255); pal[0].a = 255;
1694       pal[1].r = 0; pal[1].g = 0; pal[1].b = 0; pal[1].a = 0;
1695       int numpalette = 2;
1696       xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1697       yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1698       int realwidth = (int)sqrt(SQR(x2-x3) + SQR(y2-y3));
1699       int realheight = (int)sqrt(SQR(x1-x2) + SQR(y1-y2));
1700       for (y = 0; y < height; ++y)
1701       for (x = 0; x < width; ++x)
1702       {
1703             imgStr->getPixel(buf);
1704             if(invert) 
1705                 buf[0]=1-buf[0];
1706             pic[width*y+x] = buf[0];
1707             xid+=x*buf[0]+1;
1708             yid+=y*buf[0]*3+1;
1709       }
1710       
1711       /* the size of the drawn image is added to the identifier
1712          as the same image may require different bitmaps if displayed
1713          at different sizes (due to antialiasing): */
1714       if(type3active) {
1715           xid += realwidth;
1716           yid += realheight;
1717       }
1718       int t,found = -1;
1719       for(t=0;t<picpos;t++)
1720       {
1721           if(pic_xids[t] == xid &&
1722              pic_yids[t] == yid) {
1723               /* if the image was antialiased, the size has changed: */
1724               width = pic_width[t];
1725               height = pic_height[t];
1726               found = t;break;
1727           }
1728       }
1729       if(found<0) {
1730           if(type3active) {
1731               numpalette = 16;
1732               unsigned char*pic2 = 0;
1733               
1734               pic2 = antialize(pic,width,height,realwidth,realheight, numpalette);
1735
1736               if(pic2) {
1737                   width = realwidth;
1738                   height = realheight;
1739                   free(pic);
1740                   pic = pic2;
1741                   /* make a black/white palette */
1742                   int t;
1743                   GfxRGB rgb2;
1744                   rgb2.r = 1 - rgb.r;
1745                   rgb2.g = 1 - rgb.g;
1746                   rgb2.b = 1 - rgb.b;
1747
1748                   float r = 255/(numpalette-1);
1749                   for(t=0;t<numpalette;t++) {
1750                       /*pal[t].r = (U8)(t*r*rgb.r+(numpalette-1-t)*r*rgb2.r);
1751                       pal[t].g = (U8)(t*r*rgb.g+(numpalette-1-t)*r*rgb2.g);
1752                       pal[t].b = (U8)(t*r*rgb.b+(numpalette-1-t)*r*rgb2.b);
1753                       pal[t].a = 255; */
1754                       pal[t].r = (U8)(255*rgb.r);
1755                       pal[t].g = (U8)(255*rgb.g);
1756                       pal[t].b = (U8)(255*rgb.b);
1757                       pal[t].a = (U8)(t*r);
1758                   }
1759               }
1760           }
1761           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, 
1762                   x1,y1,x2,y2,x3,y3,x4,y4, numpalette);
1763           pic_xids[picpos] = xid;
1764           pic_yids[picpos] = yid;
1765           pic_width[picpos] = width;
1766           pic_height[picpos] = height;
1767           if(picpos<1024)
1768               picpos++;
1769       } else {
1770           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1771                   x1,y1,x2,y2,x3,y3,x4,y4);
1772       }
1773       free(pic);
1774       delete imgStr;
1775       return;
1776   } 
1777
1778   int x,y;
1779   
1780   if(colorMap->getNumPixelComps()!=1 || str->getKind()==strDCT)
1781   {
1782       RGBA*pic=new RGBA[width*height];
1783       int xid = 0;
1784       int yid = 0;
1785       for (y = 0; y < height; ++y) {
1786         for (x = 0; x < width; ++x) {
1787           int r,g,b,a;
1788           imgStr->getPixel(pixBuf);
1789           colorMap->getRGB(pixBuf, &rgb);
1790           pic[width*y+x].r = r = (U8)(rgb.r * 255 + 0.5);
1791           pic[width*y+x].g = g = (U8)(rgb.g * 255 + 0.5);
1792           pic[width*y+x].b = b = (U8)(rgb.b * 255 + 0.5);
1793           pic[width*y+x].a = a = 255;//(U8)(rgb.a * 255 + 0.5);
1794           xid += x*r+x*b*3+x*g*7+x*a*11;
1795           yid += y*r*3+y*b*17+y*g*19+y*a*11;
1796         }
1797       }
1798       int t,found = -1;
1799       for(t=0;t<picpos;t++)
1800       {
1801           if(pic_xids[t] == xid &&
1802              pic_yids[t] == yid) {
1803               found = t;break;
1804           }
1805       }
1806       if(found<0) {
1807           if(str->getKind()==strDCT)
1808               pic_ids[picpos] = swfoutput_drawimagejpeg(&output, pic, width, height, 
1809                       x1,y1,x2,y2,x3,y3,x4,y4);
1810           else
1811               pic_ids[picpos] = swfoutput_drawimagelossless(&output, pic, width, height, 
1812                       x1,y1,x2,y2,x3,y3,x4,y4);
1813           pic_xids[picpos] = xid;
1814           pic_yids[picpos] = yid;
1815           pic_width[picpos] = width;
1816           pic_height[picpos] = height;
1817           if(picpos<1024)
1818               picpos++;
1819       } else {
1820           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1821                   x1,y1,x2,y2,x3,y3,x4,y4);
1822       }
1823       delete pic;
1824       delete imgStr;
1825       return;
1826   }
1827   else
1828   {
1829       U8*pic = new U8[width*height];
1830       RGBA pal[256];
1831       int t;
1832       int xid=0,yid=0;
1833       for(t=0;t<256;t++)
1834       {
1835           int r,g,b,a;
1836           pixBuf[0] = t;
1837           colorMap->getRGB(pixBuf, &rgb);
1838           pal[t].r = r = (U8)(rgb.r * 255 + 0.5);
1839           pal[t].g = g = (U8)(rgb.g * 255 + 0.5);
1840           pal[t].b = b = (U8)(rgb.b * 255 + 0.5);
1841           pal[t].a = a = 255;//(U8)(rgb.b * 255 + 0.5);
1842           xid += t*r+t*b*3+t*g*7+t*a*11;
1843           xid += (~t)*r+t*b*3+t*g*7+t*a*11;
1844       }
1845       for (y = 0; y < height; ++y) {
1846         for (x = 0; x < width; ++x) {
1847           imgStr->getPixel(pixBuf);
1848           pic[width*y+x] = pixBuf[0];
1849           xid += x*pixBuf[0]*7;
1850           yid += y*pixBuf[0]*3;
1851         }
1852       }
1853       int found = -1;
1854       for(t=0;t<picpos;t++)
1855       {
1856           if(pic_xids[t] == xid &&
1857              pic_yids[t] == yid) {
1858               found = t;break;
1859           }
1860       }
1861       if(found<0) {
1862           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, 
1863                   x1,y1,x2,y2,x3,y3,x4,y4,256);
1864           pic_xids[picpos] = xid;
1865           pic_yids[picpos] = yid;
1866           pic_width[picpos] = width;
1867           pic_height[picpos] = height;
1868           if(picpos<1024)
1869               picpos++;
1870       } else {
1871           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1872                   x1,y1,x2,y2,x3,y3,x4,y4);
1873       }
1874       delete pic;
1875       delete imgStr;
1876       return;
1877   }
1878 }
1879
1880 void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1881                                    int width, int height, GBool invert,
1882                                    GBool inlineImg) 
1883 {
1884   msg("<verbose> drawImageMask %dx%d, invert=%d inline=%d", width, height, invert, inlineImg);
1885   drawGeneralImage(state,ref,str,width,height,0,invert,inlineImg,1);
1886 }
1887
1888 void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1889                          int width, int height, GfxImageColorMap *colorMap,
1890                          int *maskColors, GBool inlineImg)
1891 {
1892   msg("<verbose> drawImage %dx%d, %s %s, inline=%d", width, height, 
1893           colorMap?"colorMap":"no colorMap", 
1894           maskColors?"maskColors":"no maskColors",
1895           inlineImg);
1896   if(colorMap)
1897       msg("<verbose> colorMap pixcomps:%d bits:%d mode:%d\n", colorMap->getNumPixelComps(),
1898               colorMap->getBits(),colorMap->getColorSpace()->getMode());
1899   drawGeneralImage(state,ref,str,width,height,colorMap,0,inlineImg,0);
1900 }
1901
1902 SWFOutputDev*output = 0; 
1903
1904 static void printInfoString(Dict *infoDict, char *key, char *fmt) {
1905   Object obj;
1906   GString *s1, *s2;
1907   int i;
1908
1909   if (infoDict->lookup(key, &obj)->isString()) {
1910     s1 = obj.getString();
1911     if ((s1->getChar(0) & 0xff) == 0xfe &&
1912         (s1->getChar(1) & 0xff) == 0xff) {
1913       s2 = new GString();
1914       for (i = 2; i < obj.getString()->getLength(); i += 2) {
1915         if (s1->getChar(i) == '\0') {
1916           s2->append(s1->getChar(i+1));
1917         } else {
1918           delete s2;
1919           s2 = new GString("<unicode>");
1920           break;
1921         }
1922       }
1923       printf(fmt, s2->getCString());
1924       delete s2;
1925     } else {
1926       printf(fmt, s1->getCString());
1927     }
1928   }
1929   obj.free();
1930 }
1931
1932 static void printInfoDate(Dict *infoDict, char *key, char *fmt) {
1933   Object obj;
1934   char *s;
1935
1936   if (infoDict->lookup(key, &obj)->isString()) {
1937     s = obj.getString()->getCString();
1938     if (s[0] == 'D' && s[1] == ':') {
1939       s += 2;
1940     }
1941     printf(fmt, s);
1942   }
1943   obj.free();
1944 }
1945
1946 void pdfswf_setparameter(char*name, char*value)
1947 {
1948     msg("<verbose> setting parameter %s to \"%s\"", name, value);
1949     if(!strcmp(name, "caplinewidth")) {
1950         caplinewidth = atof(value);
1951     } else if(!strcmp(name, "zoom")) {
1952         zoom = atoi(value);
1953     } else if(!strcmp(name, "fontdir")) {
1954         pdfswf_addfontdir(value);
1955     } else if(!strcmp(name, "languagedir")) {
1956         pdfswf_addlanguagedir(value);
1957     } else if(!strcmp(name, "fontconfig")) {
1958         config_use_fontconfig = atoi(value);
1959     } else {
1960         swfoutput_setparameter(name, value);
1961     }
1962 }
1963 void pdfswf_addfont(char*filename)
1964 {
1965     fontfile_t f;
1966     memset(&f, 0, sizeof(fontfile_t));
1967     f.filename = filename;
1968     if(fontnum < sizeof(fonts)/sizeof(fonts[0])) {
1969         fonts[fontnum++] = f;
1970     } else {
1971         msg("<error> Too many external fonts. Not adding font file \"%s\".", filename);
1972     }
1973 }
1974
1975 static char* dirseparator()
1976 {
1977 #ifdef WIN32
1978     return "\\";
1979 #else
1980     return "/";
1981 #endif
1982 }
1983
1984 void pdfswf_addlanguagedir(char*dir)
1985 {
1986     if(!globalParams)
1987         globalParams = new GlobalParams("");
1988     
1989     msg("<notice> Adding %s to language pack directories", dir);
1990
1991     int l;
1992     FILE*fi = 0;
1993     char* config_file = (char*)malloc(strlen(dir) + 1 + sizeof("add-to-xpdfrc"));
1994     strcpy(config_file, dir);
1995     strcat(config_file, dirseparator());
1996     strcat(config_file, "add-to-xpdfrc");
1997
1998     fi = fopen(config_file, "rb");
1999     if(!fi) {
2000         msg("<error> Could not open %s", config_file);
2001         return;
2002     }
2003     globalParams->parseFile(new GString(config_file), fi);
2004     fclose(fi);
2005 }
2006
2007 void pdfswf_addfontdir(char*dirname)
2008 {
2009 #ifdef HAVE_DIRENT_H
2010     msg("<notice> Adding %s to font directories", dirname);
2011     DIR*dir = opendir(dirname);
2012     if(!dir) {
2013         msg("<warning> Couldn't open directory %s\n", dirname);
2014         return;
2015     }
2016     struct dirent*ent;
2017     while(1) {
2018         ent = readdir (dir);
2019         if (!ent) 
2020             break;
2021         int l;
2022         char*name = ent->d_name;
2023         char type = 0;
2024         if(!name) continue;
2025         l=strlen(name);
2026         if(l<4)
2027             continue;
2028         if(!strncasecmp(&name[l-4], ".pfa", 4)) 
2029             type=1;
2030         if(!strncasecmp(&name[l-4], ".pfb", 4)) 
2031             type=3;
2032         if(!strncasecmp(&name[l-4], ".ttf", 4)) 
2033             type=2;
2034         if(type)
2035         {
2036             char*fontname = (char*)malloc(strlen(dirname)+strlen(name)+2);
2037             strcpy(fontname, dirname);
2038             strcat(fontname, dirseparator());
2039             strcat(fontname, name);
2040             msg("<verbose> Adding %s to fonts", fontname);
2041             pdfswf_addfont(fontname);
2042         }
2043     }
2044     closedir(dir);
2045 #else
2046     msg("<warning> No dirent.h- unable to add font dir %s", dir);
2047 #endif
2048 }
2049
2050
2051 typedef struct _pdf_doc_internal
2052 {
2053     int protect;
2054     PDFDoc*doc;
2055 } pdf_doc_internal_t;
2056 typedef struct _pdf_page_internal
2057 {
2058 } pdf_page_internal_t;
2059 typedef struct _swf_output_internal
2060 {
2061     SWFOutputDev*outputDev;
2062 } swf_output_internal_t;
2063
2064 pdf_doc_t* pdf_init(char*filename, char*userPassword)
2065 {
2066     pdf_doc_t*pdf_doc = (pdf_doc_t*)malloc(sizeof(pdf_doc_t));
2067     memset(pdf_doc, 0, sizeof(pdf_doc_t));
2068     pdf_doc_internal_t*i= (pdf_doc_internal_t*)malloc(sizeof(pdf_doc_internal_t));
2069     memset(i, 0, sizeof(pdf_doc_internal_t));
2070     pdf_doc->internal = i;
2071     
2072     GString *fileName = new GString(filename);
2073     GString *userPW;
2074     Object info;
2075
2076     // read config file
2077     if(!globalParams)
2078         globalParams = new GlobalParams("");
2079
2080     // open PDF file
2081     if (userPassword && userPassword[0]) {
2082       userPW = new GString(userPassword);
2083     } else {
2084       userPW = NULL;
2085     }
2086     i->doc = new PDFDoc(fileName, userPW);
2087     if (userPW) {
2088       delete userPW;
2089     }
2090     if (!i->doc->isOk()) {
2091         return 0;
2092     }
2093
2094     // print doc info
2095     i->doc->getDocInfo(&info);
2096     if (info.isDict() &&
2097       (getScreenLogLevel()>=LOGLEVEL_NOTICE)) {
2098       printInfoString(info.getDict(), "Title",        "Title:        %s\n");
2099       printInfoString(info.getDict(), "Subject",      "Subject:      %s\n");
2100       printInfoString(info.getDict(), "Keywords",     "Keywords:     %s\n");
2101       printInfoString(info.getDict(), "Author",       "Author:       %s\n");
2102       printInfoString(info.getDict(), "Creator",      "Creator:      %s\n");
2103       printInfoString(info.getDict(), "Producer",     "Producer:     %s\n");
2104       printInfoDate(info.getDict(),   "CreationDate", "CreationDate: %s\n");
2105       printInfoDate(info.getDict(),   "ModDate",      "ModDate:      %s\n");
2106       printf("Pages:        %d\n", i->doc->getNumPages());
2107       printf("Linearized:   %s\n", i->doc->isLinearized() ? "yes" : "no");
2108       printf("Encrypted:    ");
2109       if (i->doc->isEncrypted()) {
2110         printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
2111                i->doc->okToPrint() ? "yes" : "no",
2112                i->doc->okToCopy() ? "yes" : "no",
2113                i->doc->okToChange() ? "yes" : "no",
2114                i->doc->okToAddNotes() ? "yes" : "no");
2115       } else {
2116         printf("no\n");
2117       }
2118     }
2119     info.free();
2120                    
2121     pdf_doc->num_pages = i->doc->getNumPages();
2122     i->protect = 0;
2123     if (i->doc->isEncrypted()) {
2124           if(!i->doc->okToCopy()) {
2125               printf("PDF disallows copying.\n");
2126               return 0;
2127           }
2128           if(!i->doc->okToChange() || !i->doc->okToAddNotes())
2129               i->protect = 1;
2130     }
2131    
2132     return pdf_doc;
2133 }
2134
2135 void pdfswf_preparepage(int page)
2136 {
2137     /*FIXME*/
2138     if(!pages) {
2139         pages = (int*)malloc(1024*sizeof(int));
2140         pagebuflen = 1024;
2141     } else {
2142         if(pagepos == pagebuflen)
2143         {
2144             pagebuflen+=1024;
2145             pages = (int*)realloc(pages, pagebuflen);
2146         }
2147     }
2148     pages[pagepos++] = page;
2149 }
2150
2151 class MemCheck
2152 {
2153     public: ~MemCheck()
2154     {
2155         delete globalParams;globalParams=0;
2156         Object::memCheck(stderr);
2157         gMemReport(stderr);
2158     }
2159 } myMemCheck;
2160
2161 void pdf_destroy(pdf_doc_t*pdf_doc)
2162 {
2163     pdf_doc_internal_t*i= (pdf_doc_internal_t*)pdf_doc->internal;
2164
2165     msg("<debug> pdfswf.cc: pdfswf_close()");
2166     delete i->doc; i->doc=0;
2167     
2168     free(pages); pages = 0; //FIXME
2169
2170     free(pdf_doc->internal);pdf_doc->internal=0;
2171     free(pdf_doc);pdf_doc=0;
2172 }
2173
2174 pdf_page_t* pdf_getpage(pdf_doc_t*pdf_doc, int page)
2175 {
2176     pdf_doc_internal_t*di= (pdf_doc_internal_t*)pdf_doc->internal;
2177
2178     if(page < 1 || page > pdf_doc->num_pages)
2179         return 0;
2180     
2181     pdf_page_t* pdf_page = (pdf_page_t*)malloc(sizeof(pdf_page_t));
2182     pdf_page_internal_t*pi= (pdf_page_internal_t*)malloc(sizeof(pdf_page_internal_t));
2183     memset(pi, 0, sizeof(pdf_page_internal_t));
2184     pdf_page->internal = pi;
2185
2186     pdf_page->parent = pdf_doc;
2187     pdf_page->nr = page;
2188     return pdf_page;
2189 }
2190
2191 void pdf_page_destroy(pdf_page_t*pdf_page)
2192 {
2193     pdf_page_internal_t*i= (pdf_page_internal_t*)pdf_page->internal;
2194     free(pdf_page->internal);pdf_page->internal = 0;
2195     free(pdf_page);pdf_page=0;
2196 }
2197
2198 swf_output_t* swf_output_init() 
2199 {
2200     swf_output_t*swf_output = (swf_output_t*)malloc(sizeof(swf_output_t));
2201     memset(swf_output, 0, sizeof(swf_output_t));
2202     swf_output_internal_t*i= (swf_output_internal_t*)malloc(sizeof(swf_output_internal_t));
2203     memset(i, 0, sizeof(swf_output_internal_t));
2204     swf_output->internal = i;
2205
2206     i->outputDev = new SWFOutputDev();
2207     return swf_output;
2208 }
2209
2210 void swf_output_setparameter(swf_output_t*swf_output, char*name, char*value)
2211 {
2212     /* FIXME */
2213     pdfswf_setparameter(name, value);
2214 }
2215
2216 int swf_output_save(swf_output_t*swf, char*filename)
2217 {
2218     swf_output_internal_t*i= (swf_output_internal_t*)swf->internal;
2219     int ret = i->outputDev->save(filename);
2220     i->outputDev->getDimensions(&swf->x1, &swf->y1, &swf->x2, &swf->y2);
2221     return ret;
2222 }
2223
2224 void swf_output_destroy(swf_output_t*output)
2225 {
2226     swf_output_internal_t*i = (swf_output_internal_t*)output->internal;
2227     delete i->outputDev; i->outputDev=0;
2228     free(output->internal);output->internal=0;
2229     free(output);
2230 }
2231
2232 void pdf_page_render2(pdf_page_t*page, swf_output_t*swf)
2233 {
2234     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
2235     swf_output_internal_t*si = (swf_output_internal_t*)swf->internal;
2236
2237     if(pi->protect) {
2238         swfoutput_setparameter("protect", "1");
2239     }
2240     si->outputDev->setXRef(pi->doc, pi->doc->getXRef());
2241 #ifdef XPDF_101
2242     pi->doc->displayPage((OutputDev*)si->outputDev, page->nr, /*zoom*/zoom, /*rotate*/0, /*doLinks*/(int)1);
2243 #else
2244     pi->doc->displayPage((OutputDev*)si->outputDev, page->nr, zoom, zoom, /*rotate*/0, true, /*doLinks*/(int)1);
2245 #endif
2246     si->outputDev->getDimensions(&swf->x1, &swf->y1, &swf->x2, &swf->y2);
2247 }
2248
2249 void pdf_page_rendersection(pdf_page_t*page, swf_output_t*output, int x, int y, int x1, int y1, int x2, int y2)
2250 {
2251     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
2252     swf_output_internal_t*si = (swf_output_internal_t*)output->internal;
2253
2254     si->outputDev->setMove(x,y);
2255     if((x1|y1|x2|y2)==0) x2++;
2256     si->outputDev->setClip(x1,y1,x2,y2);
2257
2258     pdf_page_render2(page, output);
2259 }
2260 void pdf_page_render(pdf_page_t*page, swf_output_t*output)
2261 {
2262     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
2263     swf_output_internal_t*si = (swf_output_internal_t*)output->internal;
2264     
2265     si->outputDev->setMove(0,0);
2266     si->outputDev->setClip(0,0,0,0);
2267     
2268     pdf_page_render2(page, output);
2269 }
2270
2271
2272 pdf_page_info_t* pdf_page_getinfo(pdf_page_t*page)
2273 {
2274     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
2275     pdf_page_internal_t*i= (pdf_page_internal_t*)page->internal;
2276     pdf_page_info_t*info = (pdf_page_info_t*)malloc(sizeof(pdf_page_info_t));
2277     memset(info, 0, sizeof(pdf_page_info_t));
2278
2279     InfoOutputDev*output = new InfoOutputDev;
2280     
2281 #ifdef XPDF_101
2282     pi->doc->displayPage((OutputDev*)output, page->nr, /*zoom*/zoom, /*rotate*/0, /*doLinks*/(int)1);
2283 #else
2284     pi->doc->displayPage((OutputDev*)output, page->nr, zoom, zoom, /*rotate*/0, true, /*doLinks*/(int)1);
2285 #endif
2286
2287     info->xMin = output->x1;
2288     info->yMin = output->y1;
2289     info->xMax = output->x2;
2290     info->yMax = output->y2;
2291     info->number_of_images = output->num_images;
2292     info->number_of_links = output->num_links;
2293     info->number_of_fonts = output->num_fonts;
2294
2295     delete output;
2296
2297     return info;
2298 }
2299
2300 void pdf_page_info_destroy(pdf_page_info_t*info)
2301 {
2302     free(info);
2303 }