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