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