switched from lrand48() to rand()
[swftools.git] / lib / devices / swf.c
1 /* gfxdevice_swf.c
2
3    Part of the swftools package.
4
5    Copyright (c) 2001,2002,2003,2004,2005 Matthias Kramm <kramm@quiss.org> 
6
7    Swftools is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    Swftools is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with swftools; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
20
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include "../../config.h"
25 #include <fcntl.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_IO_H
30 #include <io.h>
31 #endif
32 #ifdef HAVE_ASSERT_H
33 #include <assert.h>
34 #else
35 #define assert(a)
36 #endif
37 #include <math.h>
38 #include "../mem.h"
39 #include "../log.h"
40 #include "../rfxswf.h"
41 #include "../gfxdevice.h"
42 #include "../gfxtools.h"
43 #include "../art/libart.h"
44 #include "swf.h"
45 #include "../gfxpoly.h"
46
47 #define CHARDATAMAX 8192
48 #define CHARMIDX 0
49 #define CHARMIDY 0
50
51 typedef struct _chardata {
52     int charid;
53     int fontid; /* TODO: use a SWFFONT instead */
54     int x;
55     int y;
56     int size;
57     RGBA color;
58 } chardata_t;
59
60 typedef struct _fontlist
61 {
62     SWFFONT *swffont;
63     struct _fontlist*next;
64 } fontlist_t;
65
66 typedef long int twip;
67
68 typedef struct _swfmatrix {
69     double m11,m12,m21,m22,m31,m32;
70 } swfmatrix_t;
71
72 typedef struct _swfoutput_internal
73 {
74     gfxdevice_t*dev; // the gfxdevice object where this internal struct resides
75
76     double config_dumpfonts;
77     double config_ppmsubpixels;
78     double config_jpegsubpixels;
79     int config_opennewwindow;
80     int config_ignoredraworder;
81     int config_drawonlyshapes;
82     int config_jpegquality;
83     int config_storeallcharacters;
84     int config_enablezlib;
85     int config_insertstoptag;
86     int config_watermark;
87     int config_flashversion;
88     int config_reordertags;
89     int config_showclipshapes;
90     int config_splinemaxerror;
91     int config_fontsplinemaxerror;
92     int config_filloverlap;
93     int config_protect;
94     int config_bboxvars;
95     int config_disable_polygon_conversion;
96     int config_normalize_polygon_positions;
97     RGBA config_linkcolor;
98     float config_minlinewidth;
99     double config_caplinewidth;
100     char* config_linktarget;
101     char*config_internallinkfunction;
102     char*config_externallinkfunction;
103     char config_animate;
104     double config_framerate;
105
106     SWF* swf;
107
108     fontlist_t* fontlist;
109
110     char storefont;
111
112     MATRIX page_matrix;
113
114     TAG *tag;
115     int currentswfid;
116     int depth;
117     int startdepth;
118     int linewidth;
119     
120     SHAPE* shape;
121     int shapeid;
122     int textid;
123
124     int watermarks;
125     
126     int fillstyleid;
127     int linestyleid;
128     int swflastx;
129     int swflasty;
130     int lastwasfill;
131     int shapeisempty;
132     char fill;
133     int min_x,max_x;
134     int min_y,max_y;
135     TAG* cliptags[128];
136     int clipshapes[128];
137     U32 clipdepths[128];
138     int clippos;
139
140     /* image cache */
141     int pic_xids[1024];
142     int pic_yids[1024];
143     int pic_ids[1024];
144     int pic_width[1024];
145     int pic_height[1024];
146     int picpos;
147
148     int frameno;
149     int lastframeno;
150     
151     char fillstylechanged;
152
153     int jpeg; //next image type
154     
155     int bboxrectpos;
156     SRECT bboxrect;
157
158     chardata_t chardata[CHARDATAMAX];
159     int chardatapos;
160     int firstpage;
161     char pagefinished;
162
163     char overflow;
164
165     int current_font_size;
166     MATRIX fontmatrix;
167     double lastfontm11,lastfontm12,lastfontm21,lastfontm22;
168     SWFFONT *swffont;
169     RGBA strokergb;
170     RGBA fillrgb;
171     int drawmode;
172
173     int shapeposx;
174     int shapeposy;
175
176     char* mark;
177
178 } swfoutput_internal;
179     
180 static void swf_fillbitmap(gfxdevice_t*driver, gfxline_t*line, gfximage_t*img, gfxmatrix_t*move, gfxcxform_t*cxform);
181 static int  swf_setparameter(gfxdevice_t*driver, const char*key, const char*value);
182 static void swf_drawstroke(gfxdevice_t*dev, gfxline_t*line, gfxcoord_t width, gfxcolor_t*color, gfx_capType cap_style, gfx_joinType joint_style, gfxcoord_t miterLimit);
183 static void swf_startclip(gfxdevice_t*dev, gfxline_t*line);
184 static void swf_endclip(gfxdevice_t*dev);
185 static void swf_stroke(gfxdevice_t*dev, gfxline_t*line, gfxcoord_t width, gfxcolor_t*color, gfx_capType cap_style, gfx_joinType joint_style, gfxcoord_t miterLimit);
186 static void swf_fill(gfxdevice_t*dev, gfxline_t*line, gfxcolor_t*color);
187 static void swf_fillbitmap(gfxdevice_t*dev, gfxline_t*line, gfximage_t*img, gfxmatrix_t*matrix, gfxcxform_t*cxform);
188 static void swf_fillgradient(gfxdevice_t*dev, gfxline_t*line, gfxgradient_t*gradient, gfxgradienttype_t type, gfxmatrix_t*matrix);
189 static void swf_drawchar(gfxdevice_t*dev, gfxfont_t*font, int glyph, gfxcolor_t*color, gfxmatrix_t*matrix);
190 static void swf_addfont(gfxdevice_t*dev, gfxfont_t*font);
191 static void swf_drawlink(gfxdevice_t*dev, gfxline_t*line, const char*action);
192 static void swf_startframe(gfxdevice_t*dev, int width, int height);
193 static void swf_endframe(gfxdevice_t*dev);
194 static gfxresult_t* swf_finish(gfxdevice_t*driver);
195
196 static swfoutput_internal* init_internal_struct()
197 {
198     swfoutput_internal*i = (swfoutput_internal*)malloc(sizeof(swfoutput_internal));
199     memset(i, 0, sizeof(swfoutput_internal));
200
201     i->storefont = 0;
202     i->currentswfid = 0;
203     i->depth = 0;
204     i->overflow = 0;
205     i->startdepth = 0;
206     i->linewidth = 0;
207     i->shapeid = -1;
208     i->textid = -1;
209     i->frameno = 0;
210     i->lastframeno = 0;
211
212     i->mark = 0;
213
214     i->fillstyleid;
215     i->linestyleid;
216     i->swflastx=0;
217     i->swflasty=0;
218     i->lastwasfill = 0;
219     i->shapeisempty = 1;
220     i->fill = 0;
221     i->clippos = 0;
222
223     i->fillstylechanged = 0;
224
225     i->bboxrectpos = -1;
226     i->chardatapos = 0;
227     i->firstpage = 1;
228     i->pagefinished = 1;
229
230     i->config_dumpfonts=0;
231     i->config_ppmsubpixels=0;
232     i->config_jpegsubpixels=0;
233     i->config_opennewwindow=1;
234     i->config_ignoredraworder=0;
235     i->config_drawonlyshapes=0;
236     i->config_jpegquality=85;
237     i->config_storeallcharacters=0;
238     i->config_enablezlib=0;
239     i->config_insertstoptag=0;
240     i->config_flashversion=6;
241     i->config_framerate=0.25;
242     i->config_splinemaxerror=1;
243     i->config_fontsplinemaxerror=1;
244     i->config_filloverlap=0;
245     i->config_protect=0;
246     i->config_bboxvars=0;
247     i->config_showclipshapes=0;
248     i->config_minlinewidth=0.05;
249     i->config_caplinewidth=1;
250     i->config_linktarget=0;
251     i->config_internallinkfunction=0;
252     i->config_externallinkfunction=0;
253     i->config_reordertags=1;
254
255     i->config_linkcolor.r = i->config_linkcolor.g = i->config_linkcolor.b = 255;
256     i->config_linkcolor.a = 0x40;
257
258     return i;
259 };
260
261 static int id_error = 0;
262
263 static U16 getNewID(gfxdevice_t* dev)
264 {
265     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
266     if(i->currentswfid == 65535) {
267         if(!id_error) {
268             msg("<error> ID Table overflow");
269             msg("<error> This file is too complex to render- SWF only supports 65536 shapes at once");
270         }
271         id_error=1;
272         i->overflow = 1;
273         exit(1);
274     }
275     return ++i->currentswfid;
276 }
277 static U16 getNewDepth(gfxdevice_t* dev)
278 {
279     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
280     if(i->depth == 65535) {
281         if(!id_error) {
282             msg("<error> Depth Table overflow");
283             msg("<error> This file is too complex to render- SWF only supports 65536 shapes at once");
284         }
285         id_error=1;
286         i->overflow = 1;
287         exit(1);
288     }
289     return ++i->depth;
290 }
291
292 static void startshape(gfxdevice_t* dev);
293 static void starttext(gfxdevice_t* dev);
294 static void endshape(gfxdevice_t* dev);
295 static void endtext(gfxdevice_t* dev);
296
297 typedef struct _plotxy
298 {
299     double x,y;
300 } plotxy_t;
301
302 // write a move-to command into the swf
303 static int movetoxy(gfxdevice_t*dev, TAG*tag, plotxy_t p0)
304 {
305     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
306     int rx = (int)(p0.x*20);
307     int ry = (int)(p0.y*20);
308     if(rx!=i->swflastx || ry!=i->swflasty || i->fillstylechanged) {
309       swf_ShapeSetMove (tag, i->shape, rx,ry);
310       i->fillstylechanged = 0;
311       i->swflastx=rx;
312       i->swflasty=ry;
313       return 1;
314     }
315     return 0;
316 }
317 static int moveto(gfxdevice_t*dev, TAG*tag, double  x, double y)
318 {
319     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
320     plotxy_t p;
321     p.x = x;
322     p.y = y;
323     return movetoxy(dev, tag, p);
324 }
325 static void addPointToBBox(gfxdevice_t*dev, int px, int py) 
326 {
327     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
328
329     SPOINT p;
330     p.x = px;
331     p.y = py;
332     if(i->fill) {
333         swf_ExpandRect(&i->bboxrect, p);
334     } else {
335         swf_ExpandRect3(&i->bboxrect, p, i->linewidth*3/2);
336     }
337 }
338
339 /*static void plot(gfxdevice_t*dev, int x, int y, TAG*tag)
340 {
341     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
342     int width = i->linewidth/4;
343     if(width > 5)
344         width = 5;
345     ////square
346     //swf_ShapeSetLine(tag, i->shape,-width,-width);
347     //swf_ShapeSetLine(tag, i->shape,width*2,0);
348     //swf_ShapeSetLine(tag, i->shape,0,width*2);
349     //swf_ShapeSetLine(tag, i->shape,-width*2,0);
350     //swf_ShapeSetLine(tag, i->shape,0,-width*2);
351     //swf_ShapeSetLine(tag, i->shape,width,width);
352    
353     // diamond
354     swf_ShapeSetLine(tag, i->shape,-width,0);
355     swf_ShapeSetLine(tag, i->shape,width,-width);
356     swf_ShapeSetLine(tag, i->shape,width,width);
357     swf_ShapeSetLine(tag, i->shape,-width,width);
358     swf_ShapeSetLine(tag, i->shape,-width,-width);
359     swf_ShapeSetLine(tag, i->shape,width,0);
360
361     addPointToBBox(dev, x-width ,y-width);
362     addPointToBBox(dev, x+width ,y+width);
363 }*/
364
365 // write a line-to command into the swf
366 static void linetoxy(gfxdevice_t*dev, TAG*tag, plotxy_t p0)
367 {
368     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
369     int px = (int)(p0.x*20);
370     int py = (int)(p0.y*20);
371     int rx = (px-i->swflastx);
372     int ry = (py-i->swflasty);
373     if(rx|ry) {
374         swf_ShapeSetLine (tag, i->shape, rx,ry);
375         addPointToBBox(dev, i->swflastx,i->swflasty);
376         addPointToBBox(dev, px,py);
377     }/* else if(!i->fill) {
378        // treat lines of length 0 as plots, making them
379        // at least 1 twip wide so Flash will display them
380         plot(dev, i->swflastx, i->swflasty, tag);
381     }*/
382
383     i->shapeisempty = 0;
384     i->swflastx+=rx;
385     i->swflasty+=ry;
386 }
387 static void lineto(gfxdevice_t*dev, TAG*tag, double x, double y)
388 {
389     plotxy_t p;
390     p.x = x;
391     p.y = y;
392     linetoxy(dev,tag, p);
393 }
394
395 // write a spline-to command into the swf
396 static void splineto(gfxdevice_t*dev, TAG*tag, plotxy_t control,plotxy_t end)
397 {
398     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
399     int lastlastx = i->swflastx;
400     int lastlasty = i->swflasty;
401
402     int cx = ((int)(control.x*20)-i->swflastx);
403     int cy = ((int)(control.y*20)-i->swflasty);
404     i->swflastx += cx;
405     i->swflasty += cy;
406     int ex = ((int)(end.x*20)-i->swflastx);
407     int ey = ((int)(end.y*20)-i->swflasty);
408     i->swflastx += ex;
409     i->swflasty += ey;
410     
411     if((cx || cy) && (ex || ey)) {
412         swf_ShapeSetCurve(tag, i->shape, cx,cy,ex,ey);
413         addPointToBBox(dev, lastlastx   ,lastlasty   );
414         addPointToBBox(dev, lastlastx+cx,lastlasty+cy);
415         addPointToBBox(dev, lastlastx+cx+ex,lastlasty+cy+ey);
416     } else if(cx || cy || ex || ey) {
417         swf_ShapeSetLine(tag, i->shape, cx+ex,cy+ey);
418         addPointToBBox(dev, lastlastx   ,lastlasty   );
419         addPointToBBox(dev, lastlastx+cx,lastlasty+cy);
420         addPointToBBox(dev, lastlastx+cx+ex,lastlasty+cy+ey);
421     }
422
423     i->shapeisempty = 0;
424 }
425
426 /* write a line, given two points and the transformation
427    matrix. */
428 /*static void line(gfxdevice_t*dev, TAG*tag, plotxy_t p0, plotxy_t p1)
429 {
430     moveto(dev, tag, p0);
431     lineto(dev, tag, p1);
432 }*/
433
434 void resetdrawer(gfxdevice_t*dev)
435 {
436     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
437     i->swflastx = 0;
438     i->swflasty = 0;
439 }
440
441 static void stopFill(gfxdevice_t*dev)
442 {
443     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
444     if(i->lastwasfill!=0)
445     {
446         swf_ShapeSetStyle(i->tag,i->shape,i->linestyleid,0x8000,0);
447         i->fillstylechanged = 1;
448         i->lastwasfill = 0;
449     }
450 }
451 static void startFill(gfxdevice_t*dev)
452 {
453     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
454     if(i->lastwasfill!=1)
455     {
456         swf_ShapeSetStyle(i->tag,i->shape,0x8000,i->fillstyleid,0);
457         i->fillstylechanged = 1;
458         i->lastwasfill = 1;
459     }
460 }
461
462 static inline int colorcompare(gfxdevice_t*dev, RGBA*a,RGBA*b)
463 {
464
465     if(a->r!=b->r ||
466        a->g!=b->g ||
467        a->b!=b->b ||
468        a->a!=b->a) {
469         return 0;
470     }
471     return 1;
472 }
473
474 static SRECT getcharacterbbox(gfxdevice_t*dev, SWFFONT*font, MATRIX* m)
475 {
476     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
477     SRECT r;
478     char debug = 0;
479     memset(&r, 0, sizeof(r));
480
481     int t;
482     if(debug) printf("\n");
483     for(t=0;t<i->chardatapos;t++)
484     {
485         if(i->chardata[t].fontid != font->id) {
486             msg("<error> Internal error: fontid %d != fontid %d", i->chardata[t].fontid, font->id);
487             exit(1);
488         }
489         SRECT b = font->layout->bounds[i->chardata[t].charid];
490         b.xmin *= i->chardata[t].size;
491         b.ymin *= i->chardata[t].size;
492         b.xmax *= i->chardata[t].size;
493         b.ymax *= i->chardata[t].size;
494
495         /* divide by 1024, rounding xmax/ymax up */
496         b.xmax += 1023; b.ymax += 1023; b.xmin /= 1024; b.ymin /= 1024; b.xmax /= 1024; b.ymax /= 1024;
497
498         b.xmin += i->chardata[t].x;
499         b.ymin += i->chardata[t].y;
500         b.xmax += i->chardata[t].x;
501         b.ymax += i->chardata[t].y;
502
503         /* until we solve the INTERNAL_SCALING problem (see below)
504            make sure the bounding box is big enough */
505         b.xmin -= 20;
506         b.ymin -= 20;
507         b.xmax += 20;
508         b.ymax += 20;
509
510         b = swf_TurnRect(b, m);
511
512         if(debug) printf("(%f,%f,%f,%f) -> (%f,%f,%f,%f) [font %d/%d, char %d]\n",
513                 font->layout->bounds[i->chardata[t].charid].xmin/20.0,
514                 font->layout->bounds[i->chardata[t].charid].ymin/20.0,
515                 font->layout->bounds[i->chardata[t].charid].xmax/20.0,
516                 font->layout->bounds[i->chardata[t].charid].ymax/20.0,
517                 b.xmin/20.0,
518                 b.ymin/20.0,
519                 b.xmax/20.0,
520                 b.ymax/20.0,
521                 i->chardata[t].fontid,
522                 font->id,
523                 i->chardata[t].charid
524                 );
525         swf_ExpandRect2(&r, &b);
526     }
527     if(debug) printf("-----> (%f,%f,%f,%f)\n",
528             r.xmin/20.0,
529             r.ymin/20.0,
530             r.xmax/20.0,
531             r.ymax/20.0);
532     return r;
533 }
534
535 static void putcharacters(gfxdevice_t*dev, TAG*tag)
536 {
537     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
538     int t;
539     SWFFONT font;
540     RGBA color;
541     color.r = i->chardata[0].color.r^255;
542     color.g = 0;
543     color.b = 0;
544     color.a = 0;
545     int lastfontid;
546     int lastx;
547     int lasty;
548     int lastsize;
549     int charids[128];
550     int charadvance[128];
551     int charstorepos;
552     int pass;
553     int glyphbits=1; //TODO: can this be zero?
554     int advancebits=1;
555
556     if(tag->id != ST_DEFINETEXT &&
557         tag->id != ST_DEFINETEXT2) {
558         msg("<error> internal error: putcharacters needs an text tag, not %d\n",tag->id);
559         exit(1);
560     }
561     if(!i->chardatapos) {
562         msg("<warning> putcharacters called with zero characters");
563     }
564
565     for(pass = 0; pass < 2; pass++)
566     {
567         charstorepos = 0;
568         lastfontid = -1;
569         lastx = CHARMIDX;
570         lasty = CHARMIDY;
571         lastsize = -1;
572
573         if(pass==1)
574         {
575             advancebits++; // add sign bit
576             swf_SetU8(tag, glyphbits);
577             swf_SetU8(tag, advancebits);
578         }
579
580         for(t=0;t<=i->chardatapos;t++)
581         {
582             if(lastfontid != i->chardata[t].fontid || 
583                     lastx!=i->chardata[t].x ||
584                     lasty!=i->chardata[t].y ||
585                     !colorcompare(dev,&color, &i->chardata[t].color) ||
586                     charstorepos==127 ||
587                     lastsize != i->chardata[t].size ||
588                     t == i->chardatapos)
589             {
590                 if(charstorepos && pass==0)
591                 {
592                     int s;
593                     for(s=0;s<charstorepos;s++)
594                     {
595                         while(charids[s]>=(1<<glyphbits))
596                             glyphbits++;
597                         while(charadvance[s]>=(1<<advancebits))
598                             advancebits++;
599                     }
600                 }
601                 if(charstorepos && pass==1)
602                 {
603                     tag->writeBit = 0; // Q&D
604                     swf_SetBits(tag, 0, 1); // GLYPH Record
605                     swf_SetBits(tag, charstorepos, 7); // number of glyphs
606                     int s;
607                     for(s=0;s<charstorepos;s++)
608                     {
609                         swf_SetBits(tag, charids[s], glyphbits);
610                         swf_SetBits(tag, charadvance[s], advancebits);
611                     }
612                 }
613                 charstorepos = 0;
614
615                 if(pass == 1 && t<i->chardatapos)
616                 {
617                     RGBA*newcolor=0;
618                     SWFFONT*newfont=0;
619                     int newx = 0;
620                     int newy = 0;
621                     if(lastx != i->chardata[t].x ||
622                        lasty != i->chardata[t].y)
623                     {
624                         newx = i->chardata[t].x;
625                         newy = i->chardata[t].y;
626                         if(newx == 0)
627                             newx = SET_TO_ZERO;
628                         if(newy == 0)
629                             newy = SET_TO_ZERO;
630                     }
631                     if(!colorcompare(dev,&color, &i->chardata[t].color)) 
632                     {
633                         color = i->chardata[t].color;
634                         newcolor = &color;
635                     }
636                     font.id = i->chardata[t].fontid;
637                     if(lastfontid != i->chardata[t].fontid || lastsize != i->chardata[t].size)
638                         newfont = &font;
639
640                     tag->writeBit = 0; // Q&D
641                     swf_TextSetInfoRecord(tag, newfont, i->chardata[t].size, newcolor, newx,newy);
642                 }
643
644                 lastfontid = i->chardata[t].fontid;
645                 lastx = i->chardata[t].x;
646                 lasty = i->chardata[t].y;
647                 lastsize = i->chardata[t].size;
648             }
649
650             if(t==i->chardatapos)
651                     break;
652
653             int advance;
654             int nextt = t==i->chardatapos-1?t:t+1;
655             int rel = i->chardata[nextt].x-i->chardata[t].x;
656             if(rel>=0 && (rel<(1<<(advancebits-1)) || pass==0)) {
657                advance = rel;
658                lastx=i->chardata[nextt].x;
659             }
660             else {
661                advance = 0;
662                lastx=i->chardata[t].x;
663             }
664             charids[charstorepos] = i->chardata[t].charid;
665             charadvance[charstorepos] = advance;
666             charstorepos ++;
667         }
668     }
669     i->chardatapos = 0;
670 }
671
672 static void putcharacter(gfxdevice_t*dev, int fontid, int charid, int x,int y, int size, RGBA color)
673 {
674     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
675     if(i->chardatapos == CHARDATAMAX)
676     {
677         msg("<warning> Character buffer too small. SWF will be slightly bigger");
678         endtext(dev);
679         starttext(dev);
680     }
681     i->chardata[i->chardatapos].fontid = fontid;
682     i->chardata[i->chardatapos].charid = charid;
683     i->chardata[i->chardatapos].x = x;
684     i->chardata[i->chardatapos].y = y;
685     i->chardata[i->chardatapos].color = color;
686     i->chardata[i->chardatapos].size = size;
687     i->chardatapos++;
688 }
689
690 /* Notice: we can only put chars in the range -1639,1638 (-32768/20,32768/20).
691    So if we set this value to high, the char coordinates will overflow.
692    If we set it to low, however, the char positions will be inaccurate */
693 #define GLYPH_SCALE 1
694
695 static void endtext(gfxdevice_t*dev)
696 {
697     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
698     if(i->textid<0)
699         return;
700
701     i->tag = swf_InsertTag(i->tag,ST_DEFINETEXT2);
702     swf_SetU16(i->tag, i->textid);
703
704     SRECT r;
705     r = getcharacterbbox(dev, i->swffont, &i->fontmatrix);
706     
707     swf_SetRect(i->tag,&r);
708
709     swf_SetMatrix(i->tag,&i->fontmatrix);
710
711     msg("<trace> Placing text (%d characters) as ID %d", i->chardatapos, i->textid);
712
713     putcharacters(dev, i->tag);
714     swf_SetU8(i->tag,0);
715
716     if(i->swf->fileVersion >= 8) {
717         i->tag = swf_InsertTag(i->tag, ST_CSMTEXTSETTINGS);
718         swf_SetU16(i->tag, i->textid);
719
720         //swf_SetU8(i->tag, /*subpixel grid*/(2<<3)|/*flashtype*/0x40);
721         swf_SetU8(i->tag, /*grid*/(1<<3)|/*flashtype*/0x40);
722         //swf_SetU8(i->tag, /*no grid*/(0<<3)|/*flashtype*/0x40);
723
724         swf_SetU32(i->tag, 0);//thickness
725         swf_SetU32(i->tag, 0);//sharpness
726         swf_SetU8(i->tag, 0);//reserved
727     }
728     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
729     
730     swf_ObjectPlace(i->tag,i->textid,getNewDepth(dev),&i->page_matrix,NULL,NULL);
731     i->textid = -1;
732 }
733
734 /* set's the matrix which is to be applied to characters drawn by swfoutput_drawchar() */
735 static void setfontscale(gfxdevice_t*dev,double m11,double m12, double m21,double m22,double x, double y, char force)
736 {
737     m11 *= 1024;
738     m12 *= 1024;
739     m21 *= 1024;
740     m22 *= 1024;
741     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
742     if(i->lastfontm11 == m11 &&
743        i->lastfontm12 == m12 &&
744        i->lastfontm21 == m21 &&
745        i->lastfontm22 == m22 && !force)
746         return;
747    if(i->textid>=0)
748         endtext(dev);
749     
750     i->lastfontm11 = m11;
751     i->lastfontm12 = m12;
752     i->lastfontm21 = m21;
753     i->lastfontm22 = m22;
754
755     double xsize = sqrt(m11*m11 + m12*m12);
756     double ysize = sqrt(m21*m21 + m22*m22);
757     i->current_font_size = (xsize>ysize?xsize:ysize)*1;
758     if(i->current_font_size < 1)
759         i->current_font_size = 1;
760     double ifs = 1.0 / (i->current_font_size*GLYPH_SCALE);
761
762     MATRIX m;
763     m.sx = (S32)((m11*ifs)*65536); m.r1 = (S32)((m21*ifs)*65536);
764     m.r0 = (S32)((m12*ifs)*65536); m.sy = (S32)((m22*ifs)*65536); 
765     /* this is the position of the first char to set a new fontmatrix-
766        we hope that it's close enough to all other characters using the
767        font, so we use its position as origin for the matrix */
768     m.tx = x*20;
769     m.ty = y*20;
770     i->fontmatrix = m;
771 }
772
773 static int watermark2_width=47;
774 static int watermark2_height=11;
775 static int watermark2[47] = {95,1989,71,0,2015,337,1678,0,2015,5,1921,320,1938,25,2006,1024,
776                              1042,21,13,960,1039,976,8,2000,1359,1088,31,1989,321,1728,0,1152,
777                              1344,832,0,1984,0,896,1088,1088,896,0,1984,128,256,512,1984};
778
779 static void draw_watermark(gfxdevice_t*dev, gfxbbox_t r, char drawall)
780 {
781     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
782     double wx = r.xmax / 5.0;
783     double tx = r.xmax*4.0 / 5.0;
784     double ty = r.ymax-wx*watermark2_height/watermark2_width;
785     double sx = (r.xmax - tx) / watermark2_width;
786     double sy = (r.ymax - ty) / watermark2_height;
787     double px = sx-0.5;
788     double py = sy-0.5;
789     if(ty > 0 && px > 1.0 && py > 1.0) {
790         int x,y;
791         for(y=0;y<watermark2_height;y++)
792         for(x=0;x<watermark2_width;x++) {
793             if(((watermark2[x]>>y)&1)) {
794                 if(!drawall && rand()%5)
795                     continue;
796                 unsigned int b = rand();
797                 moveto(dev, i->tag, x*sx+tx+((b>>1)&1)/20.0, y*sy+ty+((b>>3)&1)/20.0);
798                 lineto(dev, i->tag, x*sx+px+tx+((b>>2)&1)/20.0, y*sy+ty+((b>>3)&1)/20.0);
799                 lineto(dev, i->tag, x*sx+px+tx+((b>>2)&1)/20.0, y*sy+py+ty+((b>>4)&1)/20.0);
800                 lineto(dev, i->tag, x*sx+tx+((b>>1)&1)/20.0, y*sy+py+ty+((b>>4)&1)/20.0);
801                 lineto(dev, i->tag, x*sx+tx+((b>>1)&1)/20.0, y*sy+ty+((b>>3)&1)/20.0);
802             }
803         }
804     }
805 }
806
807 static void swfoutput_setfillcolor(gfxdevice_t* dev, U8 r, U8 g, U8 b, U8 a)
808 {
809     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
810     if(i->fillrgb.r == r &&
811        i->fillrgb.g == g &&
812        i->fillrgb.b == b &&
813        i->fillrgb.a == a) return;
814     if(i->shapeid>=0)
815      endshape(dev);
816
817     i->fillrgb.r = r;
818     i->fillrgb.g = g;
819     i->fillrgb.b = b;
820     i->fillrgb.a = a;
821 }
822 static void insert_watermark(gfxdevice_t*dev, char drawall)
823 {
824     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
825     if(!drawall && i->watermarks>20)
826         return;
827     endshape(dev);
828     endtext(dev);
829    
830     if(drawall) {
831         swfoutput_setfillcolor(dev, 0,0,255,192);
832     } else {
833         swfoutput_setfillcolor(dev, rand(),rand(),rand(),(rand()&127)+128);
834     }
835     startshape(dev);
836     startFill(dev);
837
838     gfxbbox_t r; r.xmin = r.ymin = 0;
839     r.xmax = i->max_x;
840     r.ymax = i->max_y;
841     draw_watermark(dev, r, drawall);
842     endshape(dev);
843     i->watermarks++;
844 }
845
846
847 static void endpage(gfxdevice_t*dev)
848 {
849     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
850     if(i->pagefinished)
851       return;
852     if(i->shapeid>=0)
853       endshape(dev);
854     if(i->textid>=0)
855       endtext(dev);
856     
857     while(i->clippos)
858         dev->endclip(dev);
859
860     if(i->config_watermark) {
861         insert_watermark(dev, 1);
862     }
863
864     i->pagefinished = 1;
865 }
866
867 void swf_startframe(gfxdevice_t*dev, int width, int height)
868 {
869     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
870     if(!i->firstpage && !i->pagefinished)
871         endpage(dev);
872     msg("<verbose> Starting new SWF page of size %dx%d", width, height);
873
874     swf_GetMatrix(0, &i->page_matrix);
875     i->page_matrix.tx = 0;
876     i->page_matrix.ty = 0;
877     i->min_x = 0;
878     i->min_y = 0;
879     i->max_x = width;
880     i->max_y = height;
881     i->watermarks = 0;
882
883     /* set clipping/background rectangle */
884     /* TODO: this should all be done in SWFOutputDev */
885     //setBackground(dev, x1, y1, x2, y2);
886
887     /* increase SWF's bounding box */
888     SRECT r;
889     r.xmin = 0;
890     r.ymin = 0;
891     r.xmax = width*20;
892     r.ymax = height*20;
893     swf_ExpandRect2(&i->swf->movieSize, &r);
894
895     i->lastframeno = i->frameno;
896     i->firstpage = 0;
897     i->pagefinished = 0;
898 }
899
900 void swf_endframe(gfxdevice_t*dev)
901 {
902     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
903     
904     if(!i->pagefinished)
905         endpage(dev);
906
907     if( (i->swf->fileVersion <= 8) && (i->config_insertstoptag) ) {
908         ActionTAG*atag=0;
909         atag = action_Stop(atag);
910         atag = action_End(atag);
911         i->tag = swf_InsertTag(i->tag,ST_DOACTION);
912         swf_ActionSet(i->tag,atag);
913     }
914     i->tag = swf_InsertTag(i->tag,ST_SHOWFRAME);
915     i->frameno ++;
916     
917     for(i->depth;i->depth>i->startdepth;i->depth--) {
918         i->tag = swf_InsertTag(i->tag,ST_REMOVEOBJECT2);
919         swf_SetU16(i->tag,i->depth);
920     }
921     i->depth = i->startdepth;
922 }
923
924 static void setBackground(gfxdevice_t*dev, int x1, int y1, int x2, int y2)
925 {
926     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
927     RGBA rgb;
928     rgb.a = rgb.r = rgb.g = rgb.b = 0xff;
929     SRECT r;
930     SHAPE* s;
931     int ls1=0,fs1=0;
932     int shapeid = getNewID(dev);
933     r.xmin = x1;
934     r.ymin = y1;
935     r.xmax = x2;
936     r.ymax = y2;
937     i->tag = swf_InsertTag(i->tag, ST_DEFINESHAPE);
938     swf_ShapeNew(&s);
939     fs1 = swf_ShapeAddSolidFillStyle(s, &rgb);
940     swf_SetU16(i->tag,shapeid);
941     swf_SetRect(i->tag,&r);
942     swf_SetShapeHeader(i->tag,s);
943     swf_ShapeSetAll(i->tag,s,x1,y1,ls1,fs1,0);
944     swf_ShapeSetLine(i->tag,s,(x2-x1),0);
945     swf_ShapeSetLine(i->tag,s,0,(y2-y1));
946     swf_ShapeSetLine(i->tag,s,(x1-x2),0);
947     swf_ShapeSetLine(i->tag,s,0,(y1-y2));
948     swf_ShapeSetEnd(i->tag);
949     swf_ShapeFree(s);
950     i->tag = swf_InsertTag(i->tag, ST_PLACEOBJECT2);
951     swf_ObjectPlace(i->tag,shapeid,getNewDepth(dev),0,0,0);
952     i->tag = swf_InsertTag(i->tag, ST_PLACEOBJECT2);
953     swf_ObjectPlaceClip(i->tag,shapeid,getNewDepth(dev),0,0,0,65535);
954 }
955
956 /* initialize the swf writer */
957 void gfxdevice_swf_init(gfxdevice_t* dev)
958 {
959     memset(dev, 0, sizeof(gfxdevice_t));
960     
961     dev->name = "swf";
962
963     dev->internal = init_internal_struct();
964
965     dev->startpage = swf_startframe;
966     dev->endpage = swf_endframe;
967     dev->finish = swf_finish;
968     dev->fillbitmap = swf_fillbitmap;
969     dev->setparameter = swf_setparameter;
970     dev->stroke = swf_stroke;
971     dev->startclip = swf_startclip;
972     dev->endclip = swf_endclip;
973     dev->fill = swf_fill;
974     dev->fillbitmap = swf_fillbitmap;
975     dev->fillgradient = swf_fillgradient;
976     dev->addfont = swf_addfont;
977     dev->drawchar = swf_drawchar;
978     dev->drawlink = swf_drawlink;
979
980     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
981     i->dev = dev;
982
983     RGBA rgb;
984
985     msg("<verbose> initializing swf output\n", i->max_x,i->max_y);
986
987     i->swffont = 0;
988    
989     i->swf = (SWF*)rfx_calloc(sizeof(SWF));
990     i->swf->fileVersion    = i->config_flashversion;
991     i->swf->frameRate      = i->config_framerate*0x100;
992     i->swf->movieSize.xmin = 0;
993     i->swf->movieSize.ymin = 0;
994     i->swf->movieSize.xmax = 0;
995     i->swf->movieSize.ymax = 0;
996     
997     i->swf->firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
998     i->tag = i->swf->firstTag;
999     rgb.a = rgb.r = rgb.g = rgb.b = 0xff;
1000     rgb.r = 0;
1001     swf_SetRGB(i->tag,&rgb);
1002
1003     i->startdepth = i->depth = 0;
1004     
1005     if(i->config_protect)
1006       i->tag = swf_InsertTag(i->tag, ST_PROTECT);
1007 }
1008
1009 static void startshape(gfxdevice_t*dev)
1010 {
1011     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1012     SRECT r;
1013
1014     if(i->shapeid>=0)
1015         return;
1016     //if(i->chardatapos && i->chardata[i->chardatapos-1].color.a)
1017     endtext(dev);
1018
1019     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE3);
1020
1021     swf_ShapeNew(&i->shape);
1022     i->linestyleid = swf_ShapeAddLineStyle(i->shape,i->linewidth,&i->strokergb);
1023     i->fillstyleid = swf_ShapeAddSolidFillStyle(i->shape,&i->fillrgb);
1024     if(i->mark) {
1025         RGBA markcol = {0,i->mark[0],i->mark[1],i->mark[2]};
1026         swf_ShapeAddSolidFillStyle(i->shape,&markcol);
1027     }
1028
1029     i->shapeid = getNewID(dev);
1030     
1031     msg("<debug> Using shape id %d", i->shapeid);
1032
1033     swf_SetU16(i->tag,i->shapeid);  // ID
1034
1035     i->bboxrectpos = i->tag->len;
1036     /* changed later */
1037     r.xmin = 0;
1038     r.ymin = 0;
1039     r.xmax = 20*i->max_x;
1040     r.ymax = 20*i->max_y;
1041     swf_SetRect(i->tag,&r);
1042    
1043     memset(&i->bboxrect, 0, sizeof(i->bboxrect));
1044
1045     swf_SetShapeStyles(i->tag,i->shape);
1046     swf_ShapeCountBits(i->shape,NULL,NULL);
1047     swf_SetShapeBits(i->tag,i->shape);
1048
1049     /* TODO: do we really need this? */
1050     //swf_ShapeSetAll(i->tag,i->shape,/*x*/0,/*y*/0,i->linestyleid,0,0);
1051     //swf_ShapeSetAll(i->tag,i->shape,/*x*/UNDEFINED_COORD,/*y*/UNDEFINED_COORD,i->linestyleid,0,0);
1052     i->swflastx=i->swflasty=UNDEFINED_COORD;
1053     i->lastwasfill = -1;
1054     i->shapeisempty = 1;
1055 }
1056
1057 static void starttext(gfxdevice_t*dev)
1058 {
1059     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1060     if(i->shapeid>=0)
1061         endshape(dev);
1062
1063     if(i->config_watermark) {
1064         insert_watermark(dev, 0);
1065     }
1066     i->textid = getNewID(dev);
1067     i->swflastx=i->swflasty=0;
1068 }
1069             
1070
1071 /* TODO: move to ../lib/rfxswf */
1072 void changeRect(gfxdevice_t*dev, TAG*tag, int pos, SRECT*newrect)
1073 {
1074     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1075     /* determine length of old rect */
1076     tag->pos = pos;
1077     tag->readBit = 0;
1078     SRECT old;
1079     swf_GetRect(tag, &old);
1080     swf_ResetReadBits(tag);
1081     int pos_end = tag->pos;
1082
1083     int len = tag->len - pos_end;
1084     U8*data = (U8*)malloc(len);
1085     memcpy(data, &tag->data[pos_end], len);
1086     tag->writeBit = 0;
1087     tag->len = pos;
1088     swf_SetRect(tag, newrect);
1089     swf_SetBlock(tag, data, len);
1090     free(data);
1091     tag->pos = tag->readBit = 0;
1092 }
1093
1094 void cancelshape(gfxdevice_t*dev)
1095 {
1096     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1097     /* delete old shape tag */
1098     TAG*todel = i->tag;
1099     i->tag = i->tag->prev;
1100     swf_DeleteTag(todel);
1101     if(i->shape) {swf_ShapeFree(i->shape);i->shape=0;}
1102     i->shapeid = -1;
1103     i->bboxrectpos = -1;
1104
1105 //    i->currentswfid--; // this was an *exceptionally* bad idea
1106 }
1107
1108 void fixAreas(gfxdevice_t*dev)
1109 {
1110     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1111     if(!i->shapeisempty && i->fill &&
1112        (i->bboxrect.xmin == i->bboxrect.xmax ||
1113         i->bboxrect.ymin == i->bboxrect.ymax) &&
1114         i->config_minlinewidth >= 0.001
1115        ) {
1116         msg("<debug> Shape has size 0: width=%.2f height=%.2f",
1117                 (i->bboxrect.xmax-i->bboxrect.xmin)/20.0,
1118                 (i->bboxrect.ymax-i->bboxrect.ymin)/20.0
1119                 );
1120     
1121         SRECT r = i->bboxrect;
1122         
1123         if(r.xmin == r.xmax && r.ymin == r.ymax) {
1124             /* this thing comes down to a single dot- nothing to fix here */
1125             return;
1126         }
1127
1128         cancelshape(dev);
1129
1130         RGBA save_col = i->strokergb;
1131         int  save_width = i->linewidth;
1132
1133         i->strokergb = i->fillrgb;
1134         i->linewidth = (int)(i->config_minlinewidth*20);
1135         if(i->linewidth==0) i->linewidth = 1;
1136         
1137         startshape(dev);
1138         stopFill(dev);
1139
1140         moveto(dev, i->tag, r.xmin/20.0,r.ymin/20.0);
1141         lineto(dev, i->tag, r.xmax/20.0,r.ymax/20.0);
1142
1143         i->strokergb = save_col;
1144         i->linewidth = save_width;
1145     }
1146     
1147 }
1148
1149 static void endshape_noput(gfxdevice_t*dev)
1150 {
1151     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1152     if(i->shapeid<0) 
1153         return;
1154     //changeRect(dev, i->tag, i->bboxrectpos, &i->bboxrect);
1155     i->shapeid = -1;
1156     if(i->shape) {
1157         swf_ShapeFree(i->shape);
1158         i->shape=0;
1159     }
1160     i->fill=0;
1161     i->shapeposx=0;
1162     i->shapeposy=0;
1163 }
1164
1165 static void endshape(gfxdevice_t*dev)
1166 {
1167     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1168     if(i->shapeid<0) 
1169         return;
1170
1171     fixAreas(dev);
1172         
1173     if(i->shapeisempty ||
1174        /*bbox empty?*/
1175        (i->bboxrect.xmin == i->bboxrect.xmax && 
1176         i->bboxrect.ymin == i->bboxrect.ymax))
1177     {
1178         // delete the shape again, we didn't do anything
1179         msg("<debug> cancelling shape: bbox is (%f,%f,%f,%f)",
1180                 i->bboxrect.xmin /20.0,
1181                 i->bboxrect.ymin /20.0,
1182                 i->bboxrect.xmax /20.0,
1183                 i->bboxrect.ymax /20.0
1184                 );
1185         cancelshape(dev);
1186         return;
1187     }
1188     
1189     swf_ShapeSetEnd(i->tag);
1190
1191     changeRect(dev, i->tag, i->bboxrectpos, &i->bboxrect);
1192
1193     msg("<trace> Placing shape ID %d", i->shapeid);
1194
1195     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
1196     MATRIX m = i->page_matrix;
1197     m.tx += i->shapeposx;
1198     m.ty += i->shapeposy;
1199     swf_ObjectPlace(i->tag,i->shapeid,getNewDepth(dev),&m,NULL,NULL);
1200
1201     if(i->config_animate) {
1202         i->tag = swf_InsertTag(i->tag,ST_SHOWFRAME);
1203     }
1204
1205     swf_ShapeFree(i->shape);
1206     i->shape = 0;
1207     i->shapeid = -1;
1208     i->bboxrectpos = -1;
1209
1210     i->fill=0;
1211     i->shapeposx=0;
1212     i->shapeposy=0;
1213 }
1214
1215 void wipeSWF(SWF*swf)
1216 {
1217     TAG*tag = swf->firstTag;
1218     while(tag) {
1219         TAG*next = tag->next;
1220         if(tag->id != ST_SETBACKGROUNDCOLOR &&
1221            tag->id != ST_END &&
1222            tag->id != ST_DOACTION &&
1223            tag->id != ST_SHOWFRAME) {
1224             swf_DeleteTag(tag);
1225         }
1226         tag = next;
1227     }
1228 }
1229
1230 void swfoutput_finalize(gfxdevice_t*dev)
1231 {
1232     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1233
1234     if(i->tag && i->tag->id == ST_END)
1235         return; //already done
1236
1237     if(i->config_bboxvars) {
1238         TAG* tag = swf_InsertTag(i->swf->firstTag, ST_DOACTION);
1239         ActionTAG*a = 0;
1240         a = action_PushString(a, "xmin");
1241         a = action_PushFloat(a, i->swf->movieSize.xmin / 20.0);
1242         a = action_SetVariable(a);
1243         a = action_PushString(a, "ymin");
1244         a = action_PushFloat(a, i->swf->movieSize.ymin / 20.0);
1245         a = action_SetVariable(a);
1246         a = action_PushString(a, "xmax");
1247         a = action_PushFloat(a, i->swf->movieSize.xmax / 20.0);
1248         a = action_SetVariable(a);
1249         a = action_PushString(a, "ymax");
1250         a = action_PushFloat(a, i->swf->movieSize.ymax / 20.0);
1251         a = action_SetVariable(a);
1252         a = action_PushString(a, "width");
1253         a = action_PushFloat(a, (i->swf->movieSize.xmax - i->swf->movieSize.xmin) / 20.0);
1254         a = action_SetVariable(a);
1255         a = action_PushString(a, "height");
1256         a = action_PushFloat(a, (i->swf->movieSize.ymax - i->swf->movieSize.ymin) / 20.0);
1257         a = action_SetVariable(a);
1258         a = action_End(a);
1259         swf_ActionSet(tag, a);
1260         swf_ActionFree(a);
1261     }
1262
1263     if(i->mark) {
1264         free(i->mark);i->mark = 0;
1265     }
1266
1267     endpage(dev);
1268     fontlist_t *iterator = i->fontlist;
1269     while(iterator) {
1270         TAG*mtag = i->swf->firstTag;
1271         if(iterator->swffont) {
1272             if(!i->config_storeallcharacters) {
1273                 msg("<debug> Reducing font %s", iterator->swffont->name);
1274                 swf_FontReduce(iterator->swffont);
1275             }
1276             int used = iterator->swffont->use && iterator->swffont->use->used_glyphs;
1277             if(used) {
1278                 mtag = swf_InsertTag(mtag, ST_DEFINEFONT2);
1279                 swf_FontSetDefine2(mtag, iterator->swffont);
1280             }
1281         }
1282
1283         iterator = iterator->next;
1284     }
1285     i->tag = swf_InsertTag(i->tag,ST_END);
1286     TAG* tag = i->tag->prev;
1287
1288     /* remove the removeobject2 tags between the last ST_SHOWFRAME
1289        and the ST_END- they confuse the flash player  */
1290     while(tag->id == ST_REMOVEOBJECT2) {
1291         TAG* prev = tag->prev;
1292         swf_DeleteTag(tag);
1293         tag = prev;
1294     }
1295     
1296     if(i->overflow) {
1297         wipeSWF(i->swf);
1298     }
1299     if(i->config_enablezlib || i->config_flashversion>=6) {
1300         i->swf->compressed = 1;
1301     }
1302
1303     /* Initialize AVM2 if it is a Flash9 file */
1304     if(i->config_flashversion>=9 && i->config_insertstoptag) {
1305         AVM2_InsertStops(i->swf);
1306     }
1307 //    if(i->config_reordertags)
1308 //      swf_Optimize(i->swf);
1309 }
1310
1311 int swfresult_save(gfxresult_t*gfx, const char*filename)
1312 {
1313     SWF*swf = (SWF*)gfx->internal;
1314     int fi;
1315     if(filename)
1316      fi = open(filename, O_BINARY|O_CREAT|O_TRUNC|O_WRONLY, 0777);
1317     else
1318      fi = 1; // stdout
1319     
1320     if(fi<=0) {
1321         msg("<fatal> Could not create \"%s\". ", FIXNULL(filename));
1322         return -1;
1323     }
1324     
1325     if FAILED(swf_WriteSWF(fi,swf)) 
1326         msg("<error> WriteSWF() failed.\n");
1327
1328     if(filename)
1329      close(fi);
1330     return 0;
1331 }
1332 void* swfresult_get(gfxresult_t*gfx, const char*name)
1333 {
1334     SWF*swf = (SWF*)gfx->internal;
1335     if(!strcmp(name, "swf")) {
1336         return (void*)swf_CopySWF(swf);
1337     } else if(!strcmp(name, "xmin")) {
1338         return (void*)(swf->movieSize.xmin/20);
1339     } else if(!strcmp(name, "ymin")) {
1340         return (void*)(swf->movieSize.ymin/20);
1341     } else if(!strcmp(name, "xmax")) {
1342         return (void*)(swf->movieSize.xmax/20);
1343     } else if(!strcmp(name, "ymax")) {
1344         return (void*)(swf->movieSize.ymax/20);
1345     } else if(!strcmp(name, "width")) {
1346         return (void*)((swf->movieSize.xmax - swf->movieSize.xmin)/20);
1347     } else if(!strcmp(name, "height")) {
1348         return (void*)((swf->movieSize.ymax - swf->movieSize.ymin)/20);
1349     }
1350     return 0;
1351 }
1352 void swfresult_destroy(gfxresult_t*gfx)
1353 {
1354     if(gfx->internal) {
1355         swf_FreeTags((SWF*)gfx->internal);
1356         free(gfx->internal);
1357         gfx->internal = 0;
1358     }
1359     memset(gfx, 0, sizeof(gfxresult_t));
1360     free(gfx);
1361 }
1362
1363 static void swfoutput_destroy(gfxdevice_t* dev);
1364
1365 gfxresult_t* swf_finish(gfxdevice_t* dev)
1366 {
1367     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1368     gfxresult_t*result;
1369
1370     if(i->config_linktarget) {
1371         free(i->config_linktarget);
1372         i->config_linktarget = 0;
1373     }
1374
1375     swfoutput_finalize(dev);
1376     SWF* swf = i->swf;i->swf = 0;
1377     swfoutput_destroy(dev);
1378
1379     result = (gfxresult_t*)rfx_calloc(sizeof(gfxresult_t));
1380     result->internal = swf;
1381     result->save = swfresult_save;
1382     result->write = 0;
1383     result->get = swfresult_get;
1384     result->destroy = swfresult_destroy;
1385     return result;
1386 }
1387
1388 /* Perform cleaning up */
1389 static void swfoutput_destroy(gfxdevice_t* dev) 
1390 {
1391     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1392     if(!i) {
1393         /* not initialized yet- nothing to destroy */
1394         return;
1395     }
1396
1397     fontlist_t *tmp,*iterator = i->fontlist;
1398     while(iterator) {
1399         if(iterator->swffont) {
1400             swf_FontFree(iterator->swffont);iterator->swffont=0;
1401         }
1402         tmp = iterator;
1403         iterator = iterator->next;
1404         free(tmp);
1405     }
1406     if(i->swf) {swf_FreeTags(i->swf);free(i->swf);i->swf = 0;}
1407
1408     free(i);i=0;
1409     memset(dev, 0, sizeof(gfxdevice_t));
1410 }
1411
1412 static void swfoutput_setstrokecolor(gfxdevice_t* dev, U8 r, U8 g, U8 b, U8 a)
1413 {
1414     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1415     if(i->strokergb.r == r &&
1416        i->strokergb.g == g &&
1417        i->strokergb.b == b &&
1418        i->strokergb.a == a) return;
1419
1420     if(i->shapeid>=0)
1421      endshape(dev);
1422     i->strokergb.r = r;
1423     i->strokergb.g = g;
1424     i->strokergb.b = b;
1425     i->strokergb.a = a;
1426 }
1427
1428 //#define ROUND_UP 19
1429 //#define ROUND_UP 10
1430
1431 static void swfoutput_setlinewidth(gfxdevice_t*dev, double _linewidth)
1432 {
1433     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1434     if(i->linewidth == (U16)(_linewidth*20+19.0/20.0))
1435         return;
1436     if(i->shapeid>=0)
1437         endshape(dev);
1438     i->linewidth = (U16)(_linewidth*20+19.0/20.0);
1439 }
1440
1441
1442 static void drawlink(gfxdevice_t*dev, ActionTAG*,ActionTAG*, gfxline_t*points, char mouseover);
1443 static void swfoutput_namedlink(gfxdevice_t*dev, char*name, gfxline_t*points);
1444 static void swfoutput_linktopage(gfxdevice_t*dev, int page, gfxline_t*points);
1445 static void swfoutput_linktourl(gfxdevice_t*dev, const char*url, gfxline_t*points);
1446
1447 /*void swfoutput_drawlink(gfxdevice_t*dev, char*url, gfxline_t*points)
1448 {
1449     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1450     dev->drawlink(dev, points, url);
1451 }*/
1452
1453 void swf_drawlink(gfxdevice_t*dev, gfxline_t*points, const char*url)
1454 {
1455     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1456
1457     if(!strncmp("http://pdf2swf:", url, 15)) {
1458         char*tmp = strdup(url);
1459         int l = strlen(tmp);
1460         if(tmp[l-1] == '/')
1461            tmp[l-1] = 0;
1462         swfoutput_namedlink(dev, tmp+15, points);
1463         free(tmp);
1464         return;
1465     } else if(!strncmp("page", url, 4)) {
1466         int t, nodigit=0;
1467         for(t=4;url[t];t++)
1468             if(url[t]<'0' || url[t]>'9')
1469                 nodigit = 1;
1470         if(!nodigit) {
1471             int page = atoi(&url[4]);
1472             if(page<0) page = 0;
1473             swfoutput_linktopage(dev, page, points);
1474         }
1475     } else {
1476         swfoutput_linktourl(dev, url, points);
1477     }
1478 }
1479 void swfoutput_linktourl(gfxdevice_t*dev, const char*url, gfxline_t*points)
1480 {
1481     ActionTAG* actions = 0;
1482     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1483     if(i->shapeid>=0)
1484         endshape(dev);
1485     if(i->textid>=0)
1486         endtext(dev);
1487     
1488     if(i->config_externallinkfunction) {
1489         actions = action_PushString(actions, url); //parameter
1490         actions = action_PushInt(actions, 1); //number of parameters (1)
1491         actions = action_PushString(actions, i->config_externallinkfunction); //function name
1492         actions = action_CallFunction(actions);
1493     } else if(!i->config_linktarget) {
1494         if(!i->config_opennewwindow)
1495           actions = action_GetUrl(actions, url, "_parent");
1496         else
1497           actions = action_GetUrl(actions, url, "_this");
1498     } else {
1499         actions = action_GetUrl(actions, url, i->config_linktarget);
1500     }
1501     actions = action_End(actions);
1502     
1503     drawlink(dev, actions, 0, points,0);
1504 }
1505 void swfoutput_linktopage(gfxdevice_t*dev, int page, gfxline_t*points)
1506 {
1507     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1508     ActionTAG* actions = 0;
1509
1510     if(i->shapeid>=0)
1511         endshape(dev);
1512     if(i->textid>=0)
1513         endtext(dev);
1514   
1515     if(!i->config_internallinkfunction) {
1516         actions = action_GotoFrame(actions, page-1);
1517         actions = action_End(actions);
1518     } else {
1519         actions = action_PushInt(actions, page); //parameter
1520         actions = action_PushInt(actions, 1); //number of parameters (1)
1521         actions = action_PushString(actions, i->config_internallinkfunction); //function name
1522         actions = action_CallFunction(actions);
1523         actions = action_End(actions);
1524     }
1525
1526     drawlink(dev, actions, 0, points,0);
1527 }
1528
1529 /* Named Links (a.k.a. Acrobatmenu) are used to implement various gadgets
1530    of the viewer objects, like subtitles, index elements etc.
1531 */
1532 void swfoutput_namedlink(gfxdevice_t*dev, char*name, gfxline_t*points)
1533 {
1534     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1535     ActionTAG *actions1,*actions2;
1536     char*tmp = strdup(name);
1537     char mouseover = 1;
1538
1539     if(i->shapeid>=0)
1540         endshape(dev);
1541     if(i->textid>=0)
1542         endtext(dev);
1543
1544     if(!strncmp(tmp, "call:", 5))
1545     {
1546         char*x = strchr(&tmp[5], ':');
1547         if(!x) {
1548             actions1 = action_PushInt(0, 0); //number of parameters (0)
1549             actions1 = action_PushString(actions1, &tmp[5]); //function name
1550             actions1 = action_CallFunction(actions1);
1551             actions1 = action_End(actions1);
1552         } else {
1553             *x = 0;
1554             actions1 = action_PushString(0, x+1); //parameter
1555             actions1 = action_PushInt(actions1, 1); //number of parameters (1)
1556             actions1 = action_PushString(actions1, &tmp[5]); //function name
1557             actions1 = action_CallFunction(actions1);
1558             actions1 = action_End(actions1);
1559         }
1560         actions2 = action_End(0);
1561         mouseover = 0;
1562     }
1563     else
1564     {
1565         actions1 = action_PushString(0, "/:subtitle");
1566         actions1 = action_PushString(actions1, name);
1567         actions1 = action_SetVariable(actions1);
1568         actions1 = action_End(actions1);
1569
1570         actions2 = action_PushString(0, "/:subtitle");
1571         actions2 = action_PushString(actions2, "");
1572         actions2 = action_SetVariable(actions2);
1573         actions2 = action_End(actions2);
1574     }
1575
1576     drawlink(dev, actions1, actions2, points,mouseover);
1577
1578     swf_ActionFree(actions1);
1579     swf_ActionFree(actions2);
1580     free(tmp);
1581 }
1582
1583 static void drawgfxline(gfxdevice_t*dev, gfxline_t*line)
1584 {
1585     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1586     gfxcoord_t lastx=0,lasty=0,px=0,py=0;
1587     char lastwasmoveto;
1588     int lines= 0, splines=0;
1589     while(1) {
1590         if(!line)
1591             break;
1592         /* check whether the next segment is zero */
1593         if(line->type == gfx_moveTo) {
1594             moveto(dev, i->tag, line->x, line->y);
1595             px = lastx = line->x;
1596             py = lasty = line->y;
1597             lastwasmoveto = 1;
1598         } if(line->type == gfx_lineTo) {
1599             lineto(dev, i->tag, line->x, line->y);
1600             px = line->x;
1601             py = line->y;
1602             lastwasmoveto = 0;
1603             lines++;
1604         } else if(line->type == gfx_splineTo) {
1605             plotxy_t s,p;
1606             s.x = line->sx;p.x = line->x;
1607             s.y = line->sy;p.y = line->y;
1608             splineto(dev, i->tag, s, p);
1609             px = line->x;
1610             py = line->y;
1611             lastwasmoveto = 0;
1612             splines++;
1613         }
1614         line = line->next;
1615     }
1616     msg("<trace> drawgfxline, %d lines, %d splines", lines, splines);
1617 }
1618
1619
1620 static void drawlink(gfxdevice_t*dev, ActionTAG*actions1, ActionTAG*actions2, gfxline_t*points, char mouseover)
1621 {
1622     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1623     RGBA rgb;
1624     SRECT r;
1625     int lsid=0;
1626     int fsid;
1627     int myshapeid;
1628     int myshapeid2;
1629     double posx = 0;
1630     double posy = 0;
1631     int buttonid = getNewID(dev);
1632     gfxbbox_t bbox = gfxline_getbbox(points);
1633
1634     /* shape */
1635     myshapeid = getNewID(dev);
1636     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE3);
1637     swf_ShapeNew(&i->shape);
1638     rgb.r = rgb.b = rgb.a = rgb.g = 0; 
1639     fsid = swf_ShapeAddSolidFillStyle(i->shape,&rgb);
1640     swf_SetU16(i->tag, myshapeid);
1641     r.xmin = (int)(bbox.xmin*20);
1642     r.ymin = (int)(bbox.ymin*20);
1643     r.xmax = (int)(bbox.xmax*20);
1644     r.ymax = (int)(bbox.ymax*20);
1645     swf_SetRect(i->tag,&r);
1646     swf_SetShapeStyles(i->tag,i->shape);
1647     swf_ShapeCountBits(i->shape,NULL,NULL);
1648     swf_SetShapeBits(i->tag,i->shape);
1649     swf_ShapeSetAll(i->tag,i->shape,/*x*/0,/*y*/0,0,fsid,0);
1650     i->swflastx = i->swflasty = 0;
1651     drawgfxline(dev, points);
1652     swf_ShapeSetEnd(i->tag);
1653
1654     /* shape2 */
1655     myshapeid2 = getNewID(dev);
1656     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE3);
1657     swf_ShapeNew(&i->shape);
1658     
1659     rgb = i->config_linkcolor;
1660
1661     fsid = swf_ShapeAddSolidFillStyle(i->shape,&rgb);
1662     swf_SetU16(i->tag, myshapeid2);
1663     r.xmin = (int)(bbox.xmin*20);
1664     r.ymin = (int)(bbox.ymin*20);
1665     r.xmax = (int)(bbox.xmax*20);
1666     r.ymax = (int)(bbox.ymax*20);
1667     swf_SetRect(i->tag,&r);
1668     swf_SetShapeStyles(i->tag,i->shape);
1669     swf_ShapeCountBits(i->shape,NULL,NULL);
1670     swf_SetShapeBits(i->tag,i->shape);
1671     swf_ShapeSetAll(i->tag,i->shape,/*x*/0,/*y*/0,0,fsid,0);
1672     i->swflastx = i->swflasty = 0;
1673     drawgfxline(dev, points);
1674     swf_ShapeSetEnd(i->tag);
1675
1676     if(!mouseover)
1677     {
1678         i->tag = swf_InsertTag(i->tag,ST_DEFINEBUTTON);
1679         swf_SetU16(i->tag,buttonid); //id
1680         swf_ButtonSetFlags(i->tag, 0); //menu=no
1681         swf_ButtonSetRecord(i->tag,0x01,myshapeid,i->depth,0,0);
1682         swf_ButtonSetRecord(i->tag,0x02,myshapeid2,i->depth,0,0);
1683         swf_ButtonSetRecord(i->tag,0x04,myshapeid2,i->depth,0,0);
1684         swf_ButtonSetRecord(i->tag,0x08,myshapeid,i->depth,0,0);
1685         swf_SetU8(i->tag,0);
1686         swf_ActionSet(i->tag,actions1);
1687         swf_SetU8(i->tag,0);
1688     }
1689     else
1690     {
1691         i->tag = swf_InsertTag(i->tag,ST_DEFINEBUTTON2);
1692         swf_SetU16(i->tag,buttonid); //id
1693         swf_ButtonSetFlags(i->tag, 0); //menu=no
1694         swf_ButtonSetRecord(i->tag,0x01,myshapeid,i->depth,0,0);
1695         swf_ButtonSetRecord(i->tag,0x02,myshapeid2,i->depth,0,0);
1696         swf_ButtonSetRecord(i->tag,0x04,myshapeid2,i->depth,0,0);
1697         swf_ButtonSetRecord(i->tag,0x08,myshapeid,i->depth,0,0);
1698         swf_SetU8(i->tag,0); // end of button records
1699         swf_ButtonSetCondition(i->tag, BC_IDLE_OVERUP);
1700         swf_ActionSet(i->tag,actions1);
1701         if(actions2) {
1702             swf_ButtonSetCondition(i->tag, BC_OVERUP_IDLE);
1703             swf_ActionSet(i->tag,actions2);
1704             swf_SetU8(i->tag,0);
1705             swf_ButtonPostProcess(i->tag, 2);
1706         } else {
1707             swf_SetU8(i->tag,0);
1708             swf_ButtonPostProcess(i->tag, 1);
1709         }
1710     }
1711     
1712     msg("<trace> Placing link ID %d", buttonid);
1713     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
1714
1715     if(posx!=0 || posy!=0) {
1716         SPOINT p;
1717         p.x = (int)(posx*20);
1718         p.y = (int)(posy*20);
1719         p = swf_TurnPoint(p, &i->page_matrix);
1720         MATRIX m;
1721         m = i->page_matrix;
1722         m.tx = p.x;
1723         m.ty = p.y;
1724         swf_ObjectPlace(i->tag, buttonid, getNewDepth(dev),&m,0,0);
1725     } else {
1726         swf_ObjectPlace(i->tag, buttonid, getNewDepth(dev),&i->page_matrix,0,0);
1727     }
1728 }
1729
1730       
1731 ///////////
1732 /*
1733 for(t=0;t<picpos;t++)
1734       {
1735           if(pic_xids[t] == xid &&
1736              pic_yids[t] == yid) {
1737               width = pic_width[t];
1738               height = pic_height[t];
1739               found = t;break;
1740           }
1741       }
1742           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, x1,y1,x2,y2,x3,y3,x4,y4, numpalette);
1743           pic_xids[picpos] = xid;
1744           pic_yids[picpos] = yid;
1745           pic_width[picpos] = width;
1746           pic_height[picpos] = height;
1747           if(picpos<1024)
1748               picpos++;
1749             pic[width*y+x] = buf[0];
1750             xid+=x*buf[0]+1;
1751             yid+=y*buf[0]*3+1;
1752       
1753             xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1754       yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1755       
1756       int xid = 0;
1757       int yid = 0;
1758           xid += x*r+x*b*3+x*g*7+x*a*11;
1759           yid += y*r*3+y*b*17+y*g*19+y*a*11;
1760       int t,found = -1;
1761       for(t=0;t<picpos;t++)
1762       {
1763           if(pic_xids[t] == xid &&
1764              pic_yids[t] == yid) {
1765               found = t;break;
1766           }
1767       }
1768       if(found<0) {
1769 */
1770 ///////////
1771
1772
1773 int swf_setparameter(gfxdevice_t*dev, const char*name, const char*value)
1774 {
1775     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1776
1777     msg("<trace> swfdevice: %s=%s", name, value);
1778     if(!strcmp(name, "jpegsubpixels")) {
1779         i->config_jpegsubpixels = atof(value);
1780     } else if(!strcmp(name, "ppmsubpixels")) {
1781         i->config_ppmsubpixels = atof(value);
1782     } else if(!strcmp(name, "subpixels")) {
1783         i->config_ppmsubpixels = i->config_jpegsubpixels = atof(value);
1784     } else if(!strcmp(name, "drawonlyshapes")) {
1785         i->config_drawonlyshapes = atoi(value);
1786     } else if(!strcmp(name, "ignoredraworder")) {
1787         i->config_ignoredraworder = atoi(value);
1788     } else if(!strcmp(name, "mark")) {
1789         if(!value || !value[0]) {
1790             if(i->mark) free(i->mark);
1791             i->mark = 0;
1792         } else {
1793             int t;
1794             i->mark = strdup("...");
1795             for(t=0;t<3;t++) if(value[t]) i->mark[t] = value[t];
1796         }
1797     } else if(!strcmp(name, "filloverlap")) {
1798         i->config_filloverlap = atoi(value);
1799     } else if(!strcmp(name, "linksopennewwindow")) {
1800         i->config_opennewwindow = atoi(value);
1801     } else if(!strcmp(name, "opennewwindow")) {
1802         i->config_opennewwindow = atoi(value);
1803     } else if(!strcmp(name, "storeallcharacters")) {
1804         i->config_storeallcharacters = atoi(value);
1805     } else if(!strcmp(name, "enablezlib")) {
1806         i->config_enablezlib = atoi(value);
1807     } else if(!strcmp(name, "bboxvars")) {
1808         i->config_bboxvars = atoi(value);
1809     } else if(!strcmp(name, "showclipshapes")) {
1810         i->config_showclipshapes = atoi(value);
1811     } else if(!strcmp(name, "reordertags")) {
1812         i->config_reordertags = atoi(value);
1813     } else if(!strcmp(name, "internallinkfunction")) {
1814         i->config_internallinkfunction = strdup(value);
1815     } else if(!strcmp(name, "externallinkfunction")) {
1816         i->config_externallinkfunction = strdup(value);
1817     } else if(!strcmp(name, "linkfunction")) { //sets both internallinkfunction and externallinkfunction
1818         i->config_internallinkfunction = strdup(value);
1819         i->config_externallinkfunction = strdup(value);
1820     } else if(!strcmp(name, "disable_polygon_conversion")) {
1821         i->config_disable_polygon_conversion = atoi(value);
1822     } else if(!strcmp(name, "normalize_polygon_positions")) {
1823         i->config_normalize_polygon_positions = atoi(value);
1824     } else if(!strcmp(name, "wxwindowparams")) {
1825         i->config_watermark = atoi(value);
1826     } else if(!strcmp(name, "insertstop")) {
1827         i->config_insertstoptag = atoi(value);
1828     } else if(!strcmp(name, "protect")) {
1829         i->config_protect = atoi(value);
1830         if(i->config_protect && i->tag) {
1831             i->tag = swf_InsertTag(i->tag, ST_PROTECT);
1832         }
1833     } else if(!strcmp(name, "flashversion")) {
1834         i->config_flashversion = atoi(value);
1835         if(i->swf) {
1836             i->swf->fileVersion = i->config_flashversion;
1837         }
1838     } else if(!strcmp(name, "framerate")) {
1839         i->config_framerate = atoi(value);
1840         if(i->swf) {
1841             i->swf->frameRate = i->config_framerate*0x100;
1842         }
1843     } else if(!strcmp(name, "minlinewidth")) {
1844         i->config_minlinewidth = atof(value);
1845     } else if(!strcmp(name, "caplinewidth")) {
1846         i->config_caplinewidth = atof(value);
1847     } else if(!strcmp(name, "linktarget")) {
1848         i->config_linktarget = strdup(value);
1849     } else if(!strcmp(name, "dumpfonts")) {
1850         i->config_dumpfonts = atoi(value);
1851     } else if(!strcmp(name, "animate")) {
1852         i->config_animate = atoi(value);
1853     } else if(!strcmp(name, "next_bitmap_is_jpeg")) {
1854         i->jpeg = 1;
1855     } else if(!strcmp(name, "jpegquality")) {
1856         int val = atoi(value);
1857         if(val<0) val=0;
1858         if(val>101) val=101;
1859         i->config_jpegquality = val;
1860     } else if(!strcmp(name, "splinequality")) {
1861         int v = atoi(value);
1862         v = 500-(v*5); // 100% = 0.25 pixel, 0% = 25 pixel
1863         if(v<1) v = 1;
1864         i->config_splinemaxerror = v;
1865     } else if(!strcmp(name, "fontquality")) {
1866         int v = atoi(value);
1867         v = 500-(v*5); // 100% = 0.25 pixel, 0% = 25 pixel
1868         if(v<1) v = 1;
1869         i->config_fontsplinemaxerror = v;
1870     } else if(!strcmp(name, "linkcolor")) {
1871         if(strlen(value)!=8) {
1872             fprintf(stderr, "Unknown format for option 'linkcolor'. (%s <-> RRGGBBAA)\n", value);
1873             return 1;
1874         }
1875 #       define NIBBLE(s) (((s)>='0' && (s)<='9')?((s)-'0'):((s)&0x0f)+9)
1876         i->config_linkcolor.r = NIBBLE(value[0])<<4 | NIBBLE(value[1]);
1877         i->config_linkcolor.g = NIBBLE(value[2])<<4 | NIBBLE(value[3]);
1878         i->config_linkcolor.b = NIBBLE(value[4])<<4 | NIBBLE(value[5]);
1879         i->config_linkcolor.a = NIBBLE(value[6])<<4 | NIBBLE(value[7]);
1880     } else if(!strcmp(name, "help")) {
1881         printf("\nSWF layer options:\n");
1882         printf("jpegdpi=<dpi>               resolution adjustment for jpeg images\n");
1883         printf("jpegsubpixels=<pixels>      resolution adjustment for jpeg images (same as jpegdpi, but in pixels)\n");
1884         printf("ppmdpi=<dpi>                resolution adjustment for lossless images\n");
1885         printf("ppmsubpixels=<pixels        resolution adjustment for  lossless images (same as ppmdpi, but in pixels)\n");
1886         printf("subpixels=<pixels>          shortcut for setting both jpegsubpixels and ppmsubpixels\n");
1887         printf("drawonlyshapes              convert everything to shapes (currently broken)\n");
1888         printf("ignoredraworder             allow to perform a few optimizations for creating smaller SWFs\n");
1889         printf("linksopennewwindow          make links open a new browser window\n");
1890         printf("linktarget                  target window name of new links\n");
1891         printf("linkcolor=<color)           color of links (format: RRGGBBAA)\n");
1892         printf("storeallcharacters          don't reduce the fonts to used characters in the output file\n");
1893         printf("enablezlib                  switch on zlib compression (also done if flashversion>=7)\n");
1894         printf("bboxvars                    store the bounding box of the SWF file in actionscript variables\n");
1895         printf("reordertags=0/1             (default: 1) perform some tag optimizations\n");
1896         printf("internallinkfunction=<name> when the user clicks a internal link (to a different page) in the converted file, this actionscript function is called\n");
1897         printf("externallinkfunction=<name> when the user clicks an external link (e.g. http://www.foo.bar/) on the converted file, this actionscript function is called\n");
1898         printf("disable_polygon_conversion  never convert strokes to polygons (will remove capstyles and joint styles)\n");
1899         printf("caplinewidth=<width>        the minimum thichness a line needs to have so that capstyles become visible (and are converted)\n");
1900         printf("insertstop                  put an ActionScript \"STOP\" tag in every frame\n");
1901         printf("protect                     add a \"protect\" tag to the file, to prevent loading in the Flash editor\n");
1902         printf("flashversion=<version>      the SWF fileversion (6)\n");
1903         printf("minlinewidth=<width>        convert horizontal/vertical boxes smaller than this width to lines (0.05) \n");
1904         printf("animate                     insert a showframe tag after each placeobject (animate draw order of PDF files)\n");
1905         printf("jpegquality=<quality>       set compression quality of jpeg images\n");
1906     } else {
1907         return 0;
1908     }
1909     return 1;
1910 }
1911
1912 // --------------------------------------------------------------------
1913
1914 static CXFORM gfxcxform_to_cxform(gfxcxform_t* c)
1915 {
1916     CXFORM cx;
1917     swf_GetCXForm(0, &cx, 1);
1918     if(!c)
1919         return cx;
1920     if(c->rg!=0 || c->rb!=0 || c->ra!=0 ||
1921        c->gr!=0 || c->gb!=0 || c->ga!=0 ||
1922        c->br!=0 || c->bg!=0 || c->ba!=0 ||
1923        c->ar!=0 || c->ag!=0 || c->ab!=0)
1924         msg("<warning> CXForm not SWF-compatible");
1925
1926     cx.a0 = (S16)(c->aa*256);
1927     cx.r0 = (S16)(c->rr*256);
1928     cx.g0 = (S16)(c->gg*256);
1929     cx.b0 = (S16)(c->bb*256);
1930     cx.a1 = c->ta;
1931     cx.r1 = c->tr;
1932     cx.g1 = c->tg;
1933     cx.b1 = c->tb;
1934     return cx;
1935 }
1936
1937 /* TODO */
1938 static int imageInCache(gfxdevice_t*dev, void*data, int width, int height)
1939 {
1940     return -1;
1941 }
1942 static void addImageToCache(gfxdevice_t*dev, void*data, int width, int height)
1943 {
1944 }
1945     
1946 static int add_image(swfoutput_internal*i, gfximage_t*img, int targetwidth, int targetheight, int* newwidth, int* newheight)
1947 {
1948     gfxdevice_t*dev = i->dev;
1949     RGBA*newpic = 0;
1950     RGBA*mem = (RGBA*)img->data;
1951     
1952     int sizex = img->width;
1953     int sizey = img->height;
1954     int is_jpeg = i->jpeg;
1955     i->jpeg = 0;
1956
1957     int newsizex=sizex, newsizey=sizey;
1958
1959     /// {
1960     if(is_jpeg && i->config_jpegsubpixels) {
1961         newsizex = (int)(targetwidth*i->config_jpegsubpixels + 0.5);
1962         newsizey = (int)(targetheight*i->config_jpegsubpixels + 0.5);
1963     } else if(!is_jpeg && i->config_ppmsubpixels) {
1964         newsizex = (int)(targetwidth*i->config_ppmsubpixels + 0.5);
1965         newsizey = (int)(targetheight*i->config_ppmsubpixels + 0.5);
1966     }
1967     /// }
1968
1969     if(sizex<=0 || sizey<=0)
1970         return -1;
1971     if(newsizex<=0)
1972         newsizex = 1;
1973     if(newsizey<=0)
1974         newsizey = 1;
1975
1976     /* TODO: cache images */
1977     
1978     if(newsizex<sizex || newsizey<sizey) {
1979         msg("<verbose> Scaling %dx%d image to %dx%d", sizex, sizey, newsizex, newsizey);
1980         newpic = swf_ImageScale(mem, sizex, sizey, newsizex, newsizey);
1981         *newwidth = sizex = newsizex;
1982         *newheight  = sizey = newsizey;
1983         mem = newpic;
1984     } else {
1985         *newwidth = newsizex = sizex;
1986         *newheight = newsizey  = sizey;
1987     }
1988
1989     int num_colors = swf_ImageGetNumberOfPaletteEntries(mem,sizex,sizey,0);
1990     int has_alpha = swf_ImageHasAlpha(mem,sizex,sizey);
1991     
1992     msg("<verbose> Drawing %dx%d %s%simage (id %d) at size %dx%d (%dx%d), %s%d colors",
1993             sizex, sizey, 
1994             has_alpha?(has_alpha==2?"semi-transparent ":"transparent "):"", 
1995             is_jpeg?"jpeg-":"", i->currentswfid+1,
1996             newsizex, newsizey,
1997             targetwidth, targetheight,
1998             /*newsizex, newsizey,*/
1999             num_colors>256?">":"", num_colors>256?256:num_colors);
2000
2001     /*RGBA* pal = (RGBA*)rfx_alloc(sizeof(RGBA)*num_colors);
2002     swf_ImageGetNumberOfPaletteEntries(mem,sizex,sizey,pal);
2003     int t;
2004     for(t=0;t<num_colors;t++) {
2005         printf("%02x%02x%02x%02x ",
2006                 pal[t].r, pal[t].g, pal[t].b, pal[t].a);
2007         if((t&7)==7)
2008             printf("\n");
2009     }
2010     printf("\n");*/
2011
2012     int bitid = -1;
2013     int cacheid = imageInCache(dev, mem, sizex, sizey);
2014
2015     if(cacheid<=0) {
2016         bitid = getNewID(dev);
2017         i->tag = swf_AddImage(i->tag, bitid, mem, sizex, sizey, i->config_jpegquality);
2018         addImageToCache(dev, mem, sizex, sizey);
2019     } else {
2020         bitid = cacheid;
2021     }
2022
2023     if(newpic)
2024         free(newpic);
2025     return bitid;
2026 }
2027
2028 static SRECT gfxline_getSWFbbox(gfxline_t*line)
2029 {
2030     gfxbbox_t bbox = gfxline_getbbox(line);
2031     SRECT r;
2032     r.xmin = (int)(bbox.xmin*20);
2033     r.ymin = (int)(bbox.ymin*20);
2034     r.xmax = (int)(bbox.xmax*20);
2035     r.ymax = (int)(bbox.ymax*20);
2036     return r;
2037 }
2038
2039 int line_is_empty(gfxline_t*line)
2040 {
2041     while(line) {
2042         if(line->type != gfx_moveTo)
2043             return 0;
2044         line = line->next;
2045     }
2046     return 1;
2047 }
2048
2049 static void swf_fillbitmap(gfxdevice_t*dev, gfxline_t*line, gfximage_t*img, gfxmatrix_t*matrix, gfxcxform_t*cxform)
2050 {
2051     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2052     
2053     if(line_is_empty(line))
2054         return;
2055
2056     endshape(dev);
2057     endtext(dev);
2058
2059     int targetx = (int)(sqrt(matrix->m00*matrix->m00 + matrix->m01*matrix->m01)*img->width);
2060     int targety = (int)(sqrt(matrix->m10*matrix->m10 + matrix->m11*matrix->m11)*img->height);
2061
2062     int newwidth=0,newheight=0;
2063     int bitid = add_image(i, img, targetx, targety, &newwidth, &newheight);
2064     if(bitid<0)
2065         return;
2066     double fx = (double)img->width / (double)newwidth;
2067     double fy = (double)img->height / (double)newheight;
2068
2069     MATRIX m;
2070     m.sx = (int)(65536*20*matrix->m00*fx); m.r1 = (int)(65536*20*matrix->m10*fy);
2071     m.r0 = (int)(65536*20*matrix->m01*fx); m.sy = (int)(65536*20*matrix->m11*fy);
2072     m.tx = (int)(matrix->tx*20);
2073     m.ty = (int)(matrix->ty*20);
2074   
2075     /* shape */
2076     int myshapeid = getNewID(dev);
2077     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE);
2078     SHAPE*shape;
2079     swf_ShapeNew(&shape);
2080     int fsid = swf_ShapeAddBitmapFillStyle(shape,&m,bitid,1);
2081     swf_SetU16(i->tag, myshapeid);
2082     SRECT r = gfxline_getSWFbbox(line);
2083     swf_SetRect(i->tag,&r);
2084     swf_SetShapeStyles(i->tag,shape);
2085     swf_ShapeCountBits(shape,NULL,NULL);
2086     swf_SetShapeBits(i->tag,shape);
2087     swf_ShapeSetAll(i->tag,shape,UNDEFINED_COORD,UNDEFINED_COORD,0,fsid,0);
2088     i->swflastx = i->swflasty = UNDEFINED_COORD;
2089     drawgfxline(dev, line);
2090     swf_ShapeSetEnd(i->tag);
2091     swf_ShapeFree(shape);
2092
2093     msg("<trace> Placing image, shape ID %d, bitmap ID %d", myshapeid, bitid);
2094     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
2095     CXFORM cxform2 = gfxcxform_to_cxform(cxform);
2096     swf_ObjectPlace(i->tag,myshapeid,getNewDepth(dev),&i->page_matrix,&cxform2,NULL);
2097 }
2098
2099 static RGBA col_black = {255,0,0,0};
2100
2101 static void drawoutline(gfxdevice_t*dev, gfxline_t*line)
2102 {
2103     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2104
2105     int myshapeid = getNewID(dev);
2106     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE3);
2107
2108     SHAPE*shape;
2109     swf_ShapeNew(&shape);
2110     int lsid = swf_ShapeAddLineStyle(shape,1,&col_black);
2111
2112     swf_SetU16(i->tag,myshapeid);
2113     SRECT r = gfxline_getSWFbbox(line);
2114     swf_SetRect(i->tag,&r);
2115     swf_SetShapeStyles(i->tag,shape);
2116     swf_ShapeCountBits(shape,NULL,NULL);
2117     swf_SetShapeBits(i->tag,shape);
2118     swf_ShapeSetAll(i->tag,shape,UNDEFINED_COORD,UNDEFINED_COORD,lsid,0,0);
2119     drawgfxline(dev, line);
2120     swf_ShapeSetEnd(i->tag);
2121     swf_ShapeFree(shape);
2122         
2123     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
2124     swf_ObjectPlace(i->tag, myshapeid, getNewDepth(dev), 0,0,0);
2125 }
2126
2127 static void swf_startclip(gfxdevice_t*dev, gfxline_t*line)
2128 {
2129     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2130
2131     endtext(dev);
2132     endshape(dev);
2133
2134     if(i->clippos >= 127)
2135     {
2136         msg("<warning> Too many clip levels.");
2137         i->clippos --;
2138     } 
2139
2140     if(i->config_showclipshapes)
2141         drawoutline(dev, line);
2142
2143     int myshapeid = getNewID(dev);
2144     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE3);
2145     RGBA col;
2146     memset(&col, 0, sizeof(RGBA));
2147     col.a = 255;
2148     SHAPE*shape;
2149     swf_ShapeNew(&shape);
2150     int fsid = swf_ShapeAddSolidFillStyle(shape,&col);
2151     if(i->mark) {
2152         RGBA markcol = {0,i->mark[0],i->mark[1],i->mark[2]};
2153         swf_ShapeAddSolidFillStyle(shape,&markcol);
2154     }
2155     swf_SetU16(i->tag,myshapeid);
2156     SRECT r = gfxline_getSWFbbox(line);
2157     swf_SetRect(i->tag,&r);
2158     swf_SetShapeStyles(i->tag,shape);
2159     swf_ShapeCountBits(shape,NULL,NULL);
2160     swf_SetShapeBits(i->tag,shape);
2161     swf_ShapeSetAll(i->tag,shape,UNDEFINED_COORD,UNDEFINED_COORD,0,fsid,0);
2162     i->swflastx = i->swflasty = UNDEFINED_COORD;
2163     i->shapeisempty = 1;
2164     drawgfxline(dev, line);
2165     if(i->shapeisempty) {
2166         /* an empty clip shape is equivalent to a shape with no area */
2167         int x = line?line->x:0;
2168         int y = line?line->y:0;
2169         moveto(dev, i->tag, x,y);
2170         lineto(dev, i->tag, x,y);
2171         lineto(dev, i->tag, x,y);
2172     }
2173     if(!i->shapeisempty && i->currentswfid==1 && r.xmin==0 && r.ymin==0 && r.xmax==(int)(i->max_x*20) && r.ymax==(int)(i->max_y*20)) {
2174         if(i->config_watermark) {
2175             gfxbbox_t r; r.xmin = r.ymin = 0;r.xmax = i->max_x;r.ymax = i->max_y;
2176             draw_watermark(dev, r, 1);
2177         }
2178     }
2179     swf_ShapeSetEnd(i->tag);
2180     swf_ShapeFree(shape);
2181
2182     /* TODO: remember the bbox, and check all shapes against it */
2183     
2184     msg("<trace> Placing clip ID %d", myshapeid);
2185     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
2186     i->cliptags[i->clippos] = i->tag;
2187     i->clipshapes[i->clippos] = myshapeid;
2188     i->clipdepths[i->clippos] = getNewDepth(dev);
2189     i->clippos++;
2190 }
2191
2192 static void swf_endclip(gfxdevice_t*dev)
2193 {
2194     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2195     if(i->textid>=0)
2196         endtext(dev);
2197     if(i->shapeid>=0)
2198         endshape(dev);
2199
2200     if(!i->clippos) {
2201         msg("<error> Invalid end of clipping region");
2202         return;
2203     }
2204     i->clippos--;
2205     /*swf_ObjectPlaceClip(i->cliptags[i->clippos],i->clipshapes[i->clippos],i->clipdepths[i->clippos],&i->page_matrix,NULL,NULL,
2206             / * clip to depth: * / i->depth <= i->clipdepths[i->clippos]? i->depth : i->depth - 1);
2207     i->depth ++;*/
2208     swf_ObjectPlaceClip(i->cliptags[i->clippos],i->clipshapes[i->clippos],i->clipdepths[i->clippos],&i->page_matrix,NULL,NULL,i->depth);
2209 }
2210 static int gfxline_type(gfxline_t*line)
2211 {
2212     int tmplines=0;
2213     int tmpsplines=0;
2214     int lines=0;
2215     int splines=0;
2216     int haszerosegments=0;
2217     int length=0;
2218     while(line) {
2219         if(line->type == gfx_moveTo) {
2220             tmplines=0;
2221             tmpsplines=0;
2222         } else if(line->type == gfx_lineTo) {
2223             tmplines++;
2224             if(tmplines>lines)
2225                 lines=tmplines;
2226         } else if(line->type == gfx_splineTo) {
2227             tmpsplines++;
2228             if(tmpsplines>lines)
2229                 splines=tmpsplines;
2230         }
2231         length++;
2232         line = line->next;
2233     }
2234     if(length>400)
2235         return 5;
2236     if(lines==0 && splines==0) return 0;
2237     else if(lines==1 && splines==0) return 1;
2238     else if(lines==0 && splines==1) return 2;
2239     else if(splines==0) return 3;
2240     else return 4;
2241 }
2242
2243 static int gfxline_has_dots(gfxline_t*line)
2244 {
2245     int tmplines=0;
2246     double x=0,y=0;
2247     double dist = 0;
2248     int isline = 0;
2249     int short_gap = 0;
2250     while(line) {
2251         if(line->type == gfx_moveTo) {
2252             /* test the length of the preceding line, and assume it is a dot if
2253                it's length is less than 1.0. But *only* if there's a noticable 
2254                gap between the previous line and the next moveTo. (I've come
2255                across a PDF where thousands of "dots" were stringed together,
2256                forming a line) */
2257             int last_short_gap = short_gap;
2258             if((fabs(line->x - x) + fabs(line->y - y)) < 1.0) {
2259                 short_gap = 1;
2260             } else {
2261                 short_gap = 0;
2262             }
2263             if(isline && dist < 1 && !short_gap && !last_short_gap) {
2264                 return 1;
2265             }
2266             dist = 0;
2267             isline = 0;
2268         } else if(line->type == gfx_lineTo) {
2269             dist += fabs(line->x - x) + fabs(line->y - y);
2270             isline = 1;
2271         } else if(line->type == gfx_splineTo) {
2272             dist += fabs(line->sx - x) + fabs(line->sy - y) + 
2273                     fabs(line->x - line->sx) + fabs(line->y - line->sy);
2274             isline = 1;
2275         }
2276         x = line->x;
2277         y = line->y;
2278         line = line->next;
2279     }
2280     if(isline && dist < 1 && !short_gap) {
2281         return 1;
2282     }
2283     return 0;
2284 }
2285
2286 static int gfxline_fix_short_edges(gfxline_t*line)
2287 {
2288     double x,y;
2289     while(line) {
2290         if(line->type == gfx_lineTo) {
2291             if(fabs(line->x - x) + fabs(line->y - y) < 0.01) {
2292                 line->x += 0.01;
2293             }
2294         } else if(line->type == gfx_splineTo) {
2295             if(fabs(line->sx - x) + fabs(line->sy - y) + 
2296                fabs(line->x - line->sx) + fabs(line->y - line->sy) < 0.01) {
2297                 line->x += 0.01;
2298             }
2299         }
2300         x = line->x;
2301         y = line->y;
2302         line = line->next;
2303     }
2304     return 0;
2305 }
2306
2307 static char is_inside_page(gfxdevice_t*dev, gfxcoord_t x, gfxcoord_t y)
2308 {
2309     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2310     if(x<i->min_x || x>i->max_x) return 0;
2311     if(y<i->min_y || y>i->max_y) return 0;
2312     return 1;
2313 }
2314
2315 gfxline_t* gfxline_move(gfxline_t*line, double x, double y)
2316 {
2317     gfxline_t*l = line = gfxline_clone(line);
2318
2319     while(l) {
2320         l->x += x;
2321         l->y += y;
2322         l->sx += x;
2323         l->sy += y;
2324         l = l->next;
2325     }
2326     return line;
2327 }
2328
2329 //#define NORMALIZE_POLYGON_POSITIONS
2330
2331 static void swf_stroke(gfxdevice_t*dev, gfxline_t*line, gfxcoord_t width, gfxcolor_t*color, gfx_capType cap_style, gfx_joinType joint_style, gfxcoord_t miterLimit)
2332 {
2333     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2334     if(line_is_empty(line))
2335         return;
2336     int type = gfxline_type(line);
2337     int has_dots = gfxline_has_dots(line);
2338     gfxbbox_t r = gfxline_getbbox(line);
2339     int is_outside_page = !is_inside_page(dev, r.xmin, r.ymin) || !is_inside_page(dev, r.xmax, r.ymax);
2340
2341     /* TODO: * split line into segments, and perform this check for all segments */
2342
2343     if(i->config_disable_polygon_conversion || type>=5 ||
2344        (!has_dots &&
2345         (width <= i->config_caplinewidth 
2346         || (cap_style == gfx_capRound && joint_style == gfx_joinRound)
2347         || (cap_style == gfx_capRound && type<=2)))) {} else 
2348     {
2349         /* convert line to polygon */
2350         msg("<trace> draw as polygon, type=%d dots=%d", type, has_dots);
2351         if(has_dots)
2352             gfxline_fix_short_edges(line);
2353         /* we need to convert the line into a polygon */
2354         gfxpoly_t* poly = gfxpoly_strokeToPoly(line, width, cap_style, joint_style, miterLimit);
2355         gfxline_t*gfxline = gfxpoly_to_gfxline(poly);
2356         dev->fill(dev, gfxline, color);
2357         gfxline_free(gfxline);
2358         gfxpoly_free(poly);
2359         return;
2360     }
2361
2362     msg("<trace> draw as stroke, type=%d dots=%d", type, has_dots);
2363     endtext(dev);
2364
2365     if(i->config_normalize_polygon_positions) {
2366         endshape(dev);
2367         double startx = 0, starty = 0;
2368         if(line && line->type == gfx_moveTo) {
2369             startx = line->x;
2370             starty = line->y;
2371         }
2372         line = gfxline_move(line, -startx, -starty);
2373         i->shapeposx = (int)(startx*20);
2374         i->shapeposy = (int)(starty*20);
2375     }
2376
2377     swfoutput_setstrokecolor(dev, color->r, color->g, color->b, color->a);
2378     swfoutput_setlinewidth(dev, width);
2379     startshape(dev);
2380     stopFill(dev);
2381     drawgfxline(dev, line);
2382
2383     if(i->config_normalize_polygon_positions) {
2384         free(line); //account for _move
2385     }
2386
2387 }
2388
2389 static void swf_fill(gfxdevice_t*dev, gfxline_t*line, gfxcolor_t*color)
2390 {
2391     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2392     if(line_is_empty(line))
2393         return;
2394     if(!color->a)
2395         return;
2396     gfxbbox_t r = gfxline_getbbox(line);
2397     int is_outside_page = !is_inside_page(dev, r.xmin, r.ymin) || !is_inside_page(dev, r.xmax, r.ymax);
2398
2399     //if(i->chardatapos && i->chardata[i->chardatapos-1].color.a) {
2400     endtext(dev);
2401
2402     if(!i->config_ignoredraworder)
2403         endshape(dev);
2404
2405     if(i->config_normalize_polygon_positions) {
2406         endshape(dev);
2407         double startx = 0, starty = 0;
2408         if(line && line->type == gfx_moveTo) {
2409             startx = line->x;
2410             starty = line->y;
2411         }
2412         line = gfxline_move(line, -startx, -starty);
2413         i->shapeposx = (int)(startx*20);
2414         i->shapeposy = (int)(starty*20);
2415     }
2416
2417     swfoutput_setfillcolor(dev, color->r, color->g, color->b, color->a);
2418     startshape(dev);
2419     startFill(dev);
2420     i->fill=1;
2421     drawgfxline(dev, line);
2422     
2423     if(i->currentswfid==2 && r.xmin==0 && r.ymin==0 && r.xmax==i->max_x && r.ymax==i->max_y) {
2424         if(i->config_watermark) {
2425             draw_watermark(dev, r, 1);
2426         }
2427     }
2428
2429     msg("<trace> end of swf_fill (shapeid=%d)", i->shapeid);
2430
2431     if(i->config_normalize_polygon_positions) {
2432         free(line); //account for _move
2433     }
2434 }
2435
2436 static GRADIENT* gfxgradient_to_GRADIENT(gfxgradient_t*gradient)
2437 {
2438     int num = 0;
2439     gfxgradient_t*g = gradient;
2440     while(g) {
2441         num++;
2442         g = g->next;
2443     }
2444     GRADIENT* swfgradient = malloc(sizeof(GRADIENT));
2445     swfgradient->num = num;
2446     swfgradient->rgba = malloc(sizeof(swfgradient->rgba[0])*num);
2447     swfgradient->ratios = malloc(sizeof(swfgradient->ratios[0])*num);
2448
2449     g = gradient;
2450     num = 0;
2451     while(g) {
2452         swfgradient->ratios[num] = g->pos*255;
2453         swfgradient->rgba[num] = *(RGBA*)&g->color;
2454         num++;
2455         g = g->next;
2456     }
2457     return swfgradient;
2458 }
2459
2460 static void swf_fillgradient(gfxdevice_t*dev, gfxline_t*line, gfxgradient_t*gradient, gfxgradienttype_t type, gfxmatrix_t*matrix)
2461 {
2462     if(line_is_empty(line))
2463         return;
2464     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2465     
2466     if(line_is_empty(line))
2467         return;
2468
2469     GRADIENT* swfgradient = gfxgradient_to_GRADIENT(gradient);
2470     if(!swfgradient)
2471         return;
2472   
2473     endshape(dev);
2474     endtext(dev);
2475
2476     double f = type==gfxgradient_radial?4:4;
2477     MATRIX m;
2478     m.sx = (int)(matrix->m00*20*f); m.r1 = (int)(matrix->m10*20*f);
2479     m.r0 = (int)(matrix->m01*20*f); m.sy = (int)(matrix->m11*20*f);
2480     m.tx = (int)(matrix->tx*20);
2481     m.ty = (int)(matrix->ty*20);
2482
2483     /* shape */
2484     int myshapeid = getNewID(dev);
2485     i->tag = swf_InsertTag(i->tag, ST_DEFINESHAPE2);
2486     SHAPE*shape;
2487     swf_ShapeNew(&shape);
2488     int fsid = swf_ShapeAddGradientFillStyle(shape,&m,swfgradient,type==gfxgradient_radial);
2489     swf_SetU16(i->tag, myshapeid);
2490     SRECT r = gfxline_getSWFbbox(line);
2491     swf_SetRect(i->tag,&r);
2492     swf_SetShapeStyles(i->tag,shape);
2493     swf_ShapeCountBits(shape,NULL,NULL);
2494     swf_SetShapeBits(i->tag,shape);
2495     swf_ShapeSetAll(i->tag,shape,UNDEFINED_COORD,UNDEFINED_COORD,0,fsid,0);
2496     i->swflastx = i->swflasty = UNDEFINED_COORD;
2497     drawgfxline(dev, line);
2498     swf_ShapeSetEnd(i->tag);
2499     swf_ShapeFree(shape);
2500
2501     int depth = getNewDepth(dev);
2502     msg("<trace> Placing gradient, shape ID %d, depth %d", myshapeid, depth);
2503     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
2504     swf_ObjectPlace(i->tag,myshapeid,depth,&i->page_matrix,NULL,NULL);
2505
2506     swf_FreeGradient(swfgradient);free(swfgradient);
2507 }
2508
2509 static SWFFONT* gfxfont_to_swffont(gfxfont_t*font, const char* id)
2510 {
2511     SWFFONT*swffont = (SWFFONT*)rfx_calloc(sizeof(SWFFONT));
2512     int t;
2513     SRECT bounds = {0,0,0,0};
2514     swffont->id = -1;
2515     swffont->version = 2;
2516     swffont->name = (U8*)strdup(id);
2517     swffont->layout = (SWFLAYOUT*)rfx_calloc(sizeof(SWFLAYOUT));
2518     swffont->layout->ascent = 0; /* ? */
2519     swffont->layout->descent = 0;
2520     swffont->layout->leading = 0;
2521     swffont->layout->bounds = (SRECT*)rfx_calloc(sizeof(SRECT)*font->num_glyphs);
2522     swffont->encoding = FONT_ENCODING_UNICODE;
2523     swffont->numchars = font->num_glyphs;
2524     swffont->maxascii = font->max_unicode;
2525     swffont->ascii2glyph = (int*)rfx_calloc(sizeof(int)*swffont->maxascii);
2526     swffont->glyph2ascii = (U16*)rfx_calloc(sizeof(U16)*swffont->numchars);
2527     swffont->glyph = (SWFGLYPH*)rfx_calloc(sizeof(SWFGLYPH)*swffont->numchars);
2528     swffont->glyphnames = (char**)rfx_calloc(sizeof(char*)*swffont->numchars);
2529     for(t=0;t<font->max_unicode;t++) {
2530         swffont->ascii2glyph[t] = font->unicode2glyph[t];
2531     }
2532     for(t=0;t<font->num_glyphs;t++) {
2533         drawer_t draw;
2534         gfxline_t*line;
2535         int advance = 0;
2536         swffont->glyph2ascii[t] = font->glyphs[t].unicode;
2537         if(swffont->glyph2ascii[t] == 0xffff || swffont->glyph2ascii[t] == 0x0000) {
2538             /* flash 8 flashtype requires unique unicode IDs for each character.
2539                We use the Unicode private user area to assign characters, hoping that
2540                the font doesn't contain more than 2048 glyphs */
2541             swffont->glyph2ascii[t] = 0xe000 + (t&0x1fff);
2542         }
2543
2544         if(font->glyphs[t].name) {
2545             swffont->glyphnames[t] = strdup(font->glyphs[t].name);
2546         } else {
2547             swffont->glyphnames[t] = 0;
2548         }
2549         advance = (int)(font->glyphs[t].advance);
2550
2551         swf_Shape01DrawerInit(&draw, 0);
2552         line = font->glyphs[t].line;
2553         while(line) {
2554             FPOINT c,to;
2555             c.x = line->sx * GLYPH_SCALE; c.y = line->sy * GLYPH_SCALE;
2556             to.x = line->x * GLYPH_SCALE; to.y = line->y * GLYPH_SCALE;
2557             if(line->type == gfx_moveTo) {
2558                 draw.moveTo(&draw, &to);
2559             } else if(line->type == gfx_lineTo) {
2560                 draw.lineTo(&draw, &to);
2561             } else if(line->type == gfx_splineTo) {
2562                 draw.splineTo(&draw, &c, &to);
2563             }
2564             line = line->next;
2565         }
2566         draw.finish(&draw);
2567         swffont->glyph[t].shape = swf_ShapeDrawerToShape(&draw);
2568         swffont->layout->bounds[t] = swf_ShapeDrawerGetBBox(&draw);
2569
2570         int xmax = swffont->layout->bounds[t].xmax / 20;
2571         if(xmax>0 && xmax*2 < advance) {
2572             printf("fix bad advance value: bbox=%d, advance=%d (%f)\n", xmax, advance, font->glyphs[t].advance);
2573             advance = xmax;
2574         }
2575             
2576         if(advance<32768/20) {
2577             swffont->glyph[t].advance = advance*20;
2578         } else {
2579             swffont->glyph[t].advance = 32767;
2580         }
2581
2582         draw.dealloc(&draw);
2583
2584         swf_ExpandRect2(&bounds, &swffont->layout->bounds[t]);
2585     }
2586     if(bounds.ymin < 0 && bounds.ymax > 0) {
2587         swffont->layout->ascent = -bounds.ymin;
2588         swffont->layout->descent = bounds.ymax;
2589         swffont->layout->leading = bounds.ymax - bounds.ymin;
2590     } else {
2591         swffont->layout->ascent = (bounds.ymax - bounds.ymin)/2;
2592         swffont->layout->descent = (bounds.ymax - bounds.ymin)/2;
2593         swffont->layout->leading = bounds.ymax - bounds.ymin;
2594     }
2595     swffont->layout->descent= (bounds.ymax - bounds.ymin);
2596     swffont->layout->ascent = 0;
2597     swffont->layout->leading = bounds.ymax - bounds.ymin;
2598
2599     return swffont;
2600 }
2601
2602 static void swf_addfont(gfxdevice_t*dev, gfxfont_t*font)
2603 {
2604     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2605
2606     if(i->swffont && i->swffont->name && !strcmp((char*)i->swffont->name,font->id))
2607         return; // the requested font is the current font
2608     
2609     fontlist_t*last=0,*l = i->fontlist;
2610     while(l) {
2611         last = l;
2612         if(!strcmp((char*)l->swffont->name, font->id)) {
2613             return; // we already know this font
2614         }
2615         l = l->next;
2616     }
2617     l = (fontlist_t*)rfx_calloc(sizeof(fontlist_t));
2618     l->swffont = gfxfont_to_swffont(font, font->id);
2619     l->next = 0;
2620     if(last) {
2621         last->next = l;
2622     } else {
2623         i->fontlist = l;
2624     }
2625     swf_FontSetID(l->swffont, getNewID(i->dev));
2626
2627     if(getScreenLogLevel() >= LOGLEVEL_DEBUG)  {
2628         int iii;
2629         // print font information
2630         msg("<debug> Font %s",font->id);
2631         msg("<debug> |   ID: %d", l->swffont->id);
2632         msg("<debug> |   Version: %d", l->swffont->version);
2633         msg("<debug> |   Name: %s", l->swffont->name);
2634         msg("<debug> |   Numchars: %d", l->swffont->numchars);
2635         msg("<debug> |   Maxascii: %d", l->swffont->maxascii);
2636         msg("<debug> |   Style: %d", l->swffont->style);
2637         msg("<debug> |   Encoding: %d", l->swffont->encoding);
2638         for(iii=0; iii<l->swffont->numchars;iii++) {
2639             msg("<debug> |   Glyph %d) name=%s, unicode=%d size=%d bbox=(%.2f,%.2f,%.2f,%.2f)\n", iii, l->swffont->glyphnames?l->swffont->glyphnames[iii]:"<nonames>", l->swffont->glyph2ascii[iii], l->swffont->glyph[iii].shape->bitlen, 
2640                     l->swffont->layout->bounds[iii].xmin/20.0,
2641                     l->swffont->layout->bounds[iii].ymin/20.0,
2642                     l->swffont->layout->bounds[iii].xmax/20.0,
2643                     l->swffont->layout->bounds[iii].ymax/20.0
2644                     );
2645             int t;
2646             for(t=0;t<l->swffont->maxascii;t++) {
2647                 if(l->swffont->ascii2glyph[t] == iii)
2648                     msg("<debug> | - maps to %d",t);
2649             }
2650         }
2651     }
2652 }
2653
2654 static void swf_switchfont(gfxdevice_t*dev, const char*fontid)
2655 {
2656     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2657
2658     if(i->swffont && i->swffont->name && !strcmp((char*)i->swffont->name,fontid))
2659         return; // the requested font is the current font
2660     
2661     fontlist_t*l = i->fontlist;
2662     while(l) {
2663         if(!strcmp((char*)l->swffont->name, fontid)) {
2664             i->swffont = l->swffont;
2665             return; //done!
2666         }
2667         l = l->next;
2668     }
2669     msg("<error> Unknown font id: %s", fontid);
2670     return;
2671 }
2672
2673 static void swf_drawchar(gfxdevice_t*dev, gfxfont_t*font, int glyph, gfxcolor_t*color, gfxmatrix_t*matrix)
2674 {
2675     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2676     if(!font) {
2677         msg("<error> swf_drawchar called (glyph %d) without font", glyph);
2678         return;
2679     }
2680     if(!i->swffont || !i->swffont->name || strcmp((char*)i->swffont->name,font->id)) // not equal to current font
2681     {
2682         /* TODO: remove the need for this (enhance getcharacterbbox so that it can cope
2683                  with multiple fonts */
2684         endtext(dev);
2685         swf_switchfont(dev, font->id); // set the current font
2686     }
2687     if(!i->swffont) {
2688         msg("<warning> swf_drawchar: Font is NULL");
2689         return;
2690     }
2691     if(glyph<0 || glyph>=i->swffont->numchars) {
2692         msg("<warning> No character %d in font %s (%d chars)", glyph, FIXNULL((char*)i->swffont->name), i->swffont->numchars);
2693         return;
2694     }
2695     
2696     setfontscale(dev, matrix->m00, matrix->m01, matrix->m10, matrix->m11, matrix->tx, matrix->ty, 0);
2697     
2698     double det = i->fontmatrix.sx/65536.0 * i->fontmatrix.sy/65536.0 - 
2699                  i->fontmatrix.r0/65536.0 * i->fontmatrix.r1/65536.0;
2700     if(fabs(det) < 0.0005) { 
2701         /* x direction equals y direction- the text is invisible */
2702         msg("<verbose> Not drawing invisible character character %d (det=%f, m=[%f %f;%f %f]\n", glyph, 
2703                 det,
2704                 i->fontmatrix.sx/65536.0, i->fontmatrix.r1/65536.0, 
2705                 i->fontmatrix.r0/65536.0, i->fontmatrix.sy/65536.0);
2706         return;
2707     }
2708
2709     /*if(i->swffont->glyph[glyph].shape->bitlen <= 16) {
2710         msg("<warning> Glyph %d in current charset (%s, %d characters) is empty", 
2711                 glyph, FIXNULL((char*)i->swffont->name), i->swffont->numchars);
2712         return 1;
2713     }*/
2714
2715     /* calculate character position with respect to the current font matrix */
2716     double s = 20 * GLYPH_SCALE / det;
2717     double px = matrix->tx - i->fontmatrix.tx/20.0;
2718     double py = matrix->ty - i->fontmatrix.ty/20.0;
2719     int x = (SCOORD)((  px * i->fontmatrix.sy/65536.0 - py * i->fontmatrix.r1/65536.0)*s);
2720     int y = (SCOORD)((- px * i->fontmatrix.r0/65536.0 + py * i->fontmatrix.sx/65536.0)*s);
2721     if(x>32767 || x<-32768 || y>32767 || y<-32768) {
2722         msg("<verbose> Moving character origin to %f %f\n", matrix->tx, matrix->ty);
2723         endtext(dev);
2724         setfontscale(dev, matrix->m00, matrix->m01, matrix->m10, matrix->m11, matrix->tx, matrix->ty, 1);
2725     }
2726     
2727     if(i->shapeid>=0)
2728         endshape(dev);
2729     if(i->textid<0)
2730         starttext(dev);
2731
2732     msg("<trace> Drawing char %d in font %d at %d,%d in color %02x%02x%02x%02x", 
2733             glyph, i->swffont->id, x, y, color->r, color->g, color->b, color->a);
2734
2735     putcharacter(dev, i->swffont->id, glyph, x, y, i->current_font_size, *(RGBA*)color);
2736     swf_FontUseGlyph(i->swffont, glyph);
2737     return;
2738 }