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