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