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