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