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