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