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