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