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