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