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