fixed page52.pdf segfault (added null pointer handling to
[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 static int forceType0Fonts = 0;
92
93 static void printInfoString(Dict *infoDict, char *key, char *fmt);
94 static void printInfoDate(Dict *infoDict, char *key, char *fmt);
95
96 struct mapping {
97     char*pdffont;
98     char*filename;
99 } pdf2t1map[] ={
100 {"Times-Roman",           "n021003l"},
101 {"Times-Italic",          "n021023l"},
102 {"Times-Bold",            "n021004l"},
103 {"Times-BoldItalic",      "n021024l"},
104 {"Helvetica",             "n019003l"},
105 {"Helvetica-Oblique",     "n019023l"},
106 {"Helvetica-Bold",        "n019004l"},
107 {"Helvetica-BoldOblique", "n019024l"},
108 {"Courier",               "n022003l"},
109 {"Courier-Oblique",       "n022023l"},
110 {"Courier-Bold",          "n022004l"},
111 {"Courier-BoldOblique",   "n022024l"},
112 {"Symbol",                "s050000l"},
113 {"ZapfDingbats",          "d050000l"}};
114
115 class SWFOutputDev:  public OutputDev {
116   int outputstarted;
117   struct swfoutput output;
118 public:
119
120   // Constructor.
121   SWFOutputDev();
122
123   // Destructor.
124   virtual ~SWFOutputDev() ;
125
126   void setMove(int x,int y);
127   void setClip(int x1,int y1,int x2,int y2);
128   
129   int save(char*filename);
130   void  pagefeed();
131   void* getSWF();
132
133   void getDimensions(int*x1,int*y1,int*x2,int*y2);
134
135   //----- get info about output device
136
137   // Does this device use upside-down coordinates?
138   // (Upside-down means (0,0) is the top left corner of the page.)
139   virtual GBool upsideDown();
140
141   // Does this device use drawChar() or drawString()?
142   virtual GBool useDrawChar();
143   
144   // Can this device draw gradients?
145   virtual GBool useGradients();
146   
147   virtual GBool interpretType3Chars() {return gTrue;}
148
149   //----- initialization and control
150
151   void setXRef(PDFDoc*doc, XRef *xref);
152
153   // Start a page.
154   virtual void startPage(int pageNum, GfxState *state, double x1, double y1, double x2, double y2) ;
155
156   //----- link borders
157   virtual void drawLink(Link *link, Catalog *catalog) ;
158
159   //----- save/restore graphics state
160   virtual void saveState(GfxState *state) ;
161   virtual void restoreState(GfxState *state) ;
162
163   //----- update graphics state
164
165   virtual void updateFont(GfxState *state);
166   virtual void updateFillColor(GfxState *state);
167   virtual void updateStrokeColor(GfxState *state);
168   virtual void updateLineWidth(GfxState *state);
169   virtual void updateLineJoin(GfxState *state);
170   virtual void updateLineCap(GfxState *state);
171   
172   virtual void updateAll(GfxState *state) 
173   {
174       updateFont(state);
175       updateFillColor(state);
176       updateStrokeColor(state);
177       updateLineWidth(state);
178       updateLineJoin(state);
179       updateLineCap(state);
180   };
181
182   //----- path painting
183   virtual void stroke(GfxState *state) ;
184   virtual void fill(GfxState *state) ;
185   virtual void eoFill(GfxState *state) ;
186
187   //----- path clipping
188   virtual void clip(GfxState *state) ;
189   virtual void eoClip(GfxState *state) ;
190
191   //----- text drawing
192   virtual void beginString(GfxState *state, GString *s) ;
193   virtual void endString(GfxState *state) ;
194   virtual void drawChar(GfxState *state, double x, double y,
195                         double dx, double dy,
196                         double originX, double originY,
197                         CharCode code, Unicode *u, int uLen);
198
199   //----- image drawing
200   virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
201                              int width, int height, GBool invert,
202                              GBool inlineImg);
203   virtual void drawImage(GfxState *state, Object *ref, Stream *str,
204                          int width, int height, GfxImageColorMap *colorMap,
205                          int *maskColors, GBool inlineImg);
206   
207   virtual GBool beginType3Char(GfxState *state,
208                                CharCode code, Unicode *u, int uLen);
209   virtual void endType3Char(GfxState *state);
210
211   private:
212   void drawGeneralImage(GfxState *state, Object *ref, Stream *str,
213                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
214                                    GBool inlineImg, int mask);
215   int clipping[64];
216   int clippos;
217
218   int currentpage;
219
220   PDFDoc*doc;
221   XRef*xref;
222
223   char* searchFont(char*name);
224   char* substituteFont(GfxFont*gfxFont, char*oldname);
225   char* writeEmbeddedFontToFile(XRef*ref, GfxFont*font);
226   int t1id;
227   int jpeginfo; // did we write "File contains jpegs" yet?
228   int pbminfo; // did we write "File contains jpegs" yet?
229   int linkinfo; // did we write "File contains links" yet?
230   int ttfinfo; // did we write "File contains TrueType Fonts" yet?
231   int gradientinfo; // did we write "File contains Gradients yet?
232
233   int type3active; // are we between beginType3()/endType3()?
234
235   GfxState *laststate;
236
237   int pic_xids[1024];
238   int pic_yids[1024];
239   int pic_ids[1024];
240   int pic_width[1024];
241   int pic_height[1024];
242   int picpos;
243   int pic_id;
244   char type3Warning;
245
246   char* substitutetarget[256];
247   char* substitutesource[256];
248   int substitutepos;
249
250   int user_movex,user_movey;
251   int user_clipx1,user_clipx2,user_clipy1,user_clipy2;
252 };
253
254 static char*getFontID(GfxFont*font);
255
256 class InfoOutputDev:  public OutputDev 
257 {
258   public:
259   int x1,y1,x2,y2;
260   int num_links;
261   int num_images;
262   int num_fonts;
263
264   InfoOutputDev() 
265   {
266       num_links = 0;
267       num_images = 0;
268       num_fonts = 0;
269   }
270   virtual ~InfoOutputDev() 
271   {
272   }
273   virtual GBool upsideDown() {return gTrue;}
274   virtual GBool useDrawChar() {return gTrue;}
275   virtual GBool useGradients() {return gTrue;}
276   virtual GBool interpretType3Chars() {return gTrue;}
277   virtual void startPage(int pageNum, GfxState *state, double crop_x1, double crop_y1, double crop_x2, double crop_y2)
278   {
279       double x1,y1,x2,y2;
280       state->transform(crop_x1,crop_y1,&x1,&y1);
281       state->transform(crop_x2,crop_y2,&x2,&y2);
282       if(x2<x1) {double x3=x1;x1=x2;x2=x3;}
283       if(y2<y1) {double y3=y1;y1=y2;y2=y3;}
284       this->x1 = (int)x1;
285       this->y1 = (int)y1;
286       this->x2 = (int)x2;
287       this->y2 = (int)y2;
288   }
289   virtual void drawLink(Link *link, Catalog *catalog) 
290   {
291       num_links++;
292   }
293   virtual void updateFont(GfxState *state) 
294   {
295       GfxFont*font = state->getFont();
296       if(!font)
297           return;
298       char*id = getFontID(font);
299       /* FIXME*/
300       num_fonts++;
301   }
302   virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
303                              int width, int height, GBool invert,
304                              GBool inlineImg) 
305   {
306       num_images++;
307   }
308   virtual void drawImage(GfxState *state, Object *ref, Stream *str,
309                          int width, int height, GfxImageColorMap *colorMap,
310                          int *maskColors, GBool inlineImg)
311   {
312       num_images++;
313   }
314 };
315
316 SWFOutputDev::SWFOutputDev()
317 {
318     jpeginfo = 0;
319     ttfinfo = 0;
320     linkinfo = 0;
321     pbminfo = 0;
322     type3active = 0;
323     clippos = 0;
324     clipping[clippos] = 0;
325     outputstarted = 0;
326     xref = 0;
327     picpos = 0;
328     pic_id = 0;
329     substitutepos = 0;
330     type3Warning = 0;
331     user_movex = 0;
332     user_movey = 0;
333     user_clipx1 = 0;
334     user_clipy1 = 0;
335     user_clipx2 = 0;
336     user_clipy2 = 0;
337     memset(&output, 0, sizeof(output));
338 //    printf("SWFOutputDev::SWFOutputDev() \n");
339 };
340   
341 void SWFOutputDev::setMove(int x,int y)
342 {
343     this->user_movex = x;
344     this->user_movey = y;
345 }
346
347 void SWFOutputDev::setClip(int x1,int y1,int x2,int y2)
348 {
349     if(x2<x1) {int x3=x1;x1=x2;x2=x3;}
350     if(y2<y1) {int y3=y1;y1=y2;y2=y3;}
351
352     this->user_clipx1 = x1;
353     this->user_clipy1 = y1;
354     this->user_clipx2 = x2;
355     this->user_clipy2 = y2;
356 }
357 void SWFOutputDev::getDimensions(int*x1,int*y1,int*x2,int*y2)
358 {
359     return swfoutput_getdimensions(&output, x1,y1,x2,y2);
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
803 /* pass through functions for swf_output */
804 int SWFOutputDev::save(char*filename)
805 {
806     return swfoutput_save(&output, filename);
807 }
808 void SWFOutputDev::pagefeed()
809 {
810     swfoutput_pagefeed(&output);
811 }
812 void* SWFOutputDev::getSWF()
813 {
814     return (void*)swfoutput_get(&output);
815 }
816
817 SWFOutputDev::~SWFOutputDev() 
818 {
819     swfoutput_destroy(&output);
820     outputstarted = 0;
821 };
822 GBool SWFOutputDev::upsideDown() 
823 {
824     msg("<debug> upsidedown? yes");
825     return gTrue;
826 };
827 GBool SWFOutputDev::useDrawChar() 
828 {
829     return gTrue;
830 }
831 GBool SWFOutputDev::useGradients()
832 {
833     if(!gradientinfo)
834     {
835         msg("<notice> File contains gradients");
836         gradientinfo = 1;
837     }
838     return gTrue;
839 }
840
841 void SWFOutputDev::beginString(GfxState *state, GString *s) 
842
843     double m11,m21,m12,m22;
844 //    msg("<debug> %s beginstring \"%s\"\n", gfxstate2str(state), s->getCString());
845     state->getFontTransMat(&m11, &m12, &m21, &m22);
846     m11 *= state->getHorizScaling();
847     m21 *= state->getHorizScaling();
848     swfoutput_setfontmatrix(&output, m11, -m21, m12, -m22);
849 }
850
851 void SWFOutputDev::drawChar(GfxState *state, double x, double y,
852                         double dx, double dy,
853                         double originX, double originY,
854                         CharCode c, Unicode *_u, int uLen)
855 {
856     // check for invisible text -- this is used by Acrobat Capture
857     if ((state->getRender() & 3) == 3)
858         return;
859     Gushort *CIDToGIDMap = 0;
860     GfxFont*font = state->getFont();
861
862     if(font->getType() == fontType3) {
863         /* type 3 chars are passed as graphics */
864         return;
865     }
866     double x1,y1;
867     x1 = x;
868     y1 = y;
869     state->transform(x, y, &x1, &y1);
870     
871     Unicode u=0;
872     char*name=0;
873
874     if(_u && uLen) {
875         u = *_u;
876         if (u) {
877             int t;
878             /* find out char name from unicode index 
879                TODO: should be precomputed
880              */
881             for(t=0;t<sizeof(nameToUnicodeTab)/sizeof(nameToUnicodeTab[0]);t++) {
882                 if(nameToUnicodeTab[t].u == u) {
883                     name = nameToUnicodeTab[t].name;
884                     break;
885                 }
886             }
887         }
888     }
889
890     if(font->isCIDFont()) {
891         GfxCIDFont*cfont = (GfxCIDFont*)font;
892
893         if(font->getType() == fontCIDType2) {
894             CIDToGIDMap = cfont->getCIDToGID();
895         }
896     } else {
897         Gfx8BitFont*font8;
898         font8 = (Gfx8BitFont*)font;
899         char**enc=font8->getEncoding();
900         if(enc && enc[c])
901            name = enc[c];
902     }
903  
904     if (CIDToGIDMap) {
905         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));
906         swfoutput_drawchar(&output, x1, y1, name, CIDToGIDMap[c], u);
907     } else {
908         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));
909         swfoutput_drawchar(&output, x1, y1, name, c, u);
910     }
911 }
912
913 void SWFOutputDev::endString(GfxState *state) { 
914 }    
915
916  
917 GBool SWFOutputDev::beginType3Char(GfxState *state,
918                                CharCode code, Unicode *u, int uLen)
919 {
920     msg("<debug> beginType3Char %d, %08x, %d", code, *u, uLen);
921     type3active = 1;
922     /* the character itself is going to be passed using
923        drawImageMask() */
924     return gFalse; /* gTrue= is_in_cache? */
925 }
926
927 void SWFOutputDev::endType3Char(GfxState *state)
928 {
929     type3active = 0;
930     msg("<debug> endType3Char");
931 }
932
933 void SWFOutputDev::startPage(int pageNum, GfxState *state, double crop_x1, double crop_y1, double crop_x2, double crop_y2) 
934 {
935     this->currentpage = pageNum;
936     double x1,y1,x2,y2;
937     int rot = doc->getPageRotate(1);
938     laststate = state;
939     msg("<verbose> startPage %d (%f,%f,%f,%f)\n", pageNum, crop_x1, crop_y1, crop_x2, crop_y2);
940     if(rot!=0)
941         msg("<verbose> page is rotated %d degrees\n", rot);
942
943     /* state->transform(state->getX1(),state->getY1(),&x1,&y1);
944     state->transform(state->getX2(),state->getY2(),&x2,&y2);
945     Use CropBox, not MediaBox, as page size
946     */
947     
948     /*x1 = crop_x1;
949     y1 = crop_y1;
950     x2 = crop_x2;
951     y2 = crop_y2;*/
952     state->transform(crop_x1,crop_y1,&x1,&y1);
953     state->transform(crop_x2,crop_y2,&x2,&y2);
954
955     if(x2<x1) {double x3=x1;x1=x2;x2=x3;}
956     if(y2<y1) {double y3=y1;y1=y2;y2=y3;}
957
958     /* apply user clip box */
959     if(user_clipx1|user_clipy1|user_clipx2|user_clipy2) {
960         /*if(user_clipx1 > x1)*/ x1 = user_clipx1;
961         /*if(user_clipx2 < x2)*/ x2 = user_clipx2;
962         /*if(user_clipy1 > y1)*/ y1 = user_clipy1;
963         /*if(user_clipy2 < y2)*/ y2 = user_clipy2;
964     }
965
966     if(!outputstarted) {
967         msg("<verbose> Bounding box is (%f,%f)-(%f,%f)", x1,y1,x2,y2);
968         swfoutput_init(&output);
969         outputstarted = 1;
970     }
971       
972     swfoutput_newpage(&output, pageNum, user_movex, user_movey, (int)x1, (int)y1, (int)x2, (int)y2);
973 }
974
975 void SWFOutputDev::drawLink(Link *link, Catalog *catalog) 
976 {
977     msg("<debug> drawlink\n");
978     double x1, y1, x2, y2, w;
979     GfxRGB rgb;
980     swfcoord points[5];
981     int x, y;
982
983 #ifdef XPDF_101
984     link->getBorder(&x1, &y1, &x2, &y2, &w);
985 #else
986     link->getRect(&x1, &y1, &x2, &y2);
987 #endif
988     rgb.r = 0;
989     rgb.g = 0;
990     rgb.b = 1;
991     cvtUserToDev(x1, y1, &x, &y);
992     points[0].x = points[4].x = (int)x;
993     points[0].y = points[4].y = (int)y;
994     cvtUserToDev(x2, y1, &x, &y);
995     points[1].x = (int)x;
996     points[1].y = (int)y;
997     cvtUserToDev(x2, y2, &x, &y);
998     points[2].x = (int)x;
999     points[2].y = (int)y;
1000     cvtUserToDev(x1, y2, &x, &y);
1001     points[3].x = (int)x;
1002     points[3].y = (int)y;
1003
1004     LinkAction*action=link->getAction();
1005     char buf[128];
1006     char*s = 0;
1007     char*type = "-?-";
1008     char*url = 0;
1009     char*named = 0;
1010     int page = -1;
1011     switch(action->getKind())
1012     {
1013         case actionGoTo: {
1014             type = "GoTo";
1015             LinkGoTo *ha=(LinkGoTo *)link->getAction();
1016             LinkDest *dest=NULL;
1017             if (ha->getDest()==NULL) 
1018                 dest=catalog->findDest(ha->getNamedDest());
1019             else dest=ha->getDest();
1020             if (dest){ 
1021               if (dest->isPageRef()){
1022                 Ref pageref=dest->getPageRef();
1023                 page=catalog->findPage(pageref.num,pageref.gen);
1024               }
1025               else  page=dest->getPageNum();
1026               sprintf(buf, "%d", page);
1027               s = strdup(buf);
1028             }
1029         }
1030         break;
1031         case actionGoToR: {
1032             type = "GoToR";
1033             LinkGoToR*l = (LinkGoToR*)action;
1034             GString*g = l->getNamedDest();
1035             if(g)
1036              s = strdup(g->getCString());
1037         }
1038         break;
1039         case actionNamed: {
1040             type = "Named";
1041             LinkNamed*l = (LinkNamed*)action;
1042             GString*name = l->getName();
1043             if(name) {
1044                 s = strdup(name->lowerCase()->getCString());
1045                 named = name->getCString();
1046                 if(!strchr(s,':')) 
1047                 {
1048                     if(strstr(s, "next") || strstr(s, "forward"))
1049                     {
1050                         page = currentpage + 1;
1051                     }
1052                     else if(strstr(s, "prev") || strstr(s, "back"))
1053                     {
1054                         page = currentpage - 1;
1055                     }
1056                     else if(strstr(s, "last") || strstr(s, "end"))
1057                     {
1058                         page = pagepos>0?pages[pagepos-1]:0;
1059                     }
1060                     else if(strstr(s, "first") || strstr(s, "top"))
1061                     {
1062                         page = 1;
1063                     }
1064                 }
1065             }
1066         }
1067         break;
1068         case actionLaunch: {
1069             type = "Launch";
1070             LinkLaunch*l = (LinkLaunch*)action;
1071             GString * str = new GString(l->getFileName());
1072             str->append(l->getParams());
1073             s = strdup(str->getCString());
1074             delete str;
1075         }
1076         break;
1077         case actionURI: {
1078             type = "URI";
1079             LinkURI*l = (LinkURI*)action;
1080             GString*g = l->getURI();
1081             if(g) {
1082              url = g->getCString();
1083              s = strdup(url);
1084             }
1085         }
1086         break;
1087         case actionUnknown: {
1088             type = "Unknown";
1089             LinkUnknown*l = (LinkUnknown*)action;
1090             s = strdup("");
1091         }
1092         break;
1093         default: {
1094             msg("<error> Unknown link type!\n");
1095             break;
1096         }
1097     }
1098     if(!s) s = strdup("-?-");
1099
1100     if(!linkinfo && (page || url))
1101     {
1102         msg("<notice> File contains links");
1103         linkinfo = 1;
1104     }
1105     if(page>0)
1106     {
1107         int t;
1108         for(t=0;t<pagepos;t++)
1109             if(pages[t]==page)
1110                 break;
1111         if(t!=pagepos)
1112             swfoutput_linktopage(&output, t, points);
1113     }
1114     else if(url)
1115     {
1116         swfoutput_linktourl(&output, url, points);
1117     }
1118     else if(named)
1119     {
1120         swfoutput_namedlink(&output, named, points);
1121     }
1122     msg("<verbose> \"%s\" link to \"%s\" (%d)\n", type, FIXNULL(s), page);
1123     free(s);s=0;
1124 }
1125
1126 void SWFOutputDev::saveState(GfxState *state) {
1127   msg("<debug> saveState\n");
1128   updateAll(state);
1129   if(clippos<64)
1130     clippos ++;
1131   else
1132     msg("<error> Too many nested states in pdf.");
1133   clipping[clippos] = 0;
1134 };
1135
1136 void SWFOutputDev::restoreState(GfxState *state) {
1137   msg("<debug> restoreState\n");
1138   updateAll(state);
1139   while(clipping[clippos]) {
1140       swfoutput_endclip(&output);
1141       clipping[clippos]--;
1142   }
1143   clippos--;
1144 }
1145
1146 char* SWFOutputDev::searchFont(char*name) 
1147 {       
1148     int i;
1149     char*filename=0;
1150     int is_standard_font = 0;
1151         
1152     msg("<verbose> SearchFont(%s)", name);
1153
1154     /* see if it is a pdf standard font */
1155     for(i=0;i<sizeof(pdf2t1map)/sizeof(mapping);i++) 
1156     {
1157         if(!strcmp(name, pdf2t1map[i].pdffont))
1158         {
1159             name = pdf2t1map[i].filename;
1160             is_standard_font = 1;
1161             break;
1162         }
1163     }
1164     /* look in all font files */
1165     for(i=0;i<fontnum;i++) 
1166     {
1167         if(strstr(fonts[i].filename, name))
1168         {
1169             if(!fonts[i].used) {
1170
1171                 fonts[i].used = 1;
1172                 if(!is_standard_font)
1173                     msg("<notice> Using %s for %s", fonts[i].filename, name);
1174             }
1175             return strdup(fonts[i].filename);
1176         }
1177     }
1178     return 0;
1179 }
1180
1181 void SWFOutputDev::updateLineWidth(GfxState *state)
1182 {
1183     double width = state->getTransformedLineWidth();
1184     swfoutput_setlinewidth(&output, width);
1185 }
1186
1187 void SWFOutputDev::updateLineCap(GfxState *state)
1188 {
1189     int c = state->getLineCap();
1190 }
1191
1192 void SWFOutputDev::updateLineJoin(GfxState *state)
1193 {
1194     int j = state->getLineJoin();
1195 }
1196
1197 void SWFOutputDev::updateFillColor(GfxState *state) 
1198 {
1199     GfxRGB rgb;
1200     double opaq = state->getFillOpacity();
1201     state->getFillRGB(&rgb);
1202
1203     swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
1204                                     (char)(rgb.b*255), (char)(opaq*255));
1205 }
1206
1207 void SWFOutputDev::updateStrokeColor(GfxState *state) 
1208 {
1209     GfxRGB rgb;
1210     double opaq = state->getStrokeOpacity();
1211     state->getStrokeRGB(&rgb);
1212
1213     swfoutput_setstrokecolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
1214                                       (char)(rgb.b*255), (char)(opaq*255));
1215 }
1216
1217 void FoFiWrite(void *stream, char *data, int len)
1218 {
1219    fwrite(data, len, 1, (FILE*)stream);
1220 }
1221
1222 char*SWFOutputDev::writeEmbeddedFontToFile(XRef*ref, GfxFont*font)
1223 {
1224     char*tmpFileName = NULL;
1225     FILE *f;
1226     int c;
1227     char *fontBuf;
1228     int fontLen;
1229     Ref embRef;
1230     Object refObj, strObj;
1231     char namebuf[512];
1232     tmpFileName = mktmpname(namebuf);
1233     int ret;
1234
1235     ret = font->getEmbeddedFontID(&embRef);
1236     if(!ret) {
1237         msg("<verbose> Didn't get embedded font id");
1238         /* not embedded- the caller should now search the font
1239            directories for this font */
1240         return 0;
1241     }
1242
1243     f = fopen(tmpFileName, "wb");
1244     if (!f) {
1245       msg("<error> Couldn't create temporary Type 1 font file");
1246         return 0;
1247     }
1248
1249     /*if(font->isCIDFont()) {
1250         GfxCIDFont* cidFont = (GfxCIDFont *)font;
1251         GString c = cidFont->getCollection();
1252         msg("<notice> Collection: %s", c.getCString());
1253     }*/
1254
1255     if (font->getType() == fontType1C ||
1256         font->getType() == fontCIDType0C) {
1257       if (!(fontBuf = font->readEmbFontFile(xref, &fontLen))) {
1258         fclose(f);
1259         msg("<error> Couldn't read embedded font file");
1260         return 0;
1261       }
1262 #ifdef XPDF_101
1263       Type1CFontFile *cvt = new Type1CFontFile(fontBuf, fontLen);
1264       if(!cvt) return 0;
1265       cvt->convertToType1(f);
1266 #else
1267       FoFiType1C *cvt = FoFiType1C::make(fontBuf, fontLen);
1268       if(!cvt) return 0;
1269       cvt->convertToType1(NULL, gTrue, FoFiWrite, f);
1270 #endif
1271       //cvt->convertToCIDType0("test", f);
1272       //cvt->convertToType0("test", f);
1273       delete cvt;
1274       gfree(fontBuf);
1275     } else if(font->getType() == fontTrueType) {
1276       msg("<verbose> writing font using TrueTypeFontFile::writeTTF");
1277       if (!(fontBuf = font->readEmbFontFile(xref, &fontLen))) {
1278         fclose(f);
1279         msg("<error> Couldn't read embedded font file");
1280         return 0;
1281       }
1282 #ifdef XPDF_101
1283       TrueTypeFontFile *cvt = new TrueTypeFontFile(fontBuf, fontLen);
1284       cvt->writeTTF(f);
1285 #else
1286       FoFiTrueType *cvt = FoFiTrueType::make(fontBuf, fontLen);
1287       cvt->writeTTF(FoFiWrite, f);
1288 #endif
1289       delete cvt;
1290       gfree(fontBuf);
1291     } else {
1292       font->getEmbeddedFontID(&embRef);
1293       refObj.initRef(embRef.num, embRef.gen);
1294       refObj.fetch(ref, &strObj);
1295       refObj.free();
1296       strObj.streamReset();
1297       int f4[4];
1298       char f4c[4];
1299       int t;
1300       for(t=0;t<4;t++) {
1301           f4[t] = strObj.streamGetChar();
1302           f4c[t] = (char)f4[t];
1303           if(f4[t] == EOF)
1304               break;
1305       }
1306       if(t==4) {
1307           if(!strncmp(f4c, "true", 4)) {
1308               /* some weird TTF fonts don't start with 0,1,0,0 but with "true".
1309                  Change this on the fly */
1310               f4[0] = f4[2] = f4[3] = 0;
1311               f4[1] = 1;
1312           }
1313           fputc(f4[0], f);
1314           fputc(f4[1], f);
1315           fputc(f4[2], f);
1316           fputc(f4[3], f);
1317
1318           while ((c = strObj.streamGetChar()) != EOF) {
1319             fputc(c, f);
1320           }
1321       }
1322       strObj.streamClose();
1323       strObj.free();
1324     }
1325     fclose(f);
1326
1327     return strdup(tmpFileName);
1328 }
1329     
1330 char* searchForSuitableFont(GfxFont*gfxFont)
1331 {
1332     char*name = getFontName(gfxFont);
1333     char*fontname = 0;
1334     char*filename = 0;
1335
1336     if(!config_use_fontconfig)
1337         return 0;
1338     
1339 #ifdef HAVE_FONTCONFIG
1340     FcPattern *pattern, *match;
1341     FcResult result;
1342     FcChar8 *v;
1343
1344     static int fcinitcalled = false; 
1345         
1346     msg("<debug> searchForSuitableFont(%s)", name);
1347     
1348     // call init ony once
1349     if (!fcinitcalled) {
1350         msg("<debug> Initializing FontConfig...");
1351         fcinitcalled = true;
1352         if(FcInit()) {
1353             msg("<debug> FontConfig Initialization failed. Disabling.");
1354             config_use_fontconfig = 0;
1355             return 0;
1356         }
1357         msg("<debug> ...initialized FontConfig");
1358     }
1359    
1360     msg("<debug> FontConfig: Create \"%s\" Family Pattern", name);
1361     pattern = FcPatternBuild(NULL, FC_FAMILY, FcTypeString, name, NULL);
1362     if (gfxFont->isItalic()) // check for italic
1363         msg("<debug> FontConfig: Adding Italic Slant");
1364         FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1365     if (gfxFont->isBold()) // check for bold
1366         msg("<debug> FontConfig: Adding Bold Weight");
1367         FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1368
1369     msg("<debug> FontConfig: Try to match...");
1370     // configure and match using the original font name 
1371     FcConfigSubstitute(0, pattern, FcMatchPattern); 
1372     FcDefaultSubstitute(pattern);
1373     match = FcFontMatch(0, pattern, &result);
1374     
1375     if (FcPatternGetString(match, "family", 0, &v) == FcResultMatch) {
1376         msg("<debug> FontConfig: family=%s", (char*)v);
1377         // if we get an exact match
1378         if (strcmp((char *)v, name) == 0) {
1379             if (FcPatternGetString(match, "file", 0, &v) == FcResultMatch) {
1380                 filename = strdup((char*)v);
1381                 char *nfn = strrchr(filename, '/');
1382                 if(nfn) fontname = strdup(nfn+1);
1383                 else    fontname = filename;
1384             }
1385             msg("<debug> FontConfig: Returning \"%s\"", fontname);
1386         } else {
1387             // initialize patterns
1388             FcPatternDestroy(pattern);
1389             FcPatternDestroy(match);
1390
1391             // now match against serif etc.
1392             if (gfxFont->isSerif()) {
1393                 msg("<debug> FontConfig: Create Serif Family Pattern");
1394                 pattern = FcPatternBuild (NULL, FC_FAMILY, FcTypeString, "serif", NULL);
1395             } else if (gfxFont->isFixedWidth()) {
1396                 msg("<debug> FontConfig: Create Monospace Family Pattern");
1397                 pattern = FcPatternBuild (NULL, FC_FAMILY, FcTypeString, "monospace", NULL);
1398             } else {
1399                 msg("<debug> FontConfig: Create Sans Family Pattern");
1400                 pattern = FcPatternBuild (NULL, FC_FAMILY, FcTypeString, "sans", NULL);
1401             }
1402
1403             // check for italic
1404             if (gfxFont->isItalic()) {
1405                 msg("<debug> FontConfig: Adding Italic Slant");
1406                 int bb = FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
1407             }
1408             // check for bold
1409             if (gfxFont->isBold()) {
1410                 msg("<debug> FontConfig: Adding Bold Weight");
1411                 int bb = FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
1412             }
1413
1414             msg("<debug> FontConfig: Try to match... (2)");
1415             // configure and match using serif etc
1416             FcConfigSubstitute (0, pattern, FcMatchPattern);
1417             FcDefaultSubstitute (pattern);
1418             match = FcFontMatch (0, pattern, &result);
1419             
1420             if (FcPatternGetString(match, "file", 0, &v) == FcResultMatch) {
1421                 filename = strdup((char*)v);
1422                 char *nfn = strrchr(filename, '/');
1423                 if(nfn) fontname = strdup(nfn+1);
1424                 else    fontname = filename;
1425             }
1426             msg("<debug> FontConfig: Returning \"%s\"", fontname);
1427         }        
1428     }
1429
1430     //printf("FONTCONFIG: pattern");
1431     //FcPatternPrint(pattern);
1432     //printf("FONTCONFIG: match");
1433     //FcPatternPrint(match);
1434  
1435     FcPatternDestroy(pattern);
1436     FcPatternDestroy(match);
1437
1438     pdfswf_addfont(filename);
1439     return fontname;
1440 #else
1441     return 0;
1442 #endif
1443 }
1444
1445 char* SWFOutputDev::substituteFont(GfxFont*gfxFont, char* oldname)
1446 {
1447     char*fontname = 0, *filename = 0;
1448     msg("<notice> subsituteFont(%s)", oldname);
1449
1450     if(!(fontname = searchForSuitableFont(gfxFont))) {
1451         fontname = "Times-Roman";
1452     }
1453     filename = searchFont(fontname);
1454     if(!filename) {
1455         msg("<error> Couldn't find font %s- did you install the default fonts?");
1456         return 0;
1457     }
1458
1459     if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
1460         msg("<fatal> Too many fonts in file.");
1461         exit(1);
1462     }
1463     if(oldname) {
1464         substitutesource[substitutepos] = oldname;
1465         substitutetarget[substitutepos] = fontname;
1466         msg("<notice> substituting %s -> %s", FIXNULL(oldname), FIXNULL(fontname));
1467         substitutepos ++;
1468     }
1469     return strdup(filename);
1470 }
1471
1472 void unlinkfont(char* filename)
1473 {
1474     int l;
1475     if(!filename)
1476         return;
1477     l=strlen(filename);
1478     unlink(filename);
1479     if(!strncmp(&filename[l-4],".afm",4)) {
1480         memcpy(&filename[l-4],".pfb",4);
1481         unlink(filename);
1482         memcpy(&filename[l-4],".pfa",4);
1483         unlink(filename);
1484         memcpy(&filename[l-4],".afm",4);
1485         return;
1486     } else 
1487     if(!strncmp(&filename[l-4],".pfa",4)) {
1488         memcpy(&filename[l-4],".afm",4);
1489         unlink(filename);
1490         memcpy(&filename[l-4],".pfa",4);
1491         return;
1492     } else 
1493     if(!strncmp(&filename[l-4],".pfb",4)) {
1494         memcpy(&filename[l-4],".afm",4);
1495         unlink(filename);
1496         memcpy(&filename[l-4],".pfb",4);
1497         return;
1498     }
1499 }
1500
1501 void SWFOutputDev::setXRef(PDFDoc*doc, XRef *xref) 
1502 {
1503     this->doc = doc;
1504     this->xref = xref;
1505 }
1506
1507
1508 void SWFOutputDev::updateFont(GfxState *state) 
1509 {
1510     GfxFont*gfxFont = state->getFont();
1511       
1512     if (!gfxFont) {
1513         return;
1514     }  
1515     char * fontid = getFontID(gfxFont);
1516     
1517     int t;
1518     /* first, look if we substituted this font before-
1519        this way, we don't initialize the T1 Fonts
1520        too often */
1521     for(t=0;t<substitutepos;t++) {
1522         if(!strcmp(fontid, substitutesource[t])) {
1523             fontid = substitutetarget[t];
1524             break;
1525         }
1526     }
1527
1528     /* second, see if swfoutput already has this font
1529        cached- if so, we are done */
1530     if(swfoutput_queryfont(&output, fontid))
1531     {
1532         swfoutput_setfont(&output, fontid, 0);
1533         
1534         msg("<debug> updateFont(%s) [cached]", fontid);
1535         return;
1536     }
1537
1538     // look for Type 3 font
1539     if (gfxFont->getType() == fontType3) {
1540         if(!type3Warning) {
1541             type3Warning = gTrue;
1542             showFontError(gfxFont, 2);
1543         }
1544         return;
1545     }
1546
1547     /* now either load the font, or find a substitution */
1548
1549     Ref embRef;
1550     GBool embedded = gfxFont->getEmbeddedFontID(&embRef);
1551
1552     char*fileName = 0;
1553     int del = 0;
1554     if(embedded &&
1555        (gfxFont->getType() == fontType1 ||
1556         gfxFont->getType() == fontType1C ||
1557        (gfxFont->getType() == fontCIDType0C && forceType0Fonts) ||
1558         gfxFont->getType() == fontTrueType ||
1559         gfxFont->getType() == fontCIDType2
1560        ))
1561     {
1562       fileName = writeEmbeddedFontToFile(xref, gfxFont);
1563       if(!fileName) showFontError(gfxFont,0);
1564       else del = 1;
1565     } else {
1566       char * fontname = getFontName(gfxFont);
1567       fileName = searchFont(fontname);
1568       if(!fileName) showFontError(gfxFont,0);
1569     }
1570     if(!fileName) {
1571         char * fontname = getFontName(gfxFont);
1572         msg("<warning> Font %s %scould not be loaded.", fontname, embedded?"":"(not embedded) ");
1573         msg("<warning> Try putting a TTF version of that font (named \"%s.ttf\") into /swftools/fonts", fontname);
1574         fileName = substituteFont(gfxFont, fontid);
1575         if(fontid) { fontid = substitutetarget[substitutepos-1]; /*ugly hack*/};
1576         msg("<notice> Font is now %s (%s)", fontid, fileName);
1577     }
1578
1579     if(!fileName) {
1580         msg("<error> Couldn't set font %s\n", fontid);
1581         return;
1582     }
1583         
1584     msg("<verbose> updateFont(%s) -> %s", fontid, fileName);
1585     dumpFontInfo("<verbose>", gfxFont);
1586
1587     swfoutput_setfont(&output, fontid, fileName);
1588    
1589     if(fileName && del)
1590         unlinkfont(fileName);
1591     if(fileName)
1592         free(fileName);
1593 }
1594
1595 #define SQR(x) ((x)*(x))
1596
1597 unsigned char* antialize(unsigned char*data, int width, int height, int newwidth, int newheight, int palettesize)
1598 {
1599     if((newwidth<2 || newheight<2) ||
1600        (width<=newwidth || height<=newheight))
1601         return 0;
1602     unsigned char*newdata;
1603     int x,y;
1604     newdata= (unsigned char*)malloc(newwidth*newheight);
1605     int t;
1606     double fx = (double)(width)/newwidth;
1607     double fy = (double)(height)/newheight;
1608     double px = 0;
1609     int blocksize = (int)(8192/(fx*fy));
1610     int r = 8192*256/palettesize;
1611     for(x=0;x<newwidth;x++) {
1612         double ex = px + fx;
1613         int fromx = (int)px;
1614         int tox = (int)ex;
1615         int xweight1 = (int)(((fromx+1)-px)*256);
1616         int xweight2 = (int)((ex-tox)*256);
1617         double py =0;
1618         for(y=0;y<newheight;y++) {
1619             double ey = py + fy;
1620             int fromy = (int)py;
1621             int toy = (int)ey;
1622             int yweight1 = (int)(((fromy+1)-py)*256);
1623             int yweight2 = (int)((ey-toy)*256);
1624             int a = 0;
1625             int xx,yy;
1626             for(xx=fromx;xx<=tox;xx++)
1627             for(yy=fromy;yy<=toy;yy++) {
1628                 int b = 1-data[width*yy+xx];
1629                 int weight=256;
1630                 if(xx==fromx) weight = (weight*xweight1)/256;
1631                 if(xx==tox) weight = (weight*xweight2)/256;
1632                 if(yy==fromy) weight = (weight*yweight1)/256;
1633                 if(yy==toy) weight = (weight*yweight2)/256;
1634                 a+=b*weight;
1635             }
1636             //if(a) a=(palettesize-1)*r/blocksize;
1637             newdata[y*newwidth+x] = (a*blocksize)/r;
1638             py = ey;
1639         }
1640         px = ex;
1641     }
1642     return newdata;
1643 }
1644
1645 void SWFOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
1646                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
1647                                    GBool inlineImg, int mask)
1648 {
1649   FILE *fi;
1650   int c;
1651   char fileName[128];
1652   double x1,y1,x2,y2,x3,y3,x4,y4;
1653   ImageStream *imgStr;
1654   Guchar pixBuf[4];
1655   GfxRGB rgb;
1656   int ncomps = 1;
1657   int bits = 1;
1658                                  
1659   if(colorMap) {
1660     ncomps = colorMap->getNumPixelComps();
1661     bits = colorMap->getBits();
1662   }
1663   imgStr = new ImageStream(str, width, ncomps,bits);
1664   imgStr->reset();
1665
1666   if(!width || !height || (height<=1 && width<=1))
1667   {
1668       msg("<verbose> Ignoring %d by %d image", width, height);
1669       unsigned char buf[8];
1670       int x,y;
1671       for (y = 0; y < height; ++y)
1672       for (x = 0; x < width; ++x) {
1673           imgStr->getPixel(buf);
1674       }
1675       delete imgStr;
1676       return;
1677   }
1678   
1679   state->transform(0, 1, &x1, &y1);
1680   state->transform(0, 0, &x2, &y2);
1681   state->transform(1, 0, &x3, &y3);
1682   state->transform(1, 1, &x4, &y4);
1683
1684   if(!pbminfo && !(str->getKind()==strDCT)) {
1685       if(!type3active) {
1686           msg("<notice> file contains pbm pictures %s",mask?"(masked)":"");
1687           pbminfo = 1;
1688       }
1689       if(mask)
1690       msg("<verbose> drawing %d by %d masked picture\n", width, height);
1691   }
1692   if(!jpeginfo && (str->getKind()==strDCT)) {
1693       msg("<notice> file contains jpeg pictures");
1694       jpeginfo = 1;
1695   }
1696
1697   if(mask) {
1698       int yes=0,i,j;
1699       unsigned char buf[8];
1700       int xid = 0;
1701       int yid = 0;
1702       int x,y;
1703       unsigned char*pic = new unsigned char[width*height];
1704       RGBA pal[256];
1705       GfxRGB rgb;
1706       state->getFillRGB(&rgb);
1707       memset(pal,255,sizeof(pal));
1708       pal[0].r = (int)(rgb.r*255); pal[0].g = (int)(rgb.g*255); 
1709       pal[0].b = (int)(rgb.b*255); pal[0].a = 255;
1710       pal[1].r = 0; pal[1].g = 0; pal[1].b = 0; pal[1].a = 0;
1711       int numpalette = 2;
1712       xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1713       yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1714       int realwidth = (int)sqrt(SQR(x2-x3) + SQR(y2-y3));
1715       int realheight = (int)sqrt(SQR(x1-x2) + SQR(y1-y2));
1716       for (y = 0; y < height; ++y)
1717       for (x = 0; x < width; ++x)
1718       {
1719             imgStr->getPixel(buf);
1720             if(invert) 
1721                 buf[0]=1-buf[0];
1722             pic[width*y+x] = buf[0];
1723             xid+=x*buf[0]+1;
1724             yid+=y*buf[0]*3+1;
1725       }
1726       
1727       /* the size of the drawn image is added to the identifier
1728          as the same image may require different bitmaps if displayed
1729          at different sizes (due to antialiasing): */
1730       if(type3active) {
1731           xid += realwidth;
1732           yid += realheight;
1733       }
1734       int t,found = -1;
1735       for(t=0;t<picpos;t++)
1736       {
1737           if(pic_xids[t] == xid &&
1738              pic_yids[t] == yid) {
1739               /* if the image was antialiased, the size has changed: */
1740               width = pic_width[t];
1741               height = pic_height[t];
1742               found = t;break;
1743           }
1744       }
1745       if(found<0) {
1746           if(type3active) {
1747               numpalette = 16;
1748               unsigned char*pic2 = 0;
1749               
1750               pic2 = antialize(pic,width,height,realwidth,realheight, numpalette);
1751
1752               if(pic2) {
1753                   width = realwidth;
1754                   height = realheight;
1755                   free(pic);
1756                   pic = pic2;
1757                   /* make a black/white palette */
1758                   int t;
1759                   GfxRGB rgb2;
1760                   rgb2.r = 1 - rgb.r;
1761                   rgb2.g = 1 - rgb.g;
1762                   rgb2.b = 1 - rgb.b;
1763
1764                   float r = 255/(numpalette-1);
1765                   for(t=0;t<numpalette;t++) {
1766                       /*pal[t].r = (U8)(t*r*rgb.r+(numpalette-1-t)*r*rgb2.r);
1767                       pal[t].g = (U8)(t*r*rgb.g+(numpalette-1-t)*r*rgb2.g);
1768                       pal[t].b = (U8)(t*r*rgb.b+(numpalette-1-t)*r*rgb2.b);
1769                       pal[t].a = 255; */
1770                       pal[t].r = (U8)(255*rgb.r);
1771                       pal[t].g = (U8)(255*rgb.g);
1772                       pal[t].b = (U8)(255*rgb.b);
1773                       pal[t].a = (U8)(t*r);
1774                   }
1775               }
1776           }
1777           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, 
1778                   x1,y1,x2,y2,x3,y3,x4,y4, numpalette);
1779           pic_xids[picpos] = xid;
1780           pic_yids[picpos] = yid;
1781           pic_width[picpos] = width;
1782           pic_height[picpos] = height;
1783           if(picpos<1024)
1784               picpos++;
1785       } else {
1786           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1787                   x1,y1,x2,y2,x3,y3,x4,y4);
1788       }
1789       free(pic);
1790       delete imgStr;
1791       return;
1792   } 
1793
1794   int x,y;
1795   
1796   if(colorMap->getNumPixelComps()!=1 || str->getKind()==strDCT)
1797   {
1798       RGBA*pic=new RGBA[width*height];
1799       int xid = 0;
1800       int yid = 0;
1801       for (y = 0; y < height; ++y) {
1802         for (x = 0; x < width; ++x) {
1803           int r,g,b,a;
1804           imgStr->getPixel(pixBuf);
1805           colorMap->getRGB(pixBuf, &rgb);
1806           pic[width*y+x].r = r = (U8)(rgb.r * 255 + 0.5);
1807           pic[width*y+x].g = g = (U8)(rgb.g * 255 + 0.5);
1808           pic[width*y+x].b = b = (U8)(rgb.b * 255 + 0.5);
1809           pic[width*y+x].a = a = 255;//(U8)(rgb.a * 255 + 0.5);
1810           xid += x*r+x*b*3+x*g*7+x*a*11;
1811           yid += y*r*3+y*b*17+y*g*19+y*a*11;
1812         }
1813       }
1814       int t,found = -1;
1815       for(t=0;t<picpos;t++)
1816       {
1817           if(pic_xids[t] == xid &&
1818              pic_yids[t] == yid) {
1819               found = t;break;
1820           }
1821       }
1822       if(found<0) {
1823           if(str->getKind()==strDCT)
1824               pic_ids[picpos] = swfoutput_drawimagejpeg(&output, pic, width, height, 
1825                       x1,y1,x2,y2,x3,y3,x4,y4);
1826           else
1827               pic_ids[picpos] = swfoutput_drawimagelossless(&output, pic, width, height, 
1828                       x1,y1,x2,y2,x3,y3,x4,y4);
1829           pic_xids[picpos] = xid;
1830           pic_yids[picpos] = yid;
1831           pic_width[picpos] = width;
1832           pic_height[picpos] = height;
1833           if(picpos<1024)
1834               picpos++;
1835       } else {
1836           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1837                   x1,y1,x2,y2,x3,y3,x4,y4);
1838       }
1839       delete pic;
1840       delete imgStr;
1841       return;
1842   }
1843   else
1844   {
1845       U8*pic = new U8[width*height];
1846       RGBA pal[256];
1847       int t;
1848       int xid=0,yid=0;
1849       for(t=0;t<256;t++)
1850       {
1851           int r,g,b,a;
1852           pixBuf[0] = t;
1853           colorMap->getRGB(pixBuf, &rgb);
1854           pal[t].r = r = (U8)(rgb.r * 255 + 0.5);
1855           pal[t].g = g = (U8)(rgb.g * 255 + 0.5);
1856           pal[t].b = b = (U8)(rgb.b * 255 + 0.5);
1857           pal[t].a = a = 255;//(U8)(rgb.b * 255 + 0.5);
1858           xid += t*r+t*b*3+t*g*7+t*a*11;
1859           xid += (~t)*r+t*b*3+t*g*7+t*a*11;
1860       }
1861       for (y = 0; y < height; ++y) {
1862         for (x = 0; x < width; ++x) {
1863           imgStr->getPixel(pixBuf);
1864           pic[width*y+x] = pixBuf[0];
1865           xid += x*pixBuf[0]*7;
1866           yid += y*pixBuf[0]*3;
1867         }
1868       }
1869       int found = -1;
1870       for(t=0;t<picpos;t++)
1871       {
1872           if(pic_xids[t] == xid &&
1873              pic_yids[t] == yid) {
1874               found = t;break;
1875           }
1876       }
1877       if(found<0) {
1878           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, 
1879                   x1,y1,x2,y2,x3,y3,x4,y4,256);
1880           pic_xids[picpos] = xid;
1881           pic_yids[picpos] = yid;
1882           pic_width[picpos] = width;
1883           pic_height[picpos] = height;
1884           if(picpos<1024)
1885               picpos++;
1886       } else {
1887           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1888                   x1,y1,x2,y2,x3,y3,x4,y4);
1889       }
1890       delete pic;
1891       delete imgStr;
1892       return;
1893   }
1894 }
1895
1896 void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1897                                    int width, int height, GBool invert,
1898                                    GBool inlineImg) 
1899 {
1900   msg("<verbose> drawImageMask %dx%d, invert=%d inline=%d", width, height, invert, inlineImg);
1901   drawGeneralImage(state,ref,str,width,height,0,invert,inlineImg,1);
1902 }
1903
1904 void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1905                          int width, int height, GfxImageColorMap *colorMap,
1906                          int *maskColors, GBool inlineImg)
1907 {
1908   msg("<verbose> drawImage %dx%d, %s %s, inline=%d", width, height, 
1909           colorMap?"colorMap":"no colorMap", 
1910           maskColors?"maskColors":"no maskColors",
1911           inlineImg);
1912   if(colorMap)
1913       msg("<verbose> colorMap pixcomps:%d bits:%d mode:%d\n", colorMap->getNumPixelComps(),
1914               colorMap->getBits(),colorMap->getColorSpace()->getMode());
1915   drawGeneralImage(state,ref,str,width,height,colorMap,0,inlineImg,0);
1916 }
1917
1918 SWFOutputDev*output = 0; 
1919
1920 static void printInfoString(Dict *infoDict, char *key, char *fmt) {
1921   Object obj;
1922   GString *s1, *s2;
1923   int i;
1924
1925   if (infoDict->lookup(key, &obj)->isString()) {
1926     s1 = obj.getString();
1927     if ((s1->getChar(0) & 0xff) == 0xfe &&
1928         (s1->getChar(1) & 0xff) == 0xff) {
1929       s2 = new GString();
1930       for (i = 2; i < obj.getString()->getLength(); i += 2) {
1931         if (s1->getChar(i) == '\0') {
1932           s2->append(s1->getChar(i+1));
1933         } else {
1934           delete s2;
1935           s2 = new GString("<unicode>");
1936           break;
1937         }
1938       }
1939       printf(fmt, s2->getCString());
1940       delete s2;
1941     } else {
1942       printf(fmt, s1->getCString());
1943     }
1944   }
1945   obj.free();
1946 }
1947
1948 static void printInfoDate(Dict *infoDict, char *key, char *fmt) {
1949   Object obj;
1950   char *s;
1951
1952   if (infoDict->lookup(key, &obj)->isString()) {
1953     s = obj.getString()->getCString();
1954     if (s[0] == 'D' && s[1] == ':') {
1955       s += 2;
1956     }
1957     printf(fmt, s);
1958   }
1959   obj.free();
1960 }
1961
1962 void pdfswf_setparameter(char*name, char*value)
1963 {
1964     msg("<verbose> setting parameter %s to \"%s\"", name, value);
1965     if(!strcmp(name, "caplinewidth")) {
1966         caplinewidth = atof(value);
1967     } else if(!strcmp(name, "zoom")) {
1968         zoom = atoi(value);
1969     } else if(!strcmp(name, "forceType0Fonts")) {
1970         forceType0Fonts = atoi(value);
1971     } else if(!strcmp(name, "fontdir")) {
1972         pdfswf_addfontdir(value);
1973     } else if(!strcmp(name, "languagedir")) {
1974         pdfswf_addlanguagedir(value);
1975     } else if(!strcmp(name, "fontconfig")) {
1976         config_use_fontconfig = atoi(value);
1977     } else {
1978         swfoutput_setparameter(name, value);
1979     }
1980 }
1981 void pdfswf_addfont(char*filename)
1982 {
1983     fontfile_t f;
1984     memset(&f, 0, sizeof(fontfile_t));
1985     f.filename = filename;
1986     if(fontnum < sizeof(fonts)/sizeof(fonts[0])) {
1987         fonts[fontnum++] = f;
1988     } else {
1989         msg("<error> Too many external fonts. Not adding font file \"%s\".", filename);
1990     }
1991 }
1992
1993 static char* dirseparator()
1994 {
1995 #ifdef WIN32
1996     return "\\";
1997 #else
1998     return "/";
1999 #endif
2000 }
2001
2002 void pdfswf_addlanguagedir(char*dir)
2003 {
2004     if(!globalParams)
2005         globalParams = new GlobalParams("");
2006     
2007     msg("<notice> Adding %s to language pack directories", dir);
2008
2009     int l;
2010     FILE*fi = 0;
2011     char* config_file = (char*)malloc(strlen(dir) + 1 + sizeof("add-to-xpdfrc"));
2012     strcpy(config_file, dir);
2013     strcat(config_file, dirseparator());
2014     strcat(config_file, "add-to-xpdfrc");
2015
2016     fi = fopen(config_file, "rb");
2017     if(!fi) {
2018         msg("<error> Could not open %s", config_file);
2019         return;
2020     }
2021     globalParams->parseFile(new GString(config_file), fi);
2022     fclose(fi);
2023 }
2024
2025 void pdfswf_addfontdir(char*dirname)
2026 {
2027 #ifdef HAVE_DIRENT_H
2028     msg("<notice> Adding %s to font directories", dirname);
2029     DIR*dir = opendir(dirname);
2030     if(!dir) {
2031         msg("<warning> Couldn't open directory %s\n", dirname);
2032         return;
2033     }
2034     struct dirent*ent;
2035     while(1) {
2036         ent = readdir (dir);
2037         if (!ent) 
2038             break;
2039         int l;
2040         char*name = ent->d_name;
2041         char type = 0;
2042         if(!name) continue;
2043         l=strlen(name);
2044         if(l<4)
2045             continue;
2046         if(!strncasecmp(&name[l-4], ".pfa", 4)) 
2047             type=1;
2048         if(!strncasecmp(&name[l-4], ".pfb", 4)) 
2049             type=3;
2050         if(!strncasecmp(&name[l-4], ".ttf", 4)) 
2051             type=2;
2052         if(type)
2053         {
2054             char*fontname = (char*)malloc(strlen(dirname)+strlen(name)+2);
2055             strcpy(fontname, dirname);
2056             strcat(fontname, dirseparator());
2057             strcat(fontname, name);
2058             msg("<verbose> Adding %s to fonts", fontname);
2059             pdfswf_addfont(fontname);
2060         }
2061     }
2062     closedir(dir);
2063 #else
2064     msg("<warning> No dirent.h- unable to add font dir %s", dir);
2065 #endif
2066 }
2067
2068
2069 typedef struct _pdf_doc_internal
2070 {
2071     int protect;
2072     PDFDoc*doc;
2073 } pdf_doc_internal_t;
2074 typedef struct _pdf_page_internal
2075 {
2076 } pdf_page_internal_t;
2077 typedef struct _swf_output_internal
2078 {
2079     SWFOutputDev*outputDev;
2080 } swf_output_internal_t;
2081
2082 pdf_doc_t* pdf_init(char*filename, char*userPassword)
2083 {
2084     pdf_doc_t*pdf_doc = (pdf_doc_t*)malloc(sizeof(pdf_doc_t));
2085     memset(pdf_doc, 0, sizeof(pdf_doc_t));
2086     pdf_doc_internal_t*i= (pdf_doc_internal_t*)malloc(sizeof(pdf_doc_internal_t));
2087     memset(i, 0, sizeof(pdf_doc_internal_t));
2088     pdf_doc->internal = i;
2089     
2090     GString *fileName = new GString(filename);
2091     GString *userPW;
2092     Object info;
2093
2094     // read config file
2095     if(!globalParams)
2096         globalParams = new GlobalParams("");
2097
2098     // open PDF file
2099     if (userPassword && userPassword[0]) {
2100       userPW = new GString(userPassword);
2101     } else {
2102       userPW = NULL;
2103     }
2104     i->doc = new PDFDoc(fileName, userPW);
2105     if (userPW) {
2106       delete userPW;
2107     }
2108     if (!i->doc->isOk()) {
2109         return 0;
2110     }
2111
2112     // print doc info
2113     i->doc->getDocInfo(&info);
2114     if (info.isDict() &&
2115       (getScreenLogLevel()>=LOGLEVEL_NOTICE)) {
2116       printInfoString(info.getDict(), "Title",        "Title:        %s\n");
2117       printInfoString(info.getDict(), "Subject",      "Subject:      %s\n");
2118       printInfoString(info.getDict(), "Keywords",     "Keywords:     %s\n");
2119       printInfoString(info.getDict(), "Author",       "Author:       %s\n");
2120       printInfoString(info.getDict(), "Creator",      "Creator:      %s\n");
2121       printInfoString(info.getDict(), "Producer",     "Producer:     %s\n");
2122       printInfoDate(info.getDict(),   "CreationDate", "CreationDate: %s\n");
2123       printInfoDate(info.getDict(),   "ModDate",      "ModDate:      %s\n");
2124       printf("Pages:        %d\n", i->doc->getNumPages());
2125       printf("Linearized:   %s\n", i->doc->isLinearized() ? "yes" : "no");
2126       printf("Encrypted:    ");
2127       if (i->doc->isEncrypted()) {
2128         printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
2129                i->doc->okToPrint() ? "yes" : "no",
2130                i->doc->okToCopy() ? "yes" : "no",
2131                i->doc->okToChange() ? "yes" : "no",
2132                i->doc->okToAddNotes() ? "yes" : "no");
2133       } else {
2134         printf("no\n");
2135       }
2136     }
2137     info.free();
2138                    
2139     pdf_doc->num_pages = i->doc->getNumPages();
2140     i->protect = 0;
2141     if (i->doc->isEncrypted()) {
2142           if(!i->doc->okToCopy()) {
2143               printf("PDF disallows copying.\n");
2144               return 0;
2145           }
2146           if(!i->doc->okToChange() || !i->doc->okToAddNotes())
2147               i->protect = 1;
2148     }
2149    
2150     return pdf_doc;
2151 }
2152
2153 void pdfswf_preparepage(int page)
2154 {
2155     /*FIXME*/
2156     if(!pages) {
2157         pages = (int*)malloc(1024*sizeof(int));
2158         pagebuflen = 1024;
2159     } else {
2160         if(pagepos == pagebuflen)
2161         {
2162             pagebuflen+=1024;
2163             pages = (int*)realloc(pages, pagebuflen);
2164         }
2165     }
2166     pages[pagepos++] = page;
2167 }
2168
2169 class MemCheck
2170 {
2171     public: ~MemCheck()
2172     {
2173         delete globalParams;globalParams=0;
2174         Object::memCheck(stderr);
2175         gMemReport(stderr);
2176     }
2177 } myMemCheck;
2178
2179 void pdf_destroy(pdf_doc_t*pdf_doc)
2180 {
2181     pdf_doc_internal_t*i= (pdf_doc_internal_t*)pdf_doc->internal;
2182
2183     msg("<debug> pdfswf.cc: pdfswf_close()");
2184     delete i->doc; i->doc=0;
2185     
2186     free(pages); pages = 0; //FIXME
2187
2188     free(pdf_doc->internal);pdf_doc->internal=0;
2189     free(pdf_doc);pdf_doc=0;
2190 }
2191
2192 pdf_page_t* pdf_getpage(pdf_doc_t*pdf_doc, int page)
2193 {
2194     pdf_doc_internal_t*di= (pdf_doc_internal_t*)pdf_doc->internal;
2195
2196     if(page < 1 || page > pdf_doc->num_pages)
2197         return 0;
2198     
2199     pdf_page_t* pdf_page = (pdf_page_t*)malloc(sizeof(pdf_page_t));
2200     pdf_page_internal_t*pi= (pdf_page_internal_t*)malloc(sizeof(pdf_page_internal_t));
2201     memset(pi, 0, sizeof(pdf_page_internal_t));
2202     pdf_page->internal = pi;
2203
2204     pdf_page->parent = pdf_doc;
2205     pdf_page->nr = page;
2206     return pdf_page;
2207 }
2208
2209 void pdf_page_destroy(pdf_page_t*pdf_page)
2210 {
2211     pdf_page_internal_t*i= (pdf_page_internal_t*)pdf_page->internal;
2212     free(pdf_page->internal);pdf_page->internal = 0;
2213     free(pdf_page);pdf_page=0;
2214 }
2215
2216 swf_output_t* swf_output_init() 
2217 {
2218     swf_output_t*swf_output = (swf_output_t*)malloc(sizeof(swf_output_t));
2219     memset(swf_output, 0, sizeof(swf_output_t));
2220     swf_output_internal_t*i= (swf_output_internal_t*)malloc(sizeof(swf_output_internal_t));
2221     memset(i, 0, sizeof(swf_output_internal_t));
2222     swf_output->internal = i;
2223
2224     i->outputDev = new SWFOutputDev();
2225     return swf_output;
2226 }
2227
2228 void swf_output_setparameter(swf_output_t*swf_output, char*name, char*value)
2229 {
2230     /* FIXME */
2231     pdfswf_setparameter(name, value);
2232 }
2233
2234 void swf_output_pagefeed(swf_output_t*swf)
2235 {
2236     swf_output_internal_t*i= (swf_output_internal_t*)swf->internal;
2237     i->outputDev->pagefeed();
2238     i->outputDev->getDimensions(&swf->x1, &swf->y1, &swf->x2, &swf->y2);
2239 }
2240
2241 int swf_output_save(swf_output_t*swf, char*filename)
2242 {
2243     swf_output_internal_t*i= (swf_output_internal_t*)swf->internal;
2244     int ret = i->outputDev->save(filename);
2245     i->outputDev->getDimensions(&swf->x1, &swf->y1, &swf->x2, &swf->y2);
2246     return ret;
2247 }
2248
2249 void* swf_output_get(swf_output_t*swf)
2250 {
2251     swf_output_internal_t*i= (swf_output_internal_t*)swf->internal;
2252     void* ret = i->outputDev->getSWF();
2253     i->outputDev->getDimensions(&swf->x1, &swf->y1, &swf->x2, &swf->y2);
2254     return ret;
2255 }
2256
2257 void swf_output_destroy(swf_output_t*output)
2258 {
2259     swf_output_internal_t*i = (swf_output_internal_t*)output->internal;
2260     delete i->outputDev; i->outputDev=0;
2261     free(output->internal);output->internal=0;
2262     free(output);
2263 }
2264
2265 void pdf_page_render2(pdf_page_t*page, swf_output_t*swf)
2266 {
2267     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
2268     swf_output_internal_t*si = (swf_output_internal_t*)swf->internal;
2269
2270     if(pi->protect) {
2271         swfoutput_setparameter("protect", "1");
2272     }
2273     si->outputDev->setXRef(pi->doc, pi->doc->getXRef());
2274 #ifdef XPDF_101
2275     pi->doc->displayPage((OutputDev*)si->outputDev, page->nr, /*zoom*/zoom, /*rotate*/0, /*doLinks*/(int)1);
2276 #else
2277     pi->doc->displayPage((OutputDev*)si->outputDev, page->nr, zoom, zoom, /*rotate*/0, true, /*doLinks*/(int)1);
2278 #endif
2279     si->outputDev->getDimensions(&swf->x1, &swf->y1, &swf->x2, &swf->y2);
2280 }
2281
2282 void pdf_page_rendersection(pdf_page_t*page, swf_output_t*output, int x, int y, int x1, int y1, int x2, int y2)
2283 {
2284     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
2285     swf_output_internal_t*si = (swf_output_internal_t*)output->internal;
2286
2287     si->outputDev->setMove(x,y);
2288     if((x1|y1|x2|y2)==0) x2++;
2289     si->outputDev->setClip(x1,y1,x2,y2);
2290
2291     pdf_page_render2(page, output);
2292 }
2293 void pdf_page_render(pdf_page_t*page, swf_output_t*output)
2294 {
2295     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
2296     swf_output_internal_t*si = (swf_output_internal_t*)output->internal;
2297     
2298     si->outputDev->setMove(0,0);
2299     si->outputDev->setClip(0,0,0,0);
2300     
2301     pdf_page_render2(page, output);
2302 }
2303
2304
2305 pdf_page_info_t* pdf_page_getinfo(pdf_page_t*page)
2306 {
2307     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
2308     pdf_page_internal_t*i= (pdf_page_internal_t*)page->internal;
2309     pdf_page_info_t*info = (pdf_page_info_t*)malloc(sizeof(pdf_page_info_t));
2310     memset(info, 0, sizeof(pdf_page_info_t));
2311
2312     InfoOutputDev*output = new InfoOutputDev;
2313     
2314 #ifdef XPDF_101
2315     pi->doc->displayPage((OutputDev*)output, page->nr, /*zoom*/zoom, /*rotate*/0, /*doLinks*/(int)1);
2316 #else
2317     pi->doc->displayPage((OutputDev*)output, page->nr, zoom, zoom, /*rotate*/0, true, /*doLinks*/(int)1);
2318 #endif
2319
2320     info->xMin = output->x1;
2321     info->yMin = output->y1;
2322     info->xMax = output->x2;
2323     info->yMax = output->y2;
2324     info->number_of_images = output->num_images;
2325     info->number_of_links = output->num_links;
2326     info->number_of_fonts = output->num_fonts;
2327
2328     delete output;
2329
2330     return info;
2331 }
2332
2333 void pdf_page_info_destroy(pdf_page_info_t*info)
2334 {
2335     free(info);
2336 }