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