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