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