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