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