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