changed logf to msg.
[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     msg("<debug> drawChar(%f,%f,%f,%f,'%c')\n",x,y,dx,dy,c);
628     
629     // check for invisible text -- this is used by Acrobat Capture
630     if ((state->getRender() & 3) == 3)
631         return;
632
633     GfxFont*font = state->getFont();
634
635     if(font->getType() == fontType3) {
636         /* type 3 chars are passed primarily as graphics */
637         return;
638     }
639     double x1,y1;
640     x1 = x;
641     y1 = y;
642     state->transform(x, y, &x1, &y1);
643
644     if(font->isCIDFont()) {
645         GfxCIDFont*cfont = (GfxCIDFont*)font;
646         Unicode u=0;
647         char*name=0;
648         if(_u) 
649             u = *_u;
650         if(u) {
651             int t;
652             for(t=0;t<sizeof(nameToUnicodeTab)/sizeof(nameToUnicodeTab[0]);t++)
653                 /* todo: should be precomputed */
654                 if(nameToUnicodeTab[t].u == u) {
655                     name = nameToUnicodeTab[t].name;
656                     break;
657                 }
658         }
659 /*         printf("%02x %04x/%04x-%d \"%s\" %s %d\n", c,u, *_u, uLen, name, cfont->getName()->getCString(),
660                 cfont->getType());*/
661
662         if(name)
663            swfoutput_drawchar(&output, x1, y1, name, c);
664         else
665            msg("<warning> couldn't get name for CID character %02x from Encoding", 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         }
676     }
677 }
678
679 void SWFOutputDev::endString(GfxState *state) 
680
681     msg("<debug> endstring\n");
682 }    
683
684  
685 GBool SWFOutputDev::beginType3Char(GfxState *state,
686                                CharCode code, Unicode *u, int uLen)
687 {
688     msg("<debug> beginType3Char %d, %08x, %d", code, *u, uLen);
689     type3active = 1;
690     /* the character itself is going to be passed using
691        drawImageMask() */
692     return gFalse; /* gTrue= is_in_cache? */
693 }
694
695 void SWFOutputDev::endType3Char(GfxState *state)
696 {
697     type3active = 0;
698     msg("<debug> endType3Char");
699 }
700
701 void SWFOutputDev::startPage(int pageNum, GfxState *state) 
702 {
703   double x1,y1,x2,y2;
704   laststate = state;
705   msg("<debug> startPage %d\n", pageNum);
706   msg("<notice> processing page %d", pageNum);
707
708   state->transform(state->getX1(),state->getY1(),&x1,&y1);
709   state->transform(state->getX2(),state->getY2(),&x2,&y2);
710   if(!outputstarted) {
711     swfoutput_init(&output, swffilename, abs((int)(x2-x1)),abs((int)(y2-y1)));
712     outputstarted = 1;
713   }
714   else
715     swfoutput_newpage(&output);
716 }
717
718 void SWFOutputDev::drawLink(Link *link, Catalog *catalog) 
719 {
720   msg("<debug> drawlink\n");
721   double x1, y1, x2, y2, w;
722   GfxRGB rgb;
723   swfcoord points[5];
724   int x, y;
725
726   link->getBorder(&x1, &y1, &x2, &y2, &w);
727 //  if (w > 0) 
728   {
729     rgb.r = 0;
730     rgb.g = 0;
731     rgb.b = 1;
732     cvtUserToDev(x1, y1, &x, &y);
733     points[0].x = points[4].x = (int)x;
734     points[0].y = points[4].y = (int)y;
735     cvtUserToDev(x2, y1, &x, &y);
736     points[1].x = (int)x;
737     points[1].y = (int)y;
738     cvtUserToDev(x2, y2, &x, &y);
739     points[2].x = (int)x;
740     points[2].y = (int)y;
741     cvtUserToDev(x1, y2, &x, &y);
742     points[3].x = (int)x;
743     points[3].y = (int)y;
744
745     LinkAction*action=link->getAction();
746     char buf[128];
747     char*s = "-?-";
748     char*type = "-?-";
749     char*url = 0;
750     char*named = 0;
751     int page = -1;
752     switch(action->getKind())
753     {
754         case actionGoTo: {
755             type = "GoTo";
756             LinkGoTo *ha=(LinkGoTo *)link->getAction();
757             LinkDest *dest=NULL;
758             if (ha->getDest()==NULL) 
759                 dest=catalog->findDest(ha->getNamedDest());
760             else dest=ha->getDest();
761             if (dest){ 
762               if (dest->isPageRef()){
763                 Ref pageref=dest->getPageRef();
764                 page=catalog->findPage(pageref.num,pageref.gen);
765               }
766               else  page=dest->getPageNum();
767               sprintf(buf, "%d", page);
768               s = buf;
769             }
770         }
771         break;
772         case actionGoToR: {
773             type = "GoToR";
774             LinkGoToR*l = (LinkGoToR*)action;
775             GString*g = l->getNamedDest();
776             if(g)
777              s = g->getCString();
778         }
779         break;
780         case actionNamed: {
781             type = "Named";
782             LinkNamed*l = (LinkNamed*)action;
783             GString*name = l->getName();
784             if(name) {
785                 s = name->lowerCase()->getCString();
786                 named = name->getCString();
787                 if(!strchr(s,':')) 
788                 {
789                     if(strstr(s, "next") || strstr(s, "forward"))
790                     {
791                         page = currentpage + 1;
792                     }
793                     else if(strstr(s, "prev") || strstr(s, "back"))
794                     {
795                         page = currentpage - 1;
796                     }
797                     else if(strstr(s, "last") || strstr(s, "end"))
798                     {
799                         page = pages[pagepos-1]; //:)
800                     }
801                     else if(strstr(s, "first") || strstr(s, "top"))
802                     {
803                         page = 1;
804                     }
805                 }
806             }
807         }
808         break;
809         case actionLaunch: {
810             type = "Launch";
811             LinkLaunch*l = (LinkLaunch*)action;
812             GString * str = new GString(l->getFileName());
813             str->append(l->getParams());
814             s = str->getCString();
815         }
816         break;
817         case actionURI: {
818             type = "URI";
819             LinkURI*l = (LinkURI*)action;
820             GString*g = l->getURI();
821             if(g) {
822              url = g->getCString();
823              s = url;
824             }
825         }
826         break;
827         case actionUnknown: {
828             type = "Unknown";
829             LinkUnknown*l = (LinkUnknown*)action;
830             s = "";
831         }
832         break;
833         default: {
834             msg("<error> Unknown link type!\n");
835             break;
836         }
837     }
838     if(!linkinfo && (page || url))
839     {
840         msg("<notice> File contains links");
841         linkinfo = 1;
842     }
843     if(page>0)
844     {
845         int t;
846         for(t=0;t<pagepos;t++)
847             if(pages[t]==page)
848                 break;
849         if(t!=pagepos)
850         swfoutput_linktopage(&output, t, points);
851     }
852     else if(url)
853     {
854         swfoutput_linktourl(&output, url, points);
855     }
856     else if(named)
857     {
858         swfoutput_namedlink(&output, named, points);
859     }
860     msg("<verbose> \"%s\" link to \"%s\" (%d)\n", type, FIXNULL(s), page);
861   }
862 }
863
864 void SWFOutputDev::saveState(GfxState *state) {
865   msg("<debug> saveState\n");
866   updateAll(state);
867   if(clippos<64)
868     clippos ++;
869   else
870     msg("<error> Too many nested states in pdf.");
871   clipping[clippos] = 0;
872 };
873
874 void SWFOutputDev::restoreState(GfxState *state) {
875   msg("<debug> restoreState\n");
876   updateAll(state);
877   while(clipping[clippos]) {
878       swfoutput_endclip(&output);
879       clipping[clippos]--;
880   }
881   clippos--;
882 }
883
884 char type3Warning=0;
885
886 int SWFOutputDev::searchT1Font(char*name) 
887 {       
888     int i;
889     int mapid=-1;
890     char*filename=0;
891
892     for(i=0;i<sizeof(pdf2t1map)/sizeof(mapping);i++) 
893     {
894         if(!strcmp(name, pdf2t1map[i].pdffont))
895         {
896             filename = pdf2t1map[i].filename;
897             mapid = i;
898         }
899     }
900     if(filename) {
901         for(i=0; i<T1_Get_no_fonts(); i++)
902         {
903             char*fontfilename = T1_GetFontFileName (i);
904             if(strstr(fontfilename, filename))
905             {
906                     pdf2t1map[i].id = mapid;
907                     return i;
908             }
909         }
910     } else {
911         for(i=0; i<T1_Get_no_fonts(); i++)
912         {
913             char*fontname = T1_GetFontName (i);
914             if(!fontname) {
915                 T1_LoadFont(i);
916                 fontname = T1_GetFontName (i);
917                 msg("<verbose> Loading extra font %s from %s\n", FIXNULL(fontname), 
918                                                                   FIXNULL(T1_GetFontFileName(i)));
919             }
920
921             if(fontname && !strcmp(name, fontname)) {
922                 msg("<notice> Extra font %d, \"%s\" is being used.\n", i, fontname);
923                 return i;
924             }
925             fontname = T1_GetFontFileName(i);
926             if(strrchr(fontname,'/'))
927                     fontname = strrchr(fontname,'/')+1;
928  
929             if(strstr(fontname, name)) {
930                 msg("<notice> Extra font %d, \"%s\" is being used.\n", i, fontname);
931                 return i;
932             }
933         }
934     }
935     return -1;
936 }
937
938 void SWFOutputDev::updateLineWidth(GfxState *state)
939 {
940     double width = state->getTransformedLineWidth();
941     swfoutput_setlinewidth(&output, width);
942 }
943
944 void SWFOutputDev::updateLineCap(GfxState *state)
945 {
946     int c = state->getLineCap();
947 }
948
949 void SWFOutputDev::updateLineJoin(GfxState *state)
950 {
951     int j = state->getLineJoin();
952 }
953
954 void SWFOutputDev::updateFillColor(GfxState *state) 
955 {
956     GfxRGB rgb;
957     double opaq = state->getFillOpacity();
958     state->getFillRGB(&rgb);
959
960     swfoutput_setfillcolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
961                                     (char)(rgb.b*255), (char)(opaq*255));
962 }
963
964 void SWFOutputDev::updateStrokeColor(GfxState *state) 
965 {
966     GfxRGB rgb;
967     double opaq = state->getStrokeOpacity();
968     state->getStrokeRGB(&rgb);
969
970     swfoutput_setstrokecolor(&output, (char)(rgb.r*255), (char)(rgb.g*255), 
971                                       (char)(rgb.b*255), (char)(opaq*255));
972 }
973
974 char*SWFOutputDev::writeEmbeddedFontToFile(XRef*ref, GfxFont*font)
975 {
976       char*tmpFileName = NULL;
977       FILE *f;
978       int c;
979       char *fontBuf;
980       int fontLen;
981       Type1CFontFile *cvt;
982       Ref embRef;
983       Object refObj, strObj;
984       tmpFileName = "/tmp/tmpfont";
985       int ret;
986
987       ret = font->getEmbeddedFontID(&embRef);
988       if(!ret) {
989           msg("<verbose> Didn't get embedded font id");
990           /* not embedded- the caller should now search the font
991              directories for this font */
992           return 0;
993       }
994
995       f = fopen(tmpFileName, "wb");
996       if (!f) {
997         msg("<error> Couldn't create temporary Type 1 font file");
998           return 0;
999       }
1000       if (font->getType() == fontType1C) {
1001         if (!(fontBuf = font->readEmbFontFile(xref, &fontLen))) {
1002           fclose(f);
1003           msg("<error> Couldn't read embedded font file");
1004           return 0;
1005         }
1006         cvt = new Type1CFontFile(fontBuf, fontLen);
1007         cvt->convertToType1(f);
1008         delete cvt;
1009         gfree(fontBuf);
1010       } else {
1011         font->getEmbeddedFontID(&embRef);
1012         refObj.initRef(embRef.num, embRef.gen);
1013         refObj.fetch(ref, &strObj);
1014         refObj.free();
1015         strObj.streamReset();
1016         int f4[4];
1017         char f4c[4];
1018         int t;
1019         for(t=0;t<4;t++) {
1020             f4[t] = strObj.streamGetChar();
1021             f4c[t] = (char)f4[t];
1022             if(f4[t] == EOF)
1023                 break;
1024         }
1025         if(t==4) {
1026             if(!strncmp(f4c, "true", 4)) {
1027                 /* some weird TTF fonts don't start with 0,1,0,0 but with "true".
1028                    Change this on the fly */
1029                 f4[0] = f4[2] = f4[3] = 0;
1030                 f4[1] = 1;
1031             }
1032             fputc(f4[0], f);
1033             fputc(f4[1], f);
1034             fputc(f4[2], f);
1035             fputc(f4[3], f);
1036
1037             while ((c = strObj.streamGetChar()) != EOF) {
1038               fputc(c, f);
1039             }
1040         }
1041         strObj.streamClose();
1042         strObj.free();
1043       }
1044       fclose(f);
1045
1046       if(font->getType() == fontTrueType ||
1047          font->getType() == fontCIDType2)
1048       {
1049           if(!ttfinfo) {
1050               msg("<notice> File contains TrueType fonts");
1051               ttfinfo = 1;
1052           }
1053           char name2[80];
1054           char*tmp;
1055           tmp = strdup(mktmpname((char*)name2));
1056           sprintf(name2, "%s", tmp);
1057           char*a[] = {"./ttf2pt1", "-W0",
1058 #ifndef USE_FREETYPE
1059               "-pttf",
1060 #else
1061               "-pft",
1062 #endif
1063               "-b", tmpFileName, name2};
1064           msg("<verbose> Invoking ttf2pt1...");
1065           ttf2pt1_main(6,a);
1066           unlink(tmpFileName);
1067           sprintf(name2,"%s.pfb",tmp);
1068           tmpFileName = strdup(name2);
1069       }
1070
1071     return tmpFileName;
1072 }
1073
1074 char* gfxFontName(GfxFont* gfxFont)
1075 {
1076       GString *gstr;
1077       gstr = gfxFont->getName();
1078       if(gstr) {
1079           return gstr->getCString();
1080       }
1081       else {
1082           char buf[32];
1083           Ref*r=gfxFont->getID();
1084           sprintf(buf, "UFONT%d", r->num);
1085           return strdup(buf);
1086       }
1087 }
1088
1089 char* substitutetarget[256];
1090 char* substitutesource[256];
1091 int substitutepos = 0;
1092
1093 char* SWFOutputDev::substituteFont(GfxFont*gfxFont, char* oldname)
1094 {
1095 /* ------------------------------ V1 */
1096
1097     char*fontname = "Times-Roman";
1098     msg("<verbose> substituteFont(,%s)", FIXNULL(oldname));
1099     this->t1id = searchT1Font(fontname);
1100     if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
1101         msg("<fatal> Too many fonts in file.");
1102         exit(1);
1103     }
1104     if(oldname) {
1105         substitutesource[substitutepos] = oldname;
1106         substitutetarget[substitutepos] = fontname;
1107         msg("<verbose> substituting %s -> %s", FIXNULL(oldname), FIXNULL(fontname));
1108         substitutepos ++;
1109     }
1110     return fontname;
1111
1112 /* ------------------------------ V2 */
1113
1114 /*      //substitute font
1115       char* fontname = 0;
1116       double m11, m12, m21, m22;
1117       int index;
1118       int code;
1119       double w,w1,w2;
1120       double*fm;
1121       double v;
1122       if(gfxFont->getName()) {
1123         fontname = gfxFont->getName()->getCString();
1124       }
1125
1126 //        printf("%d %s\n", t, gfxFont->getCharName(t));
1127       showFontError(gfxFont, 1);
1128       if(1) { //if (!gfxFont->isCIDFont()) { FIXME: xpdf 1.01 does not have is16Bit()
1129         if(gfxFont->isSymbolic()) {
1130           if(fontname && (strstr(fontname,"ing"))) //Dingbats, Wingdings etc.
1131            index = 16;
1132           else 
1133            index = 12;
1134         } else if (gfxFont->isFixedWidth()) {
1135           index = 8;
1136         } else if (gfxFont->isSerif()) {
1137           index = 4;
1138         } else {
1139           index = 0;
1140         }
1141         if (gfxFont->isBold() && index!=16)
1142           index += 2;
1143         if (gfxFont->isItalic() && index!=16)
1144           index += 1;
1145         fontname = fontnames[index];
1146         // get width of 'm' in real font and substituted font
1147         if ((code = gfxFont->getCharCode("m")) >= 0)
1148           w1 = gfxFont->getWidth(code);
1149         else
1150           w1 = 0;
1151         w2 = fontsizes[index];
1152         if (gfxFont->getType() == fontType3) {
1153           // This is a hack which makes it possible to substitute for some
1154           // Type 3 fonts.  The problem is that it's impossible to know what
1155           // the base coordinate system used in the font is without actually
1156           // rendering the font.  This code tries to guess by looking at the
1157           // width of the character 'm' (which breaks if the font is a
1158           // subset that doesn't contain 'm').
1159           if (w1 > 0 && (w1 > 1.1 * w2 || w1 < 0.9 * w2)) {
1160             w1 /= w2;
1161             m11 *= w1;
1162             m12 *= w1;
1163             m21 *= w1;
1164             m22 *= w1;
1165           }
1166           fm = gfxFont->getFontMatrix();
1167           v = (fm[0] == 0) ? 1 : (fm[3] / fm[0]);
1168           m21 *= v;
1169           m22 *= v;
1170         } else if (!gfxFont->isSymbolic()) {
1171           // if real font is substantially narrower than substituted
1172           // font, reduce the font size accordingly
1173           if (w1 > 0.01 && w1 < 0.9 * w2) {
1174             w1 /= w2;
1175             if (w1 < 0.8) {
1176               w1 = 0.8;
1177             }
1178             m11 *= w1;
1179             m12 *= w1;
1180             m21 *= w1;
1181             m22 *= w1;
1182           }
1183         }
1184       }
1185       if(fontname) {
1186         this->t1id = searchT1Font(fontname);
1187       }
1188       if(substitutepos>=sizeof(substitutesource)/sizeof(char*)) {
1189           msg("<fatal> Too many fonts in file.");
1190           exit(1);
1191       }
1192       if(oldname) {
1193           substitutesource[substitutepos] = oldname;
1194           substitutetarget[substitutepos] = fontname;
1195           msg("<verbose> substituting %s -> %s", FIXNULL(oldname), FIXNULL(fontname));
1196           substitutepos ++;
1197       }
1198       return fontname;*/
1199 }
1200
1201 void unlinkfont(char* filename)
1202 {
1203     int l;
1204     if(!filename)
1205         return;
1206     l=strlen(filename);
1207     unlink(filename);
1208     if(!strncmp(&filename[l-4],".afm",4)) {
1209         memcpy(&filename[l-4],".pfb",4);
1210         unlink(filename);
1211         memcpy(&filename[l-4],".pfa",4);
1212         unlink(filename);
1213         memcpy(&filename[l-4],".afm",4);
1214         return;
1215     } else 
1216     if(!strncmp(&filename[l-4],".pfa",4)) {
1217         memcpy(&filename[l-4],".afm",4);
1218         unlink(filename);
1219         memcpy(&filename[l-4],".pfa",4);
1220         return;
1221     } else 
1222     if(!strncmp(&filename[l-4],".pfb",4)) {
1223         memcpy(&filename[l-4],".afm",4);
1224         unlink(filename);
1225         memcpy(&filename[l-4],".pfb",4);
1226         return;
1227     }
1228 }
1229
1230 void SWFOutputDev::startDoc(XRef *xref) 
1231 {
1232   this->xref = xref;
1233 }
1234
1235
1236 void SWFOutputDev::updateFont(GfxState *state) 
1237 {
1238   GfxFont*gfxFont = state->getFont();
1239   char * fileName = 0;
1240     
1241   if (!gfxFont) {
1242     return;
1243   }  
1244   char * fontname = gfxFontName(gfxFont);
1245  
1246   int t;
1247   /* first, look if we substituted this font before-
1248      this way, we don't initialize the T1 Fonts
1249      too often */
1250   for(t=0;t<substitutepos;t++) {
1251       if(!strcmp(fontname, substitutesource[t])) {
1252           fontname = substitutetarget[t];
1253           break;
1254       }
1255   }
1256
1257   /* second, see if swfoutput already has this font
1258      cached- if so, we are done */
1259
1260   if(swfoutput_queryfont(&output, fontname))
1261   {
1262       swfoutput_setfont(&output, fontname, -1, 0);
1263       return;
1264   }
1265
1266   // look for Type 3 font
1267   if (!type3Warning && gfxFont->getType() == fontType3) {
1268     type3Warning = gTrue;
1269     showFontError(gfxFont, 2);
1270   }
1271
1272   /* now either load the font, or find a substitution */
1273
1274   Ref embRef;
1275   GBool embedded = gfxFont->getEmbeddedFontID(&embRef);
1276   if(embedded) {
1277     if (gfxFont->getType() == fontType1 ||
1278         gfxFont->getType() == fontType1C ||
1279         gfxFont->getType() == fontTrueType ||
1280         gfxFont->getType() == fontCIDType2) 
1281     {
1282         fileName = writeEmbeddedFontToFile(xref, gfxFont);
1283         if(!fileName) {
1284           msg("<error> Couldn't write font to file");
1285           showFontError(gfxFont,0);
1286           return ;
1287         }
1288         this->t1id = T1_AddFont(fileName);
1289         if(this->t1id<0) {
1290           msg("<error> Couldn't load font from file");
1291           showFontError(gfxFont,0);
1292           unlinkfont(fileName);
1293           return ;
1294         }
1295     }
1296     else {
1297         /* in case the font is embedded, but has an
1298            unsupported format, we just look through the
1299            font directories */
1300         int newt1id = searchT1Font(fontname);
1301         if(newt1id<0) {
1302             showFontError(gfxFont,0);
1303             fontname = substituteFont(gfxFont, fontname);
1304         } else
1305             this->t1id = newt1id;
1306     }
1307   } else {
1308     if(fontname) {
1309         int newt1id = searchT1Font(fontname);
1310         if(newt1id<0) {
1311             showFontError(gfxFont,1);
1312             fontname = substituteFont(gfxFont, fontname);
1313         } else
1314             this->t1id = newt1id;
1315     }
1316     else {
1317         showFontError(gfxFont,1);
1318         fontname = substituteFont(gfxFont, fontname);
1319     }
1320   }
1321
1322   if(t1id<0) {
1323       showFontError(gfxFont,0);
1324       return;
1325   }
1326  
1327   /* we may have done some substitutions here, so check
1328      again if this font is cached. */
1329   if(swfoutput_queryfont(&output, fontname))
1330   {
1331       swfoutput_setfont(&output, fontname, -1, 0);
1332       return;
1333   }
1334
1335   msg("<verbose> Creating new SWF font: t1id: %d, filename: %s name:%s", this->t1id, FIXNULL(fileName), FIXNULL(fontname));
1336   swfoutput_setfont(&output, fontname, this->t1id, fileName);
1337   if(fileName)
1338       unlinkfont(fileName);
1339 }
1340
1341 int pic_xids[1024];
1342 int pic_yids[1024];
1343 int pic_ids[1024];
1344 int pic_width[1024];
1345 int pic_height[1024];
1346 int picpos = 0;
1347 int pic_id = 0;
1348
1349 #define SQR(x) ((x)*(x))
1350
1351 unsigned char* antialize(unsigned char*data, int width, int height, int newwidth, int newheight, int palettesize)
1352 {
1353     if((newwidth<2 || newheight<2) ||
1354        (width<=newwidth || height<=newheight))
1355         return 0;
1356     unsigned char*newdata;
1357     int x,y;
1358     newdata= (unsigned char*)malloc(newwidth*newheight);
1359     int t;
1360     double fx = (double)(width)/newwidth;
1361     double fy = (double)(height)/newheight;
1362     double px = 0;
1363     int blocksize = (int)(8192/(fx*fy));
1364     int r = 8192*256/palettesize;
1365     for(x=0;x<newwidth;x++) {
1366         double ex = px + fx;
1367         int fromx = (int)px;
1368         int tox = (int)ex;
1369         int xweight1 = (int)(((fromx+1)-px)*256);
1370         int xweight2 = (int)((ex-tox)*256);
1371         double py =0;
1372         for(y=0;y<newheight;y++) {
1373             double ey = py + fy;
1374             int fromy = (int)py;
1375             int toy = (int)ey;
1376             int yweight1 = (int)(((fromy+1)-py)*256);
1377             int yweight2 = (int)((ey-toy)*256);
1378             int a = 0;
1379             int xx,yy;
1380             for(xx=fromx;xx<=tox;xx++)
1381             for(yy=fromy;yy<=toy;yy++) {
1382                 int b = 1-data[width*yy+xx];
1383                 int weight=256;
1384                 if(xx==fromx) weight = (weight*xweight1)/256;
1385                 if(xx==tox) weight = (weight*xweight2)/256;
1386                 if(yy==fromy) weight = (weight*yweight1)/256;
1387                 if(yy==toy) weight = (weight*yweight2)/256;
1388                 a+=b*weight;
1389             }
1390             //if(a) a=(palettesize-1)*r/blocksize;
1391             newdata[y*newwidth+x] = (a*blocksize)/r;
1392             py = ey;
1393         }
1394         px = ex;
1395     }
1396     return newdata;
1397 }
1398
1399 void SWFOutputDev::drawGeneralImage(GfxState *state, Object *ref, Stream *str,
1400                                    int width, int height, GfxImageColorMap*colorMap, GBool invert,
1401                                    GBool inlineImg, int mask)
1402 {
1403   FILE *fi;
1404   int c;
1405   char fileName[128];
1406   double x1,y1,x2,y2,x3,y3,x4,y4;
1407   ImageStream *imgStr;
1408   Guchar pixBuf[4];
1409   GfxRGB rgb;
1410   int ncomps = 1;
1411   int bits = 1;
1412                                  
1413   if(colorMap) {
1414     ncomps = colorMap->getNumPixelComps();
1415     bits = colorMap->getBits();
1416   }
1417   imgStr = new ImageStream(str, width, ncomps,bits);
1418   imgStr->reset();
1419
1420   if(!width || !height || (height<=1 && width<=1))
1421   {
1422       msg("<verbose> Ignoring %d by %d image", width, height);
1423       unsigned char buf[8];
1424       int x,y;
1425       for (y = 0; y < height; ++y)
1426       for (x = 0; x < width; ++x) {
1427           imgStr->getPixel(buf);
1428       }
1429       delete imgStr;
1430       return;
1431   }
1432   
1433   state->transform(0, 1, &x1, &y1);
1434   state->transform(0, 0, &x2, &y2);
1435   state->transform(1, 0, &x3, &y3);
1436   state->transform(1, 1, &x4, &y4);
1437
1438   if(!pbminfo && !(str->getKind()==strDCT)) {
1439       if(!type3active) {
1440           msg("<notice> file contains pbm pictures %s",mask?"(masked)":"");
1441           pbminfo = 1;
1442       }
1443       if(mask)
1444       msg("<verbose> drawing %d by %d masked picture\n", width, height);
1445   }
1446   if(!jpeginfo && (str->getKind()==strDCT)) {
1447       msg("<notice> file contains jpeg pictures");
1448       jpeginfo = 1;
1449   }
1450
1451   if(mask) {
1452       int yes=0,i,j;
1453       unsigned char buf[8];
1454       int xid = 0;
1455       int yid = 0;
1456       int x,y;
1457       unsigned char*pic = new unsigned char[width*height];
1458       RGBA pal[256];
1459       GfxRGB rgb;
1460       state->getFillRGB(&rgb);
1461       memset(pal,255,sizeof(pal));
1462       pal[0].r = (int)(rgb.r*255); pal[0].g = (int)(rgb.g*255); 
1463       pal[0].b = (int)(rgb.b*255); pal[0].a = 255;
1464       pal[1].r = 0; pal[1].g = 0; pal[1].b = 0; pal[1].a = 0;
1465       int numpalette = 2;
1466       xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1467       yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1468       int realwidth = (int)sqrt(SQR(x2-x3) + SQR(y2-y3));
1469       int realheight = (int)sqrt(SQR(x1-x2) + SQR(y1-y2));
1470       for (y = 0; y < height; ++y)
1471       for (x = 0; x < width; ++x)
1472       {
1473             imgStr->getPixel(buf);
1474             if(invert) 
1475                 buf[0]=1-buf[0];
1476             pic[width*y+x] = buf[0];
1477             xid+=x*buf[0]+1;
1478             yid+=y*buf[0]*3+1;
1479       }
1480       
1481       /* the size of the drawn image is added to the identifier
1482          as the same image may require different bitmaps if displayed
1483          at different sizes (due to antialiasing): */
1484       if(type3active) {
1485           xid += realwidth;
1486           yid += realheight;
1487       }
1488       int t,found = -1;
1489       for(t=0;t<picpos;t++)
1490       {
1491           if(pic_xids[t] == xid &&
1492              pic_yids[t] == yid) {
1493               /* if the image was antialiased, the size has changed: */
1494               width = pic_width[t];
1495               height = pic_height[t];
1496               found = t;break;
1497           }
1498       }
1499       if(found<0) {
1500           if(type3active) {
1501               numpalette = 16;
1502               unsigned char*pic2 = 0;
1503               
1504               pic2 = antialize(pic,width,height,realwidth,realheight, numpalette);
1505
1506               if(pic2) {
1507                   width = realwidth;
1508                   height = realheight;
1509                   free(pic);
1510                   pic = pic2;
1511                   /* make a black/white palette */
1512                   int t;
1513                   GfxRGB rgb2;
1514                   rgb2.r = 1 - rgb.r;
1515                   rgb2.g = 1 - rgb.g;
1516                   rgb2.b = 1 - rgb.b;
1517
1518                   float r = 255/(numpalette-1);
1519                   for(t=0;t<numpalette;t++) {
1520                       /*pal[t].r = (U8)(t*r*rgb.r+(numpalette-1-t)*r*rgb2.r);
1521                       pal[t].g = (U8)(t*r*rgb.g+(numpalette-1-t)*r*rgb2.g);
1522                       pal[t].b = (U8)(t*r*rgb.b+(numpalette-1-t)*r*rgb2.b);
1523                       pal[t].a = 255; */
1524                       pal[t].r = (U8)(255*rgb.r);
1525                       pal[t].g = (U8)(255*rgb.g);
1526                       pal[t].b = (U8)(255*rgb.b);
1527                       pal[t].a = (U8)(t*r);
1528                   }
1529               }
1530           }
1531           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, 
1532                   x1,y1,x2,y2,x3,y3,x4,y4, numpalette);
1533           pic_xids[picpos] = xid;
1534           pic_yids[picpos] = yid;
1535           pic_width[picpos] = width;
1536           pic_height[picpos] = height;
1537           if(picpos<1024)
1538               picpos++;
1539       } else {
1540           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1541                   x1,y1,x2,y2,x3,y3,x4,y4);
1542       }
1543       free(pic);
1544       delete imgStr;
1545       return;
1546   } 
1547
1548   int x,y;
1549   
1550   if(colorMap->getNumPixelComps()!=1 || str->getKind()==strDCT)
1551   {
1552       RGBA*pic=new RGBA[width*height];
1553       int xid = 0;
1554       int yid = 0;
1555       for (y = 0; y < height; ++y) {
1556         for (x = 0; x < width; ++x) {
1557           int r,g,b,a;
1558           imgStr->getPixel(pixBuf);
1559           colorMap->getRGB(pixBuf, &rgb);
1560           pic[width*y+x].r = r = (U8)(rgb.r * 255 + 0.5);
1561           pic[width*y+x].g = g = (U8)(rgb.g * 255 + 0.5);
1562           pic[width*y+x].b = b = (U8)(rgb.b * 255 + 0.5);
1563           pic[width*y+x].a = a = 255;//(U8)(rgb.a * 255 + 0.5);
1564           xid += x*r+x*b*3+x*g*7+x*a*11;
1565           yid += y*r*3+y*b*17+y*g*19+y*a*11;
1566         }
1567       }
1568       int t,found = -1;
1569       for(t=0;t<picpos;t++)
1570       {
1571           if(pic_xids[t] == xid &&
1572              pic_yids[t] == yid) {
1573               found = t;break;
1574           }
1575       }
1576       if(found<0) {
1577           if(str->getKind()==strDCT)
1578               pic_ids[picpos] = swfoutput_drawimagejpeg(&output, pic, width, height, 
1579                       x1,y1,x2,y2,x3,y3,x4,y4);
1580           else
1581               pic_ids[picpos] = swfoutput_drawimagelossless(&output, pic, width, height, 
1582                       x1,y1,x2,y2,x3,y3,x4,y4);
1583           pic_xids[picpos] = xid;
1584           pic_yids[picpos] = yid;
1585           pic_width[picpos] = width;
1586           pic_height[picpos] = height;
1587           if(picpos<1024)
1588               picpos++;
1589       } else {
1590           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1591                   x1,y1,x2,y2,x3,y3,x4,y4);
1592       }
1593       delete pic;
1594       delete imgStr;
1595       return;
1596   }
1597   else
1598   {
1599       U8*pic = new U8[width*height];
1600       RGBA pal[256];
1601       int t;
1602       int xid=0,yid=0;
1603       for(t=0;t<256;t++)
1604       {
1605           int r,g,b,a;
1606           pixBuf[0] = t;
1607           colorMap->getRGB(pixBuf, &rgb);
1608           pal[t].r = r = (U8)(rgb.r * 255 + 0.5);
1609           pal[t].g = g = (U8)(rgb.g * 255 + 0.5);
1610           pal[t].b = b = (U8)(rgb.b * 255 + 0.5);
1611           pal[t].a = a = 255;//(U8)(rgb.b * 255 + 0.5);
1612           xid += t*r+t*b*3+t*g*7+t*a*11;
1613           xid += (~t)*r+t*b*3+t*g*7+t*a*11;
1614       }
1615       for (y = 0; y < height; ++y) {
1616         for (x = 0; x < width; ++x) {
1617           imgStr->getPixel(pixBuf);
1618           pic[width*y+x] = pixBuf[0];
1619           xid += x*pixBuf[0]*7;
1620           yid += y*pixBuf[0]*3;
1621         }
1622       }
1623       int found = -1;
1624       for(t=0;t<picpos;t++)
1625       {
1626           if(pic_xids[t] == xid &&
1627              pic_yids[t] == yid) {
1628               found = t;break;
1629           }
1630       }
1631       if(found<0) {
1632           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, 
1633                   x1,y1,x2,y2,x3,y3,x4,y4,256);
1634           pic_xids[picpos] = xid;
1635           pic_yids[picpos] = yid;
1636           pic_width[picpos] = width;
1637           pic_height[picpos] = height;
1638           if(picpos<1024)
1639               picpos++;
1640       } else {
1641           swfoutput_drawimageagain(&output, pic_ids[found], width, height,
1642                   x1,y1,x2,y2,x3,y3,x4,y4);
1643       }
1644       delete pic;
1645       delete imgStr;
1646       return;
1647   }
1648 }
1649
1650 void SWFOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1651                                    int width, int height, GBool invert,
1652                                    GBool inlineImg) 
1653 {
1654   msg("<verbose> drawImageMask %dx%d, invert=%d inline=%d", width, height, invert, inlineImg);
1655   drawGeneralImage(state,ref,str,width,height,0,invert,inlineImg,1);
1656 }
1657
1658 void SWFOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1659                          int width, int height, GfxImageColorMap *colorMap,
1660                          int *maskColors, GBool inlineImg)
1661 {
1662   msg("<verbose> drawImage %dx%d, %s %s, inline=%d", width, height, 
1663           colorMap?"colorMap":"no colorMap", 
1664           maskColors?"maskColors":"no maskColors",
1665           inlineImg);
1666   if(colorMap)
1667       msg("<verbose> colorMap pixcomps:%d bits:%d mode:%d\n", colorMap->getNumPixelComps(),
1668               colorMap->getBits(),colorMap->getColorSpace()->getMode());
1669   drawGeneralImage(state,ref,str,width,height,colorMap,0,inlineImg,0);
1670 }
1671
1672 SWFOutputDev*output = 0; 
1673
1674 static void printInfoString(Dict *infoDict, char *key, char *fmt) {
1675   Object obj;
1676   GString *s1, *s2;
1677   int i;
1678
1679   if (infoDict->lookup(key, &obj)->isString()) {
1680     s1 = obj.getString();
1681     if ((s1->getChar(0) & 0xff) == 0xfe &&
1682         (s1->getChar(1) & 0xff) == 0xff) {
1683       s2 = new GString();
1684       for (i = 2; i < obj.getString()->getLength(); i += 2) {
1685         if (s1->getChar(i) == '\0') {
1686           s2->append(s1->getChar(i+1));
1687         } else {
1688           delete s2;
1689           s2 = new GString("<unicode>");
1690           break;
1691         }
1692       }
1693       printf(fmt, s2->getCString());
1694       delete s2;
1695     } else {
1696       printf(fmt, s1->getCString());
1697     }
1698   }
1699   obj.free();
1700 }
1701
1702 static void printInfoDate(Dict *infoDict, char *key, char *fmt) {
1703   Object obj;
1704   char *s;
1705
1706   if (infoDict->lookup(key, &obj)->isString()) {
1707     s = obj.getString()->getCString();
1708     if (s[0] == 'D' && s[1] == ':') {
1709       s += 2;
1710     }
1711     printf(fmt, s);
1712   }
1713   obj.free();
1714 }
1715
1716 void pdfswf_init(char*filename, char*userPassword) 
1717 {
1718   GString *fileName = new GString(filename);
1719   GString *userPW;
1720   Object info;
1721
1722   // read config file
1723   globalParams = new GlobalParams("");
1724
1725   // open PDF file
1726   if (userPassword && userPassword[0]) {
1727     userPW = new GString(userPassword);
1728   } else {
1729     userPW = NULL;
1730   }
1731   doc = new PDFDoc(fileName, userPW);
1732   if (userPW) {
1733     delete userPW;
1734   }
1735   if (!doc->isOk()) {
1736     exit(1);
1737   }
1738
1739   // print doc info
1740   doc->getDocInfo(&info);
1741   if (info.isDict() &&
1742     (screenloglevel>=LOGLEVEL_NOTICE)) {
1743     printInfoString(info.getDict(), "Title",        "Title:        %s\n");
1744     printInfoString(info.getDict(), "Subject",      "Subject:      %s\n");
1745     printInfoString(info.getDict(), "Keywords",     "Keywords:     %s\n");
1746     printInfoString(info.getDict(), "Author",       "Author:       %s\n");
1747     printInfoString(info.getDict(), "Creator",      "Creator:      %s\n");
1748     printInfoString(info.getDict(), "Producer",     "Producer:     %s\n");
1749     printInfoDate(info.getDict(),   "CreationDate", "CreationDate: %s\n");
1750     printInfoDate(info.getDict(),   "ModDate",      "ModDate:      %s\n");
1751     printf("Pages:        %d\n", doc->getNumPages());
1752     printf("Linearized:   %s\n", doc->isLinearized() ? "yes" : "no");
1753     printf("Encrypted:    ");
1754     if (doc->isEncrypted()) {
1755       printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
1756              doc->okToPrint() ? "yes" : "no",
1757              doc->okToCopy() ? "yes" : "no",
1758              doc->okToChange() ? "yes" : "no",
1759              doc->okToAddNotes() ? "yes" : "no");
1760     } else {
1761       printf("no\n");
1762     }
1763   }
1764   info.free();
1765
1766   numpages = doc->getNumPages();
1767   if (doc->isEncrypted()) {
1768         /*ERROR: This pdf is encrypted, and disallows copying.
1769           Due to the DMCA, paragraph 1201, (2) A-C, circumventing
1770           a technological measure that efficively controls access to
1771           a protected work is violating American law. 
1772           See www.eff.org for more information about DMCA issues.
1773          */
1774         if(!doc->okToCopy()) {
1775             printf("PDF disallows copying. Bailing out.\n");
1776             exit(1); //bail out
1777         }
1778         if(!doc->okToChange() || !doc->okToAddNotes())
1779             swfoutput_setprotected();
1780   }
1781
1782   output = new SWFOutputDev();
1783   output->startDoc(doc->getXRef());
1784 }
1785
1786 void pdfswf_setparameter(char*name, char*value)
1787 {
1788     if(!strcmp(name, "drawonlyshapes")) {
1789         drawonlyshapes = atoi(value);
1790     } else if(!strcmp(name, "ignoredraworder")) {
1791         ignoredraworder = atoi(value);
1792     } else if(!strcmp(name, "linksopennewwindow")) {
1793         opennewwindow = atoi(value);
1794     } else if(!strcmp(name, "storeallcharacters")) {
1795         storeallcharacters = atoi(value);
1796     } else if(!strcmp(name, "enablezlib")) {
1797         enablezlib = atoi(value);
1798     } else if(!strcmp(name, "insertstop")) {
1799         insertstoptag = atoi(value);
1800     } else if(!strcmp(name, "flashversion")) {
1801         flashversion = atoi(value);
1802     } else if(!strcmp(name, "jpegquality")) {
1803         int val = atoi(value);
1804         if(val<0) val=0;
1805         if(val>100) val=100;
1806         jpegquality = val;
1807     } else if(!strcmp(name, "outputfilename")) {
1808         swffilename = value;
1809     } else if(!strcmp(name, "caplinewidth")) {
1810         caplinewidth = atof(value);
1811     } else if(!strcmp(name, "splinequality")) {
1812         int v = atoi(value);
1813         v = 500-(v*5); // 100% = 0.25 pixel, 0% = 25 pixel
1814         if(v<1) v = 1;
1815         splinemaxerror = v;
1816     } else if(!strcmp(name, "fontquality")) {
1817         int v = atoi(value);
1818         v = 500-(v*5); // 100% = 0.25 pixel, 0% = 25 pixel
1819         if(v<1) v = 1;
1820         fontsplinemaxerror = v;
1821     } else {
1822         fprintf(stderr, "unknown parameter: %s (=%s)\n", name, value);
1823     }
1824 }
1825
1826 void pdfswf_drawonlyshapes()
1827 {
1828     drawonlyshapes = 1;
1829 }
1830
1831 void pdfswf_ignoredraworder()
1832 {
1833     ignoredraworder = 1;
1834 }
1835
1836 void pdfswf_linksopennewwindow()
1837 {
1838     opennewwindow = 1;
1839 }
1840
1841 void pdfswf_storeallcharacters()
1842 {
1843     storeallcharacters = 1;
1844 }
1845
1846 void pdfswf_enablezlib()
1847 {
1848     enablezlib = 1;
1849 }
1850
1851 void pdfswf_jpegquality(int val)
1852 {
1853     if(val<0) val=0;
1854     if(val>100) val=100;
1855     jpegquality = val;
1856 }
1857
1858 void pdfswf_setoutputfilename(char*_filename)
1859 {
1860     swffilename = _filename;
1861 }
1862
1863 void pdfswf_insertstop()
1864 {
1865     insertstoptag = 1;
1866 }
1867
1868 void pdfswf_setversion(int n)
1869 {
1870     flashversion = n;
1871 }
1872
1873
1874 void pdfswf_convertpage(int page)
1875 {
1876     if(!pages)
1877     {
1878         pages = (int*)malloc(1024*sizeof(int));
1879         pagebuflen = 1024;
1880     } else {
1881         if(pagepos == pagebuflen)
1882         {
1883             pagebuflen+=1024;
1884             pages = (int*)realloc(pages, pagebuflen);
1885         }
1886     }
1887     pages[pagepos++] = page;
1888 }
1889
1890 void pdfswf_performconversion()
1891 {
1892     int t;
1893     for(t=0;t<pagepos;t++)
1894     {
1895        currentpage = pages[t];
1896        doc->displayPage((OutputDev*)output, currentpage, /*dpi*/72, /*rotate*/0, /*doLinks*/(int)1);
1897     }
1898 }
1899
1900 int pdfswf_numpages()
1901 {
1902   return doc->getNumPages();
1903 }
1904 int closed=0;
1905 void pdfswf_close()
1906 {
1907     msg("<debug> pdfswf.cc: pdfswf_close()");
1908     delete output;
1909     delete doc;
1910     //freeParams();
1911     // check for memory leaks
1912     Object::memCheck(stderr);
1913     gMemReport(stderr);
1914 }
1915
1916