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