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