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