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