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