simplified routine drawGeneralImage().
[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?FIXNULL(gstr->getCString()):"(unknown font)", r.num,r.gen);
347
348   gstr  = font->getTag();
349   if(gstr) 
350    logf("%sTag: %s\n", loglevel, FIXNULL(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, FIXNULL(name), embRef.num);
380
381   gstr = font->getExtFontFile();
382   if(gstr)
383    logf("%sExternal Font file: %s\n", loglevel, FIXNULL(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   logf("<debug> drawlink\n");
606   double x1, y1, x2, y2, w;
607   GfxRGB rgb;
608   swfcoord points[5];
609   int x, y;
610
611   link->getBorder(&x1, &y1, &x2, &y2, &w);
612 //  if (w > 0) 
613   {
614     rgb.r = 0;
615     rgb.g = 0;
616     rgb.b = 1;
617     cvtUserToDev(x1, y1, &x, &y);
618     points[0].x = points[4].x = (int)x;
619     points[0].y = points[4].y = (int)y;
620     cvtUserToDev(x2, y1, &x, &y);
621     points[1].x = (int)x;
622     points[1].y = (int)y;
623     cvtUserToDev(x2, y2, &x, &y);
624     points[2].x = (int)x;
625     points[2].y = (int)y;
626     cvtUserToDev(x1, y2, &x, &y);
627     points[3].x = (int)x;
628     points[3].y = (int)y;
629
630     LinkAction*action=link->getAction();
631     char buf[128];
632     char*s = "-?-";
633     char*type = "-?-";
634     char*url = 0;
635     char*named = 0;
636     int page = -1;
637     switch(action->getKind())
638     {
639         case actionGoTo: {
640             type = "GoTo";
641             LinkGoTo *ha=(LinkGoTo *)link->getAction();
642             LinkDest *dest=NULL;
643             if (ha->getDest()==NULL) 
644                 dest=catalog->findDest(ha->getNamedDest());
645             else dest=ha->getDest();
646             if (dest){ 
647               if (dest->isPageRef()){
648                 Ref pageref=dest->getPageRef();
649                 page=catalog->findPage(pageref.num,pageref.gen);
650               }
651               else  page=dest->getPageNum();
652               sprintf(buf, "%d", page);
653               s = buf;
654             }
655         }
656         break;
657         case actionGoToR: {
658             type = "GoToR";
659             LinkGoToR*l = (LinkGoToR*)action;
660             GString*g = l->getNamedDest();
661             if(g)
662              s = g->getCString();
663         }
664         break;
665         case actionNamed: {
666             type = "Named";
667             LinkNamed*l = (LinkNamed*)action;
668             GString*name = l->getName();
669             if(name) {
670               s = name->lowerCase()->getCString();
671               named = name->getCString();
672               if(strstr(s, "next") || strstr(s, "forward"))
673               {
674                   page = currentpage + 1;
675               }
676               else if(strstr(s, "prev") || strstr(s, "back"))
677               {
678                   page = currentpage - 1;
679               }
680               else if(strstr(s, "last") || strstr(s, "end"))
681               {
682                   page = pages[pagepos-1]; //:)
683               }
684               else if(strstr(s, "first") || strstr(s, "top"))
685               {
686                   page = 1;
687               }
688             }
689         }
690         break;
691         case actionLaunch: {
692             type = "Launch";
693             LinkLaunch*l = (LinkLaunch*)action;
694             GString * str = new GString(l->getFileName());
695             str->append(l->getParams());
696             s = str->getCString();
697         }
698         break;
699         case actionURI: {
700             type = "URI";
701             LinkURI*l = (LinkURI*)action;
702             GString*g = l->getURI();
703             if(g) {
704              url = g->getCString();
705              s = url;
706             }
707         }
708         break;
709         case actionUnknown: {
710             type = "Unknown";
711             LinkUnknown*l = (LinkUnknown*)action;
712             s = "";
713         }
714         break;
715         default: {
716             logf("<error> Unknown link type!\n");
717             break;
718         }
719     }
720     if(!linkinfo && (page || url))
721     {
722         logf("<notice> File contains links");
723         linkinfo = 1;
724     }
725     if(page>0)
726     {
727         int t;
728         for(t=0;t<pagepos;t++)
729             if(pages[t]==page)
730                 break;
731         if(t!=pagepos)
732         swfoutput_linktopage(&output, t, points);
733     }
734     else if(url)
735     {
736         swfoutput_linktourl(&output, url, points);
737     }
738     else if(named)
739     {
740         swfoutput_namedlink(&output, named, points);
741     }
742     logf("<verbose> \"%s\" link to \"%s\" (%d)\n", type, FIXNULL(s), page);
743   }
744 }
745
746 void SWFOutputDev::saveState(GfxState *state) {
747   logf("<debug> saveState\n");
748   updateAll(state);
749   if(clippos<64)
750     clippos ++;
751   else
752     logf("<error> Too many nested states in pdf.");
753   clipping[clippos] = 0;
754 };
755
756 void SWFOutputDev::restoreState(GfxState *state) {
757   logf("<debug> restoreState\n");
758   updateAll(state);
759   while(clipping[clippos]) {
760       swfoutput_endclip(&output);
761       clipping[clippos]--;
762   }
763   clippos--;
764 }
765
766 char type3Warning=0;
767
768 int SWFOutputDev::searchT1Font(char*name) 
769 {       
770     int i;
771     int mapid=-1;
772     char*filename=0;
773     for(i=0;i<sizeof(pdf2t1map)/sizeof(mapping);i++) 
774     {
775         if(!strcmp(name, pdf2t1map[i].pdffont))
776         {
777             filename = pdf2t1map[i].filename;
778             mapid = i;
779         }
780     }
781     if(filename) {
782         for(i=0; i<T1_Get_no_fonts(); i++)
783         {
784             char*fontfilename = T1_GetFontFileName (i);
785             if(strstr(fontfilename, filename))
786             {
787                     pdf2t1map[i].id = mapid;
788                     return i;
789             }
790         }
791     } else {
792         for(i=0; i<T1_Get_no_fonts(); i++)
793         {
794             char*fontname = T1_GetFontName (i);
795             if(!fontname) {
796                 T1_LoadFont(i);
797                 fontname = T1_GetFontName (i);
798                 logf("<verbose> Loading extra font %s from %s\n", FIXNULL(fontname), 
799                                                                   FIXNULL(T1_GetFontFileName(i)));
800             }
801             if(fontname && !strcmp(name, fontname)) {
802                 logf("<notice> Extra font %s is being used.\n", fontname);
803                 return i;
804             }
805             fontname = T1_GetFontFileName(i);
806             if(strrchr(fontname,'/'))
807                     fontname = strrchr(fontname,'/')+1;
808  
809             if(strstr(fontname, name)) {
810                 logf("<notice> Extra font %s is being used.\n", fontname);
811                 return i;
812             }
813         }
814     }
815     return -1;
816 }
817
818 void SWFOutputDev::updateLineWidth(GfxState *state)
819 {
820     double width = state->getTransformedLineWidth();
821     swfoutput_setlinewidth(&output, width);
822 }
823
824 void SWFOutputDev::updateFillColor(GfxState *state) 
825 {
826     GfxRGB rgb;
827     double opaq = state->getFillOpacity();
828     state->getFillRGB(&rgb);
829
830     swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
831                                     (char)(rgb.b*255), (char)(opaq*255));
832 }
833
834 void SWFOutputDev::updateStrokeColor(GfxState *state) 
835 {
836     GfxRGB rgb;
837     double opaq = state->getStrokeOpacity();
838     state->getStrokeRGB(&rgb);
839
840     swfoutput_setstrokecolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
841                                       (char)(rgb.b*255), (char)(opaq*255));
842 }
843
844 char*SWFOutputDev::writeEmbeddedFontToFile(GfxFont*font)
845 {
846       char*tmpFileName = NULL;
847       FILE *f;
848       int c;
849       char *fontBuf;
850       int fontLen;
851       Type1CFontConverter *cvt;
852       Ref embRef;
853       Object refObj, strObj;
854       tmpFileName = "/tmp/tmpfont";
855       font->getEmbeddedFontID(&embRef);
856
857       f = fopen(tmpFileName, "wb");
858       if (!f) {
859         logf("<error> Couldn't create temporary Type 1 font file");
860         return 0;
861       }
862       if (font->getType() == fontType1C) {
863         if (!(fontBuf = font->readEmbFontFile(&fontLen))) {
864           fclose(f);
865           logf("<error> Couldn't read embedded font file");
866           return 0;
867         }
868         cvt = new Type1CFontConverter(fontBuf, fontLen, f);
869         cvt->convert();
870         delete cvt;
871         gfree(fontBuf);
872       } else {
873         font->getEmbeddedFontID(&embRef);
874         refObj.initRef(embRef.num, embRef.gen);
875         refObj.fetch(&strObj);
876         refObj.free();
877         strObj.streamReset();
878         while ((c = strObj.streamGetChar()) != EOF) {
879           fputc(c, f);
880         }
881         strObj.streamClose();
882         strObj.free();
883       }
884       fclose(f);
885
886       if(font->getType() == fontTrueType)
887       {
888           if(!ttfinfo) {
889               logf("<notice> File contains TrueType fonts");
890               ttfinfo = 1;
891           }
892           char name2[80];
893           char*tmp;
894           tmp = strdup(mktmpname((char*)name2));
895           sprintf(name2, "%s", tmp);
896           char*a[] = {"./ttf2pt1","-pttf","-b", tmpFileName, name2};
897           logf("<verbose> Invoking ttf2pt1...");
898           ttf2pt1_main(5,a);
899           unlink(tmpFileName);
900           sprintf(name2,"%s.pfb",tmp);
901           tmpFileName = strdup(name2);
902       }
903
904       return tmpFileName;
905 }
906
907 char* gfxFontName(GfxFont* gfxFont)
908 {
909       GString *gstr;
910       gstr = gfxFont->getName();
911       if(gstr) {
912           return gstr->getCString();
913       }
914       else {
915           char buf[32];
916           Ref r=gfxFont->getID();
917           sprintf(buf, "UFONT%d", r.num);
918           return strdup(buf);
919       }
920 }
921
922 char* substitutetarget[256];
923 char* substitutesource[256];
924 int substitutepos = 0;
925
926 char* SWFOutputDev::substituteFont(GfxFont*gfxFont, char* oldname)
927 {
928       //substitute font
929       char* fontname = 0;
930       double m11, m12, m21, m22;
931       int index;
932       int code;
933       double w,w1,w2;
934       double*fm;
935       double v;
936       if(gfxFont->getName()) {
937         fontname = gfxFont->getName()->getCString();
938       }
939
940 //        printf("%d %s\n", t, gfxFont->getCharName(t));
941       showFontError(gfxFont, 1);
942       if (!gfxFont->is16Bit()) {
943         if(gfxFont->isSymbolic()) {
944           if(fontname && (strstr(fontname,"ing"))) //Dingbats, Wingdings etc.
945            index = 16;
946           else 
947            index = 12;
948         } else if (gfxFont->isFixedWidth()) {
949           index = 8;
950         } else if (gfxFont->isSerif()) {
951           index = 4;
952         } else {
953           index = 0;
954         }
955         if (gfxFont->isBold() && index!=16)
956           index += 2;
957         if (gfxFont->isItalic() && index!=16)
958           index += 1;
959         fontname = fontnames[index];
960         // get width of 'm' in real font and substituted font
961         if ((code = gfxFont->getCharCode("m")) >= 0)
962           w1 = gfxFont->getWidth(code);
963         else
964           w1 = 0;
965         w2 = fontsizes[index];
966         if (gfxFont->getType() == fontType3) {
967           // This is a hack which makes it possible to substitute for some
968           // Type 3 fonts.  The problem is that it's impossible to know what
969           // the base coordinate system used in the font is without actually
970           // rendering the font.  This code tries to guess by looking at the
971           // width of the character 'm' (which breaks if the font is a
972           // subset that doesn't contain 'm').
973           if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
974             w1 /= w2;
975             m11 *= w1;
976             m12 *= w1;
977             m21 *= w1;
978             m22 *= w1;
979           }
980           fm = gfxFont->getFontMatrix();
981           v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
982           m21 *= v;
983           m22 *= v;
984         } else if (!gfxFont->isSymbolic()) {
985           // if real font is substantially narrower than substituted
986           // font, reduce the font size accordingly
987           if (w1 > 0.01 && w1 < 0.9 * w2) {
988             w1 /= w2;
989             if (w1 < 0.8) {
990               w1 = 0.8;
991             }
992             m11 *= w1;
993             m12 *= w1;
994             m21 *= w1;
995             m22 *= w1;
996           }
997         }
998       }
999       if(fontname) {
1000         this->t1id = searchT1Font(fontname);
1001       }
1002       if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
1003           logf("<fatal> Too many fonts in file.");
1004           exit(1);
1005       }
1006       if(oldname) {
1007           substitutesource[substitutepos] = oldname;
1008           substitutetarget[substitutepos] = fontname;
1009           logf("<verbose> substituting %s -> %s", FIXNULL(oldname), FIXNULL(fontname));
1010           substitutepos ++;
1011       }
1012       return fontname;
1013 }
1014
1015 void unlinkfont(char* filename)
1016 {
1017     int l;
1018     if(!filename)
1019         return;
1020     l=strlen(filename);
1021     unlink(filename);
1022     if(!strncmp(&filename[l-4],".afm",4)) {
1023         memcpy(&filename[l-4],".pfb",4);
1024         unlink(filename);
1025         memcpy(&filename[l-4],".pfa",4);
1026         unlink(filename);
1027         memcpy(&filename[l-4],".afm",4);
1028         return;
1029     } else 
1030     if(!strncmp(&filename[l-4],".pfa",4)) {
1031         memcpy(&filename[l-4],".afm",4);
1032         unlink(filename);
1033         memcpy(&filename[l-4],".pfa",4);
1034         return;
1035     } else 
1036     if(!strncmp(&filename[l-4],".pfb",4)) {
1037         memcpy(&filename[l-4],".afm",4);
1038         unlink(filename);
1039         memcpy(&filename[l-4],".pfb",4);
1040         return;
1041     }
1042 }
1043
1044 void SWFOutputDev::updateFont(GfxState *state) 
1045 {
1046   GfxFont*gfxFont = state->getFont();
1047   char * fileName = 0;
1048     
1049   if (!gfxFont) {
1050     return;
1051   }  
1052   char * fontname = gfxFontName(gfxFont);
1053  
1054   int t;
1055   for(t=0;t<substitutepos;t++) {
1056       if(!strcmp(fontname, substitutesource[t])) {
1057           fontname = substitutetarget[t];
1058           break;
1059       }
1060   }
1061
1062   if(swfoutput_queryfont(&output, fontname))
1063   {
1064       swfoutput_setfont(&output, fontname, -1, 0);
1065       return;
1066   }
1067
1068   // look for Type 3 font
1069   if (!type3Warning && gfxFont->getType() == fontType3) {
1070     type3Warning = gTrue;
1071     showFontError(gfxFont, 2);
1072   }
1073   //dumpFontInfo ("<notice>", gfxFont);
1074
1075   Ref embRef;
1076   GBool embedded = gfxFont->getEmbeddedFontID(&embRef);
1077   if(embedded) {
1078     if (!gfxFont->is16Bit() &&
1079         (gfxFont->getType() == fontType1 ||
1080          gfxFont->getType() == fontType1C ||
1081          gfxFont->getType() == fontTrueType)) {
1082         
1083         fileName = writeEmbeddedFontToFile(gfxFont);
1084         if(!fileName) {
1085           logf("<error> Couldn't write font to file");
1086           showFontError(gfxFont,0);
1087           return ;
1088         }
1089         this->t1id = T1_AddFont(fileName);
1090         if(this->t1id<0) {
1091           logf("<error> Couldn't load font from file");
1092           showFontError(gfxFont,0);
1093           unlinkfont(fileName);
1094           return ;
1095         }
1096     }
1097     else {
1098         showFontError(gfxFont,0);
1099         fontname = substituteFont(gfxFont, fontname);
1100     }
1101   } else {
1102     if(fontname) {
1103         int newt1id = searchT1Font(fontname);
1104         if(newt1id<0) {
1105             fontname = substituteFont(gfxFont, fontname);
1106         } else
1107             this->t1id = newt1id;
1108     }
1109     else
1110         fontname = substituteFont(gfxFont, fontname);
1111   }
1112
1113   if(t1id<0) {
1114       showFontError(gfxFont,0);
1115       return;
1116   }
1117  
1118   /* we may have done some substitutions here, so check
1119      again if this font is cached. */
1120   if(swfoutput_queryfont(&output, fontname))
1121   {
1122       swfoutput_setfont(&output, fontname, -1, 0);
1123       return;
1124   }
1125
1126   logf("<verbose> Creating new SWF font: t1id: %d, filename: %s name:%s", this->t1id, FIXNULL(fileName), FIXNULL(fontname));
1127   swfoutput_setfont(&output, fontname, this->t1id, fileName);
1128   if(fileName)
1129       unlinkfont(fileName);
1130 }
1131
1132 int pic_xids[1024];
1133 int pic_yids[1024];
1134 int pic_ids[1024];
1135 int picpos = 0;
1136 int pic_id = 0;
1137
1138 void SWFOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
1139                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
1140                                    GBool inlineImg, int mask)
1141 {
1142   FILE *fi;
1143   int c;
1144   char fileName[128];
1145   double x1,y1,x2,y2,x3,y3,x4,y4;
1146   ImageStream *imgStr;
1147   Guchar pixBuf[4];
1148   GfxRGB rgb;
1149   int ncomps = 1;
1150   int bits = 1;
1151                                  
1152   if(colorMap) {
1153     ncomps = colorMap->getNumPixelComps();
1154     bits = colorMap->getBits();
1155   }
1156   imgStr = new ImageStream(str, width, ncomps,bits);
1157   imgStr->reset();
1158
1159   if(!width || !height || (height<=1 && width<=1))
1160   {
1161       logf("<verbose> Ignoring %d by %d image", width, height);
1162       unsigned char buf[8];
1163       int x,y;
1164       for (y = 0; y < height; ++y)
1165       for (x = 0; x < width; ++x) {
1166           imgStr->getPixel(buf);
1167       }
1168       delete imgStr;
1169       return;
1170   }
1171   
1172   state->transform(0, 1, &x1, &y1);
1173   state->transform(0, 0, &x2, &y2);
1174   state->transform(1, 0, &x3, &y3);
1175   state->transform(1, 1, &x4, &y4);
1176
1177   if(!pbminfo && !(str->getKind()==strDCT)) {
1178       logf("<notice> file contains pbm pictures %s",mask?"(masked)":"");
1179       if(mask)
1180       logf("<verbose> drawing %d by %d masked picture\n", width, height);
1181       pbminfo = 1;
1182   }
1183   if(!jpeginfo && (str->getKind()==strDCT)) {
1184       logf("<notice> file contains jpeg pictures");
1185       jpeginfo = 1;
1186   }
1187
1188   if(mask) {
1189       int yes=0,i,j;
1190       unsigned char buf[8];
1191       int xid = 0;
1192       int yid = 0;
1193       int x,y;
1194       int width2 = (width+3)&(~3);
1195       unsigned char*pic = new unsigned char[width2*height];
1196       RGBA pal[256];
1197       GfxRGB rgb;
1198       state->getFillRGB(&rgb);
1199       pal[0].r = (int)(rgb.r*255); pal[0].g = (int)(rgb.g*255); 
1200       pal[0].b = (int)(rgb.b*255); pal[0].a = 255;
1201       pal[1].r = 0; pal[1].g = 0; pal[1].b = 0; pal[1].a = 0;
1202       xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1203       yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1204       for (y = 0; y < height; ++y)
1205       for (x = 0; x < width; ++x)
1206       {
1207             imgStr->getPixel(buf);
1208             // if(invert) buf[0]=255-buf[0]?
1209             pic[width*y+x] = buf[0];
1210             xid+=x*buf[0]+1;
1211             yid+=y*buf[0]+1;
1212       }
1213       int t,found = -1;
1214       for(t=0;t<picpos;t++)
1215       {
1216           if(pic_xids[t] == xid &&
1217              pic_yids[t] == yid) {
1218               found = t;break;
1219           }
1220       }
1221       if(found<0) {
1222           pic_ids[picpos] = swfoutput_drawimagelossless256(&output, pic, pal, width, height, 
1223                   x1,y1,x2,y2,x3,y3,x4,y4);
1224           pic_xids[picpos] = xid;
1225           pic_yids[picpos] = yid;
1226           if(picpos<1024)
1227               picpos++;
1228       } else {
1229           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1230                   x1,y1,x2,y2,x3,y3,x4,y4);
1231       }
1232       free(pic);
1233       delete imgStr;
1234       return;
1235   } 
1236
1237   int x,y;
1238   
1239   if(colorMap->getNumPixelComps()!=1 || str->getKind()==strDCT)
1240   {
1241       RGBA*pic=new RGBA[width*height];
1242       int xid = 0;
1243       int yid = 0;
1244       for (y = 0; y < height; ++y) {
1245         for (x = 0; x < width; ++x) {
1246           int r,g,b,a;
1247           imgStr->getPixel(pixBuf);
1248           colorMap->getRGB(pixBuf, &rgb);
1249           pic[width*y+x].r = r = (U8)(rgb.r * 255 + 0.5);
1250           pic[width*y+x].g = g = (U8)(rgb.g * 255 + 0.5);
1251           pic[width*y+x].b = b = (U8)(rgb.b * 255 + 0.5);
1252           pic[width*y+x].a = a = 255;//(U8)(rgb.a * 255 + 0.5);
1253           xid += x*r+x*b*3+x*g*7+x*a*11;
1254           yid += y*r*3+y*b*17+y*g*19+y*a*11;
1255         }
1256       }
1257       int t,found = -1;
1258       for(t=0;t<picpos;t++)
1259       {
1260           if(pic_xids[t] == xid &&
1261              pic_yids[t] == yid) {
1262               found = t;break;
1263           }
1264       }
1265       if(found<0) {
1266           if(str->getKind()==strDCT)
1267               pic_ids[picpos] = swfoutput_drawimagejpeg(&output, pic, width, height, 
1268                       x1,y1,x2,y2,x3,y3,x4,y4);
1269           else
1270               pic_ids[picpos] = swfoutput_drawimagelossless(&output, pic, width, height, 
1271                       x1,y1,x2,y2,x3,y3,x4,y4);
1272           pic_xids[picpos] = xid;
1273           pic_yids[picpos] = yid;
1274           if(picpos<1024)
1275               picpos++;
1276       } else {
1277           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1278                   x1,y1,x2,y2,x3,y3,x4,y4);
1279       }
1280       delete pic;
1281       delete imgStr;
1282       return;
1283   }
1284   else
1285   {
1286       U8*pic = new U8[width*height];
1287       RGBA pal[256];
1288       int t;
1289       int xid=0,yid=0;
1290       for(t=0;t<256;t++)
1291       {
1292           int r,g,b,a;
1293           pixBuf[0] = t;
1294           colorMap->getRGB(pixBuf, &rgb);
1295           pal[t].r = r = (U8)(rgb.r * 255 + 0.5);
1296           pal[t].g = g = (U8)(rgb.g * 255 + 0.5);
1297           pal[t].b = b = (U8)(rgb.b * 255 + 0.5);
1298           pal[t].a = a = 255;//(U8)(rgb.b * 255 + 0.5);
1299           xid += t*r+t*b*3+t*g*7+t*a*11;
1300           xid += (~t)*r+t*b*3+t*g*7+t*a*11;
1301       }
1302       for (y = 0; y < height; ++y) {
1303         for (x = 0; x < width; ++x) {
1304           imgStr->getPixel(pixBuf);
1305           pic[width*y+x] = pixBuf[0];
1306           xid += x*pixBuf[0]*7;
1307           yid += y*pixBuf[0]*3;
1308         }
1309       }
1310       int found = -1;
1311       for(t=0;t<picpos;t++)
1312       {
1313           if(pic_xids[t] == xid &&
1314              pic_yids[t] == yid) {
1315               found = t;break;
1316           }
1317       }
1318       if(found<0) {
1319           pic_ids[picpos] = swfoutput_drawimagelossless256(&output, pic, pal, width, height, 
1320                   x1,y1,x2,y2,x3,y3,x4,y4);
1321           pic_xids[picpos] = xid;
1322           pic_yids[picpos] = yid;
1323           if(picpos<1024)
1324               picpos++;
1325       } else {
1326           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1327                   x1,y1,x2,y2,x3,y3,x4,y4);
1328       }
1329       delete pic;
1330       delete imgStr;
1331       return;
1332   }
1333 }
1334
1335 void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1336                                    int width, int height, GBool invert,
1337                                    GBool inlineImg) 
1338 {
1339   logf("<verbose> drawImageMask %dx%d, invert=%d inline=%d", width, height, invert, inlineImg);
1340   drawGeneralImage(state,ref,str,width,height,0,invert,inlineImg,1);
1341 }
1342
1343 void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1344                                int width, int height,
1345                                GfxImageColorMap *colorMap, GBool inlineImg) 
1346 {
1347   logf("<verbose> drawImage %dx%d, %s, inline=%d", width, height, 
1348           colorMap?"colorMap":"no colorMap", inlineImg);
1349   if(colorMap)
1350       logf("<verbose> colorMap pixcomps:%d bits:%d mode:%d\n", colorMap->getNumPixelComps(),
1351               colorMap->getBits(),colorMap->getColorSpace()->getMode());
1352   drawGeneralImage(state,ref,str,width,height,colorMap,0,inlineImg,0);
1353 }
1354
1355 SWFOutputDev*output = 0; 
1356
1357 static void printInfoString(Dict *infoDict, char *key, char *fmt) {
1358   Object obj;
1359   GString *s1, *s2;
1360   int i;
1361
1362   if (infoDict->lookup(key, &obj)->isString()) {
1363     s1 = obj.getString();
1364     if ((s1->getChar(0) & 0xff) == 0xfe &&
1365         (s1->getChar(1) & 0xff) == 0xff) {
1366       s2 = new GString();
1367       for (i = 2; i < obj.getString()->getLength(); i += 2) {
1368         if (s1->getChar(i) == '\0') {
1369           s2->append(s1->getChar(i+1));
1370         } else {
1371           delete s2;
1372           s2 = new GString("<unicode>");
1373           break;
1374         }
1375       }
1376       printf(fmt, s2->getCString());
1377       delete s2;
1378     } else {
1379       printf(fmt, s1->getCString());
1380     }
1381   }
1382   obj.free();
1383 }
1384
1385 static void printInfoDate(Dict *infoDict, char *key, char *fmt) {
1386   Object obj;
1387   char *s;
1388
1389   if (infoDict->lookup(key, &obj)->isString()) {
1390     s = obj.getString()->getCString();
1391     if (s[0] == 'D' && s[1] == ':') {
1392       s += 2;
1393     }
1394     printf(fmt, s);
1395   }
1396   obj.free();
1397 }
1398
1399 void pdfswf_init(char*filename, char*userPassword) 
1400 {
1401   GString *fileName = new GString(filename);
1402   GString *userPW;
1403   Object info;
1404   // init error file
1405   errorInit();
1406
1407   // read config file
1408   initParams(xpdfConfigFile);
1409
1410   // open PDF file
1411   xref = NULL;
1412   if (userPassword && userPassword[0]) {
1413     userPW = new GString(userPassword);
1414   } else {
1415     userPW = NULL;
1416   }
1417   doc = new PDFDoc(fileName, userPW);
1418   if (userPW) {
1419     delete userPW;
1420   }
1421   if (!doc->isOk()) {
1422     exit(1);
1423   }
1424
1425   // print doc info
1426   doc->getDocInfo(&info);
1427   if (info.isDict()) {
1428     printInfoString(info.getDict(), "Title",        "Title:        %s\n");
1429     printInfoString(info.getDict(), "Subject",      "Subject:      %s\n");
1430     printInfoString(info.getDict(), "Keywords",     "Keywords:     %s\n");
1431     printInfoString(info.getDict(), "Author",       "Author:       %s\n");
1432     printInfoString(info.getDict(), "Creator",      "Creator:      %s\n");
1433     printInfoString(info.getDict(), "Producer",     "Producer:     %s\n");
1434     printInfoDate(info.getDict(),   "CreationDate", "CreationDate: %s\n");
1435     printInfoDate(info.getDict(),   "ModDate",      "ModDate:      %s\n");
1436   }
1437   info.free();
1438
1439   // print page count
1440   printf("Pages:        %d\n", doc->getNumPages());
1441   numpages = doc->getNumPages();
1442   
1443   // print linearization info
1444   printf("Linearized:   %s\n", doc->isLinearized() ? "yes" : "no");
1445
1446   // print encryption info
1447   printf("Encrypted:    ");
1448   if (doc->isEncrypted()) {
1449     printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
1450            doc->okToPrint() ? "yes" : "no",
1451            doc->okToCopy() ? "yes" : "no",
1452            doc->okToChange() ? "yes" : "no",
1453            doc->okToAddNotes() ? "yes" : "no");
1454         /*ERROR: This pdf is encrypted, and disallows copying.
1455           Due to the DMCA, paragraph 1201, (2) A-C, circumventing
1456           a technological measure that efficively controls access to
1457           a protected work is violating American law. 
1458           See www.eff.org for more information about DMCA issues.
1459          */
1460         if(!doc->okToCopy()) {
1461             printf("PDF disallows copying. Bailing out.\n");
1462             exit(1); //bail out
1463         }
1464         if(!doc->okToChange() || !doc->okToAddNotes())
1465             swfoutput_setprotected();
1466     }
1467   else {
1468     printf("no\n");
1469   }
1470
1471
1472   output = new SWFOutputDev();
1473 }
1474
1475 void pdfswf_drawonlyshapes()
1476 {
1477     drawonlyshapes = 1;
1478 }
1479
1480 void pdfswf_ignoredraworder()
1481 {
1482     ignoredraworder = 1;
1483 }
1484
1485 void pdfswf_linksopennewwindow()
1486 {
1487     opennewwindow = 1;
1488 }
1489
1490 void pdfswf_storeallcharacters()
1491 {
1492     storeallcharacters = 1;
1493 }
1494
1495 void pdfswf_enablezlib()
1496 {
1497     enablezlib = 1;
1498 }
1499
1500 void pdfswf_jpegquality(int val)
1501 {
1502     if(val<0) val=0;
1503     if(val>100) val=100;
1504     jpegquality = val;
1505 }
1506
1507 void pdfswf_setoutputfilename(char*_filename)
1508 {
1509     swffilename = _filename;
1510 }
1511
1512
1513 void pdfswf_convertpage(int page)
1514 {
1515     if(!pages)
1516     {
1517         pages = (int*)malloc(1024*sizeof(int));
1518         pagebuflen = 1024;
1519     } else {
1520         if(pagepos == pagebuflen)
1521         {
1522             pagebuflen+=1024;
1523             pages = (int*)realloc(pages, pagebuflen);
1524         }
1525     }
1526     pages[pagepos++] = page;
1527 }
1528
1529 void pdfswf_performconversion()
1530 {
1531     int t;
1532     for(t=0;t<pagepos;t++)
1533     {
1534        currentpage = pages[t];
1535        doc->displayPage((OutputDev*)output, currentpage, /*dpi*/72, /*rotate*/0, /*doLinks*/(int)1);
1536     }
1537 }
1538
1539 int pdfswf_numpages()
1540 {
1541   return doc->getNumPages();
1542 }
1543
1544 int closed=0;
1545 void pdfswf_close()
1546 {
1547     logf("<debug> pdfswf.cc: pdfswf_close()");
1548     delete output;
1549     delete doc;
1550     freeParams();
1551     // check for memory leaks
1552     Object::memCheck(stderr);
1553     gMemReport(stderr);
1554 }
1555