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