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