fixed font matrix.
[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 //xpdf header files
26 #include "gfile.h"
27 #include "GString.h"
28 #include "gmem.h"
29 #include "Object.h"
30 #include "Stream.h"
31 #include "Array.h"
32 #include "Dict.h"
33 #include "XRef.h"
34 #include "Catalog.h"
35 #include "Page.h"
36 #include "PDFDoc.h"
37 #include "Params.h"
38 #include "Error.h"
39 #include "config.h"
40 #include "OutputDev.h"
41 #include "GfxState.h"
42 #include "GfxFont.h"
43 #include "FontFile.h"
44 //swftools header files
45 #include "swfoutput.h"
46 extern "C" {
47 #include "../lib/log.h"
48 #include "ttf2pt1.h"
49 }
50
51 static PDFDoc*doc = 0;
52 static char* swffilename = 0;
53 int numpages;
54 int currentpage;
55
56 // swf <-> pdf pages
57 int*pages = 0;
58 int pagebuflen = 0;
59 int pagepos = 0;
60
61 static void printInfoString(Dict *infoDict, char *key, char *fmt);
62 static void printInfoDate(Dict *infoDict, char *key, char *fmt);
63
64 double fontsizes[] = 
65 {
66  0.833,0.833,0.889,0.889,
67  0.788,0.722,0.833,0.778,
68  0.600,0.600,0.600,0.600,
69  0.576,0.576,0.576,0.576,
70  0.733 //?
71 };
72 char*fontnames[]={
73 "Helvetica",             
74 "Helvetica-Bold",        
75 "Helvetica-BoldOblique", 
76 "Helvetica-Oblique",     
77 "Times-Roman",           
78 "Times-Bold",            
79 "Times-BoldItalic",      
80 "Times-Italic",          
81 "Courier",               
82 "Courier-Bold",          
83 "Courier-BoldOblique",   
84 "Courier-Oblique",       
85 "Symbol",                
86 "Symbol",                
87 "Symbol",                
88 "Symbol",
89 "ZapfDingBats"
90 };
91
92 struct mapping {
93     char*pdffont;
94     char*filename;
95     int id;
96 } pdf2t1map[] ={
97 {"Times-Roman",           "n021003l.pfb"},
98 {"Times-Italic",          "n021023l.pfb"},
99 {"Times-Bold",            "n021004l.pfb"},
100 {"Times-BoldItalic",      "n021024l.pfb"},
101 {"Helvetica",             "n019003l.pfb"},
102 {"Helvetica-Oblique",     "n019023l.pfb"},
103 {"Helvetica-Bold",        "n019004l.pfb"},
104 {"Helvetica-BoldOblique", "n019024l.pfb"},
105 {"Courier",               "n022003l.pfb"},
106 {"Courier-Oblique",       "n022023l.pfb"},
107 {"Courier-Bold",          "n022004l.pfb"},
108 {"Courier-BoldOblique",   "n022024l.pfb"},
109 {"Symbol",                "s050000l.pfb"},
110 {"ZapfDingbats",          "d050000l.pfb"}};
111
112 class GfxState;
113 class GfxImageColorMap;
114
115 class SWFOutputDev:  public OutputDev {
116   struct swfoutput output;
117   int outputstarted;
118 public:
119
120   // Constructor.
121   SWFOutputDev();
122
123   // Destructor.
124   virtual ~SWFOutputDev() ;
125
126   //----- get info about output device
127
128   // Does this device use upside-down coordinates?
129   // (Upside-down means (0,0) is the top left corner of the page.)
130   virtual GBool upsideDown();
131
132   // Does this device use drawChar() or drawString()?
133   virtual GBool useDrawChar();
134
135   //----- initialization and control
136
137   // Start a page.
138   virtual void startPage(int pageNum, GfxState *state) ;
139
140   //----- link borders
141   virtual void drawLink(Link *link, Catalog *catalog) ;
142
143   //----- save/restore graphics state
144   virtual void saveState(GfxState *state) ;
145   virtual void restoreState(GfxState *state) ;
146
147   //----- update graphics state
148
149   virtual void updateFont(GfxState *state);
150   virtual void updateFillColor(GfxState *state);
151   virtual void updateStrokeColor(GfxState *state);
152   virtual void updateLineWidth(GfxState *state);
153   
154   virtual void updateAll(GfxState *state) 
155   {
156       updateFont(state);
157       updateFillColor(state);
158       updateStrokeColor(state);
159       updateLineWidth(state);
160   };
161
162   //----- path painting
163   virtual void stroke(GfxState *state) ;
164   virtual void fill(GfxState *state) ;
165   virtual void eoFill(GfxState *state) ;
166
167   //----- path clipping
168   virtual void clip(GfxState *state) ;
169   virtual void eoClip(GfxState *state) ;
170
171   //----- text drawing
172   virtual void beginString(GfxState *state, GString *s) ;
173   virtual void endString(GfxState *state) ;
174   virtual void drawChar(GfxState *state, double x, double y,
175                         double dx, double dy, Guchar c) ;
176   virtual void drawChar16(GfxState *state, double x, double y,
177                           double dx, double dy, int c) ;
178
179   //----- image drawing
180   virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
181                              int width, int height, GBool invert,
182                              GBool inlineImg);
183   virtual void drawImage(GfxState *state, Object *ref, Stream *str,
184                          int width, int height, GfxImageColorMap *colorMap,
185                          GBool inlineImg);
186
187   private:
188   void drawGeneralImage(GfxState *state, Object *ref, Stream *str,
189                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
190                                    GBool inlineImg, int mask);
191   int clipping[64];
192   int clippos;
193
194   int searchT1Font(char*name);
195   char* substituteFont(GfxFont*gfxFont, char*oldname);
196   char* writeEmbeddedFontToFile(GfxFont*font);
197   int t1id;
198   int jpeginfo; // did we write "File contains jpegs" yet?
199   int pbminfo; // did we write "File contains jpegs" yet?
200   int linkinfo; // did we write "File contains links" yet?
201   int ttfinfo; // did we write "File contains TrueType Fonts" yet?
202
203   GfxState *laststate;
204 };
205
206 char mybuf[1024];
207 char* gfxstate2str(GfxState *state)
208 {
209   char*bufpos = mybuf;
210   GfxRGB rgb;
211   bufpos+=sprintf(bufpos,"CTM[%.3f/%.3f/%.3f/%.3f/%.3f/%.3f] ",
212                                     state->getCTM()[0],
213                                     state->getCTM()[1],
214                                     state->getCTM()[2],
215                                     state->getCTM()[3],
216                                     state->getCTM()[4],
217                                     state->getCTM()[5]);
218   if(state->getX1()!=0.0)
219   bufpos+=sprintf(bufpos,"X1-%.1f ",state->getX1());
220   if(state->getY1()!=0.0)
221   bufpos+=sprintf(bufpos,"Y1-%.1f ",state->getY1());
222   bufpos+=sprintf(bufpos,"X2-%.1f ",state->getX2());
223   bufpos+=sprintf(bufpos,"Y2-%.1f ",state->getY2());
224   bufpos+=sprintf(bufpos,"PW%.1f ",state->getPageWidth());
225   bufpos+=sprintf(bufpos,"PH%.1f ",state->getPageHeight());
226   /*bufpos+=sprintf(bufpos,"FC[%.1f/%.1f] ",
227           state->getFillColor()->c[0], state->getFillColor()->c[1]);
228   bufpos+=sprintf(bufpos,"SC[%.1f/%.1f] ",
229           state->getStrokeColor()->c[0], state->getFillColor()->c[1]);*/
230 /*  bufpos+=sprintf(bufpos,"FC[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f]",
231           state->getFillColor()->c[0], state->getFillColor()->c[1],
232           state->getFillColor()->c[2], state->getFillColor()->c[3],
233           state->getFillColor()->c[4], state->getFillColor()->c[5],
234           state->getFillColor()->c[6], state->getFillColor()->c[7]);
235   bufpos+=sprintf(bufpos,"SC[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f/%.1f]",
236           state->getStrokeColor()->c[0], state->getFillColor()->c[1],
237           state->getStrokeColor()->c[2], state->getFillColor()->c[3],
238           state->getStrokeColor()->c[4], state->getFillColor()->c[5],
239           state->getStrokeColor()->c[6], state->getFillColor()->c[7]);*/
240   state->getFillRGB(&rgb);
241   if(rgb.r || rgb.g || rgb.b)
242   bufpos+=sprintf(bufpos,"FR[%.1f/%.1f/%.1f] ", rgb.r,rgb.g,rgb.b);
243   state->getStrokeRGB(&rgb);
244   if(rgb.r || rgb.g || rgb.b)
245   bufpos+=sprintf(bufpos,"SR[%.1f/%.1f/%.1f] ", rgb.r,rgb.g,rgb.b);
246   if(state->getFillColorSpace()->getNComps()>1)
247   bufpos+=sprintf(bufpos,"CS[[%d]] ",state->getFillColorSpace()->getNComps());
248   if(state->getStrokeColorSpace()->getNComps()>1)
249   bufpos+=sprintf(bufpos,"SS[[%d]] ",state->getStrokeColorSpace()->getNComps());
250   if(state->getFillPattern())
251   bufpos+=sprintf(bufpos,"FP%08x ", state->getFillPattern());
252   if(state->getStrokePattern())
253   bufpos+=sprintf(bufpos,"SP%08x ", state->getStrokePattern());
254  
255   if(state->getFillOpacity()!=1.0)
256   bufpos+=sprintf(bufpos,"FO%.1f ", state->getFillOpacity());
257   if(state->getStrokeOpacity()!=1.0)
258   bufpos+=sprintf(bufpos,"SO%.1f ", state->getStrokeOpacity());
259
260   bufpos+=sprintf(bufpos,"LW%.1f ", state->getLineWidth());
261  
262   double * dash;
263   int length;
264   double start;
265   state->getLineDash(&dash, &length, &start);
266   int t;
267   if(length)
268   {
269       bufpos+=sprintf(bufpos,"DASH%.1f[",start);
270       for(t=0;t<length;t++) {
271           bufpos+=sprintf(bufpos,"D%.1f",dash[t]);
272       }
273       bufpos+=sprintf(bufpos,"]");
274   }
275
276   if(state->getFlatness()!=1)
277   bufpos+=sprintf(bufpos,"F%d ", state->getFlatness());
278   if(state->getLineJoin()!=0)
279   bufpos+=sprintf(bufpos,"J%d ", state->getLineJoin());
280   if(state->getLineJoin()!=0)
281   bufpos+=sprintf(bufpos,"C%d ", state->getLineCap());
282   if(state->getLineJoin()!=0)
283   bufpos+=sprintf(bufpos,"ML%d ", state->getMiterLimit());
284
285   if(state->getFont() && state->getFont()->getName() && state->getFont()->getName()->getCString())
286   bufpos+=sprintf(bufpos,"F\"%s\" ",((state->getFont())->getName())->getCString());
287   bufpos+=sprintf(bufpos,"FS%.1f ", state->getFontSize());
288   bufpos+=sprintf(bufpos,"MAT[%.1f/%.1f/%.1f/%.1f/%.1f/%.1f] ", state->getTextMat()[0],state->getTextMat()[1],state->getTextMat()[2],
289                                    state->getTextMat()[3],state->getTextMat()[4],state->getTextMat()[5]);
290   if(state->getCharSpace())
291   bufpos+=sprintf(bufpos,"CS%.5f ", state->getCharSpace());
292   if(state->getWordSpace())
293   bufpos+=sprintf(bufpos,"WS%.5f ", state->getWordSpace());
294   if(state->getHorizScaling()!=1.0)
295   bufpos+=sprintf(bufpos,"SC%.1f ", state->getHorizScaling());
296   if(state->getLeading())
297   bufpos+=sprintf(bufpos,"L%.1f ", state->getLeading());
298   if(state->getRise())
299   bufpos+=sprintf(bufpos,"R%.1f ", state->getRise());
300   if(state->getRender())
301   bufpos+=sprintf(bufpos,"R%d ", state->getRender());
302   bufpos+=sprintf(bufpos,"P%08x ", state->getPath());
303   bufpos+=sprintf(bufpos,"CX%.1f ", state->getCurX());
304   bufpos+=sprintf(bufpos,"CY%.1f ", state->getCurY());
305   if(state->getLineX())
306   bufpos+=sprintf(bufpos,"LX%.1f ", state->getLineX());
307   if(state->getLineY())
308   bufpos+=sprintf(bufpos,"LY%.1f ", state->getLineY());
309   bufpos+=sprintf(bufpos," ");
310   return mybuf;
311 }
312
313 void dumpFontInfo(char*loglevel, GfxFont*font);
314 int lastdumps[1024];
315 int lastdumppos = 0;
316 /* nr = 0  unknown
317    nr = 1  substituting
318    nr = 2  type 3
319  */
320 void showFontError(GfxFont*font, int nr) 
321 {  
322     Ref r=font->getID();
323     int t;
324     for(t=0;t<lastdumppos;t++)
325         if(lastdumps[t] == r.num)
326             break;
327     if(t < lastdumppos)
328       return;
329     if(lastdumppos<sizeof(lastdumps)/sizeof(int))
330     lastdumps[lastdumppos++] = r.num;
331     if(nr == 0)
332       logf("<warning> The following font caused problems:");
333     else if(nr == 1)
334       logf("<warning> The following font caused problems (substituting):");
335     else if(nr == 2)
336       logf("<warning> This document contains Type 3 Fonts: (some text may be incorrectly displayed)");
337     dumpFontInfo("<warning>", font);
338 }
339
340 void dumpFontInfo(char*loglevel, GfxFont*font)
341 {
342   GString *gstr;
343   char*name;
344   gstr = font->getName();
345   Ref r=font->getID();
346   logf("%s=========== %s (ID:%d,%d) ==========\n", loglevel, gstr?gstr->getCString():"(unknown font)", r.num,r.gen);
347
348   gstr  = font->getTag();
349   if(gstr) 
350    logf("%sTag: %s\n", loglevel, gstr->getCString());
351   if(font->is16Bit()) logf("%sis 16 bit\n", loglevel);
352
353   GfxFontType type=font->getType();
354   switch(type) {
355     case fontUnknownType:
356      logf("%sType: unknown\n",loglevel);
357     break;
358     case fontType0:
359      logf("%sType: 0\n",loglevel);
360     break;
361     case fontType1:
362      logf("%sType: 1\n",loglevel);
363     break;
364     case fontType1C:
365      logf("%sType: 1C\n",loglevel);
366     break;
367     case fontType3:
368      logf("%sType: 3\n",loglevel);
369     break;
370     case fontTrueType:
371      logf("%sType: TrueType\n",loglevel);
372     break;
373   }
374   
375   Ref embRef;
376   GBool embedded = font->getEmbeddedFontID(&embRef);
377   name = font->getEmbeddedFontName();
378   if(embedded)
379    logf("%sEmbedded name: %s id: %d\n",loglevel, name, embRef.num);
380
381   gstr = font->getExtFontFile();
382   if(gstr)
383    logf("%sExternal Font file: %s\n", loglevel, gstr->getCString());
384
385   // Get font descriptor flags.
386   if(font->isFixedWidth()) logf("%sis fixed width\n", loglevel);
387   if(font->isSerif()) logf("%sis serif\n", loglevel);
388   if(font->isSymbolic()) logf("%sis symbolic\n", loglevel);
389   if(font->isItalic()) logf("%sis italic\n", loglevel);
390   if(font->isBold()) logf("%sis bold\n", loglevel);
391 }
392
393 //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");}
394 //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");}
395
396 SWFOutputDev::SWFOutputDev() 
397 {
398     jpeginfo = 0;
399     ttfinfo = 0;
400     linkinfo = 0;
401     pbminfo = 0;
402     clippos = 0;
403     clipping[clippos] = 0;
404     outputstarted = 0;
405 //    printf("SWFOutputDev::SWFOutputDev() \n");
406 };
407
408 T1_OUTLINE* gfxPath_to_T1_OUTLINE(GfxState*state, GfxPath*path)
409 {
410     int num = path->getNumSubpaths();
411     int s,t;
412     bezierpathsegment*start,*last=0;
413     bezierpathsegment*outline = start = new bezierpathsegment();
414     int cpos = 0;
415     double lastx=0,lasty=0;
416     for(t = 0; t < num; t++) {
417         GfxSubpath *subpath = path->getSubpath(t);
418         int subnum = subpath->getNumPoints();
419
420         for(s=0;s<subnum;s++) {
421            double nx,ny;
422            state->transform(subpath->getX(s),subpath->getY(s),&nx,&ny);
423            int x = (int)((nx-lastx)*0xffff);
424            int y = (int)((ny-lasty)*0xffff);
425            if(s==0) 
426            {
427                 last = outline;
428                 outline->type = T1_PATHTYPE_MOVE;
429                 outline->dest.x = x;
430                 outline->dest.y = y;
431                 outline->link = (T1_OUTLINE*)new bezierpathsegment();
432                 outline = (bezierpathsegment*)outline->link;
433                 cpos = 0;
434                 lastx = nx;
435                 lasty = ny;
436            }
437            else if(subpath->getCurve(s) && !cpos)
438            {
439                 outline->B.x = x;
440                 outline->B.y = y;
441                 cpos = 1;
442            } 
443            else if(subpath->getCurve(s) && cpos)
444            {
445                 outline->C.x = x;
446                 outline->C.y = y;
447                 cpos = 2;
448            }
449            else
450            {
451                 last = outline;
452                 outline->dest.x = x;
453                 outline->dest.y = y;
454                 outline->type = cpos?T1_PATHTYPE_BEZIER:T1_PATHTYPE_LINE;
455                 outline->link = 0;
456                 outline->link = (T1_OUTLINE*)new bezierpathsegment();
457                 outline = (bezierpathsegment*)outline->link;
458                 cpos = 0;
459                 lastx = nx;
460                 lasty = ny;
461            }
462         }
463     }
464     last->link = 0;
465     return (T1_OUTLINE*)start;
466 }
467 /*----------------------------------------------------------------------------
468  * Primitive Graphic routines
469  *----------------------------------------------------------------------------*/
470
471 void SWFOutputDev::stroke(GfxState *state) 
472 {
473     logf("<debug> stroke\n");
474     GfxPath * path = state->getPath();
475     struct swfmatrix m;
476     m.m11 = 1; m.m21 = 0; m.m22 = 1;
477     m.m12 = 0; m.m13 = 0; m.m23 = 0;
478     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
479     swfoutput_setdrawmode(&output, DRAWMODE_STROKE);
480     swfoutput_drawpath(&output, outline, &m);
481 }
482 void SWFOutputDev::fill(GfxState *state) 
483 {
484     logf("<debug> fill\n");
485     GfxPath * path = state->getPath();
486     struct swfmatrix m;
487     m.m11 = 1; m.m21 = 0; m.m22 = 1;
488     m.m12 = 0; m.m13 = 0; m.m23 = 0;
489     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
490     swfoutput_setdrawmode(&output, DRAWMODE_FILL);
491     swfoutput_drawpath(&output, outline, &m);
492 }
493 void SWFOutputDev::eoFill(GfxState *state) 
494 {
495     logf("<debug> eofill\n");
496     GfxPath * path = state->getPath();
497     struct swfmatrix m;
498     m.m11 = 1; m.m21 = 0; m.m22 = 1;
499     m.m12 = 0; m.m13 = 0; m.m23 = 0;
500     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
501     swfoutput_setdrawmode(&output, DRAWMODE_EOFILL);
502     swfoutput_drawpath(&output, outline, &m);
503 }
504 void SWFOutputDev::clip(GfxState *state) 
505 {
506     logf("<debug> clip\n");
507     GfxPath * path = state->getPath();
508     struct swfmatrix m;
509     m.m11 = 1; m.m22 = 1;
510     m.m12 = 0; m.m21 = 0; 
511     m.m13 = 0; m.m23 = 0;
512     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
513     swfoutput_startclip(&output, outline, &m);
514     clipping[clippos] ++;
515 }
516 void SWFOutputDev::eoClip(GfxState *state) 
517 {
518     logf("<debug> eoclip\n");
519     GfxPath * path = state->getPath();
520     struct swfmatrix m;
521     m.m11 = 1; m.m21 = 0; m.m22 = 1;
522     m.m12 = 0; m.m13 = 0; m.m23 = 0;
523     T1_OUTLINE*outline = gfxPath_to_T1_OUTLINE(state, path);
524     swfoutput_startclip(&output, outline, &m);
525     clipping[clippos] ++;
526 }
527
528 SWFOutputDev::~SWFOutputDev() 
529 {
530     swfoutput_destroy(&output);
531     outputstarted = 0;
532 };
533 GBool SWFOutputDev::upsideDown() 
534 {
535     logf("<debug> upsidedown?");
536     return gTrue;
537 };
538 GBool SWFOutputDev::useDrawChar() 
539 {
540     logf("<debug> usedrawchar?");
541     return gTrue;
542 }
543
544 void SWFOutputDev::beginString(GfxState *state, GString *s) 
545
546     double m11,m21,m12,m22;
547 //    logf("<debug> %s beginstring \"%s\"\n", gfxstate2str(state), s->getCString());
548     state->getFontTransMat(&m11, &m12, &m21, &m22);
549     m11 *= state->getHorizScaling();
550     m21 *= state->getHorizScaling();
551     swfoutput_setfontmatrix(&output, m11, -m21, m12, -m22);
552 }
553
554 int charcounter = 0;
555 void SWFOutputDev::drawChar(GfxState *state, double x, double y, double dx, double dy, Guchar c) 
556 {
557     logf("<debug> drawChar(%f,%f,%f,%f,'%c')\n",x,y,dx,dy,c);
558     // check for invisible text -- this is used by Acrobat Capture
559     if ((state->getRender() & 3) != 3)
560     {
561        FontEncoding*enc=state->getFont()->getEncoding();
562
563        double x1,y1;
564        x1 = x;
565        y1 = y;
566        state->transform(x, y, &x1, &y1);
567
568        if(enc->getCharName(c))
569           swfoutput_drawchar(&output, x1, y1, enc->getCharName(c), c);
570        else
571           logf("<warning> couldn't get name for character %02x from Encoding", c);
572     }
573 }
574
575 void SWFOutputDev::drawChar16(GfxState *state, double x, double y, double dx, double dy, int c) 
576 {
577     printf("<error> drawChar16(%f,%f,%f,%f,%08x)\n",x,y,dx,dy,c);
578     exit(1);
579 }
580
581 void SWFOutputDev::endString(GfxState *state) 
582
583     logf("<debug> endstring\n");
584 }    
585
586 void SWFOutputDev::startPage(int pageNum, GfxState *state) 
587 {
588   double x1,y1,x2,y2;
589   laststate = state;
590   logf("<debug> startPage %d\n", pageNum);
591   logf("<notice> processing page %d", pageNum);
592
593   state->transform(state->getX1(),state->getY1(),&x1,&y1);
594   state->transform(state->getX2(),state->getY2(),&x2,&y2);
595   if(!outputstarted) {
596     swfoutput_init(&output, swffilename, abs((int)(x2-x1)),abs((int)(y2-y1)));
597     outputstarted = 1;
598   }
599   else
600     swfoutput_newpage(&output);
601 }
602
603 void SWFOutputDev::drawLink(Link *link, Catalog *catalog) 
604 {
605   double x1, y1, x2, y2, w;
606   GfxRGB rgb;
607   swfcoord points[5];
608   int x, y;
609
610   link->getBorder(&x1, &y1, &x2, &y2, &w);
611 //  if (w > 0) 
612   {
613     rgb.r = 0;
614     rgb.g = 0;
615     rgb.b = 1;
616     cvtUserToDev(x1, y1, &x, &y);
617     points[0].x = points[4].x = (int)x;
618     points[0].y = points[4].y = (int)y;
619     cvtUserToDev(x2, y1, &x, &y);
620     points[1].x = (int)x;
621     points[1].y = (int)y;
622     cvtUserToDev(x2, y2, &x, &y);
623     points[2].x = (int)x;
624     points[2].y = (int)y;
625     cvtUserToDev(x1, y2, &x, &y);
626     points[3].x = (int)x;
627     points[3].y = (int)y;
628
629     LinkAction*action=link->getAction();
630     char buf[128];
631     char*s = "-?-";
632     char*type = "-?-";
633     char*url = 0;
634     int page = -1;
635     switch(action->getKind())
636     {
637         case actionGoTo: {
638             type = "GoTo";
639             LinkGoTo *ha=(LinkGoTo *)link->getAction();
640             LinkDest *dest=NULL;
641             if (ha->getDest()==NULL) 
642                 dest=catalog->findDest(ha->getNamedDest());
643             else dest=ha->getDest();
644             if (dest){ 
645               if (dest->isPageRef()){
646                 Ref pageref=dest->getPageRef();
647                 page=catalog->findPage(pageref.num,pageref.gen);
648               }
649               else  page=dest->getPageNum();
650               sprintf(buf, "%d", page);
651               s = buf;
652             }
653         }
654         break;
655         case actionGoToR: {
656             type = "GoToR";
657             LinkGoToR*l = (LinkGoToR*)action;
658             GString*g = l->getNamedDest();
659             if(g)
660              s = g->getCString();
661         }
662         break;
663         case actionNamed: {
664             type = "Named";
665             LinkNamed*l = (LinkNamed*)action;
666             GString*name = l->getName();
667             if(name) {
668               s = name->lowerCase()->getCString();
669               if(strstr(s, "next") || strstr(s, "forward"))
670               {
671                   page = currentpage + 1;
672               }
673               else if(strstr(s, "prev") || strstr(s, "back"))
674               {
675                   page = currentpage - 1;
676               }
677               else if(strstr(s, "last") || strstr(s, "end"))
678               {
679                   page = pages[pagepos-1]; //:)
680               }
681               else if(strstr(s, "first") || strstr(s, "top"))
682               {
683                   page = 1;
684               }
685             }
686         }
687         break;
688         case actionLaunch: {
689             type = "Launch";
690             LinkLaunch*l = (LinkLaunch*)action;
691             GString * str = new GString(l->getFileName());
692             str->append(l->getParams());
693             s = str->getCString();
694         }
695         break;
696         case actionURI: {
697             type = "URI";
698             LinkURI*l = (LinkURI*)action;
699             GString*g = l->getURI();
700             if(g) {
701              url = g->getCString();
702              s = url;
703             }
704         }
705         break;
706         case actionUnknown: {
707             type = "Unknown";
708             LinkUnknown*l = (LinkUnknown*)action;
709             s = "";
710         }
711         break;
712         default: {
713             logf("<error> Unknown link type!\n");
714             break;
715         }
716     }
717     if(!linkinfo && (page || url))
718     {
719         logf("<notice> File contains links");
720         linkinfo = 1;
721     }
722     if(page>0)
723     {
724         int t;
725         for(t=0;t<pagepos;t++)
726             if(pages[t]==page)
727                 break;
728         if(t!=pagepos)
729         swfoutput_linktopage(&output, t, points);
730     }
731     else if(url)
732     {
733         swfoutput_linktourl(&output, url, points);
734     }
735     logf("<verbose> \"%s\" link to \"%s\" (%d)\n", type, s, page);
736   }
737 }
738
739 void SWFOutputDev::saveState(GfxState *state) {
740   logf("<debug> saveState\n");
741   updateAll(state);
742   if(clippos<64)
743     clippos ++;
744   else
745     logf("<error> Too many nested states in pdf.");
746   clipping[clippos] = 0;
747 };
748
749 void SWFOutputDev::restoreState(GfxState *state) {
750   logf("<debug> restoreState\n");
751   updateAll(state);
752   while(clipping[clippos]) {
753       swfoutput_endclip(&output);
754       clipping[clippos]--;
755   }
756   clippos--;
757 }
758
759 char type3Warning=0;
760
761 int SWFOutputDev::searchT1Font(char*name) 
762 {       
763     int i;
764     
765     int id=-1;
766     int mapid=-1;
767     char*filename=0;
768     for(i=0;i<sizeof(pdf2t1map)/sizeof(mapping);i++) 
769     {
770         if(!strcmp(name, pdf2t1map[i].pdffont))
771         {
772             filename = pdf2t1map[i].filename;
773             mapid = i;
774         }
775     }
776     if(filename)
777     for(i=0; i<T1_Get_no_fonts(); i++)
778     {
779         char*fontfilename = T1_GetFontFileName (i);
780         if(strstr(fontfilename, filename))
781         {
782                 id = i;
783                 pdf2t1map[i].id = mapid;
784         }
785     }
786     return id;
787 }
788
789 void SWFOutputDev::updateLineWidth(GfxState *state)
790 {
791     double width = state->getTransformedLineWidth();
792     swfoutput_setlinewidth(&output, width);
793 }
794
795 void SWFOutputDev::updateFillColor(GfxState *state) 
796 {
797     GfxRGB rgb;
798     double opaq = state->getFillOpacity();
799     state->getFillRGB(&rgb);
800
801     swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
802                                     (char)(rgb.b*255), (char)(opaq*255));
803 }
804
805 void SWFOutputDev::updateStrokeColor(GfxState *state) 
806 {
807     GfxRGB rgb;
808     double opaq = state->getStrokeOpacity();
809     state->getStrokeRGB(&rgb);
810
811     swfoutput_setstrokecolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
812                                       (char)(rgb.b*255), (char)(opaq*255));
813 }
814
815 char*SWFOutputDev::writeEmbeddedFontToFile(GfxFont*font)
816 {
817       char*tmpFileName = NULL;
818       FILE *f;
819       int c;
820       char *fontBuf;
821       int fontLen;
822       Type1CFontConverter *cvt;
823       Ref embRef;
824       Object refObj, strObj;
825       tmpFileName = "/tmp/tmpfont";
826       font->getEmbeddedFontID(&embRef);
827
828       f = fopen(tmpFileName, "wb");
829       if (!f) {
830         logf("<error> Couldn't create temporary Type 1 font file");
831         return 0;
832       }
833       if (font->getType() == fontType1C) {
834         if (!(fontBuf = font->readEmbFontFile(&fontLen))) {
835           fclose(f);
836           logf("<error> Couldn't read embedded font file");
837           return 0;
838         }
839         cvt = new Type1CFontConverter(fontBuf, fontLen, f);
840         cvt->convert();
841         delete cvt;
842         gfree(fontBuf);
843       } else {
844         font->getEmbeddedFontID(&embRef);
845         refObj.initRef(embRef.num, embRef.gen);
846         refObj.fetch(&strObj);
847         refObj.free();
848         strObj.streamReset();
849         while ((c = strObj.streamGetChar()) != EOF) {
850           fputc(c, f);
851         }
852         strObj.streamClose();
853         strObj.free();
854       }
855       fclose(f);
856
857       if(font->getType() == fontTrueType)
858       {
859           if(!ttfinfo) {
860               logf("<notice> File contains TrueType fonts");
861               ttfinfo = 1;
862           }
863           char name2[80];
864           char*tmp;
865           tmp = strdup(mktmpname((char*)name2));
866           sprintf(name2, "%s", tmp);
867           char*a[] = {"./ttf2pt1","-pttf","-b", tmpFileName, name2};
868           logf("<verbose> Invoking ttf2pt1...");
869           ttf2pt1_main(5,a);
870           unlink(tmpFileName);
871           sprintf(name2,"%s.pfb",tmp);
872           tmpFileName = strdup(name2);
873       }
874
875       return tmpFileName;
876 }
877
878 char* gfxFontName(GfxFont* gfxFont)
879 {
880       GString *gstr;
881       gstr = gfxFont->getName();
882       if(gstr) {
883           return gstr->getCString();
884       }
885       else {
886           char buf[32];
887           Ref r=gfxFont->getID();
888           sprintf(buf, "UFONT%d", r.num);
889           return strdup(buf);
890       }
891 }
892
893 char* substitutetarget[256];
894 char* substitutesource[256];
895 int substitutepos = 0;
896
897 char* SWFOutputDev::substituteFont(GfxFont*gfxFont, char* oldname)
898 {
899       //substitute font
900       char* fontname = 0;
901       double m11, m12, m21, m22;
902       int index;
903       int code;
904       double w,w1,w2;
905       double*fm;
906       double v;
907       if(gfxFont->getName()) {
908         fontname = gfxFont->getName()->getCString();
909       }
910
911 //        printf("%d %s\n", t, gfxFont->getCharName(t));
912       showFontError(gfxFont, 1);
913       if (!gfxFont->is16Bit()) {
914         if(gfxFont->isSymbolic()) {
915           if(fontname && (strstr(fontname,"ing"))) //Dingbats, Wingdings etc.
916            index = 16;
917           else 
918            index = 12;
919         } else if (gfxFont->isFixedWidth()) {
920           index = 8;
921         } else if (gfxFont->isSerif()) {
922           index = 4;
923         } else {
924           index = 0;
925         }
926         if (gfxFont->isBold() && index!=16)
927           index += 2;
928         if (gfxFont->isItalic() && index!=16)
929           index += 1;
930         fontname = fontnames[index];
931         // get width of 'm' in real font and substituted font
932         if ((code = gfxFont->getCharCode("m")) >= 0)
933           w1 = gfxFont->getWidth(code);
934         else
935           w1 = 0;
936         w2 = fontsizes[index];
937         if (gfxFont->getType() == fontType3) {
938           // This is a hack which makes it possible to substitute for some
939           // Type 3 fonts.  The problem is that it's impossible to know what
940           // the base coordinate system used in the font is without actually
941           // rendering the font.  This code tries to guess by looking at the
942           // width of the character 'm' (which breaks if the font is a
943           // subset that doesn't contain 'm').
944           if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
945             w1 /= w2;
946             m11 *= w1;
947             m12 *= w1;
948             m21 *= w1;
949             m22 *= w1;
950           }
951           fm = gfxFont->getFontMatrix();
952           v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
953           m21 *= v;
954           m22 *= v;
955         } else if (!gfxFont->isSymbolic()) {
956           // if real font is substantially narrower than substituted
957           // font, reduce the font size accordingly
958           if (w1 > 0.01 && w1 < 0.9 * w2) {
959             w1 /= w2;
960             if (w1 < 0.8) {
961               w1 = 0.8;
962             }
963             m11 *= w1;
964             m12 *= w1;
965             m21 *= w1;
966             m22 *= w1;
967           }
968         }
969       }
970       if(fontname) {
971         this->t1id = searchT1Font(fontname);
972       }
973       if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
974           logf("<fatal> Too many fonts in file.");
975           exit(1);
976       }
977       if(oldname) {
978           substitutesource[substitutepos] = oldname;
979           substitutetarget[substitutepos] = fontname;
980           logf("<verbose> substituting %s -> %s", oldname, fontname);
981           substitutepos ++;
982       }
983       return fontname;
984 }
985
986 void unlinkfont(char* filename)
987 {
988     int l;
989     if(!filename)
990         return;
991     l=strlen(filename);
992     unlink(filename);
993     if(!strncmp(&filename[l-4],".afm",4)) {
994         memcpy(&filename[l-4],".pfb",4);
995         unlink(filename);
996         memcpy(&filename[l-4],".pfa",4);
997         unlink(filename);
998         memcpy(&filename[l-4],".afm",4);
999         return;
1000     } else 
1001     if(!strncmp(&filename[l-4],".pfa",4)) {
1002         memcpy(&filename[l-4],".afm",4);
1003         unlink(filename);
1004         memcpy(&filename[l-4],".pfa",4);
1005         return;
1006     } else 
1007     if(!strncmp(&filename[l-4],".pfb",4)) {
1008         memcpy(&filename[l-4],".afm",4);
1009         unlink(filename);
1010         memcpy(&filename[l-4],".pfb",4);
1011         return;
1012     }
1013 }
1014
1015 void SWFOutputDev::updateFont(GfxState *state) 
1016 {
1017   GfxFont*gfxFont = state->getFont();
1018   char * fileName = 0;
1019     
1020   if (!gfxFont) {
1021     return;
1022   }  
1023   char * fontname = gfxFontName(gfxFont);
1024  
1025   int t;
1026   for(t=0;t<substitutepos;t++) {
1027       if(!strcmp(fontname, substitutesource[t])) {
1028           fontname = substitutetarget[t];
1029           break;
1030       }
1031   }
1032
1033   if(swfoutput_queryfont(&output, fontname))
1034   {
1035       swfoutput_setfont(&output, fontname, -1, 0);
1036       return;
1037   }
1038
1039   // look for Type 3 font
1040   if (!type3Warning && gfxFont->getType() == fontType3) {
1041     type3Warning = gTrue;
1042     showFontError(gfxFont, 2);
1043   }
1044   //dumpFontInfo ("<notice>", gfxFont);
1045
1046   Ref embRef;
1047   GBool embedded = gfxFont->getEmbeddedFontID(&embRef);
1048   if(embedded) {
1049     if (!gfxFont->is16Bit() &&
1050         (gfxFont->getType() == fontType1 ||
1051          gfxFont->getType() == fontType1C ||
1052          gfxFont->getType() == fontTrueType)) {
1053         
1054         fileName = writeEmbeddedFontToFile(gfxFont);
1055         if(!fileName) {
1056           logf("<error> Couldn't write font to file");
1057           showFontError(gfxFont,0);
1058           return ;
1059         }
1060         this->t1id = T1_AddFont(fileName);
1061         if(this->t1id<0) {
1062           logf("<error> Couldn't load font from file");
1063           showFontError(gfxFont,0);
1064           unlinkfont(fileName);
1065           return ;
1066         }
1067     }
1068     else {
1069         showFontError(gfxFont,0);
1070         fontname = substituteFont(gfxFont, fontname);
1071     }
1072   } else {
1073     if(fontname) {
1074         int newt1id = searchT1Font(fontname);
1075         if(newt1id<0) {
1076             fontname = substituteFont(gfxFont, fontname);
1077         } else
1078             this->t1id = newt1id;
1079     }
1080     else
1081         fontname = substituteFont(gfxFont, fontname);
1082   }
1083
1084   if(t1id<0) {
1085       showFontError(gfxFont,0);
1086       return;
1087   }
1088  
1089   /* we may have done some substitutions here, so check
1090      again if this font is cached. */
1091   if(swfoutput_queryfont(&output, fontname))
1092   {
1093       swfoutput_setfont(&output, fontname, -1, 0);
1094       return;
1095   }
1096
1097   logf("<verbose> Creating new SWF font: t1id: %d, filename: %s name:%s", this->t1id, fileName, fontname);
1098   swfoutput_setfont(&output, fontname, this->t1id, fileName);
1099   if(fileName)
1100       unlinkfont(fileName);
1101 }
1102
1103 int pic_xids[1024];
1104 int pic_yids[1024];
1105 int pic_ids[1024];
1106 int picpos = 0;
1107 int pic_id = 0;
1108
1109 void SWFOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
1110                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
1111                                    GBool inlineImg, int mask)
1112 {
1113   FILE *fi;
1114   int c;
1115   char fileName[128];
1116   double x1,y1,x2,y2,x3,y3,x4,y4;
1117   ImageStream *imgStr;
1118   Guchar pixBuf[4];
1119   GfxRGB rgb;
1120   if(!width || !height || (height<=1 && width<=1))
1121   {
1122       logf("<verbose> Ignoring %d by %d image", width, height);
1123       int i,j;
1124       if (inlineImg) {
1125         j = height * ((width + 7) / 8);
1126         str->reset();
1127         for (i = 0; i < j; ++i) {
1128           str->getChar();
1129         }
1130       }
1131       return;
1132   }
1133   
1134   state->transform(0, 1, &x1, &y1);
1135   state->transform(0, 0, &x2, &y2);
1136   state->transform(1, 0, &x3, &y3);
1137   state->transform(1, 1, &x4, &y4);
1138
1139   if (str->getKind() == strDCT &&
1140       (colorMap->getNumPixelComps() == 3 || !mask) )
1141   {
1142     sprintf(fileName, "%s.jpg",mktmpname(0));
1143     logf("<verbose> Found jpeg. Temporary storage is %s", fileName);
1144     if(!jpeginfo)
1145     {
1146         logf("<notice> file contains jpeg pictures");
1147         jpeginfo = 1;
1148     }
1149     if (!(fi = fopen(fileName, "wb"))) {
1150       logf("<error> Couldn't open temporary image file '%s'", fileName);
1151       return;
1152     }
1153     str = ((DCTStream *)str)->getRawStream();
1154     str->reset();
1155     int xid = 0;
1156     int yid = 0;
1157     int count = 0;
1158     while ((c = str->getChar()) != EOF)
1159     {
1160       fputc(c, fi);
1161       xid += count*c;
1162       yid += (~count)*c;
1163       count++;
1164     }
1165     fclose(fi);
1166     
1167     int t,found = -1;
1168     for(t=0;t<picpos;t++)
1169     {
1170         if(pic_xids[t] == xid &&
1171            pic_yids[t] == yid) {
1172             found = t;break;
1173         }
1174     }
1175     if(found<0) {
1176         pic_ids[picpos] = swfoutput_drawimagejpeg(&output, fileName, width, height, 
1177                 x1,y1,x2,y2,x3,y3,x4,y4);
1178         pic_xids[picpos] = xid;
1179         pic_yids[picpos] = yid;
1180         if(picpos<1024)
1181             picpos++;
1182     } else {
1183         swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1184                 x1,y1,x2,y2,x3,y3,x4,y4);
1185     }
1186     unlink(fileName);
1187   } else {
1188
1189     if(!pbminfo) {
1190         logf("<notice> file contains pbm pictures %s",mask?"(masked)":"");
1191         if(mask)
1192         logf("<verbose> drawing %d by %d masked picture\n", width, height);
1193         pbminfo = 1;
1194     }
1195
1196     if(mask) {
1197         imgStr = new ImageStream(str, width, 1, 1);
1198         imgStr->reset();
1199         //return;
1200         int yes=0,i,j;
1201         unsigned char buf[8];
1202         int xid = 0;
1203         int yid = 0;
1204         int x,y;
1205         int width2 = (width+3)&(~3);
1206         unsigned char*pic = new unsigned char[width2*height];
1207         RGBA pal[256];
1208         GfxRGB rgb;
1209         state->getFillRGB(&rgb);
1210         pal[0].r = (int)(rgb.r*255); pal[0].g = (int)(rgb.g*255); 
1211         pal[0].b = (int)(rgb.b*255); pal[0].a = 255;
1212         pal[1].r = 0; pal[1].g = 0; pal[1].b = 0; pal[1].a = 0;
1213         xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1214         yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1215         for (y = 0; y < height; ++y)
1216         for (x = 0; x < width; ++x)
1217         {
1218               imgStr->getPixel(buf);
1219               pic[width*y+x] = buf[0];
1220               xid+=x*buf[0]+1;
1221               yid+=y*buf[0]+1;
1222         }
1223         int t,found = -1;
1224         for(t=0;t<picpos;t++)
1225         {
1226             if(pic_xids[t] == xid &&
1227                pic_yids[t] == yid) {
1228                 found = t;break;
1229             }
1230         }
1231         if(found<0) {
1232             pic_ids[picpos] = swfoutput_drawimagelossless256(&output, pic, pal, width, height, 
1233                     x1,y1,x2,y2,x3,y3,x4,y4);
1234             pic_xids[picpos] = xid;
1235             pic_yids[picpos] = yid;
1236             if(picpos<1024)
1237                 picpos++;
1238         } else {
1239             swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1240                     x1,y1,x2,y2,x3,y3,x4,y4);
1241         }
1242         free(pic);
1243     } else {
1244         int x,y;
1245         int width2 = (width+3)&(~3);
1246         imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
1247                                    colorMap->getBits());
1248         imgStr->reset();
1249
1250         if(colorMap->getNumPixelComps()!=1)
1251         {
1252             RGBA*pic=new RGBA[width*height];
1253             int xid = 0;
1254             int yid = 0;
1255             for (y = 0; y < height; ++y) {
1256               for (x = 0; x < width; ++x) {
1257                 int r,g,b,a;
1258                 imgStr->getPixel(pixBuf);
1259                 colorMap->getRGB(pixBuf, &rgb);
1260                 pic[width*y+x].r = r = (U8)(rgb.r * 255 + 0.5);
1261                 pic[width*y+x].g = g = (U8)(rgb.g * 255 + 0.5);
1262                 pic[width*y+x].b = b = (U8)(rgb.b * 255 + 0.5);
1263                 pic[width*y+x].a = a = 255;//(U8)(rgb.a * 255 + 0.5);
1264                 xid += x*r+x*b*3+x*g*7+x*a*11;
1265                 yid += y*r*3+y*b*17+y*g*19+y*a*11;
1266               }
1267             }
1268             int t,found = -1;
1269             for(t=0;t<picpos;t++)
1270             {
1271                 if(pic_xids[t] == xid &&
1272                    pic_yids[t] == yid) {
1273                     found = t;break;
1274                 }
1275             }
1276             if(found<0) {
1277                 pic_ids[picpos] = swfoutput_drawimagelossless(&output, pic, width, height, 
1278                         x1,y1,x2,y2,x3,y3,x4,y4);
1279                 pic_xids[picpos] = xid;
1280                 pic_yids[picpos] = yid;
1281                 if(picpos<1024)
1282                     picpos++;
1283             } else {
1284                 swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1285                         x1,y1,x2,y2,x3,y3,x4,y4);
1286             }
1287             delete pic;
1288         }
1289         else
1290         {
1291             U8*pic = new U8[width2*height];
1292             RGBA pal[256];
1293             int t;
1294             int xid=0,yid=0;
1295             for(t=0;t<256;t++)
1296             {
1297                 int r,g,b,a;
1298                 pixBuf[0] = t;
1299                 colorMap->getRGB(pixBuf, &rgb);
1300                 pal[t].r = r = (U8)(rgb.r * 255 + 0.5);
1301                 pal[t].g = g = (U8)(rgb.g * 255 + 0.5);
1302                 pal[t].b = b = (U8)(rgb.b * 255 + 0.5);
1303                 pal[t].a = a = 255;//(U8)(rgb.b * 255 + 0.5);
1304                 xid += t*r+t*b*3+t*g*7+t*a*11;
1305                 xid += (~t)*r+t*b*3+t*g*7+t*a*11;
1306             }
1307             for (y = 0; y < height; ++y) {
1308               for (x = 0; x < width; ++x) {
1309                 imgStr->getPixel(pixBuf);
1310                 pic[width2*y+x] = pixBuf[0];
1311                 xid += x*pixBuf[0]*7;
1312                 yid += y*pixBuf[0]*3;
1313               }
1314             }
1315             int found = -1;
1316             for(t=0;t<picpos;t++)
1317             {
1318                 if(pic_xids[t] == xid &&
1319                    pic_yids[t] == yid) {
1320                     found = t;break;
1321                 }
1322             }
1323             if(found<0) {
1324                 pic_ids[picpos] = swfoutput_drawimagelossless256(&output, pic, pal, width, height, 
1325                         x1,y1,x2,y2,x3,y3,x4,y4);
1326                 pic_xids[picpos] = xid;
1327                 pic_yids[picpos] = yid;
1328                 if(picpos<1024)
1329                     picpos++;
1330             } else {
1331                 swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1332                         x1,y1,x2,y2,x3,y3,x4,y4);
1333             }
1334             delete pic;
1335         }
1336         delete imgStr;
1337     }
1338
1339   }
1340 }
1341
1342 void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1343                                    int width, int height, GBool invert,
1344                                    GBool inlineImg) 
1345 {
1346   drawGeneralImage(state,ref,str,width,height,0,invert,inlineImg,1);
1347 }
1348
1349 void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1350                                int width, int height,
1351                                GfxImageColorMap *colorMap, GBool inlineImg) 
1352 {
1353   drawGeneralImage(state,ref,str,width,height,colorMap,0,inlineImg,0);
1354 }
1355
1356 SWFOutputDev*output = 0; 
1357
1358 static void printInfoString(Dict *infoDict, char *key, char *fmt) {
1359   Object obj;
1360   GString *s1, *s2;
1361   int i;
1362
1363   if (infoDict->lookup(key, &obj)->isString()) {
1364     s1 = obj.getString();
1365     if ((s1->getChar(0) & 0xff) == 0xfe &&
1366         (s1->getChar(1) & 0xff) == 0xff) {
1367       s2 = new GString();
1368       for (i = 2; i < obj.getString()->getLength(); i += 2) {
1369         if (s1->getChar(i) == '\0') {
1370           s2->append(s1->getChar(i+1));
1371         } else {
1372           delete s2;
1373           s2 = new GString("<unicode>");
1374           break;
1375         }
1376       }
1377       printf(fmt, s2->getCString());
1378       delete s2;
1379     } else {
1380       printf(fmt, s1->getCString());
1381     }
1382   }
1383   obj.free();
1384 }
1385
1386 static void printInfoDate(Dict *infoDict, char *key, char *fmt) {
1387   Object obj;
1388   char *s;
1389
1390   if (infoDict->lookup(key, &obj)->isString()) {
1391     s = obj.getString()->getCString();
1392     if (s[0] == 'D' && s[1] == ':') {
1393       s += 2;
1394     }
1395     printf(fmt, s);
1396   }
1397   obj.free();
1398 }
1399
1400 void pdfswf_init(char*filename, char*userPassword) 
1401 {
1402   GString *fileName = new GString(filename);
1403   GString *userPW;
1404   Object info;
1405   // init error file
1406   errorInit();
1407
1408   // read config file
1409   initParams(xpdfConfigFile);
1410
1411   // open PDF file
1412   xref = NULL;
1413   if (userPassword && userPassword[0]) {
1414     userPW = new GString(userPassword);
1415   } else {
1416     userPW = NULL;
1417   }
1418   doc = new PDFDoc(fileName, userPW);
1419   if (userPW) {
1420     delete userPW;
1421   }
1422   if (!doc->isOk()) {
1423     exit(1);
1424   }
1425
1426   // print doc info
1427   doc->getDocInfo(&info);
1428   if (info.isDict()) {
1429     printInfoString(info.getDict(), "Title",        "Title:        %s\n");
1430     printInfoString(info.getDict(), "Subject",      "Subject:      %s\n");
1431     printInfoString(info.getDict(), "Keywords",     "Keywords:     %s\n");
1432     printInfoString(info.getDict(), "Author",       "Author:       %s\n");
1433     printInfoString(info.getDict(), "Creator",      "Creator:      %s\n");
1434     printInfoString(info.getDict(), "Producer",     "Producer:     %s\n");
1435     printInfoDate(info.getDict(),   "CreationDate", "CreationDate: %s\n");
1436     printInfoDate(info.getDict(),   "ModDate",      "ModDate:      %s\n");
1437   }
1438   info.free();
1439
1440   // print page count
1441   printf("Pages:        %d\n", doc->getNumPages());
1442   numpages = doc->getNumPages();
1443   
1444   // print linearization info
1445   printf("Linearized:   %s\n", doc->isLinearized() ? "yes" : "no");
1446
1447   // print encryption info
1448   printf("Encrypted:    ");
1449   if (doc->isEncrypted()) {
1450     printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
1451            doc->okToPrint() ? "yes" : "no",
1452            doc->okToCopy() ? "yes" : "no",
1453            doc->okToChange() ? "yes" : "no",
1454            doc->okToAddNotes() ? "yes" : "no");
1455         /*ERROR: This pdf is encrypted, and disallows copying.
1456           Due to the DMCA, paragraph 1201, (2) A-C, circumventing
1457           a technological measure that efficively controls access to
1458           a protected work is violating American law. 
1459           See www.eff.org for more information about DMCA issues.
1460          */
1461         if(!doc->okToCopy()) {
1462             printf("PDF disallows copying. Bailing out.\n");
1463             exit(1); //bail out
1464         }
1465         if(!doc->okToChange() || !doc->okToAddNotes())
1466             swfoutput_setprotected();
1467     }
1468   else {
1469     printf("no\n");
1470   }
1471
1472
1473   output = new SWFOutputDev();
1474 }
1475
1476 void pdfswf_drawonlyshapes()
1477 {
1478     drawonlyshapes = 1;
1479 }
1480
1481 void pdfswf_ignoredraworder()
1482 {
1483     ignoredraworder = 1;
1484 }
1485
1486 void pdfswf_linksopennewwindow()
1487 {
1488     opennewwindow = 1;
1489 }
1490
1491 void pdfswf_storeallcharacters()
1492 {
1493     storeallcharacters = 1;
1494 }
1495
1496 void pdfswf_jpegquality(int val)
1497 {
1498     if(val<0) val=0;
1499     if(val>100) val=100;
1500     jpegquality = val;
1501 }
1502
1503 void pdfswf_setoutputfilename(char*_filename)
1504 {
1505     swffilename = _filename;
1506 }
1507
1508
1509 void pdfswf_convertpage(int page)
1510 {
1511     if(!pages)
1512     {
1513         pages = (int*)malloc(1024*sizeof(int));
1514         pagebuflen = 1024;
1515     } else {
1516         if(pagepos == pagebuflen)
1517         {
1518             pagebuflen+=1024;
1519             pages = (int*)realloc(pages, pagebuflen);
1520         }
1521     }
1522     pages[pagepos++] = page;
1523 }
1524
1525 void pdfswf_performconversion()
1526 {
1527     int t;
1528     for(t=0;t<pagepos;t++)
1529     {
1530        currentpage = pages[t];
1531        doc->displayPage((OutputDev*)output, currentpage, /*zoom*/100, /*rotate*/0, /*doLinks*/(int)1);
1532     }
1533 }
1534
1535 int pdfswf_numpages()
1536 {
1537   return doc->getNumPages();
1538 }
1539
1540 int closed=0;
1541 void pdfswf_close()
1542 {
1543     logf("<debug> pdfswf.cc: pdfswf_close()");
1544     delete output;
1545     delete doc;
1546     freeParams();
1547     // check for memory leaks
1548     Object::memCheck(stderr);
1549     gMemReport(stderr);
1550 }
1551