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