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