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