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