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