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