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