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