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