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