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