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