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