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