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