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