initialize globalParams. Otherwise, xpdf segfaults.
[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 //xpdf header files
26 #include "gfile.h"
27 #include "GString.h"
28 #include "gmem.h"
29 #include "Object.h"
30 #include "Stream.h"
31 #include "Array.h"
32 #include "Dict.h"
33 #include "XRef.h"
34 #include "Catalog.h"
35 #include "Page.h"
36 #include "PDFDoc.h"
37 #include "Error.h"
38 #include "config.h"
39 #include "OutputDev.h"
40 #include "GfxState.h"
41 #include "GfxFont.h"
42 #include "FontFile.h"
43 #include "GlobalParams.h"
44 //swftools header files
45 #include "swfoutput.h"
46 extern "C" {
47 #include "../lib/log.h"
48 #include "ttf2pt1.h"
49 }
50
51 static PDFDoc*doc = 0;
52 static char* swffilename = 0;
53 int numpages;
54 int currentpage;
55
56 // swf <-> pdf pages
57 int*pages = 0;
58 int pagebuflen = 0;
59 int pagepos = 0;
60
61 static void printInfoString(Dict *infoDict, char *key, char *fmt);
62 static void printInfoDate(Dict *infoDict, char *key, char *fmt);
63
64 double fontsizes[] = 
65 {
66  0.833,0.833,0.889,0.889,
67  0.788,0.722,0.833,0.778,
68  0.600,0.600,0.600,0.600,
69  0.576,0.576,0.576,0.576,
70  0.733 //?
71 };
72 char*fontnames[]={
73 "Helvetica",             
74 "Helvetica-Bold",        
75 "Helvetica-BoldOblique", 
76 "Helvetica-Oblique",     
77 "Times-Roman",           
78 "Times-Bold",            
79 "Times-BoldItalic",      
80 "Times-Italic",          
81 "Courier",               
82 "Courier-Bold",          
83 "Courier-BoldOblique",   
84 "Courier-Oblique",       
85 "Symbol",                
86 "Symbol",                
87 "Symbol",                
88 "Symbol",
89 "ZapfDingBats"
90 };
91
92 struct mapping {
93     char*pdffont;
94     char*filename;
95     int id;
96 } pdf2t1map[] ={
97 {"Times-Roman",           "n021003l.pfb"},
98 {"Times-Italic",          "n021023l.pfb"},
99 {"Times-Bold",            "n021004l.pfb"},
100 {"Times-BoldItalic",      "n021024l.pfb"},
101 {"Helvetica",             "n019003l.pfb"},
102 {"Helvetica-Oblique",     "n019023l.pfb"},
103 {"Helvetica-Bold",        "n019004l.pfb"},
104 {"Helvetica-BoldOblique", "n019024l.pfb"},
105 {"Courier",               "n022003l.pfb"},
106 {"Courier-Oblique",       "n022023l.pfb"},
107 {"Courier-Bold",          "n022004l.pfb"},
108 {"Courier-BoldOblique",   "n022024l.pfb"},
109 {"Symbol",                "s050000l.pfb"},
110 {"ZapfDingbats",          "d050000l.pfb"}};
111
112 class GfxState;
113 class GfxImageColorMap;
114
115 class SWFOutputDev:  public OutputDev {
116   struct swfoutput output;
117   int outputstarted;
118 public:
119
120   // Constructor.
121   SWFOutputDev();
122
123   // Destructor.
124   virtual ~SWFOutputDev() ;
125
126   //----- get info about output device
127
128   // Does this device use upside-down coordinates?
129   // (Upside-down means (0,0) is the top left corner of the page.)
130   virtual GBool upsideDown();
131
132   // Does this device use drawChar() or drawString()?
133   virtual GBool useDrawChar();
134   
135   virtual GBool interpretType3Chars() {return gFalse;}
136
137   //----- initialization and control
138
139   // Start a page.
140   virtual void startPage(int pageNum, GfxState *state) ;
141
142   //----- link borders
143   virtual void drawLink(Link *link, Catalog *catalog) ;
144
145   //----- save/restore graphics state
146   virtual void saveState(GfxState *state) ;
147   virtual void restoreState(GfxState *state) ;
148
149   //----- update graphics state
150
151   virtual void updateFont(GfxState *state);
152   virtual void updateFillColor(GfxState *state);
153   virtual void updateStrokeColor(GfxState *state);
154   virtual void updateLineWidth(GfxState *state);
155   
156   virtual void updateAll(GfxState *state) 
157   {
158       updateFont(state);
159       updateFillColor(state);
160       updateStrokeColor(state);
161       updateLineWidth(state);
162   };
163
164   //----- path painting
165   virtual void stroke(GfxState *state) ;
166   virtual void fill(GfxState *state) ;
167   virtual void eoFill(GfxState *state) ;
168
169   //----- path clipping
170   virtual void clip(GfxState *state) ;
171   virtual void eoClip(GfxState *state) ;
172
173   //----- text drawing
174   virtual void beginString(GfxState *state, GString *s) ;
175   virtual void endString(GfxState *state) ;
176   virtual void drawChar(GfxState *state, double x, double y,
177                         double dx, double dy, Guchar c) ;
178   virtual void drawChar16(GfxState *state, double x, double y,
179                           double dx, double dy, int c) ;
180
181   //----- image drawing
182   virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
183                              int width, int height, GBool invert,
184                              GBool inlineImg);
185   virtual void drawImage(GfxState *state, Object *ref, Stream *str,
186                          int width, int height, GfxImageColorMap *colorMap,
187                          GBool inlineImg);
188
189   private:
190   void drawGeneralImage(GfxState *state, Object *ref, Stream *str,
191                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
192                                    GBool inlineImg, int mask);
193   int clipping[64];
194   int clippos;
195
196   int searchT1Font(char*name);
197   char* substituteFont(GfxFont*gfxFont, char*oldname);
198   char* writeEmbeddedFontToFile(GfxFont*font);
199   int t1id;
200   int jpeginfo; // did we write "File contains jpegs" yet?
201   int pbminfo; // did we write "File contains jpegs" yet?
202   int linkinfo; // did we write "File contains links" yet?
203   int ttfinfo; // did we write "File contains TrueType Fonts" yet?
204
205   GfxState *laststate;
206 };
207
208 char mybuf[1024];
209 char* gfxstate2str(GfxState *state)
210 {
211   char*bufpos = mybuf;
212   GfxRGB rgb;
213   bufpos+=sprintf(bufpos,"CTM[%.3f/%.3f/%.3f/%.3f/%.3f/%.3f] ",
214                                     state->getCTM()[0],
215                                     state->getCTM()[1],
216                                     state->getCTM()[2],
217                                     state->getCTM()[3],
218                                     state->getCTM()[4],
219                                     state->getCTM()[5]);
220   if(state->getX1()!=0.0)
221   bufpos+=sprintf(bufpos,"X1-%.1f ",state->getX1());
222   if(state->getY1()!=0.0)
223   bufpos+=sprintf(bufpos,"Y1-%.1f ",state->getY1());
224   bufpos+=sprintf(bufpos,"X2-%.1f ",state->getX2());
225   bufpos+=sprintf(bufpos,"Y2-%.1f ",state->getY2());
226   bufpos+=sprintf(bufpos,"PW%.1f ",state->getPageWidth());
227   bufpos+=sprintf(bufpos,"PH%.1f ",state->getPageHeight());
228   /*bufpos+=sprintf(bufpos,"FC[%.1f/%.1f] ",
229           state->getFillColor()->c[0], state->getFillColor()->c[1]);
230   bufpos+=sprintf(bufpos,"SC[%.1f/%.1f] ",
231           state->getStrokeColor()->c[0], state->getFillColor()->c[1]);*/
232 /*  bufpos+=sprintf(bufpos,"FC[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f]",
233           state->getFillColor()->c[0], state->getFillColor()->c[1],
234           state->getFillColor()->c[2], state->getFillColor()->c[3],
235           state->getFillColor()->c[4], state->getFillColor()->c[5],
236           state->getFillColor()->c[6], state->getFillColor()->c[7]);
237   bufpos+=sprintf(bufpos,"SC[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f]",
238           state->getStrokeColor()->c[0], state->getFillColor()->c[1],
239           state->getStrokeColor()->c[2], state->getFillColor()->c[3],
240           state->getStrokeColor()->c[4], state->getFillColor()->c[5],
241           state->getStrokeColor()->c[6], state->getFillColor()->c[7]);*/
242   state->getFillRGB(&rgb);
243   if(rgb.r || rgb.g || rgb.b)
244   bufpos+=sprintf(bufpos,"FR[%.1f/%.1f/%.1f] ", rgb.r,rgb.g,rgb.b);
245   state->getStrokeRGB(&rgb);
246   if(rgb.r || rgb.g || rgb.b)
247   bufpos+=sprintf(bufpos,"SR[%.1f/%.1f/%.1f] ", rgb.r,rgb.g,rgb.b);
248   if(state->getFillColorSpace()->getNComps()>1)
249   bufpos+=sprintf(bufpos,"CS[[%d]] ",state->getFillColorSpace()->getNComps());
250   if(state->getStrokeColorSpace()->getNComps()>1)
251   bufpos+=sprintf(bufpos,"SS[[%d]] ",state->getStrokeColorSpace()->getNComps());
252   if(state->getFillPattern())
253   bufpos+=sprintf(bufpos,"FP%08x ", state->getFillPattern());
254   if(state->getStrokePattern())
255   bufpos+=sprintf(bufpos,"SP%08x ", state->getStrokePattern());
256  
257   if(state->getFillOpacity()!=1.0)
258   bufpos+=sprintf(bufpos,"FO%.1f ", state->getFillOpacity());
259   if(state->getStrokeOpacity()!=1.0)
260   bufpos+=sprintf(bufpos,"SO%.1f ", state->getStrokeOpacity());
261
262   bufpos+=sprintf(bufpos,"LW%.1f ", state->getLineWidth());
263  
264   double * dash;
265   int length;
266   double start;
267   state->getLineDash(&dash, &length, &start);
268   int t;
269   if(length)
270   {
271       bufpos+=sprintf(bufpos,"DASH%.1f[",start);
272       for(t=0;t<length;t++) {
273           bufpos+=sprintf(bufpos,"D%.1f",dash[t]);
274       }
275       bufpos+=sprintf(bufpos,"]");
276   }
277
278   if(state->getFlatness()!=1)
279   bufpos+=sprintf(bufpos,"F%d ", state->getFlatness());
280   if(state->getLineJoin()!=0)
281   bufpos+=sprintf(bufpos,"J%d ", state->getLineJoin());
282   if(state->getLineJoin()!=0)
283   bufpos+=sprintf(bufpos,"C%d ", state->getLineCap());
284   if(state->getLineJoin()!=0)
285   bufpos+=sprintf(bufpos,"ML%d ", state->getMiterLimit());
286
287   if(state->getFont() && state->getFont()->getName() && state->getFont()->getName()->getCString())
288   bufpos+=sprintf(bufpos,"F\"%s\" ",((state->getFont())->getName())->getCString());
289   bufpos+=sprintf(bufpos,"FS%.1f ", state->getFontSize());
290   bufpos+=sprintf(bufpos,"MAT[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f] ", state->getTextMat()[0],state->getTextMat()[1],state->getTextMat()[2],
291                                    state->getTextMat()[3],state->getTextMat()[4],state->getTextMat()[5]);
292   if(state->getCharSpace())
293   bufpos+=sprintf(bufpos,"CS%.5f ", state->getCharSpace());
294   if(state->getWordSpace())
295   bufpos+=sprintf(bufpos,"WS%.5f ", state->getWordSpace());
296   if(state->getHorizScaling()!=1.0)
297   bufpos+=sprintf(bufpos,"SC%.1f ", state->getHorizScaling());
298   if(state->getLeading())
299   bufpos+=sprintf(bufpos,"L%.1f ", state->getLeading());
300   if(state->getRise())
301   bufpos+=sprintf(bufpos,"R%.1f ", state->getRise());
302   if(state->getRender())
303   bufpos+=sprintf(bufpos,"R%d ", state->getRender());
304   bufpos+=sprintf(bufpos,"P%08x ", state->getPath());
305   bufpos+=sprintf(bufpos,"CX%.1f ", state->getCurX());
306   bufpos+=sprintf(bufpos,"CY%.1f ", state->getCurY());
307   if(state->getLineX())
308   bufpos+=sprintf(bufpos,"LX%.1f ", state->getLineX());
309   if(state->getLineY())
310   bufpos+=sprintf(bufpos,"LY%.1f ", state->getLineY());
311   bufpos+=sprintf(bufpos," ");
312   return mybuf;
313 }
314
315 void dumpFontInfo(char*loglevel, GfxFont*font);
316 int lastdumps[1024];
317 int lastdumppos = 0;
318 /* nr = 0  unknown
319    nr = 1  substituting
320    nr = 2  type 3
321  */
322 void showFontError(GfxFont*font, int nr) 
323 {  
324     Ref*r=font->getID();
325     int t;
326     for(t=0;t<lastdumppos;t++)
327         if(lastdumps[t] == r->num)
328             break;
329     if(t < lastdumppos)
330       return;
331     if(lastdumppos<sizeof(lastdumps)/sizeof(int))
332     lastdumps[lastdumppos++] = r->num;
333     if(nr == 0)
334       logf("<warning> The following font caused problems:");
335     else if(nr == 1)
336       logf("<warning> The following font caused problems (substituting):");
337     else if(nr == 2)
338       logf("<warning> This document contains Type 3 Fonts: (some text may be incorrectly displayed)");
339     dumpFontInfo("<warning>", font);
340 }
341
342 void dumpFontInfo(char*loglevel, GfxFont*font)
343 {
344   GString *gstr;
345   char*name = 0;
346   gstr = font->getName();
347   Ref* r=font->getID();
348   logf("%s=========== %s (ID:%d,%d) ==========\n", loglevel, gstr?FIXNULL(gstr->getCString()):"(unknown font)", r->num,r->gen);
349
350   gstr  = font->getTag();
351   if(gstr) 
352    logf("%sTag: %s\n", loglevel, FIXNULL(gstr->getCString()));
353   
354   //if(font->is16Bit()) logf("%sis 16 bit\n", loglevel); //FIXME: not existing in xpdf 1.01
355
356   GfxFontType type=font->getType();
357   switch(type) {
358     case fontUnknownType:
359      logf("%sType: unknown\n",loglevel);
360     break;
361     case fontType1:
362      logf("%sType: 1\n",loglevel);
363     break;
364     case fontType1C:
365      logf("%sType: 1C\n",loglevel);
366     break;
367     case fontType3:
368      logf("%sType: 3\n",loglevel);
369     break;
370     case fontTrueType:
371      logf("%sType: TrueType\n",loglevel);
372     break;
373     case fontCIDType0:
374      logf("%sType: CIDType0\n",loglevel);
375     break;
376     case fontCIDType0C:
377      logf("%sType: CIDType0C\n",loglevel);
378     break;
379     case fontCIDType2:
380      logf("%sType: CIDType2\n",loglevel);
381     break;
382   }
383   
384   Ref embRef;
385   GBool embedded = font->getEmbeddedFontID(&embRef);
386   if(font->getEmbeddedFontName())
387     name = font->getEmbeddedFontName()->getCString();
388   if(embedded)
389    logf("%sEmbedded name: %s id: %d\n",loglevel, FIXNULL(name), embRef.num);
390
391   gstr = font->getExtFontFile();
392   if(gstr)
393    logf("%sExternal Font file: %s\n", loglevel, FIXNULL(gstr->getCString()));
394
395   // Get font descriptor flags.
396   if(font->isFixedWidth()) logf("%sis fixed width\n", loglevel);
397   if(font->isSerif()) logf("%sis serif\n", loglevel);
398   if(font->isSymbolic()) logf("%sis symbolic\n", loglevel);
399   if(font->isItalic()) logf("%sis italic\n", loglevel);
400   if(font->isBold()) logf("%sis bold\n", loglevel);
401 }
402
403 //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");}
404 //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");}
405
406 SWFOutputDev::SWFOutputDev() 
407 {
408     jpeginfo = 0;
409     ttfinfo = 0;
410     linkinfo = 0;
411     pbminfo = 0;
412     clippos = 0;
413     clipping[clippos] = 0;
414     outputstarted = 0;
415 //    printf("SWFOutputDev::SWFOutputDev() \n");
416 };
417
418 T1_OUTLINE* gfxPath_to_T1_OUTLINE(GfxState*state, GfxPath*path)
419 {
420     int num = path->getNumSubpaths();
421     int s,t;
422     bezierpathsegment*start,*last=0;
423     bezierpathsegment*outline = start = new bezierpathsegment();
424     int cpos = 0;
425     double lastx=0,lasty=0;
426     for(t = 0; t < num; t++) {
427         GfxSubpath *subpath = path->getSubpath(t);
428         int subnum = subpath->getNumPoints();
429
430         for(s=0;s<subnum;s++) {
431            double nx,ny;
432            state->transform(subpath->getX(s),subpath->getY(s),&nx,&ny);
433            int x = (int)((nx-lastx)*0xffff);
434            int y = (int)((ny-lasty)*0xffff);
435            if(s==0) 
436            {
437                 last = outline;
438                 outline->type = T1_PATHTYPE_MOVE;
439                 outline->dest.x = x;
440                 outline->dest.y = y;
441                 outline->link = (T1_OUTLINE*)new bezierpathsegment();
442                 outline = (bezierpathsegment*)outline->link;
443                 cpos = 0;
444                 lastx = nx;
445                 lasty = ny;
446            }
447            else if(subpath->getCurve(s) && !cpos)
448            {
449                 outline->B.x = x;
450                 outline->B.y = y;
451                 cpos = 1;
452            } 
453            else if(subpath->getCurve(s) && cpos)
454            {
455                 outline->C.x = x;
456                 outline->C.y = y;
457                 cpos = 2;
458            }
459            else
460            {
461                 last = outline;
462                 outline->dest.x = x;
463                 outline->dest.y = y;
464                 outline->type = cpos?T1_PATHTYPE_BEZIER:T1_PATHTYPE_LINE;
465                 outline->link = 0;
466                 outline->link = (T1_OUTLINE*)new bezierpathsegment();
467                 outline = (bezierpathsegment*)outline->link;
468                 cpos = 0;
469                 lastx = nx;
470                 lasty = ny;
471            }
472         }
473     }
474     last->link = 0;
475     return (T1_OUTLINE*)start;
476 }
477 /*----------------------------------------------------------------------------
478  * Primitive Graphic routines
479  *----------------------------------------------------------------------------*/
480
481 void SWFOutputDev::stroke(GfxState *state) 
482 {
483     logf("<debug> stroke\n");
484     GfxPath * path = state->getPath();
485     struct swfmatrix m;
486     m.m11 = 1; m.m21 = 0; m.m22 = 1;
487     m.m12 = 0; m.m13 = 0; m.m23 = 0;
488     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
489     swfoutput_setdrawmode(&output, DRAWMODE_STROKE);
490     swfoutput_drawpath(&output, outline, &m);
491 }
492 void SWFOutputDev::fill(GfxState *state) 
493 {
494     logf("<debug> fill\n");
495     GfxPath * path = state->getPath();
496     struct swfmatrix m;
497     m.m11 = 1; m.m21 = 0; m.m22 = 1;
498     m.m12 = 0; m.m13 = 0; m.m23 = 0;
499     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
500     swfoutput_setdrawmode(&output, DRAWMODE_FILL);
501     swfoutput_drawpath(&output, outline, &m);
502 }
503 void SWFOutputDev::eoFill(GfxState *state) 
504 {
505     logf("<debug> eofill\n");
506     GfxPath * path = state->getPath();
507     struct swfmatrix m;
508     m.m11 = 1; m.m21 = 0; m.m22 = 1;
509     m.m12 = 0; m.m13 = 0; m.m23 = 0;
510     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
511     swfoutput_setdrawmode(&output, DRAWMODE_EOFILL);
512     swfoutput_drawpath(&output, outline, &m);
513 }
514 void SWFOutputDev::clip(GfxState *state) 
515 {
516     logf("<debug> clip\n");
517     GfxPath * path = state->getPath();
518     struct swfmatrix m;
519     m.m11 = 1; m.m22 = 1;
520     m.m12 = 0; m.m21 = 0; 
521     m.m13 = 0; m.m23 = 0;
522     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
523     swfoutput_startclip(&output, outline, &m);
524     clipping[clippos] ++;
525 }
526 void SWFOutputDev::eoClip(GfxState *state) 
527 {
528     logf("<debug> eoclip\n");
529     GfxPath * path = state->getPath();
530     struct swfmatrix m;
531     m.m11 = 1; m.m21 = 0; m.m22 = 1;
532     m.m12 = 0; m.m13 = 0; m.m23 = 0;
533     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
534     swfoutput_startclip(&output, outline, &m);
535     clipping[clippos] ++;
536 }
537
538 SWFOutputDev::~SWFOutputDev() 
539 {
540     swfoutput_destroy(&output);
541     outputstarted = 0;
542 };
543 GBool SWFOutputDev::upsideDown() 
544 {
545     logf("<debug> upsidedown?");
546     return gTrue;
547 };
548 GBool SWFOutputDev::useDrawChar() 
549 {
550     logf("<debug> usedrawchar?");
551     return gTrue;
552 }
553
554 void SWFOutputDev::beginString(GfxState *state, GString *s) 
555
556     double m11,m21,m12,m22;
557 //    logf("<debug> %s beginstring \"%s\"\n", gfxstate2str(state), s->getCString());
558     state->getFontTransMat(&m11, &m12, &m21, &m22);
559     m11 *= state->getHorizScaling();
560     m21 *= state->getHorizScaling();
561     swfoutput_setfontmatrix(&output, m11, -m21, m12, -m22);
562 }
563
564 int charcounter = 0;
565 void SWFOutputDev::drawChar(GfxState *state, double x, double y, double dx, double dy, Guchar c) 
566 {
567     logf("<debug> drawChar(%f,%f,%f,%f,'%c')\n",x,y,dx,dy,c);
568     // check for invisible text -- this is used by Acrobat Capture
569     if ((state->getRender() & 3) != 3)
570     {
571        GfxFont*font = state->getFont();
572        Gfx8BitFont*font8;
573        if(font->isCIDFont()) {
574            logf("<error> CID Font\n");
575            return;
576        }
577        font8 = (Gfx8BitFont*)font;
578
579        char**enc=font8->getEncoding();
580
581        double x1,y1;
582        x1 = x;
583        y1 = y;
584        state->transform(x, y, &x1, &y1);
585
586        if(enc[c])
587           swfoutput_drawchar(&output, x1, y1, enc[c], c);
588        else
589           logf("<warning> couldn't get name for character %02x from Encoding", c);
590     }
591 }
592
593 void SWFOutputDev::drawChar16(GfxState *state, double x, double y, double dx, double dy, int c) 
594 {
595     printf("<error> drawChar16(%f,%f,%f,%f,%08x)\n",x,y,dx,dy,c);
596     exit(1);
597 }
598
599 void SWFOutputDev::endString(GfxState *state) 
600
601     logf("<debug> endstring\n");
602 }    
603
604 void SWFOutputDev::startPage(int pageNum, GfxState *state) 
605 {
606   double x1,y1,x2,y2;
607   laststate = state;
608   logf("<debug> startPage %d\n", pageNum);
609   logf("<notice> processing page %d", pageNum);
610
611   state->transform(state->getX1(),state->getY1(),&x1,&y1);
612   state->transform(state->getX2(),state->getY2(),&x2,&y2);
613   if(!outputstarted) {
614     swfoutput_init(&output, swffilename, abs((int)(x2-x1)),abs((int)(y2-y1)));
615     outputstarted = 1;
616   }
617   else
618     swfoutput_newpage(&output);
619 }
620
621 void SWFOutputDev::drawLink(Link *link, Catalog *catalog) 
622 {
623   logf("<debug> drawlink\n");
624   double x1, y1, x2, y2, w;
625   GfxRGB rgb;
626   swfcoord points[5];
627   int x, y;
628
629   link->getBorder(&x1, &y1, &x2, &y2, &w);
630 //  if (w > 0) 
631   {
632     rgb.r = 0;
633     rgb.g = 0;
634     rgb.b = 1;
635     cvtUserToDev(x1, y1, &x, &y);
636     points[0].x = points[4].x = (int)x;
637     points[0].y = points[4].y = (int)y;
638     cvtUserToDev(x2, y1, &x, &y);
639     points[1].x = (int)x;
640     points[1].y = (int)y;
641     cvtUserToDev(x2, y2, &x, &y);
642     points[2].x = (int)x;
643     points[2].y = (int)y;
644     cvtUserToDev(x1, y2, &x, &y);
645     points[3].x = (int)x;
646     points[3].y = (int)y;
647
648     LinkAction*action=link->getAction();
649     char buf[128];
650     char*s = "-?-";
651     char*type = "-?-";
652     char*url = 0;
653     char*named = 0;
654     int page = -1;
655     switch(action->getKind())
656     {
657         case actionGoTo: {
658             type = "GoTo";
659             LinkGoTo *ha=(LinkGoTo *)link->getAction();
660             LinkDest *dest=NULL;
661             if (ha->getDest()==NULL) 
662                 dest=catalog->findDest(ha->getNamedDest());
663             else dest=ha->getDest();
664             if (dest){ 
665               if (dest->isPageRef()){
666                 Ref pageref=dest->getPageRef();
667                 page=catalog->findPage(pageref.num,pageref.gen);
668               }
669               else  page=dest->getPageNum();
670               sprintf(buf, "%d", page);
671               s = buf;
672             }
673         }
674         break;
675         case actionGoToR: {
676             type = "GoToR";
677             LinkGoToR*l = (LinkGoToR*)action;
678             GString*g = l->getNamedDest();
679             if(g)
680              s = g->getCString();
681         }
682         break;
683         case actionNamed: {
684             type = "Named";
685             LinkNamed*l = (LinkNamed*)action;
686             GString*name = l->getName();
687             if(name) {
688               s = name->lowerCase()->getCString();
689               named = name->getCString();
690               if(strstr(s, "next") || strstr(s, "forward"))
691               {
692                   page = currentpage + 1;
693               }
694               else if(strstr(s, "prev") || strstr(s, "back"))
695               {
696                   page = currentpage - 1;
697               }
698               else if(strstr(s, "last") || strstr(s, "end"))
699               {
700                   page = pages[pagepos-1]; //:)
701               }
702               else if(strstr(s, "first") || strstr(s, "top"))
703               {
704                   page = 1;
705               }
706             }
707         }
708         break;
709         case actionLaunch: {
710             type = "Launch";
711             LinkLaunch*l = (LinkLaunch*)action;
712             GString * str = new GString(l->getFileName());
713             str->append(l->getParams());
714             s = str->getCString();
715         }
716         break;
717         case actionURI: {
718             type = "URI";
719             LinkURI*l = (LinkURI*)action;
720             GString*g = l->getURI();
721             if(g) {
722              url = g->getCString();
723              s = url;
724             }
725         }
726         break;
727         case actionUnknown: {
728             type = "Unknown";
729             LinkUnknown*l = (LinkUnknown*)action;
730             s = "";
731         }
732         break;
733         default: {
734             logf("<error> Unknown link type!\n");
735             break;
736         }
737     }
738     if(!linkinfo && (page || url))
739     {
740         logf("<notice> File contains links");
741         linkinfo = 1;
742     }
743     if(page>0)
744     {
745         int t;
746         for(t=0;t<pagepos;t++)
747             if(pages[t]==page)
748                 break;
749         if(t!=pagepos)
750         swfoutput_linktopage(&output, t, points);
751     }
752     else if(url)
753     {
754         swfoutput_linktourl(&output, url, points);
755     }
756     else if(named)
757     {
758         swfoutput_namedlink(&output, named, points);
759     }
760     logf("<verbose> \"%s\" link to \"%s\" (%d)\n", type, FIXNULL(s), page);
761   }
762 }
763
764 void SWFOutputDev::saveState(GfxState *state) {
765   logf("<debug> saveState\n");
766   updateAll(state);
767   if(clippos<64)
768     clippos ++;
769   else
770     logf("<error> Too many nested states in pdf.");
771   clipping[clippos] = 0;
772 };
773
774 void SWFOutputDev::restoreState(GfxState *state) {
775   logf("<debug> restoreState\n");
776   updateAll(state);
777   while(clipping[clippos]) {
778       swfoutput_endclip(&output);
779       clipping[clippos]--;
780   }
781   clippos--;
782 }
783
784 char type3Warning=0;
785
786 int SWFOutputDev::searchT1Font(char*name) 
787 {       
788     int i;
789     int mapid=-1;
790     char*filename=0;
791     for(i=0;i<sizeof(pdf2t1map)/sizeof(mapping);i++) 
792     {
793         if(!strcmp(name, pdf2t1map[i].pdffont))
794         {
795             filename = pdf2t1map[i].filename;
796             mapid = i;
797         }
798     }
799     if(filename) {
800         for(i=0; i<T1_Get_no_fonts(); i++)
801         {
802             char*fontfilename = T1_GetFontFileName (i);
803             if(strstr(fontfilename, filename))
804             {
805                     pdf2t1map[i].id = mapid;
806                     return i;
807             }
808         }
809     } else {
810         for(i=0; i<T1_Get_no_fonts(); i++)
811         {
812             char*fontname = T1_GetFontName (i);
813             if(!fontname) {
814                 T1_LoadFont(i);
815                 fontname = T1_GetFontName (i);
816                 logf("<verbose> Loading extra font %s from %s\n", FIXNULL(fontname), 
817                                                                   FIXNULL(T1_GetFontFileName(i)));
818             }
819             if(fontname && !strcmp(name, fontname)) {
820                 logf("<notice> Extra font %s is being used.\n", fontname);
821                 return i;
822             }
823             fontname = T1_GetFontFileName(i);
824             if(strrchr(fontname,'/'))
825                     fontname = strrchr(fontname,'/')+1;
826  
827             if(strstr(fontname, name)) {
828                 logf("<notice> Extra font %s is being used.\n", fontname);
829                 return i;
830             }
831         }
832     }
833     return -1;
834 }
835
836 void SWFOutputDev::updateLineWidth(GfxState *state)
837 {
838     double width = state->getTransformedLineWidth();
839     swfoutput_setlinewidth(&output, width);
840 }
841
842 void SWFOutputDev::updateFillColor(GfxState *state) 
843 {
844     GfxRGB rgb;
845     double opaq = state->getFillOpacity();
846     state->getFillRGB(&rgb);
847
848     swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
849                                     (char)(rgb.b*255), (char)(opaq*255));
850 }
851
852 void SWFOutputDev::updateStrokeColor(GfxState *state) 
853 {
854     GfxRGB rgb;
855     double opaq = state->getStrokeOpacity();
856     state->getStrokeRGB(&rgb);
857
858     swfoutput_setstrokecolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
859                                       (char)(rgb.b*255), (char)(opaq*255));
860 }
861
862 char*SWFOutputDev::writeEmbeddedFontToFile(GfxFont*font)
863 {
864 /*      char*tmpFileName = NULL;
865       FILE *f;
866       int c;
867       char *fontBuf;
868       int fontLen;
869 //      Type1CFontConverter *cvt;
870       Ref embRef;
871       Object refObj, strObj;
872       tmpFileName = "/tmp/tmpfont";
873       font->getEmbeddedFontID(&embRef);
874
875       f = fopen(tmpFileName, "wb");
876       if (!f) {
877         logf("<error> Couldn't create temporary Type 1 font file");
878         return 0;
879       }
880       if (font->getType() == fontType1C) {
881         if (!(fontBuf = font->readEmbFontFile(&fontLen))) {
882           fclose(f);
883           logf("<error> Couldn't read embedded font file");
884           return 0;
885         }
886         cvt = new Type1CFontConverter(fontBuf, fontLen, f);
887         cvt->convert();
888         delete cvt;
889         gfree(fontBuf);
890       } else {
891         font->getEmbeddedFontID(&embRef);
892         refObj.initRef(embRef.num, embRef.gen);
893         refObj.fetch(&strObj);
894         refObj.free();
895         strObj.streamReset();
896         while ((c = strObj.streamGetChar()) != EOF) {
897           fputc(c, f);
898         }
899         strObj.streamClose();
900         strObj.free();
901       }
902       fclose(f);
903
904       if(font->getType() == fontTrueType)
905       {
906           if(!ttfinfo) {
907               logf("<notice> File contains TrueType fonts");
908               ttfinfo = 1;
909           }
910           char name2[80];
911           char*tmp;
912           tmp = strdup(mktmpname((char*)name2));
913           sprintf(name2, "%s", tmp);
914           char*a[] = {"./ttf2pt1","-pttf","-b", tmpFileName, name2};
915           logf("<verbose> Invoking ttf2pt1...");
916           ttf2pt1_main(5,a);
917           unlink(tmpFileName);
918           sprintf(name2,"%s.pfb",tmp);
919           tmpFileName = strdup(name2);
920       }
921
922       return tmpFileName;*/
923
924     return 0;
925 }
926
927 char* gfxFontName(GfxFont* gfxFont)
928 {
929       GString *gstr;
930       gstr = gfxFont->getName();
931       if(gstr) {
932           return gstr->getCString();
933       }
934       else {
935           char buf[32];
936           Ref*r=gfxFont->getID();
937           sprintf(buf, "UFONT%d", r->num);
938           return strdup(buf);
939       }
940 }
941
942 char* substitutetarget[256];
943 char* substitutesource[256];
944 int substitutepos = 0;
945
946 char* SWFOutputDev::substituteFont(GfxFont*gfxFont, char* oldname)
947 {
948     return "Times-Roman";
949 /*      //substitute font
950       char* fontname = 0;
951       double m11, m12, m21, m22;
952       int index;
953       int code;
954       double w,w1,w2;
955       double*fm;
956       double v;
957       if(gfxFont->getName()) {
958         fontname = gfxFont->getName()->getCString();
959       }
960
961 //        printf("%d %s\n", t, gfxFont->getCharName(t));
962       showFontError(gfxFont, 1);
963       if(1) { //if (!gfxFont->is16Bit()) { FIXME: xpdf 1.01 does not have is16Bit()
964         if(gfxFont->isSymbolic()) {
965           if(fontname && (strstr(fontname,"ing"))) //Dingbats, Wingdings etc.
966            index = 16;
967           else 
968            index = 12;
969         } else if (gfxFont->isFixedWidth()) {
970           index = 8;
971         } else if (gfxFont->isSerif()) {
972           index = 4;
973         } else {
974           index = 0;
975         }
976         if (gfxFont->isBold() && index!=16)
977           index += 2;
978         if (gfxFont->isItalic() && index!=16)
979           index += 1;
980         fontname = fontnames[index];
981         // get width of 'm' in real font and substituted font
982         if ((code = gfxFont->getCharCode("m")) >= 0)
983           w1 = gfxFont->getWidth(code);
984         else
985           w1 = 0;
986         w2 = fontsizes[index];
987         if (gfxFont->getType() == fontType3) {
988           // This is a hack which makes it possible to substitute for some
989           // Type 3 fonts.  The problem is that it's impossible to know what
990           // the base coordinate system used in the font is without actually
991           // rendering the font.  This code tries to guess by looking at the
992           // width of the character 'm' (which breaks if the font is a
993           // subset that doesn't contain 'm').
994           if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
995             w1 /= w2;
996             m11 *= w1;
997             m12 *= w1;
998             m21 *= w1;
999             m22 *= w1;
1000           }
1001           fm = gfxFont->getFontMatrix();
1002           v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
1003           m21 *= v;
1004           m22 *= v;
1005         } else if (!gfxFont->isSymbolic()) {
1006           // if real font is substantially narrower than substituted
1007           // font, reduce the font size accordingly
1008           if (w1 > 0.01 && w1 < 0.9 * w2) {
1009             w1 /= w2;
1010             if (w1 < 0.8) {
1011               w1 = 0.8;
1012             }
1013             m11 *= w1;
1014             m12 *= w1;
1015             m21 *= w1;
1016             m22 *= w1;
1017           }
1018         }
1019       }
1020       if(fontname) {
1021         this->t1id = searchT1Font(fontname);
1022       }
1023       if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
1024           logf("<fatal> Too many fonts in file.");
1025           exit(1);
1026       }
1027       if(oldname) {
1028           substitutesource[substitutepos] = oldname;
1029           substitutetarget[substitutepos] = fontname;
1030           logf("<verbose> substituting %s -> %s", FIXNULL(oldname), FIXNULL(fontname));
1031           substitutepos ++;
1032       }
1033       return fontname;*/
1034 }
1035
1036 void unlinkfont(char* filename)
1037 {
1038     int l;
1039     if(!filename)
1040         return;
1041     l=strlen(filename);
1042     unlink(filename);
1043     if(!strncmp(&filename[l-4],".afm",4)) {
1044         memcpy(&filename[l-4],".pfb",4);
1045         unlink(filename);
1046         memcpy(&filename[l-4],".pfa",4);
1047         unlink(filename);
1048         memcpy(&filename[l-4],".afm",4);
1049         return;
1050     } else 
1051     if(!strncmp(&filename[l-4],".pfa",4)) {
1052         memcpy(&filename[l-4],".afm",4);
1053         unlink(filename);
1054         memcpy(&filename[l-4],".pfa",4);
1055         return;
1056     } else 
1057     if(!strncmp(&filename[l-4],".pfb",4)) {
1058         memcpy(&filename[l-4],".afm",4);
1059         unlink(filename);
1060         memcpy(&filename[l-4],".pfb",4);
1061         return;
1062     }
1063 }
1064
1065 void SWFOutputDev::updateFont(GfxState *state) 
1066 {
1067   GfxFont*gfxFont = state->getFont();
1068   char * fileName = 0;
1069     
1070   if (!gfxFont) {
1071     return;
1072   }  
1073   char * fontname = gfxFontName(gfxFont);
1074  
1075   int t;
1076   for(t=0;t<substitutepos;t++) {
1077       if(!strcmp(fontname, substitutesource[t])) {
1078           fontname = substitutetarget[t];
1079           break;
1080       }
1081   }
1082
1083   if(swfoutput_queryfont(&output, fontname))
1084   {
1085       swfoutput_setfont(&output, fontname, -1, 0);
1086       return;
1087   }
1088
1089   // look for Type 3 font
1090   if (!type3Warning && gfxFont->getType() == fontType3) {
1091     type3Warning = gTrue;
1092     showFontError(gfxFont, 2);
1093   }
1094   //dumpFontInfo ("<notice>", gfxFont);
1095
1096   Ref embRef;
1097   GBool embedded = gfxFont->getEmbeddedFontID(&embRef);
1098   if(embedded) {
1099     if (//!gfxFont->is16Bit() && FIXME: not in xpdf 1.01
1100         (gfxFont->getType() == fontType1 ||
1101          gfxFont->getType() == fontType1C ||
1102          gfxFont->getType() == fontTrueType)) {
1103         
1104         fileName = writeEmbeddedFontToFile(gfxFont);
1105         if(!fileName) {
1106           logf("<error> Couldn't write font to file");
1107           showFontError(gfxFont,0);
1108           return ;
1109         }
1110         this->t1id = T1_AddFont(fileName);
1111         if(this->t1id<0) {
1112           logf("<error> Couldn't load font from file");
1113           showFontError(gfxFont,0);
1114           unlinkfont(fileName);
1115           return ;
1116         }
1117     }
1118     else {
1119         showFontError(gfxFont,0);
1120         fontname = substituteFont(gfxFont, fontname);
1121     }
1122   } else {
1123     if(fontname) {
1124         int newt1id = searchT1Font(fontname);
1125         if(newt1id<0) {
1126             fontname = substituteFont(gfxFont, fontname);
1127         } else
1128             this->t1id = newt1id;
1129     }
1130     else
1131         fontname = substituteFont(gfxFont, fontname);
1132   }
1133
1134   if(t1id<0) {
1135       showFontError(gfxFont,0);
1136       return;
1137   }
1138  
1139   /* we may have done some substitutions here, so check
1140      again if this font is cached. */
1141   if(swfoutput_queryfont(&output, fontname))
1142   {
1143       swfoutput_setfont(&output, fontname, -1, 0);
1144       return;
1145   }
1146
1147   logf("<verbose> Creating new SWF font: t1id: %d, filename: %s name:%s", this->t1id, FIXNULL(fileName), FIXNULL(fontname));
1148   swfoutput_setfont(&output, fontname, this->t1id, fileName);
1149   if(fileName)
1150       unlinkfont(fileName);
1151 }
1152
1153 int pic_xids[1024];
1154 int pic_yids[1024];
1155 int pic_ids[1024];
1156 int picpos = 0;
1157 int pic_id = 0;
1158
1159 void SWFOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
1160                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
1161                                    GBool inlineImg, int mask)
1162 {
1163   FILE *fi;
1164   int c;
1165   char fileName[128];
1166   double x1,y1,x2,y2,x3,y3,x4,y4;
1167   ImageStream *imgStr;
1168   Guchar pixBuf[4];
1169   GfxRGB rgb;
1170   int ncomps = 1;
1171   int bits = 1;
1172                                  
1173   if(colorMap) {
1174     ncomps = colorMap->getNumPixelComps();
1175     bits = colorMap->getBits();
1176   }
1177   imgStr = new ImageStream(str, width, ncomps,bits);
1178   imgStr->reset();
1179
1180   if(!width || !height || (height<=1 && width<=1))
1181   {
1182       logf("<verbose> Ignoring %d by %d image", width, height);
1183       unsigned char buf[8];
1184       int x,y;
1185       for (y = 0; y < height; ++y)
1186       for (x = 0; x < width; ++x) {
1187           imgStr->getPixel(buf);
1188       }
1189       delete imgStr;
1190       return;
1191   }
1192   
1193   state->transform(0, 1, &x1, &y1);
1194   state->transform(0, 0, &x2, &y2);
1195   state->transform(1, 0, &x3, &y3);
1196   state->transform(1, 1, &x4, &y4);
1197
1198   if(!pbminfo && !(str->getKind()==strDCT)) {
1199       logf("<notice> file contains pbm pictures %s",mask?"(masked)":"");
1200       if(mask)
1201       logf("<verbose> drawing %d by %d masked picture\n", width, height);
1202       pbminfo = 1;
1203   }
1204   if(!jpeginfo && (str->getKind()==strDCT)) {
1205       logf("<notice> file contains jpeg pictures");
1206       jpeginfo = 1;
1207   }
1208
1209   if(mask) {
1210       int yes=0,i,j;
1211       unsigned char buf[8];
1212       int xid = 0;
1213       int yid = 0;
1214       int x,y;
1215       int width2 = (width+3)&(~3);
1216       unsigned char*pic = new unsigned char[width2*height];
1217       RGBA pal[256];
1218       GfxRGB rgb;
1219       state->getFillRGB(&rgb);
1220       pal[0].r = (int)(rgb.r*255); pal[0].g = (int)(rgb.g*255); 
1221       pal[0].b = (int)(rgb.b*255); pal[0].a = 255;
1222       pal[1].r = 0; pal[1].g = 0; pal[1].b = 0; pal[1].a = 0;
1223       xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1224       yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1225       for (y = 0; y < height; ++y)
1226       for (x = 0; x < width; ++x)
1227       {
1228             imgStr->getPixel(buf);
1229             // if(invert) buf[0]=255-buf[0]?
1230             pic[width*y+x] = buf[0];
1231             xid+=x*buf[0]+1;
1232             yid+=y*buf[0]+1;
1233       }
1234       int t,found = -1;
1235       for(t=0;t<picpos;t++)
1236       {
1237           if(pic_xids[t] == xid &&
1238              pic_yids[t] == yid) {
1239               found = t;break;
1240           }
1241       }
1242       if(found<0) {
1243           pic_ids[picpos] = swfoutput_drawimagelossless256(&output, pic, pal, width, height, 
1244                   x1,y1,x2,y2,x3,y3,x4,y4);
1245           pic_xids[picpos] = xid;
1246           pic_yids[picpos] = yid;
1247           if(picpos<1024)
1248               picpos++;
1249       } else {
1250           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1251                   x1,y1,x2,y2,x3,y3,x4,y4);
1252       }
1253       free(pic);
1254       delete imgStr;
1255       return;
1256   } 
1257
1258   int x,y;
1259   
1260   if(colorMap->getNumPixelComps()!=1 || str->getKind()==strDCT)
1261   {
1262       RGBA*pic=new RGBA[width*height];
1263       int xid = 0;
1264       int yid = 0;
1265       for (y = 0; y < height; ++y) {
1266         for (x = 0; x < width; ++x) {
1267           int r,g,b,a;
1268           imgStr->getPixel(pixBuf);
1269           colorMap->getRGB(pixBuf, &rgb);
1270           pic[width*y+x].r = r = (U8)(rgb.r * 255 + 0.5);
1271           pic[width*y+x].g = g = (U8)(rgb.g * 255 + 0.5);
1272           pic[width*y+x].b = b = (U8)(rgb.b * 255 + 0.5);
1273           pic[width*y+x].a = a = 255;//(U8)(rgb.a * 255 + 0.5);
1274           xid += x*r+x*b*3+x*g*7+x*a*11;
1275           yid += y*r*3+y*b*17+y*g*19+y*a*11;
1276         }
1277       }
1278       int t,found = -1;
1279       for(t=0;t<picpos;t++)
1280       {
1281           if(pic_xids[t] == xid &&
1282              pic_yids[t] == yid) {
1283               found = t;break;
1284           }
1285       }
1286       if(found<0) {
1287           if(str->getKind()==strDCT)
1288               pic_ids[picpos] = swfoutput_drawimagejpeg(&output, pic, width, height, 
1289                       x1,y1,x2,y2,x3,y3,x4,y4);
1290           else
1291               pic_ids[picpos] = swfoutput_drawimagelossless(&output, pic, width, height, 
1292                       x1,y1,x2,y2,x3,y3,x4,y4);
1293           pic_xids[picpos] = xid;
1294           pic_yids[picpos] = yid;
1295           if(picpos<1024)
1296               picpos++;
1297       } else {
1298           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1299                   x1,y1,x2,y2,x3,y3,x4,y4);
1300       }
1301       delete pic;
1302       delete imgStr;
1303       return;
1304   }
1305   else
1306   {
1307       U8*pic = new U8[width*height];
1308       RGBA pal[256];
1309       int t;
1310       int xid=0,yid=0;
1311       for(t=0;t<256;t++)
1312       {
1313           int r,g,b,a;
1314           pixBuf[0] = t;
1315           colorMap->getRGB(pixBuf, &rgb);
1316           pal[t].r = r = (U8)(rgb.r * 255 + 0.5);
1317           pal[t].g = g = (U8)(rgb.g * 255 + 0.5);
1318           pal[t].b = b = (U8)(rgb.b * 255 + 0.5);
1319           pal[t].a = a = 255;//(U8)(rgb.b * 255 + 0.5);
1320           xid += t*r+t*b*3+t*g*7+t*a*11;
1321           xid += (~t)*r+t*b*3+t*g*7+t*a*11;
1322       }
1323       for (y = 0; y < height; ++y) {
1324         for (x = 0; x < width; ++x) {
1325           imgStr->getPixel(pixBuf);
1326           pic[width*y+x] = pixBuf[0];
1327           xid += x*pixBuf[0]*7;
1328           yid += y*pixBuf[0]*3;
1329         }
1330       }
1331       int found = -1;
1332       for(t=0;t<picpos;t++)
1333       {
1334           if(pic_xids[t] == xid &&
1335              pic_yids[t] == yid) {
1336               found = t;break;
1337           }
1338       }
1339       if(found<0) {
1340           pic_ids[picpos] = swfoutput_drawimagelossless256(&output, pic, pal, width, height, 
1341                   x1,y1,x2,y2,x3,y3,x4,y4);
1342           pic_xids[picpos] = xid;
1343           pic_yids[picpos] = yid;
1344           if(picpos<1024)
1345               picpos++;
1346       } else {
1347           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1348                   x1,y1,x2,y2,x3,y3,x4,y4);
1349       }
1350       delete pic;
1351       delete imgStr;
1352       return;
1353   }
1354 }
1355
1356 void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1357                                    int width, int height, GBool invert,
1358                                    GBool inlineImg) 
1359 {
1360   logf("<verbose> drawImageMask %dx%d, invert=%d inline=%d", width, height, invert, inlineImg);
1361   drawGeneralImage(state,ref,str,width,height,0,invert,inlineImg,1);
1362 }
1363
1364 void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1365                                int width, int height,
1366                                GfxImageColorMap *colorMap, GBool inlineImg) 
1367 {
1368   logf("<verbose> drawImage %dx%d, %s, inline=%d", width, height, 
1369           colorMap?"colorMap":"no colorMap", inlineImg);
1370   if(colorMap)
1371       logf("<verbose> colorMap pixcomps:%d bits:%d mode:%d\n", colorMap->getNumPixelComps(),
1372               colorMap->getBits(),colorMap->getColorSpace()->getMode());
1373   drawGeneralImage(state,ref,str,width,height,colorMap,0,inlineImg,0);
1374 }
1375
1376 SWFOutputDev*output = 0; 
1377
1378 static void printInfoString(Dict *infoDict, char *key, char *fmt) {
1379   Object obj;
1380   GString *s1, *s2;
1381   int i;
1382
1383   if (infoDict->lookup(key, &obj)->isString()) {
1384     s1 = obj.getString();
1385     if ((s1->getChar(0) & 0xff) == 0xfe &&
1386         (s1->getChar(1) & 0xff) == 0xff) {
1387       s2 = new GString();
1388       for (i = 2; i < obj.getString()->getLength(); i += 2) {
1389         if (s1->getChar(i) == '\0') {
1390           s2->append(s1->getChar(i+1));
1391         } else {
1392           delete s2;
1393           s2 = new GString("<unicode>");
1394           break;
1395         }
1396       }
1397       printf(fmt, s2->getCString());
1398       delete s2;
1399     } else {
1400       printf(fmt, s1->getCString());
1401     }
1402   }
1403   obj.free();
1404 }
1405
1406 static void printInfoDate(Dict *infoDict, char *key, char *fmt) {
1407   Object obj;
1408   char *s;
1409
1410   if (infoDict->lookup(key, &obj)->isString()) {
1411     s = obj.getString()->getCString();
1412     if (s[0] == 'D' && s[1] == ':') {
1413       s += 2;
1414     }
1415     printf(fmt, s);
1416   }
1417   obj.free();
1418 }
1419
1420 void pdfswf_init(char*filename, char*userPassword) 
1421 {
1422   GString *fileName = new GString(filename);
1423   GString *userPW;
1424   Object info;
1425   // init error file
1426   //errorInit(); FIXME xpdf 1.01
1427
1428   // read config file
1429   globalParams = new GlobalParams("");
1430
1431   // open PDF file
1432   if (userPassword && userPassword[0]) {
1433     userPW = new GString(userPassword);
1434   } else {
1435     userPW = NULL;
1436   }
1437   doc = new PDFDoc(fileName, userPW);
1438   if (userPW) {
1439     delete userPW;
1440   }
1441   if (!doc->isOk()) {
1442     exit(1);
1443   }
1444
1445   // print doc info
1446   doc->getDocInfo(&info);
1447   if (info.isDict()) {
1448     printInfoString(info.getDict(), "Title",        "Title:        %s\n");
1449     printInfoString(info.getDict(), "Subject",      "Subject:      %s\n");
1450     printInfoString(info.getDict(), "Keywords",     "Keywords:     %s\n");
1451     printInfoString(info.getDict(), "Author",       "Author:       %s\n");
1452     printInfoString(info.getDict(), "Creator",      "Creator:      %s\n");
1453     printInfoString(info.getDict(), "Producer",     "Producer:     %s\n");
1454     printInfoDate(info.getDict(),   "CreationDate", "CreationDate: %s\n");
1455     printInfoDate(info.getDict(),   "ModDate",      "ModDate:      %s\n");
1456   }
1457   info.free();
1458
1459   // print page count
1460   printf("Pages:        %d\n", doc->getNumPages());
1461   numpages = doc->getNumPages();
1462   
1463   // print linearization info
1464   printf("Linearized:   %s\n", doc->isLinearized() ? "yes" : "no");
1465
1466   // print encryption info
1467   printf("Encrypted:    ");
1468   if (doc->isEncrypted()) {
1469     printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
1470            doc->okToPrint() ? "yes" : "no",
1471            doc->okToCopy() ? "yes" : "no",
1472            doc->okToChange() ? "yes" : "no",
1473            doc->okToAddNotes() ? "yes" : "no");
1474         /*ERROR: This pdf is encrypted, and disallows copying.
1475           Due to the DMCA, paragraph 1201, (2) A-C, circumventing
1476           a technological measure that efficively controls access to
1477           a protected work is violating American law. 
1478           See www.eff.org for more information about DMCA issues.
1479          */
1480         if(!doc->okToCopy()) {
1481             printf("PDF disallows copying. Bailing out.\n");
1482             exit(1); //bail out
1483         }
1484         if(!doc->okToChange() || !doc->okToAddNotes())
1485             swfoutput_setprotected();
1486     }
1487   else {
1488     printf("no\n");
1489   }
1490
1491
1492   output = new SWFOutputDev();
1493 }
1494
1495 void pdfswf_drawonlyshapes()
1496 {
1497     drawonlyshapes = 1;
1498 }
1499
1500 void pdfswf_ignoredraworder()
1501 {
1502     ignoredraworder = 1;
1503 }
1504
1505 void pdfswf_linksopennewwindow()
1506 {
1507     opennewwindow = 1;
1508 }
1509
1510 void pdfswf_storeallcharacters()
1511 {
1512     storeallcharacters = 1;
1513 }
1514
1515 void pdfswf_enablezlib()
1516 {
1517     enablezlib = 1;
1518 }
1519
1520 void pdfswf_jpegquality(int val)
1521 {
1522     if(val<0) val=0;
1523     if(val>100) val=100;
1524     jpegquality = val;
1525 }
1526
1527 void pdfswf_setoutputfilename(char*_filename)
1528 {
1529     swffilename = _filename;
1530 }
1531
1532
1533 void pdfswf_convertpage(int page)
1534 {
1535     if(!pages)
1536     {
1537         pages = (int*)malloc(1024*sizeof(int));
1538         pagebuflen = 1024;
1539     } else {
1540         if(pagepos == pagebuflen)
1541         {
1542             pagebuflen+=1024;
1543             pages = (int*)realloc(pages, pagebuflen);
1544         }
1545     }
1546     pages[pagepos++] = page;
1547 }
1548
1549 void pdfswf_performconversion()
1550 {
1551     int t;
1552     for(t=0;t<pagepos;t++)
1553     {
1554        currentpage = pages[t];
1555        doc->displayPage((OutputDev*)output, currentpage, /*dpi*/72, /*rotate*/0, /*doLinks*/(int)1);
1556     }
1557 }
1558
1559 int pdfswf_numpages()
1560 {
1561   return doc->getNumPages();
1562 }
1563
1564 int closed=0;
1565 void pdfswf_close()
1566 {
1567     logf("<debug> pdfswf.cc: pdfswf_close()");
1568     delete output;
1569     delete doc;
1570     //freeParams();
1571     // check for memory leaks
1572     Object::memCheck(stderr);
1573     gMemReport(stderr);
1574 }
1575