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