CIDFonts: look for external replacement.
[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 int ciderror = 0;
582 void SWFOutputDev::drawChar(GfxState *state, double x, double y,
583                         double dx, double dy,
584                         double originX, double originY,
585                         CharCode c, Unicode *u, int uLen)
586 {
587     logf("<debug> drawChar(%f,%f,%f,%f,'%c')\n",x,y,dx,dy,c);
588     // check for invisible text -- this is used by Acrobat Capture
589     if ((state->getRender() & 3) != 3)
590     {
591        GfxFont*font = state->getFont();
592        Gfx8BitFont*font8;
593        if(font->isCIDFont()) {
594            if(!ciderror)
595             logf("<error> Not drawing CID Font characters!");
596            ciderror++;
597            return;
598        }
599        if(font->getType() == fontType3) {
600            /* type 3 chars are passed primarily as graphics */
601            return;
602        }
603        font8 = (Gfx8BitFont*)font;
604
605        char**enc=font8->getEncoding();
606
607        double x1,y1;
608        x1 = x;
609        y1 = y;
610        state->transform(x, y, &x1, &y1);
611
612        if(enc[c])
613           swfoutput_drawchar(&output, x1, y1, enc[c], c);
614        else
615           logf("<warning> couldn't get name for character %02x from Encoding", c);
616     }
617 }
618
619 void SWFOutputDev::endString(GfxState *state) 
620
621     logf("<debug> endstring\n");
622 }    
623
624  
625 GBool SWFOutputDev::beginType3Char(GfxState *state,
626                                CharCode code, Unicode *u, int uLen)
627 {
628     logf("<debug> beginType3Char %d, %08x, %d", code, *u, uLen);
629     type3active = 1;
630     /* the character itself is going to be passed using
631        drawImageMask() */
632     return gFalse; /* gTrue= is_in_cache? */
633 }
634
635 void SWFOutputDev::endType3Char(GfxState *state)
636 {
637     type3active = 0;
638     logf("<debug> endType3Char");
639 }
640
641 void SWFOutputDev::startPage(int pageNum, GfxState *state) 
642 {
643   double x1,y1,x2,y2;
644   laststate = state;
645   logf("<debug> startPage %d\n", pageNum);
646   logf("<notice> processing page %d", pageNum);
647
648   state->transform(state->getX1(),state->getY1(),&x1,&y1);
649   state->transform(state->getX2(),state->getY2(),&x2,&y2);
650   if(!outputstarted) {
651     swfoutput_init(&output, swffilename, abs((int)(x2-x1)),abs((int)(y2-y1)));
652     outputstarted = 1;
653   }
654   else
655     swfoutput_newpage(&output);
656 }
657
658 void SWFOutputDev::drawLink(Link *link, Catalog *catalog) 
659 {
660   logf("<debug> drawlink\n");
661   double x1, y1, x2, y2, w;
662   GfxRGB rgb;
663   swfcoord points[5];
664   int x, y;
665
666   link->getBorder(&x1, &y1, &x2, &y2, &w);
667 //  if (w > 0) 
668   {
669     rgb.r = 0;
670     rgb.g = 0;
671     rgb.b = 1;
672     cvtUserToDev(x1, y1, &x, &y);
673     points[0].x = points[4].x = (int)x;
674     points[0].y = points[4].y = (int)y;
675     cvtUserToDev(x2, y1, &x, &y);
676     points[1].x = (int)x;
677     points[1].y = (int)y;
678     cvtUserToDev(x2, y2, &x, &y);
679     points[2].x = (int)x;
680     points[2].y = (int)y;
681     cvtUserToDev(x1, y2, &x, &y);
682     points[3].x = (int)x;
683     points[3].y = (int)y;
684
685     LinkAction*action=link->getAction();
686     char buf[128];
687     char*s = "-?-";
688     char*type = "-?-";
689     char*url = 0;
690     char*named = 0;
691     int page = -1;
692     switch(action->getKind())
693     {
694         case actionGoTo: {
695             type = "GoTo";
696             LinkGoTo *ha=(LinkGoTo *)link->getAction();
697             LinkDest *dest=NULL;
698             if (ha->getDest()==NULL) 
699                 dest=catalog->findDest(ha->getNamedDest());
700             else dest=ha->getDest();
701             if (dest){ 
702               if (dest->isPageRef()){
703                 Ref pageref=dest->getPageRef();
704                 page=catalog->findPage(pageref.num,pageref.gen);
705               }
706               else  page=dest->getPageNum();
707               sprintf(buf, "%d", page);
708               s = buf;
709             }
710         }
711         break;
712         case actionGoToR: {
713             type = "GoToR";
714             LinkGoToR*l = (LinkGoToR*)action;
715             GString*g = l->getNamedDest();
716             if(g)
717              s = g->getCString();
718         }
719         break;
720         case actionNamed: {
721             type = "Named";
722             LinkNamed*l = (LinkNamed*)action;
723             GString*name = l->getName();
724             if(name) {
725               s = name->lowerCase()->getCString();
726               named = name->getCString();
727               if(strstr(s, "next") || strstr(s, "forward"))
728               {
729                   page = currentpage + 1;
730               }
731               else if(strstr(s, "prev") || strstr(s, "back"))
732               {
733                   page = currentpage - 1;
734               }
735               else if(strstr(s, "last") || strstr(s, "end"))
736               {
737                   page = pages[pagepos-1]; //:)
738               }
739               else if(strstr(s, "first") || strstr(s, "top"))
740               {
741                   page = 1;
742               }
743             }
744         }
745         break;
746         case actionLaunch: {
747             type = "Launch";
748             LinkLaunch*l = (LinkLaunch*)action;
749             GString * str = new GString(l->getFileName());
750             str->append(l->getParams());
751             s = str->getCString();
752         }
753         break;
754         case actionURI: {
755             type = "URI";
756             LinkURI*l = (LinkURI*)action;
757             GString*g = l->getURI();
758             if(g) {
759              url = g->getCString();
760              s = url;
761             }
762         }
763         break;
764         case actionUnknown: {
765             type = "Unknown";
766             LinkUnknown*l = (LinkUnknown*)action;
767             s = "";
768         }
769         break;
770         default: {
771             logf("<error> Unknown link type!\n");
772             break;
773         }
774     }
775     if(!linkinfo && (page || url))
776     {
777         logf("<notice> File contains links");
778         linkinfo = 1;
779     }
780     if(page>0)
781     {
782         int t;
783         for(t=0;t<pagepos;t++)
784             if(pages[t]==page)
785                 break;
786         if(t!=pagepos)
787         swfoutput_linktopage(&output, t, points);
788     }
789     else if(url)
790     {
791         swfoutput_linktourl(&output, url, points);
792     }
793     else if(named)
794     {
795         swfoutput_namedlink(&output, named, points);
796     }
797     logf("<verbose> \"%s\" link to \"%s\" (%d)\n", type, FIXNULL(s), page);
798   }
799 }
800
801 void SWFOutputDev::saveState(GfxState *state) {
802   logf("<debug> saveState\n");
803   updateAll(state);
804   if(clippos<64)
805     clippos ++;
806   else
807     logf("<error> Too many nested states in pdf.");
808   clipping[clippos] = 0;
809 };
810
811 void SWFOutputDev::restoreState(GfxState *state) {
812   logf("<debug> restoreState\n");
813   updateAll(state);
814   while(clipping[clippos]) {
815       swfoutput_endclip(&output);
816       clipping[clippos]--;
817   }
818   clippos--;
819 }
820
821 char type3Warning=0;
822
823 int SWFOutputDev::searchT1Font(char*name) 
824 {       
825     int i;
826     int mapid=-1;
827     char*filename=0;
828     
829     char*name2 = 0;
830     if(name) name2 = strchr(name,'+');
831     if(name2) name2++;
832
833     for(i=0;i<sizeof(pdf2t1map)/sizeof(mapping);i++) 
834     {
835         if(!strcmp(name, pdf2t1map[i].pdffont))
836         {
837             filename = pdf2t1map[i].filename;
838             mapid = i;
839         }
840     }
841     if(filename) {
842         for(i=0; i<T1_Get_no_fonts(); i++)
843         {
844             char*fontfilename = T1_GetFontFileName (i);
845             if(strstr(fontfilename, filename))
846             {
847                     pdf2t1map[i].id = mapid;
848                     return i;
849             }
850         }
851     } else {
852         for(i=0; i<T1_Get_no_fonts(); i++)
853         {
854             char*fontname = T1_GetFontName (i);
855             if(!fontname) {
856                 T1_LoadFont(i);
857                 fontname = T1_GetFontName (i);
858                 logf("<verbose> Loading extra font %s from %s\n", FIXNULL(fontname), 
859                                                                   FIXNULL(T1_GetFontFileName(i)));
860             }
861
862             if(fontname) {
863                 if((!strcmp(name, fontname)) || 
864                    (name2 && !strcmp(name2, fontname)))
865                    {
866                     logf("<notice> Extra font %s is being used.\n", fontname);
867                     return i;
868                 }
869             }
870             fontname = T1_GetFontFileName(i);
871             if(strrchr(fontname,'/'))
872                     fontname = strrchr(fontname,'/')+1;
873  
874             if(strstr(fontname, name) || (name2 && strstr(fontname,name2))) {
875                 logf("<notice> Extra font %s is being used.\n", fontname);
876                 return i;
877             }
878         }
879     }
880     return -1;
881 }
882
883 void SWFOutputDev::updateLineWidth(GfxState *state)
884 {
885     double width = state->getTransformedLineWidth();
886     swfoutput_setlinewidth(&output, width);
887 }
888
889 void SWFOutputDev::updateFillColor(GfxState *state) 
890 {
891     GfxRGB rgb;
892     double opaq = state->getFillOpacity();
893     state->getFillRGB(&rgb);
894
895     swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
896                                     (char)(rgb.b*255), (char)(opaq*255));
897 }
898
899 void SWFOutputDev::updateStrokeColor(GfxState *state) 
900 {
901     GfxRGB rgb;
902     double opaq = state->getStrokeOpacity();
903     state->getStrokeRGB(&rgb);
904
905     swfoutput_setstrokecolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
906                                       (char)(rgb.b*255), (char)(opaq*255));
907 }
908
909 char*SWFOutputDev::writeEmbeddedFontToFile(XRef*ref, GfxFont*font)
910 {
911       char*tmpFileName = NULL;
912       FILE *f;
913       int c;
914       char *fontBuf;
915       int fontLen;
916       Type1CFontFile *cvt;
917       Ref embRef;
918       Object refObj, strObj;
919       tmpFileName = "/tmp/tmpfont";
920       int ret;
921
922       ret = font->getEmbeddedFontID(&embRef);
923       if(!ret) {
924           /* not embedded- the caller should now search the font
925              directories for this font */
926           return 0;
927       }
928
929       f = fopen(tmpFileName, "wb");
930       if (!f) {
931         logf("<error> Couldn't create temporary Type 1 font file");
932           return 0;
933       }
934       if (font->getType() == fontType1C) {
935         if (!(fontBuf = font->readEmbFontFile(xref, &fontLen))) {
936           fclose(f);
937           logf("<error> Couldn't read embedded font file");
938           return 0;
939         }
940         cvt = new Type1CFontFile(fontBuf, fontLen);
941         cvt->convertToType1(f);
942         delete cvt;
943         gfree(fontBuf);
944       } else {
945         font->getEmbeddedFontID(&embRef);
946         refObj.initRef(embRef.num, embRef.gen);
947         refObj.fetch(ref, &strObj);
948         refObj.free();
949         strObj.streamReset();
950         while ((c = strObj.streamGetChar()) != EOF) {
951           fputc(c, f);
952         }
953         strObj.streamClose();
954         strObj.free();
955       }
956       fclose(f);
957
958       if(font->getType() == fontTrueType)
959       {
960           if(!ttfinfo) {
961               logf("<notice> File contains TrueType fonts");
962               ttfinfo = 1;
963           }
964           char name2[80];
965           char*tmp;
966           tmp = strdup(mktmpname((char*)name2));
967           sprintf(name2, "%s", tmp);
968           char*a[] = {"./ttf2pt1","-pttf","-b", tmpFileName, name2};
969           logf("<verbose> Invoking ttf2pt1...");
970           ttf2pt1_main(5,a);
971           unlink(tmpFileName);
972           sprintf(name2,"%s.pfb",tmp);
973           tmpFileName = strdup(name2);
974       }
975
976     return tmpFileName;
977 }
978
979 char* gfxFontName(GfxFont* gfxFont)
980 {
981       GString *gstr;
982       gstr = gfxFont->getName();
983       if(gstr) {
984           return gstr->getCString();
985       }
986       else {
987           char buf[32];
988           Ref*r=gfxFont->getID();
989           sprintf(buf, "UFONT%d", r->num);
990           return strdup(buf);
991       }
992 }
993
994 char* substitutetarget[256];
995 char* substitutesource[256];
996 int substitutepos = 0;
997
998 char* SWFOutputDev::substituteFont(GfxFont*gfxFont, char* oldname)
999 {
1000 /* ------------------------------ V1 */
1001
1002     char*fontname = "Times-Roman";
1003     this->t1id = searchT1Font(fontname);
1004     if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
1005         logf("<fatal> Too many fonts in file.");
1006         exit(1);
1007     }
1008     if(oldname) {
1009         substitutesource[substitutepos] = oldname;
1010         substitutetarget[substitutepos] = fontname;
1011         logf("<verbose> substituting %s -> %s", FIXNULL(oldname), FIXNULL(fontname));
1012         substitutepos ++;
1013     }
1014     return fontname;
1015
1016 /* ------------------------------ V2 */
1017
1018 /*      //substitute font
1019       char* fontname = 0;
1020       double m11, m12, m21, m22;
1021       int index;
1022       int code;
1023       double w,w1,w2;
1024       double*fm;
1025       double v;
1026       if(gfxFont->getName()) {
1027         fontname = gfxFont->getName()->getCString();
1028       }
1029
1030 //        printf("%d %s\n", t, gfxFont->getCharName(t));
1031       showFontError(gfxFont, 1);
1032       if(1) { //if (!gfxFont->isCIDFont()) { FIXME: xpdf 1.01 does not have is16Bit()
1033         if(gfxFont->isSymbolic()) {
1034           if(fontname && (strstr(fontname,"ing"))) //Dingbats, Wingdings etc.
1035            index = 16;
1036           else 
1037            index = 12;
1038         } else if (gfxFont->isFixedWidth()) {
1039           index = 8;
1040         } else if (gfxFont->isSerif()) {
1041           index = 4;
1042         } else {
1043           index = 0;
1044         }
1045         if (gfxFont->isBold() && index!=16)
1046           index += 2;
1047         if (gfxFont->isItalic() && index!=16)
1048           index += 1;
1049         fontname = fontnames[index];
1050         // get width of 'm' in real font and substituted font
1051         if ((code = gfxFont->getCharCode("m")) >= 0)
1052           w1 = gfxFont->getWidth(code);
1053         else
1054           w1 = 0;
1055         w2 = fontsizes[index];
1056         if (gfxFont->getType() == fontType3) {
1057           // This is a hack which makes it possible to substitute for some
1058           // Type 3 fonts.  The problem is that it's impossible to know what
1059           // the base coordinate system used in the font is without actually
1060           // rendering the font.  This code tries to guess by looking at the
1061           // width of the character 'm' (which breaks if the font is a
1062           // subset that doesn't contain 'm').
1063           if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
1064             w1 /= w2;
1065             m11 *= w1;
1066             m12 *= w1;
1067             m21 *= w1;
1068             m22 *= w1;
1069           }
1070           fm = gfxFont->getFontMatrix();
1071           v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
1072           m21 *= v;
1073           m22 *= v;
1074         } else if (!gfxFont->isSymbolic()) {
1075           // if real font is substantially narrower than substituted
1076           // font, reduce the font size accordingly
1077           if (w1 > 0.01 && w1 < 0.9 * w2) {
1078             w1 /= w2;
1079             if (w1 < 0.8) {
1080               w1 = 0.8;
1081             }
1082             m11 *= w1;
1083             m12 *= w1;
1084             m21 *= w1;
1085             m22 *= w1;
1086           }
1087         }
1088       }
1089       if(fontname) {
1090         this->t1id = searchT1Font(fontname);
1091       }
1092       if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
1093           logf("<fatal> Too many fonts in file.");
1094           exit(1);
1095       }
1096       if(oldname) {
1097           substitutesource[substitutepos] = oldname;
1098           substitutetarget[substitutepos] = fontname;
1099           logf("<verbose> substituting %s -> %s", FIXNULL(oldname), FIXNULL(fontname));
1100           substitutepos ++;
1101       }
1102       return fontname;*/
1103 }
1104
1105 void unlinkfont(char* filename)
1106 {
1107     int l;
1108     if(!filename)
1109         return;
1110     l=strlen(filename);
1111     unlink(filename);
1112     if(!strncmp(&filename[l-4],".afm",4)) {
1113         memcpy(&filename[l-4],".pfb",4);
1114         unlink(filename);
1115         memcpy(&filename[l-4],".pfa",4);
1116         unlink(filename);
1117         memcpy(&filename[l-4],".afm",4);
1118         return;
1119     } else 
1120     if(!strncmp(&filename[l-4],".pfa",4)) {
1121         memcpy(&filename[l-4],".afm",4);
1122         unlink(filename);
1123         memcpy(&filename[l-4],".pfa",4);
1124         return;
1125     } else 
1126     if(!strncmp(&filename[l-4],".pfb",4)) {
1127         memcpy(&filename[l-4],".afm",4);
1128         unlink(filename);
1129         memcpy(&filename[l-4],".pfb",4);
1130         return;
1131     }
1132 }
1133
1134 void SWFOutputDev::startDoc(XRef *xref) 
1135 {
1136   this->xref = xref;
1137 }
1138
1139
1140 void SWFOutputDev::updateFont(GfxState *state) 
1141 {
1142   GfxFont*gfxFont = state->getFont();
1143   char * fileName = 0;
1144     
1145   if (!gfxFont) {
1146     return;
1147   }  
1148   char * fontname = gfxFontName(gfxFont);
1149  
1150   int t;
1151   /* first, look if we substituted this font before-
1152      this way, we don't initialize the T1 Fonts
1153      too often */
1154   for(t=0;t<substitutepos;t++) {
1155       if(!strcmp(fontname, substitutesource[t])) {
1156           fontname = substitutetarget[t];
1157           break;
1158       }
1159   }
1160
1161   /* second, see if swfoutput already has this font
1162      cached- if so, we are done */
1163
1164   if(swfoutput_queryfont(&output, fontname))
1165   {
1166       swfoutput_setfont(&output, fontname, -1, 0);
1167       return;
1168   }
1169
1170   // look for Type 3 font
1171   if (!type3Warning && gfxFont->getType() == fontType3) {
1172     type3Warning = gTrue;
1173     showFontError(gfxFont, 2);
1174   }
1175
1176   /* now either load the font, or find a substitution */
1177
1178   Ref embRef;
1179   GBool embedded = gfxFont->getEmbeddedFontID(&embRef);
1180   if(embedded) {
1181     if (!gfxFont->isCIDFont() &&
1182         (gfxFont->getType() == fontType1 ||
1183          gfxFont->getType() == fontType1C ||
1184          gfxFont->getType() == fontTrueType)) {
1185         
1186         fileName = writeEmbeddedFontToFile(xref, gfxFont);
1187         if(!fileName) {
1188           logf("<error> Couldn't write font to file");
1189           showFontError(gfxFont,0);
1190           return ;
1191         }
1192         this->t1id = T1_AddFont(fileName);
1193         if(this->t1id<0) {
1194           logf("<error> Couldn't load font from file");
1195           showFontError(gfxFont,0);
1196           unlinkfont(fileName);
1197           return ;
1198         }
1199     }
1200     else {
1201         int newt1id = searchT1Font(fontname);
1202         if(newt1id<0) {
1203             showFontError(gfxFont,0);
1204             fontname = substituteFont(gfxFont, fontname);
1205         } else
1206             this->t1id = newt1id;
1207     }
1208   } else {
1209     if(fontname) {
1210         int newt1id = searchT1Font(fontname);
1211         if(newt1id<0) {
1212             fontname = substituteFont(gfxFont, fontname);
1213         } else
1214             this->t1id = newt1id;
1215     }
1216     else
1217         fontname = substituteFont(gfxFont, fontname);
1218   }
1219
1220   if(t1id<0) {
1221       showFontError(gfxFont,0);
1222       return;
1223   }
1224  
1225   /* we may have done some substitutions here, so check
1226      again if this font is cached. */
1227   if(swfoutput_queryfont(&output, fontname))
1228   {
1229       swfoutput_setfont(&output, fontname, -1, 0);
1230       return;
1231   }
1232
1233   logf("<verbose> Creating new SWF font: t1id: %d, filename: %s name:%s", this->t1id, FIXNULL(fileName), FIXNULL(fontname));
1234   swfoutput_setfont(&output, fontname, this->t1id, fileName);
1235   if(fileName)
1236       unlinkfont(fileName);
1237 }
1238
1239 int pic_xids[1024];
1240 int pic_yids[1024];
1241 int pic_ids[1024];
1242 int pic_width[1024];
1243 int pic_height[1024];
1244 int picpos = 0;
1245 int pic_id = 0;
1246
1247 #define SQR(x) ((x)*(x))
1248
1249 unsigned char* antialize(unsigned char*data, int width, int height, int newwidth, int newheight, int palettesize)
1250 {
1251     if((newwidth<2 || newheight<2) ||
1252        (width<=newwidth || height<=newheight))
1253         return 0;
1254     unsigned char*newdata;
1255     int x,y;
1256     newdata= (unsigned char*)malloc(newwidth*newheight);
1257     int t;
1258     double fx = (double)(width)/newwidth;
1259     double fy = (double)(height)/newheight;
1260     double px = 0;
1261     int blocksize = (int)(8192/(fx*fy));
1262     int r = 8192*256/palettesize;
1263     for(x=0;x<newwidth;x++) {
1264         double ex = px + fx;
1265         int fromx = (int)px;
1266         int tox = (int)ex;
1267         int xweight1 = (int)(((fromx+1)-px)*256);
1268         int xweight2 = (int)((ex-tox)*256);
1269         double py =0;
1270         for(y=0;y<newheight;y++) {
1271             double ey = py + fy;
1272             int fromy = (int)py;
1273             int toy = (int)ey;
1274             int yweight1 = (int)(((fromy+1)-py)*256);
1275             int yweight2 = (int)((ey-toy)*256);
1276             int a = 0;
1277             int xx,yy;
1278             for(xx=fromx;xx<=tox;xx++)
1279             for(yy=fromy;yy<=toy;yy++) {
1280                 int b = 1-data[width*yy+xx];
1281                 int weight=256;
1282                 if(xx==fromx) weight = (weight*xweight1)/256;
1283                 if(xx==tox) weight = (weight*xweight2)/256;
1284                 if(yy==fromy) weight = (weight*yweight1)/256;
1285                 if(yy==toy) weight = (weight*yweight2)/256;
1286                 a+=b*weight;
1287             }
1288             //if(a) a=(palettesize-1)*r/blocksize;
1289             newdata[y*newwidth+x] = (a*blocksize)/r;
1290             py = ey;
1291         }
1292         px = ex;
1293     }
1294     return newdata;
1295 }
1296
1297 void SWFOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
1298                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
1299                                    GBool inlineImg, int mask)
1300 {
1301   FILE *fi;
1302   int c;
1303   char fileName[128];
1304   double x1,y1,x2,y2,x3,y3,x4,y4;
1305   ImageStream *imgStr;
1306   Guchar pixBuf[4];
1307   GfxRGB rgb;
1308   int ncomps = 1;
1309   int bits = 1;
1310                                  
1311   if(colorMap) {
1312     ncomps = colorMap->getNumPixelComps();
1313     bits = colorMap->getBits();
1314   }
1315   imgStr = new ImageStream(str, width, ncomps,bits);
1316   imgStr->reset();
1317
1318   if(!width || !height || (height<=1 && width<=1))
1319   {
1320       logf("<verbose> Ignoring %d by %d image", width, height);
1321       unsigned char buf[8];
1322       int x,y;
1323       for (y = 0; y < height; ++y)
1324       for (x = 0; x < width; ++x) {
1325           imgStr->getPixel(buf);
1326       }
1327       delete imgStr;
1328       return;
1329   }
1330   
1331   state->transform(0, 1, &x1, &y1);
1332   state->transform(0, 0, &x2, &y2);
1333   state->transform(1, 0, &x3, &y3);
1334   state->transform(1, 1, &x4, &y4);
1335
1336   if(!pbminfo && !(str->getKind()==strDCT)) {
1337       if(!type3active) {
1338           logf("<notice> file contains pbm pictures %s",mask?"(masked)":"");
1339           pbminfo = 1;
1340       }
1341       if(mask)
1342       logf("<verbose> drawing %d by %d masked picture\n", width, height);
1343   }
1344   if(!jpeginfo && (str->getKind()==strDCT)) {
1345       logf("<notice> file contains jpeg pictures");
1346       jpeginfo = 1;
1347   }
1348
1349   if(mask) {
1350       int yes=0,i,j;
1351       unsigned char buf[8];
1352       int xid = 0;
1353       int yid = 0;
1354       int x,y;
1355       unsigned char*pic = new unsigned char[width*height];
1356       RGBA pal[256];
1357       GfxRGB rgb;
1358       state->getFillRGB(&rgb);
1359       memset(pal,255,sizeof(pal));
1360       pal[0].r = (int)(rgb.r*255); pal[0].g = (int)(rgb.g*255); 
1361       pal[0].b = (int)(rgb.b*255); pal[0].a = 255;
1362       pal[1].r = 0; pal[1].g = 0; pal[1].b = 0; pal[1].a = 0;
1363       int numpalette = 2;
1364       xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1365       yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1366       int realwidth = (int)sqrt(SQR(x2-x3) + SQR(y2-y3));
1367       int realheight = (int)sqrt(SQR(x1-x2) + SQR(y1-y2));
1368       for (y = 0; y < height; ++y)
1369       for (x = 0; x < width; ++x)
1370       {
1371             imgStr->getPixel(buf);
1372             if(invert) 
1373                 buf[0]=1-buf[0];
1374             pic[width*y+x] = buf[0];
1375             xid+=x*buf[0]+1;
1376             yid+=y*buf[0]*3+1;
1377       }
1378       
1379       /* the size of the drawn image is added to the identifier
1380          as the same image may require different bitmaps if displayed
1381          at different sizes (due to antialiasing): */
1382       if(type3active) {
1383           xid += realwidth;
1384           yid += realheight;
1385       }
1386       int t,found = -1;
1387       for(t=0;t<picpos;t++)
1388       {
1389           if(pic_xids[t] == xid &&
1390              pic_yids[t] == yid) {
1391               /* if the image was antialiased, the size has changed: */
1392               width = pic_width[t];
1393               height = pic_height[t];
1394               found = t;break;
1395           }
1396       }
1397       if(found<0) {
1398           if(type3active) {
1399               numpalette = 16;
1400               unsigned char*pic2 = 0;
1401               
1402               pic2 = antialize(pic,width,height,realwidth,realheight, numpalette);
1403
1404               if(pic2) {
1405                   width = realwidth;
1406                   height = realheight;
1407                   free(pic);
1408                   pic = pic2;
1409                   /* make a black/white palette */
1410                   int t;
1411                   GfxRGB rgb2;
1412                   rgb2.r = 1 - rgb.r;
1413                   rgb2.g = 1 - rgb.g;
1414                   rgb2.b = 1 - rgb.b;
1415
1416                   float r = 255/(numpalette-1);
1417                   for(t=0;t<numpalette;t++) {
1418                       /*pal[t].r = (U8)(t*r*rgb.r+(numpalette-1-t)*r*rgb2.r);
1419                       pal[t].g = (U8)(t*r*rgb.g+(numpalette-1-t)*r*rgb2.g);
1420                       pal[t].b = (U8)(t*r*rgb.b+(numpalette-1-t)*r*rgb2.b);
1421                       pal[t].a = 255; */
1422                       pal[t].r = (U8)(255*rgb.r);
1423                       pal[t].g = (U8)(255*rgb.g);
1424                       pal[t].b = (U8)(255*rgb.b);
1425                       pal[t].a = (U8)(t*r);
1426                   }
1427               }
1428           }
1429           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, 
1430                   x1,y1,x2,y2,x3,y3,x4,y4, numpalette);
1431           pic_xids[picpos] = xid;
1432           pic_yids[picpos] = yid;
1433           pic_width[picpos] = width;
1434           pic_height[picpos] = height;
1435           if(picpos<1024)
1436               picpos++;
1437       } else {
1438           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1439                   x1,y1,x2,y2,x3,y3,x4,y4);
1440       }
1441       free(pic);
1442       delete imgStr;
1443       return;
1444   } 
1445
1446   int x,y;
1447   
1448   if(colorMap->getNumPixelComps()!=1 || str->getKind()==strDCT)
1449   {
1450       RGBA*pic=new RGBA[width*height];
1451       int xid = 0;
1452       int yid = 0;
1453       for (y = 0; y < height; ++y) {
1454         for (x = 0; x < width; ++x) {
1455           int r,g,b,a;
1456           imgStr->getPixel(pixBuf);
1457           colorMap->getRGB(pixBuf, &rgb);
1458           pic[width*y+x].r = r = (U8)(rgb.r * 255 + 0.5);
1459           pic[width*y+x].g = g = (U8)(rgb.g * 255 + 0.5);
1460           pic[width*y+x].b = b = (U8)(rgb.b * 255 + 0.5);
1461           pic[width*y+x].a = a = 255;//(U8)(rgb.a * 255 + 0.5);
1462           xid += x*r+x*b*3+x*g*7+x*a*11;
1463           yid += y*r*3+y*b*17+y*g*19+y*a*11;
1464         }
1465       }
1466       int t,found = -1;
1467       for(t=0;t<picpos;t++)
1468       {
1469           if(pic_xids[t] == xid &&
1470              pic_yids[t] == yid) {
1471               found = t;break;
1472           }
1473       }
1474       if(found<0) {
1475           if(str->getKind()==strDCT)
1476               pic_ids[picpos] = swfoutput_drawimagejpeg(&output, pic, width, height, 
1477                       x1,y1,x2,y2,x3,y3,x4,y4);
1478           else
1479               pic_ids[picpos] = swfoutput_drawimagelossless(&output, pic, width, height, 
1480                       x1,y1,x2,y2,x3,y3,x4,y4);
1481           pic_xids[picpos] = xid;
1482           pic_yids[picpos] = yid;
1483           pic_width[picpos] = width;
1484           pic_height[picpos] = height;
1485           if(picpos<1024)
1486               picpos++;
1487       } else {
1488           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1489                   x1,y1,x2,y2,x3,y3,x4,y4);
1490       }
1491       delete pic;
1492       delete imgStr;
1493       return;
1494   }
1495   else
1496   {
1497       U8*pic = new U8[width*height];
1498       RGBA pal[256];
1499       int t;
1500       int xid=0,yid=0;
1501       for(t=0;t<256;t++)
1502       {
1503           int r,g,b,a;
1504           pixBuf[0] = t;
1505           colorMap->getRGB(pixBuf, &rgb);
1506           pal[t].r = r = (U8)(rgb.r * 255 + 0.5);
1507           pal[t].g = g = (U8)(rgb.g * 255 + 0.5);
1508           pal[t].b = b = (U8)(rgb.b * 255 + 0.5);
1509           pal[t].a = a = 255;//(U8)(rgb.b * 255 + 0.5);
1510           xid += t*r+t*b*3+t*g*7+t*a*11;
1511           xid += (~t)*r+t*b*3+t*g*7+t*a*11;
1512       }
1513       for (y = 0; y < height; ++y) {
1514         for (x = 0; x < width; ++x) {
1515           imgStr->getPixel(pixBuf);
1516           pic[width*y+x] = pixBuf[0];
1517           xid += x*pixBuf[0]*7;
1518           yid += y*pixBuf[0]*3;
1519         }
1520       }
1521       int found = -1;
1522       for(t=0;t<picpos;t++)
1523       {
1524           if(pic_xids[t] == xid &&
1525              pic_yids[t] == yid) {
1526               found = t;break;
1527           }
1528       }
1529       if(found<0) {
1530           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, 
1531                   x1,y1,x2,y2,x3,y3,x4,y4,256);
1532           pic_xids[picpos] = xid;
1533           pic_yids[picpos] = yid;
1534           pic_width[picpos] = width;
1535           pic_height[picpos] = height;
1536           if(picpos<1024)
1537               picpos++;
1538       } else {
1539           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1540                   x1,y1,x2,y2,x3,y3,x4,y4);
1541       }
1542       delete pic;
1543       delete imgStr;
1544       return;
1545   }
1546 }
1547
1548 void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1549                                    int width, int height, GBool invert,
1550                                    GBool inlineImg) 
1551 {
1552   logf("<verbose> drawImageMask %dx%d, invert=%d inline=%d", width, height, invert, inlineImg);
1553   drawGeneralImage(state,ref,str,width,height,0,invert,inlineImg,1);
1554 }
1555
1556 void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1557                          int width, int height, GfxImageColorMap *colorMap,
1558                          int *maskColors, GBool inlineImg)
1559 {
1560   logf("<verbose> drawImage %dx%d, %s %s, inline=%d", width, height, 
1561           colorMap?"colorMap":"no colorMap", 
1562           maskColors?"maskColors":"no maskColors",
1563           inlineImg);
1564   if(colorMap)
1565       logf("<verbose> colorMap pixcomps:%d bits:%d mode:%d\n", colorMap->getNumPixelComps(),
1566               colorMap->getBits(),colorMap->getColorSpace()->getMode());
1567   drawGeneralImage(state,ref,str,width,height,colorMap,0,inlineImg,0);
1568 }
1569
1570 SWFOutputDev*output = 0; 
1571
1572 static void printInfoString(Dict *infoDict, char *key, char *fmt) {
1573   Object obj;
1574   GString *s1, *s2;
1575   int i;
1576
1577   if (infoDict->lookup(key, &obj)->isString()) {
1578     s1 = obj.getString();
1579     if ((s1->getChar(0) & 0xff) == 0xfe &&
1580         (s1->getChar(1) & 0xff) == 0xff) {
1581       s2 = new GString();
1582       for (i = 2; i < obj.getString()->getLength(); i += 2) {
1583         if (s1->getChar(i) == '\0') {
1584           s2->append(s1->getChar(i+1));
1585         } else {
1586           delete s2;
1587           s2 = new GString("<unicode>");
1588           break;
1589         }
1590       }
1591       printf(fmt, s2->getCString());
1592       delete s2;
1593     } else {
1594       printf(fmt, s1->getCString());
1595     }
1596   }
1597   obj.free();
1598 }
1599
1600 static void printInfoDate(Dict *infoDict, char *key, char *fmt) {
1601   Object obj;
1602   char *s;
1603
1604   if (infoDict->lookup(key, &obj)->isString()) {
1605     s = obj.getString()->getCString();
1606     if (s[0] == 'D' && s[1] == ':') {
1607       s += 2;
1608     }
1609     printf(fmt, s);
1610   }
1611   obj.free();
1612 }
1613
1614 void pdfswf_init(char*filename, char*userPassword) 
1615 {
1616   GString *fileName = new GString(filename);
1617   GString *userPW;
1618   Object info;
1619
1620   // read config file
1621   globalParams = new GlobalParams("");
1622
1623   // open PDF file
1624   if (userPassword && userPassword[0]) {
1625     userPW = new GString(userPassword);
1626   } else {
1627     userPW = NULL;
1628   }
1629   doc = new PDFDoc(fileName, userPW);
1630   if (userPW) {
1631     delete userPW;
1632   }
1633   if (!doc->isOk()) {
1634     exit(1);
1635   }
1636
1637   // print doc info
1638   doc->getDocInfo(&info);
1639   if (info.isDict() &&
1640     (screenloglevel>=LOGLEVEL_NOTICE)) {
1641     printInfoString(info.getDict(), "Title",        "Title:        %s\n");
1642     printInfoString(info.getDict(), "Subject",      "Subject:      %s\n");
1643     printInfoString(info.getDict(), "Keywords",     "Keywords:     %s\n");
1644     printInfoString(info.getDict(), "Author",       "Author:       %s\n");
1645     printInfoString(info.getDict(), "Creator",      "Creator:      %s\n");
1646     printInfoString(info.getDict(), "Producer",     "Producer:     %s\n");
1647     printInfoDate(info.getDict(),   "CreationDate", "CreationDate: %s\n");
1648     printInfoDate(info.getDict(),   "ModDate",      "ModDate:      %s\n");
1649     printf("Pages:        %d\n", doc->getNumPages());
1650     printf("Linearized:   %s\n", doc->isLinearized() ? "yes" : "no");
1651     printf("Encrypted:    ");
1652     if (doc->isEncrypted()) {
1653       printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
1654              doc->okToPrint() ? "yes" : "no",
1655              doc->okToCopy() ? "yes" : "no",
1656              doc->okToChange() ? "yes" : "no",
1657              doc->okToAddNotes() ? "yes" : "no");
1658     } else {
1659       printf("no\n");
1660     }
1661   }
1662   info.free();
1663
1664   numpages = doc->getNumPages();
1665   if (doc->isEncrypted()) {
1666         /*ERROR: This pdf is encrypted, and disallows copying.
1667           Due to the DMCA, paragraph 1201, (2) A-C, circumventing
1668           a technological measure that efficively controls access to
1669           a protected work is violating American law. 
1670           See www.eff.org for more information about DMCA issues.
1671          */
1672         if(!doc->okToCopy()) {
1673             printf("PDF disallows copying. Bailing out.\n");
1674             exit(1); //bail out
1675         }
1676         if(!doc->okToChange() || !doc->okToAddNotes())
1677             swfoutput_setprotected();
1678   }
1679
1680   output = new SWFOutputDev();
1681   output->startDoc(doc->getXRef());
1682 }
1683
1684 void pdfswf_drawonlyshapes()
1685 {
1686     drawonlyshapes = 1;
1687 }
1688
1689 void pdfswf_ignoredraworder()
1690 {
1691     ignoredraworder = 1;
1692 }
1693
1694 void pdfswf_linksopennewwindow()
1695 {
1696     opennewwindow = 1;
1697 }
1698
1699 void pdfswf_storeallcharacters()
1700 {
1701     storeallcharacters = 1;
1702 }
1703
1704 void pdfswf_enablezlib()
1705 {
1706     enablezlib = 1;
1707 }
1708
1709 void pdfswf_jpegquality(int val)
1710 {
1711     if(val<0) val=0;
1712     if(val>100) val=100;
1713     jpegquality = val;
1714 }
1715
1716 void pdfswf_setoutputfilename(char*_filename)
1717 {
1718     swffilename = _filename;
1719 }
1720
1721
1722 void pdfswf_convertpage(int page)
1723 {
1724     if(!pages)
1725     {
1726         pages = (int*)malloc(1024*sizeof(int));
1727         pagebuflen = 1024;
1728     } else {
1729         if(pagepos == pagebuflen)
1730         {
1731             pagebuflen+=1024;
1732             pages = (int*)realloc(pages, pagebuflen);
1733         }
1734     }
1735     pages[pagepos++] = page;
1736 }
1737
1738 void pdfswf_performconversion()
1739 {
1740     int t;
1741     for(t=0;t<pagepos;t++)
1742     {
1743        currentpage = pages[t];
1744        doc->displayPage((OutputDev*)output, currentpage, /*dpi*/72, /*rotate*/0, /*doLinks*/(int)1);
1745     }
1746 }
1747
1748 int pdfswf_numpages()
1749 {
1750   return doc->getNumPages();
1751 }
1752
1753 void pdfswf_insertstop()
1754 {
1755     insertstoptag = 1;
1756 }
1757
1758 int closed=0;
1759 void pdfswf_close()
1760 {
1761     logf("<debug> pdfswf.cc: pdfswf_close()");
1762     delete output;
1763     delete doc;
1764     //freeParams();
1765     // check for memory leaks
1766     Object::memCheck(stderr);
1767     gMemReport(stderr);
1768 }
1769
1770