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