* several cleanups
[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 static int font_active = 0;
650 static char* font_active_filename = 0;
651
652 /* process a character. */
653 static int drawchar(gfxdevice_t*dev, SWFFONT *swffont, char*character, int charnr, int u, 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     int charid = getCharID(swffont, charnr, character, u); 
662     if(font_active) {
663         char buf[1024];
664         sprintf(buf, "%s.usage", font_active_filename);
665         FILE*fi = fopen(buf, "ab+");
666         if(fi) {
667              fprintf(fi, "%d %d %d %s\n", charnr, u, charid, character);
668              fclose(fi);
669         } else 
670             msg("<error> Couldn't write to %s", buf);
671     }
672     
673     if(charid<0) {
674         msg("<warning> Didn't find character '%s' (c=%d,u=%d) in current charset (%s, %d characters)", 
675                 FIXNULL(character),charnr, u, FIXNULL((char*)swffont->name), swffont->numchars);
676         return 0;
677     }
678     /*if(swffont->glyph[charid].shape->bitlen <= 16) {
679         msg("<warning> Character '%s' (c=%d,u=%d), glyph %d in current charset (%s, %d characters) is empty", 
680                 FIXNULL(character),charnr, u, charid, FIXNULL((char*)swffont->name), swffont->numchars);
681         return 0;
682     }*/
683
684
685     if(i->shapeid>=0)
686         endshape(dev);
687     if(i->textid<0)
688         starttext(dev);
689
690     float x = m->m31;
691     float y = m->m32;
692     float det = ((m->m11*m->m22)-(m->m21*m->m12));
693     if(fabs(det) < 0.0005) { 
694         /* x direction equals y direction- the text is invisible */
695         return 1;
696     }
697     det = 20*FONT_INTERNAL_SIZE / det;
698
699     SPOINT p;
700     p.x = (SCOORD)((  x * m->m22 - y * m->m12)*det);
701     p.y = (SCOORD)((- x * m->m21 + y * m->m11)*det);
702
703     RGBA rgba = *(RGBA*)col;
704     putcharacter(dev, swffont->id, charid,p.x,p.y,FONT_INTERNAL_SIZE, rgba);
705     swf_FontUseGlyph(swffont, charid);
706     return 1;
707 }
708
709 static void endtext(gfxdevice_t*dev)
710 {
711     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
712     if(i->textid<0)
713         return;
714
715     i->tag = swf_InsertTag(i->tag,ST_DEFINETEXT);
716     swf_SetU16(i->tag, i->textid);
717
718     SRECT r;
719     r = getcharacterbbox(dev, i->swffont, &i->fontmatrix);
720     
721     swf_SetRect(i->tag,&r);
722
723     swf_SetMatrix(i->tag,&i->fontmatrix);
724
725     msg("<trace> Placing text (%d characters) as ID %d", i->chardatapos, i->textid);
726
727     putcharacters(dev, i->tag);
728     swf_SetU8(i->tag,0);
729     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
730
731     swf_ObjectPlace(i->tag,i->textid,getNewDepth(dev),&i->page_matrix,NULL,NULL);
732     i->textid = -1;
733 }
734
735 int getCharID(SWFFONT *font, int charnr, char *charname, int u)
736 {
737     int t;
738     if(charname && font->glyphnames) {
739         for(t=0;t<font->numchars;t++) {
740             if(font->glyphnames[t] && !strcmp(font->glyphnames[t],charname)) {
741                 msg("<debug> Char [%d,>%s<,%d] maps to %d\n", charnr, charname, u, t);
742                 return t;
743             }
744         }
745         /* if we didn't find the character, maybe
746            we can find the capitalized version */
747         for(t=0;t<font->numchars;t++) {
748             if(font->glyphnames[t] && !strcasecmp(font->glyphnames[t],charname)) {
749                 msg("<debug> Char [%d,>>%s<<,%d] maps to %d\n", charnr, charname, u, t);
750                 return t;
751             }
752         }
753     }
754
755     if(u>0 && font->encoding != 255) {
756         /* try to use the unicode id */
757         if(u>=0 && u<font->maxascii && font->ascii2glyph[u]>=0) {
758             msg("<debug> Char [%d,%s,>%d<] maps to %d\n", charnr, charname, u, font->ascii2glyph[u]);
759             return font->ascii2glyph[u];
760         }
761     }
762
763     if(font->encoding != FONT_ENCODING_UNICODE) {
764         /* the following only works if the font encoding
765            is US-ASCII based. It's needed for fonts which return broken unicode
766            indices */
767         if(charnr>=0 && charnr<font->maxascii && font->ascii2glyph[charnr]>=0) {
768             msg("<debug> Char [>%d<,%s,%d] maps to %d\n", charnr, charname, u, font->ascii2glyph[charnr]);
769             return font->ascii2glyph[charnr];
770         }
771     } 
772     
773     if(charnr>=0 && charnr<font->numchars) {
774         msg("<debug> Char [>%d<,%s,%d] maps to %d\n", charnr, charname, u, charnr);
775         return charnr;
776     }
777     
778     return -1;
779 }
780
781 /* set's the matrix which is to be applied to characters drawn by swfoutput_drawchar() */
782 static void swfoutput_setfontmatrix(gfxdevice_t*dev,double m11,double m21,
783                                                   double m12,double m22)
784 {
785     m11 *= 1024;
786     m12 *= 1024;
787     m21 *= 1024;
788     m22 *= 1024;
789     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
790     if(i->fontm11 == m11 &&
791        i->fontm12 == m12 &&
792        i->fontm21 == m21 &&
793        i->fontm22 == m22)
794         return;
795    if(i->textid>=0)
796         endtext(dev);
797     i->fontm11 = m11;
798     i->fontm12 = m12;
799     i->fontm21 = m21;
800     i->fontm22 = m22;
801     
802     MATRIX m;
803     m.sx = (U32)(((i->fontm11)*65536)/FONT_INTERNAL_SIZE); m.r1 = (U32)(((i->fontm12)*65536)/FONT_INTERNAL_SIZE);
804     m.r0 = (U32)(((i->fontm21)*65536)/FONT_INTERNAL_SIZE); m.sy = (U32)(((i->fontm22)*65536)/FONT_INTERNAL_SIZE); 
805     m.tx = 0;
806     m.ty = 0;
807     i->fontmatrix = m;
808 }
809
810 static void endpage(gfxdevice_t*dev)
811 {
812     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
813     if(i->shapeid>=0)
814       endshape(dev);
815     if(i->textid>=0)
816       endtext(dev);
817     while(i->clippos)
818         dev->endclip(dev);
819     i->pagefinished = 1;
820 }
821
822 void swf_startframe(gfxdevice_t*dev, int width, int height)
823 {
824     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
825     if(!i->firstpage && !i->pagefinished)
826         endpage(dev);
827     msg("<verbose> Starting new SWF page of size %dx%d", width, height);
828
829     swf_GetMatrix(0, &i->page_matrix);
830     i->page_matrix.tx = 0;
831     i->page_matrix.ty = 0;
832     i->min_x = 0;
833     i->min_y = 0;
834     i->max_x = width;
835     i->max_y = height;
836
837     /* set clipping/background rectangle */
838     /* TODO: this should all be done in SWFOutputDev */
839     //setBackground(dev, x1, y1, x2, y2);
840
841     /* increase SWF's bounding box */
842     SRECT r;
843     r.xmin = 0;
844     r.ymin = 0;
845     r.xmax = width*20;
846     r.ymax = height*20;
847     swf_ExpandRect2(&i->swf->movieSize, &r);
848
849     i->lastframeno = i->frameno;
850     i->firstpage = 0;
851     i->pagefinished = 0;
852 }
853
854 void swf_endframe(gfxdevice_t*dev)
855 {
856     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
857     
858     if(!i->pagefinished)
859         endpage(dev);
860
861     if(i->config_insertstoptag) {
862         ActionTAG*atag=0;
863         atag = action_Stop(atag);
864         atag = action_End(atag);
865         i->tag = swf_InsertTag(i->tag,ST_DOACTION);
866         swf_ActionSet(i->tag,atag);
867     }
868     i->tag = swf_InsertTag(i->tag,ST_SHOWFRAME);
869     i->frameno ++;
870     
871     for(i->depth;i->depth>i->startdepth;i->depth--) {
872         i->tag = swf_InsertTag(i->tag,ST_REMOVEOBJECT2);
873         swf_SetU16(i->tag,i->depth);
874     }
875     i->depth = i->startdepth;
876 }
877
878 static void setBackground(gfxdevice_t*dev, int x1, int y1, int x2, int y2)
879 {
880     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
881     RGBA rgb;
882     rgb.a = rgb.r = rgb.g = rgb.b = 0xff;
883     SRECT r;
884     SHAPE* s;
885     int ls1=0,fs1=0;
886     int shapeid = getNewID(dev);
887     r.xmin = x1;
888     r.ymin = y1;
889     r.xmax = x2;
890     r.ymax = y2;
891     i->tag = swf_InsertTag(i->tag, ST_DEFINESHAPE);
892     swf_ShapeNew(&s);
893     fs1 = swf_ShapeAddSolidFillStyle(s, &rgb);
894     swf_SetU16(i->tag,shapeid);
895     swf_SetRect(i->tag,&r);
896     swf_SetShapeHeader(i->tag,s);
897     swf_ShapeSetAll(i->tag,s,x1,y1,ls1,fs1,0);
898     swf_ShapeSetLine(i->tag,s,(x2-x1),0);
899     swf_ShapeSetLine(i->tag,s,0,(y2-y1));
900     swf_ShapeSetLine(i->tag,s,(x1-x2),0);
901     swf_ShapeSetLine(i->tag,s,0,(y1-y2));
902     swf_ShapeSetEnd(i->tag);
903     swf_ShapeFree(s);
904     i->tag = swf_InsertTag(i->tag, ST_PLACEOBJECT2);
905     swf_ObjectPlace(i->tag,shapeid,getNewDepth(dev),0,0,0);
906     i->tag = swf_InsertTag(i->tag, ST_PLACEOBJECT2);
907     swf_ObjectPlaceClip(i->tag,shapeid,getNewDepth(dev),0,0,0,65535);
908 }
909
910 /* initialize the swf writer */
911 void gfxdevice_swf_init(gfxdevice_t* dev)
912 {
913     memset(dev, 0, sizeof(gfxdevice_t));
914     dev->internal = init_internal_struct();
915
916     dev->startpage = swf_startframe;
917     dev->endpage = swf_endframe;
918     dev->finish = swf_finish;
919     dev->fillbitmap = swf_fillbitmap;
920     dev->setparameter = swf_setparameter;
921     dev->stroke = swf_stroke;
922     dev->startclip = swf_startclip;
923     dev->endclip = swf_endclip;
924     dev->fill = swf_fill;
925     dev->fillbitmap = swf_fillbitmap;
926     dev->fillgradient = swf_fillgradient;
927     dev->addfont = swf_addfont;
928     dev->drawchar = swf_drawchar;
929     dev->drawlink = swf_drawlink;
930
931     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
932     i->dev = dev;
933
934     SRECT r;
935     RGBA rgb;
936
937     msg("<verbose> initializing swf output\n", i->max_x,i->max_y);
938
939     i->swffont = 0;
940    
941     i->swf = (SWF*)rfx_calloc(sizeof(SWF));
942     i->swf->fileVersion    = i->config_flashversion;
943     i->swf->frameRate      = 0x0040; // 1 frame per 4 seconds
944     i->swf->movieSize.xmin = 0;
945     i->swf->movieSize.ymin = 0;
946     i->swf->movieSize.xmax = 0;
947     i->swf->movieSize.ymax = 0;
948     
949     i->swf->firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
950     i->tag = i->swf->firstTag;
951     rgb.a = rgb.r = rgb.g = rgb.b = 0xff;
952     swf_SetRGB(i->tag,&rgb);
953
954     i->startdepth = i->depth = 0;
955     
956     if(i->config_protect)
957       i->tag = swf_InsertTag(i->tag, ST_PROTECT);
958 }
959
960 static void startshape(gfxdevice_t*dev)
961 {
962     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
963     SRECT r;
964
965     if(i->shapeid>=0)
966         return;
967
968     if(i->textid>=0)
969         endtext(dev);
970
971     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE);
972
973     swf_ShapeNew(&i->shape);
974     i->linestyleid = swf_ShapeAddLineStyle(i->shape,i->linewidth,&i->strokergb);
975     i->fillstyleid = swf_ShapeAddSolidFillStyle(i->shape,&i->fillrgb);
976
977     i->shapeid = getNewID(dev);
978     
979     msg("<debug> Using shape id %d", i->shapeid);
980
981     swf_SetU16(i->tag,i->shapeid);  // ID
982
983     i->bboxrectpos = i->tag->len;
984     /* changed later */
985     r.xmin = 0;
986     r.ymin = 0;
987     r.xmax = 20*i->max_x;
988     r.ymax = 20*i->max_y;
989     swf_SetRect(i->tag,&r);
990    
991     memset(&i->bboxrect, 0, sizeof(i->bboxrect));
992
993     swf_SetShapeStyles(i->tag,i->shape);
994     swf_ShapeCountBits(i->shape,NULL,NULL);
995     swf_SetShapeBits(i->tag,i->shape);
996
997     /* TODO: do we really need this? */
998     swf_ShapeSetAll(i->tag,i->shape,/*x*/0,/*y*/0,i->linestyleid,0,0);
999     i->swflastx=i->swflasty=0;
1000     i->lastwasfill = 0;
1001     i->shapeisempty = 1;
1002 }
1003
1004 static void starttext(gfxdevice_t*dev)
1005 {
1006     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1007     if(i->shapeid>=0)
1008         endshape(dev);
1009       
1010     i->textid = getNewID(dev);
1011
1012     i->swflastx=i->swflasty=0;
1013 }
1014             
1015
1016 /* TODO: move to ../lib/rfxswf */
1017 void changeRect(gfxdevice_t*dev, TAG*tag, int pos, SRECT*newrect)
1018 {
1019     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1020     /* determine length of old rect */
1021     tag->pos = pos;
1022     tag->readBit = 0;
1023     SRECT old;
1024     swf_GetRect(tag, &old);
1025     swf_ResetReadBits(tag);
1026     int pos_end = tag->pos;
1027
1028     int len = tag->len - pos_end;
1029     U8*data = (U8*)malloc(len);
1030     memcpy(data, &tag->data[pos_end], len);
1031     tag->writeBit = 0;
1032     tag->len = pos;
1033     swf_SetRect(tag, newrect);
1034     swf_SetBlock(tag, data, len);
1035     free(data);
1036     tag->pos = tag->readBit = 0;
1037 }
1038
1039 void cancelshape(gfxdevice_t*dev)
1040 {
1041     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1042     /* delete old shape tag */
1043     TAG*todel = i->tag;
1044     i->tag = i->tag->prev;
1045     swf_DeleteTag(todel);
1046     if(i->shape) {swf_ShapeFree(i->shape);i->shape=0;}
1047     i->shapeid = -1;
1048     i->bboxrectpos = -1;
1049 }
1050
1051 void fixAreas(gfxdevice_t*dev)
1052 {
1053     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1054     if(!i->shapeisempty && i->fill &&
1055        (i->bboxrect.xmin == i->bboxrect.xmax ||
1056         i->bboxrect.ymin == i->bboxrect.ymax) &&
1057         i->config_minlinewidth >= 0.001
1058        ) {
1059         msg("<debug> Shape has size 0: width=%.2f height=%.2f",
1060                 (i->bboxrect.xmax-i->bboxrect.xmin)/20.0,
1061                 (i->bboxrect.ymax-i->bboxrect.ymin)/20.0
1062                 );
1063     
1064         SRECT r = i->bboxrect;
1065         
1066         if(r.xmin == r.xmax && r.ymin == r.ymax) {
1067             /* this thing comes down to a single dot- nothing to fix here */
1068             return;
1069         }
1070
1071         cancelshape(dev);
1072
1073         RGBA save_col = i->strokergb;
1074         int  save_width = i->linewidth;
1075
1076         i->strokergb = i->fillrgb;
1077         i->linewidth = (int)(i->config_minlinewidth*20);
1078         if(i->linewidth==0) i->linewidth = 1;
1079         
1080         startshape(dev);
1081
1082         moveto(dev, i->tag, r.xmin/20.0,r.ymin/20.0);
1083         lineto(dev, i->tag, r.xmax/20.0,r.ymax/20.0);
1084
1085         i->strokergb = save_col;
1086         i->linewidth = save_width;
1087     }
1088     
1089 }
1090
1091 static void endshape_noput(gfxdevice_t*dev)
1092 {
1093     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1094     if(i->shapeid<0) 
1095         return;
1096     //changeRect(dev, i->tag, i->bboxrectpos, &i->bboxrect);
1097     i->shapeid = -1;
1098     if(i->shape) {
1099         swf_ShapeFree(i->shape);
1100         i->shape=0;
1101     }
1102     i->fill=0;
1103 }
1104
1105 static void endshape(gfxdevice_t*dev)
1106 {
1107     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1108     if(i->shapeid<0) 
1109         return;
1110
1111     fixAreas(dev);
1112         
1113     if(i->shapeisempty ||
1114        /*bbox empty?*/
1115        (i->bboxrect.xmin == i->bboxrect.xmax && 
1116         i->bboxrect.ymin == i->bboxrect.ymax))
1117     {
1118         // delete the shape again, we didn't do anything
1119         msg("<debug> cancelling shape: bbox is (%f,%f,%f,%f)",
1120                 i->bboxrect.xmin /20.0,
1121                 i->bboxrect.ymin /20.0,
1122                 i->bboxrect.xmax /20.0,
1123                 i->bboxrect.ymax /20.0
1124                 );
1125         cancelshape(dev);
1126         return;
1127     }
1128     
1129     swf_ShapeSetEnd(i->tag);
1130
1131     changeRect(dev, i->tag, i->bboxrectpos, &i->bboxrect);
1132
1133     msg("<trace> Placing shape id %d", i->shapeid);
1134
1135     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
1136     swf_ObjectPlace(i->tag,i->shapeid,getNewDepth(dev),&i->page_matrix,NULL,NULL);
1137
1138     swf_ShapeFree(i->shape);
1139     i->shape = 0;
1140     i->shapeid = -1;
1141     i->bboxrectpos = -1;
1142     i->fill=0;
1143
1144 }
1145
1146 void wipeSWF(SWF*swf)
1147 {
1148     TAG*tag = swf->firstTag;
1149     while(tag) {
1150         TAG*next = tag->next;
1151         if(tag->id != ST_SETBACKGROUNDCOLOR &&
1152            tag->id != ST_END &&
1153            tag->id != ST_DOACTION &&
1154            tag->id != ST_SHOWFRAME) {
1155             swf_DeleteTag(tag);
1156         }
1157         tag = next;
1158     }
1159 }
1160
1161
1162 void swfoutput_finalize(gfxdevice_t*dev)
1163 {
1164     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1165
1166     if(i->tag && i->tag->id == ST_END)
1167         return; //already done
1168
1169     if(i->config_bboxvars) {
1170         TAG* tag = swf_InsertTag(i->swf->firstTag, ST_DOACTION);
1171         ActionTAG*a = 0;
1172         a = action_PushString(a, "xmin");
1173         a = action_PushFloat(a, i->swf->movieSize.xmin / 20.0);
1174         a = action_SetVariable(a);
1175         a = action_PushString(a, "ymin");
1176         a = action_PushFloat(a, i->swf->movieSize.ymin / 20.0);
1177         a = action_SetVariable(a);
1178         a = action_PushString(a, "xmax");
1179         a = action_PushFloat(a, i->swf->movieSize.xmax / 20.0);
1180         a = action_SetVariable(a);
1181         a = action_PushString(a, "ymax");
1182         a = action_PushFloat(a, i->swf->movieSize.ymax / 20.0);
1183         a = action_SetVariable(a);
1184         a = action_PushString(a, "width");
1185         a = action_PushFloat(a, (i->swf->movieSize.xmax - i->swf->movieSize.xmin) / 20.0);
1186         a = action_SetVariable(a);
1187         a = action_PushString(a, "height");
1188         a = action_PushFloat(a, (i->swf->movieSize.ymax - i->swf->movieSize.ymin) / 20.0);
1189         a = action_SetVariable(a);
1190         a = action_End(a);
1191         swf_ActionSet(tag, a);
1192         swf_ActionFree(a);
1193     }
1194
1195     if(i->frameno == i->lastframeno) // fix: add missing pagefeed
1196         dev->endpage(dev);
1197
1198     endpage(dev);
1199     fontlist_t *tmp,*iterator = i->fontlist;
1200     while(iterator) {
1201         TAG*mtag = i->swf->firstTag;
1202         if(iterator->swffont) {
1203             mtag = swf_InsertTag(mtag, ST_DEFINEFONT2);
1204             if(!i->config_storeallcharacters)
1205                 swf_FontReduce(iterator->swffont);
1206             swf_FontSetDefine2(mtag, iterator->swffont);
1207         }
1208
1209         iterator = iterator->next;
1210     }
1211     i->tag = swf_InsertTag(i->tag,ST_END);
1212     TAG* tag = i->tag->prev;
1213
1214     /* remove the removeobject2 tags between the last ST_SHOWFRAME
1215        and the ST_END- they confuse the flash player  */
1216     while(tag->id == ST_REMOVEOBJECT2) {
1217         TAG* prev = tag->prev;
1218         swf_DeleteTag(tag);
1219         tag = prev;
1220     }
1221     
1222     if(i->overflow) {
1223         wipeSWF(i->swf);
1224     }
1225     if(i->config_enablezlib || i->config_flashversion>=6) {
1226         i->swf->compressed = 1;
1227     }
1228 }
1229
1230 int swfresult_save(gfxresult_t*gfx, char*filename)
1231 {
1232     SWF*swf = (SWF*)gfx->internal;
1233     int fi;
1234     if(filename)
1235      fi = open(filename, O_BINARY|O_CREAT|O_TRUNC|O_WRONLY, 0777);
1236     else
1237      fi = 1; // stdout
1238     
1239     if(fi<=0) {
1240         msg("<fatal> Could not create \"%s\". ", FIXNULL(filename));
1241         return -1;
1242     }
1243     
1244     if(swf->compressed) {
1245         if FAILED(swf_WriteSWC(fi,swf)) 
1246             msg("<error> WriteSWC() failed.\n");
1247     } else {
1248         if FAILED(swf_WriteSWF(fi,swf)) 
1249             msg("<error> WriteSWF() failed.\n");
1250     }
1251
1252     if(filename)
1253      close(fi);
1254     return 0;
1255 }
1256 void* swfresult_get(gfxresult_t*gfx, char*name)
1257 {
1258     SWF*swf = (SWF*)gfx->internal;
1259     if(!strcmp(name, "swf")) {
1260         return (void*)swf_CopySWF(swf);
1261     } else if(!strcmp(name, "xmin")) {
1262         return (void*)(swf->movieSize.xmin/20);
1263     } else if(!strcmp(name, "ymin")) {
1264         return (void*)(swf->movieSize.ymin/20);
1265     } else if(!strcmp(name, "xmax")) {
1266         return (void*)(swf->movieSize.xmax/20);
1267     } else if(!strcmp(name, "ymax")) {
1268         return (void*)(swf->movieSize.ymax/20);
1269     }
1270     return 0;
1271 }
1272 void swfresult_destroy(gfxresult_t*gfx)
1273 {
1274     if(gfx->internal) {
1275         swf_FreeTags((SWF*)gfx->internal);
1276         free(gfx->internal);
1277         gfx->internal = 0;
1278     }
1279     memset(gfx, 0, sizeof(gfxresult_t));
1280     free(gfx);
1281 }
1282
1283 static void swfoutput_destroy(gfxdevice_t* dev);
1284
1285 gfxresult_t* swf_finish(gfxdevice_t* dev)
1286 {
1287     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1288     gfxresult_t*result;
1289
1290     swfoutput_finalize(dev);
1291     SWF* swf = i->swf;i->swf = 0;
1292     swfoutput_destroy(dev);
1293
1294     result = (gfxresult_t*)rfx_calloc(sizeof(gfxresult_t));
1295     result->internal = swf;
1296     result->save = swfresult_save;
1297     result->write = 0;
1298     result->get = swfresult_get;
1299     result->destroy = swfresult_destroy;
1300     return result;
1301 }
1302
1303 /* Perform cleaning up */
1304 static void swfoutput_destroy(gfxdevice_t* dev) 
1305 {
1306     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1307     if(!i) {
1308         /* not initialized yet- nothing to destroy */
1309         return;
1310     }
1311
1312     fontlist_t *tmp,*iterator = i->fontlist;
1313     while(iterator) {
1314         if(iterator->swffont) {
1315             swf_FontFree(iterator->swffont);iterator->swffont=0;
1316         }
1317         tmp = iterator;
1318         iterator = iterator->next;
1319         delete tmp;
1320     }
1321     if(i->swf) {swf_FreeTags(i->swf);free(i->swf);i->swf = 0;}
1322
1323     free(i);i=0;
1324     memset(dev, 0, sizeof(gfxdevice_t));
1325 }
1326
1327 static void swfoutput_setfillcolor(gfxdevice_t* dev, U8 r, U8 g, U8 b, U8 a)
1328 {
1329     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1330     if(i->fillrgb.r == r &&
1331        i->fillrgb.g == g &&
1332        i->fillrgb.b == b &&
1333        i->fillrgb.a == a) return;
1334     if(i->shapeid>=0)
1335      endshape(dev);
1336
1337     i->fillrgb.r = r;
1338     i->fillrgb.g = g;
1339     i->fillrgb.b = b;
1340     i->fillrgb.a = a;
1341 }
1342
1343 static void swfoutput_setstrokecolor(gfxdevice_t* dev, U8 r, U8 g, U8 b, U8 a)
1344 {
1345     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1346     if(i->strokergb.r == r &&
1347        i->strokergb.g == g &&
1348        i->strokergb.b == b &&
1349        i->strokergb.a == a) return;
1350
1351     if(i->shapeid>=0)
1352      endshape(dev);
1353     i->strokergb.r = r;
1354     i->strokergb.g = g;
1355     i->strokergb.b = b;
1356     i->strokergb.a = a;
1357 }
1358
1359 static void swfoutput_setlinewidth(gfxdevice_t*dev, double _linewidth)
1360 {
1361     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1362     if(i->linewidth == (U16)(_linewidth*20))
1363         return;
1364
1365     if(i->shapeid>=0)
1366         endshape(dev);
1367     i->linewidth = (U16)(_linewidth*20);
1368 }
1369
1370
1371 static void drawlink(gfxdevice_t*dev, ActionTAG*,ActionTAG*, gfxline_t*points, char mouseover);
1372 static void swfoutput_namedlink(gfxdevice_t*dev, char*name, gfxline_t*points);
1373 static void swfoutput_linktopage(gfxdevice_t*dev, int page, gfxline_t*points);
1374 static void swfoutput_linktourl(gfxdevice_t*dev, char*url, gfxline_t*points);
1375
1376 void swfoutput_drawlink(gfxdevice_t*dev, char*url, gfxline_t*points)
1377 {
1378     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1379     dev->drawlink(dev, points, url);
1380 }
1381
1382 void swf_drawlink(gfxdevice_t*dev, gfxline_t*points, char*url)
1383 {
1384     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1385
1386     if(!strncmp("http://pdf2swf:", url, 15)) {
1387         char*tmp = strdup(url);
1388         int l = strlen(tmp);
1389         if(tmp[l-1] == '/')
1390            tmp[l-1] = 0;
1391         swfoutput_namedlink(dev, tmp+15, points);
1392         free(tmp);
1393         return;
1394     } else if(!strncmp("page", url, 4)) {
1395         int t, nodigit=0;
1396         for(t=4;url[t];t++)
1397             if(url[t]<'0' || url[t]>'9')
1398                 nodigit = 1;
1399         if(!nodigit) {
1400             int page = atoi(&url[4]);
1401             swfoutput_linktopage(dev, page, points);
1402         }
1403     } else {
1404         swfoutput_linktourl(dev, url, points);
1405     }
1406 }
1407 void swfoutput_linktourl(gfxdevice_t*dev, char*url, gfxline_t*points)
1408 {
1409     ActionTAG* actions;
1410     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1411     if(i->shapeid>=0)
1412         endshape(dev);
1413     if(i->textid>=0)
1414         endtext(dev);
1415     
1416     if(!i->config_opennewwindow)
1417       actions = action_GetUrl(0, url, "_parent");
1418     else
1419       actions = action_GetUrl(0, url, "_this");
1420     actions = action_End(actions);
1421     
1422     drawlink(dev, actions, 0, points,0);
1423 }
1424 void swfoutput_linktopage(gfxdevice_t*dev, int page, gfxline_t*points)
1425 {
1426     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1427     ActionTAG* actions;
1428
1429     if(i->shapeid>=0)
1430         endshape(dev);
1431     if(i->textid>=0)
1432         endtext(dev);
1433    
1434       actions = action_GotoFrame(0, page);
1435       actions = action_End(actions);
1436
1437     drawlink(dev, actions, 0, points,0);
1438 }
1439
1440 /* Named Links (a.k.a. Acrobatmenu) are used to implement various gadgets
1441    of the viewer objects, like subtitles, index elements etc.
1442 */
1443 void swfoutput_namedlink(gfxdevice_t*dev, char*name, gfxline_t*points)
1444 {
1445     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1446     ActionTAG *actions1,*actions2;
1447     char*tmp = strdup(name);
1448     char mouseover = 1;
1449
1450     if(i->shapeid>=0)
1451         endshape(dev);
1452     if(i->textid>=0)
1453         endtext(dev);
1454
1455     if(!strncmp(tmp, "call:", 5))
1456     {
1457         char*x = strchr(&tmp[5], ':');
1458         if(!x) {
1459             actions1 = action_PushInt(0, 0); //number of parameters (0)
1460             actions1 = action_PushString(actions1, &tmp[5]); //function name
1461             actions1 = action_CallFunction(actions1);
1462         } else {
1463             *x = 0;
1464             actions1 = action_PushString(0, x+1); //parameter
1465             actions1 = action_PushInt(actions1, 1); //number of parameters (1)
1466             actions1 = action_PushString(actions1, &tmp[5]); //function name
1467             actions1 = action_CallFunction(actions1);
1468         }
1469         actions2 = action_End(0);
1470         mouseover = 0;
1471     }
1472     else
1473     {
1474         actions1 = action_PushString(0, "/:subtitle");
1475         actions1 = action_PushString(actions1, name);
1476         actions1 = action_SetVariable(actions1);
1477         actions1 = action_End(actions1);
1478
1479         actions2 = action_PushString(0, "/:subtitle");
1480         actions2 = action_PushString(actions2, "");
1481         actions2 = action_SetVariable(actions2);
1482         actions2 = action_End(actions2);
1483     }
1484
1485     drawlink(dev, actions1, actions2, points,mouseover);
1486
1487     swf_ActionFree(actions1);
1488     swf_ActionFree(actions2);
1489     free(tmp);
1490 }
1491
1492 static void drawgfxline(gfxdevice_t*dev, gfxline_t*line)
1493 {
1494     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1495     gfxcoord_t lastx=0,lasty=0,px=0,py=0;
1496     char lastwasmoveto;
1497     while(1) {
1498         if(!line)
1499             break;
1500         /* check whether the next segment is zero */
1501         if(line->type == gfx_moveTo) {
1502             msg("<trace> ======== moveTo %.2f %.2f", line->x, line->y);
1503             moveto(dev, i->tag, line->x, line->y);
1504             px = lastx = line->x;
1505             py = lasty = line->y;
1506             lastwasmoveto = 1;
1507         } if(line->type == gfx_lineTo) {
1508             msg("<trace> ======== lineTo %.2f %.2f", line->x, line->y);
1509             lineto(dev, i->tag, line->x, line->y);
1510             px = line->x;
1511             py = line->y;
1512             lastwasmoveto = 0;
1513         } else if(line->type == gfx_splineTo) {
1514             msg("<trace> ======== splineTo  %.2f %.2f", line->x, line->y);
1515             plotxy s,p;
1516             s.x = line->sx;p.x = line->x;
1517             s.y = line->sy;p.y = line->y;
1518             splineto(dev, i->tag, s, p);
1519             px = line->x;
1520             py = line->y;
1521             lastwasmoveto = 0;
1522         }
1523         line = line->next;
1524     }
1525 }
1526
1527
1528 static void drawlink(gfxdevice_t*dev, ActionTAG*actions1, ActionTAG*actions2, gfxline_t*points, char mouseover)
1529 {
1530     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1531     RGBA rgb;
1532     SRECT r;
1533     int lsid=0;
1534     int fsid;
1535     struct plotxy p1,p2,p3,p4;
1536     int myshapeid;
1537     int myshapeid2;
1538     double posx = 0;
1539     double posy = 0;
1540     int t;
1541     int buttonid = getNewID(dev);
1542     gfxbbox_t bbox = gfxline_getbbox(points);
1543
1544     /* shape */
1545     myshapeid = getNewID(dev);
1546     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE3);
1547     swf_ShapeNew(&i->shape);
1548     rgb.r = rgb.b = rgb.a = rgb.g = 0; 
1549     fsid = swf_ShapeAddSolidFillStyle(i->shape,&rgb);
1550     swf_SetU16(i->tag, myshapeid);
1551     r.xmin = (int)(bbox.xmin*20);
1552     r.ymin = (int)(bbox.ymin*20);
1553     r.xmax = (int)(bbox.xmax*20);
1554     r.ymax = (int)(bbox.ymax*20);
1555     swf_SetRect(i->tag,&r);
1556     swf_SetShapeStyles(i->tag,i->shape);
1557     swf_ShapeCountBits(i->shape,NULL,NULL);
1558     swf_SetShapeBits(i->tag,i->shape);
1559     swf_ShapeSetAll(i->tag,i->shape,/*x*/0,/*y*/0,0,fsid,0);
1560     i->swflastx = i->swflasty = 0;
1561     drawgfxline(dev, points);
1562     swf_ShapeSetEnd(i->tag);
1563
1564     /* shape2 */
1565     myshapeid2 = getNewID(dev);
1566     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE3);
1567     swf_ShapeNew(&i->shape);
1568     rgb.r = rgb.b = rgb.a = rgb.g = 255;
1569     rgb.a = 40;
1570     fsid = swf_ShapeAddSolidFillStyle(i->shape,&rgb);
1571     swf_SetU16(i->tag, myshapeid2);
1572     r.xmin = (int)(bbox.xmin*20);
1573     r.ymin = (int)(bbox.ymin*20);
1574     r.xmax = (int)(bbox.xmax*20);
1575     r.ymax = (int)(bbox.ymax*20);
1576     swf_SetRect(i->tag,&r);
1577     swf_SetShapeStyles(i->tag,i->shape);
1578     swf_ShapeCountBits(i->shape,NULL,NULL);
1579     swf_SetShapeBits(i->tag,i->shape);
1580     swf_ShapeSetAll(i->tag,i->shape,/*x*/0,/*y*/0,0,fsid,0);
1581     i->swflastx = i->swflasty = 0;
1582     drawgfxline(dev, points);
1583     swf_ShapeSetEnd(i->tag);
1584
1585     if(!mouseover)
1586     {
1587         i->tag = swf_InsertTag(i->tag,ST_DEFINEBUTTON);
1588         swf_SetU16(i->tag,buttonid); //id
1589         swf_ButtonSetFlags(i->tag, 0); //menu=no
1590         swf_ButtonSetRecord(i->tag,0x01,myshapeid,i->depth,0,0);
1591         swf_ButtonSetRecord(i->tag,0x02,myshapeid2,i->depth,0,0);
1592         swf_ButtonSetRecord(i->tag,0x04,myshapeid2,i->depth,0,0);
1593         swf_ButtonSetRecord(i->tag,0x08,myshapeid,i->depth,0,0);
1594         swf_SetU8(i->tag,0);
1595         swf_ActionSet(i->tag,actions1);
1596         swf_SetU8(i->tag,0);
1597     }
1598     else
1599     {
1600         i->tag = swf_InsertTag(i->tag,ST_DEFINEBUTTON2);
1601         swf_SetU16(i->tag,buttonid); //id
1602         swf_ButtonSetFlags(i->tag, 0); //menu=no
1603         swf_ButtonSetRecord(i->tag,0x01,myshapeid,i->depth,0,0);
1604         swf_ButtonSetRecord(i->tag,0x02,myshapeid2,i->depth,0,0);
1605         swf_ButtonSetRecord(i->tag,0x04,myshapeid2,i->depth,0,0);
1606         swf_ButtonSetRecord(i->tag,0x08,myshapeid,i->depth,0,0);
1607         swf_SetU8(i->tag,0); // end of button records
1608         swf_ButtonSetCondition(i->tag, BC_IDLE_OVERUP);
1609         swf_ActionSet(i->tag,actions1);
1610         if(actions2) {
1611             swf_ButtonSetCondition(i->tag, BC_OVERUP_IDLE);
1612             swf_ActionSet(i->tag,actions2);
1613             swf_SetU8(i->tag,0);
1614             swf_ButtonPostProcess(i->tag, 2);
1615         } else {
1616             swf_SetU8(i->tag,0);
1617             swf_ButtonPostProcess(i->tag, 1);
1618         }
1619     }
1620     
1621     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
1622
1623     if(posx!=0 || posy!=0) {
1624         SPOINT p;
1625         p.x = (int)(posx*20);
1626         p.y = (int)(posy*20);
1627         p = swf_TurnPoint(p, &i->page_matrix);
1628         MATRIX m;
1629         m = i->page_matrix;
1630         m.tx = p.x;
1631         m.ty = p.y;
1632         swf_ObjectPlace(i->tag, buttonid, getNewDepth(dev),&m,0,0);
1633     } else {
1634         swf_ObjectPlace(i->tag, buttonid, getNewDepth(dev),&i->page_matrix,0,0);
1635     }
1636 }
1637
1638       
1639 ///////////
1640 /*
1641 for(t=0;t<picpos;t++)
1642       {
1643           if(pic_xids[t] == xid &&
1644              pic_yids[t] == yid) {
1645               width = pic_width[t];
1646               height = pic_height[t];
1647               found = t;break;
1648           }
1649       }
1650           pic_ids[picpos] = swfoutput_drawimagelosslessN(&output, pic, pal, width, height, x1,y1,x2,y2,x3,y3,x4,y4, numpalette);
1651           pic_xids[picpos] = xid;
1652           pic_yids[picpos] = yid;
1653           pic_width[picpos] = width;
1654           pic_height[picpos] = height;
1655           if(picpos<1024)
1656               picpos++;
1657             pic[width*y+x] = buf[0];
1658             xid+=x*buf[0]+1;
1659             yid+=y*buf[0]*3+1;
1660       
1661             xid += pal[1].r*3 + pal[1].g*11 + pal[1].b*17;
1662       yid += pal[1].r*7 + pal[1].g*5 + pal[1].b*23;
1663       
1664       int xid = 0;
1665       int yid = 0;
1666           xid += x*r+x*b*3+x*g*7+x*a*11;
1667           yid += y*r*3+y*b*17+y*g*19+y*a*11;
1668       int t,found = -1;
1669       for(t=0;t<picpos;t++)
1670       {
1671           if(pic_xids[t] == xid &&
1672              pic_yids[t] == yid) {
1673               found = t;break;
1674           }
1675       }
1676       if(found<0) {
1677 */
1678 ///////////
1679
1680
1681 int swf_setparameter(gfxdevice_t*dev, const char*name, const char*value)
1682 {
1683     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1684
1685     if(!strcmp(name, "jpegsubpixels")) {
1686         i->config_jpegsubpixels = atof(value);
1687     } else if(!strcmp(name, "ppmsubpixels")) {
1688         i->config_ppmsubpixels = atof(value);
1689     } else if(!strcmp(name, "drawonlyshapes")) {
1690         i->config_drawonlyshapes = atoi(value);
1691     } else if(!strcmp(name, "ignoredraworder")) {
1692         i->config_ignoredraworder = atoi(value);
1693     } else if(!strcmp(name, "filloverlap")) {
1694         i->config_filloverlap = atoi(value);
1695     } else if(!strcmp(name, "linksopennewwindow")) {
1696         i->config_opennewwindow = atoi(value);
1697     } else if(!strcmp(name, "opennewwindow")) {
1698         i->config_opennewwindow = atoi(value);
1699     } else if(!strcmp(name, "storeallcharacters")) {
1700         i->config_storeallcharacters = atoi(value);
1701     } else if(!strcmp(name, "enablezlib")) {
1702         i->config_enablezlib = atoi(value);
1703     } else if(!strcmp(name, "bboxvars")) {
1704         i->config_bboxvars = atoi(value);
1705     } else if(!strcmp(name, "insertstop")) {
1706         i->config_insertstoptag = atoi(value);
1707     } else if(!strcmp(name, "protected")) {
1708         i->config_protect = atoi(value);
1709     } else if(!strcmp(name, "flashversion")) {
1710         i->config_flashversion = atoi(value);
1711     } else if(!strcmp(name, "minlinewidth")) {
1712         i->config_minlinewidth = atof(value);
1713     } else if(!strcmp(name, "caplinewidth")) {
1714         i->config_caplinewidth = atof(value);
1715     } else if(!strcmp(name, "dumpfonts")) {
1716         i->config_dumpfonts = atoi(value);
1717     } else if(!strcmp(name, "next_bitmap_is_jpeg")) {
1718         i->jpeg = 1;
1719     } else if(!strcmp(name, "jpegquality")) {
1720         int val = atoi(value);
1721         if(val<0) val=0;
1722         if(val>100) val=100;
1723         i->config_jpegquality = val;
1724     } else if(!strcmp(name, "splinequality")) {
1725         int v = atoi(value);
1726         v = 500-(v*5); // 100% = 0.25 pixel, 0% = 25 pixel
1727         if(v<1) v = 1;
1728         i->config_splinemaxerror = v;
1729     } else if(!strcmp(name, "fontquality")) {
1730         int v = atoi(value);
1731         v = 500-(v*5); // 100% = 0.25 pixel, 0% = 25 pixel
1732         if(v<1) v = 1;
1733         i->config_fontsplinemaxerror = v;
1734     } else {
1735         fprintf(stderr, "unknown parameter: %s (=%s)\n", name, value);
1736         return 0;
1737     }
1738     return 1;
1739 }
1740
1741 // --------------------------------------------------------------------
1742
1743 static CXFORM gfxcxform_to_cxform(gfxcxform_t* c)
1744 {
1745     CXFORM cx;
1746     swf_GetCXForm(0, &cx, 1);
1747     if(!c)
1748         return cx;
1749     if(c->rg!=0 || c->rb!=0 || c->ra!=0 ||
1750        c->gr!=0 || c->gb!=0 || c->ga!=0 ||
1751        c->br!=0 || c->bg!=0 || c->ba!=0 ||
1752        c->ar!=0 || c->ag!=0 || c->ab!=0)
1753         msg("<warning> CXForm not SWF-compatible");
1754
1755     cx.a0 = (S16)(c->aa*256);
1756     cx.r0 = (S16)(c->rr*256);
1757     cx.g0 = (S16)(c->gg*256);
1758     cx.b0 = (S16)(c->bb*256);
1759     cx.a1 = c->t.a;
1760     cx.r1 = c->t.r;
1761     cx.g1 = c->t.g;
1762     cx.b1 = c->t.b;
1763     return cx;
1764 }
1765
1766 static ArtVpath* gfxline_to_ArtVpath(gfxline_t*line)
1767 {
1768     ArtVpath *vec = NULL;
1769     int pos=0,len=0;
1770     gfxline_t*l2;
1771     double x=0,y=0;
1772
1773     /* factor which determines into how many line fragments a spline is converted */
1774     double subfraction = 1.2;//0.3
1775
1776     l2 = line;
1777     while(l2) {
1778         if(l2->type == gfx_moveTo) {
1779             pos ++;
1780         } if(l2->type == gfx_lineTo) {
1781             pos ++;
1782         } if(l2->type == gfx_splineTo) {
1783             int parts = (int)(sqrt(fabs(l2->x-2*l2->sx+x) + fabs(l2->y-2*l2->sy+y))*subfraction);
1784             if(!parts) parts = 1;
1785             pos += parts + 1;
1786         }
1787         x = l2->x;
1788         y = l2->y;
1789         l2 = l2->next;
1790     }
1791     pos++;
1792     len = pos;
1793
1794     vec = art_new (ArtVpath, len);
1795
1796     pos = 0;
1797     l2 = line;
1798     while(l2) {
1799         if(l2->type == gfx_moveTo) {
1800             vec[pos].code = ART_MOVETO;
1801             vec[pos].x = l2->x;
1802             vec[pos].y = l2->y;
1803             pos++; 
1804             assert(pos<=len);
1805         } else if(l2->type == gfx_lineTo) {
1806             vec[pos].code = ART_LINETO;
1807             vec[pos].x = l2->x;
1808             vec[pos].y = l2->y;
1809             pos++; 
1810             assert(pos<=len);
1811         } else if(l2->type == gfx_splineTo) {
1812             int i;
1813             int parts = (int)(sqrt(fabs(l2->x-2*l2->sx+x) + fabs(l2->y-2*l2->sy+y))*subfraction);
1814             if(!parts) parts = 1;
1815             for(i=0;i<=parts;i++) {
1816                 double t = (double)i/(double)parts;
1817                 vec[pos].code = ART_LINETO;
1818                 vec[pos].x = l2->x*t*t + 2*l2->sx*t*(1-t) + x*(1-t)*(1-t);
1819                 vec[pos].y = l2->y*t*t + 2*l2->sy*t*(1-t) + y*(1-t)*(1-t);
1820                 pos++;
1821                 assert(pos<=len);
1822             }
1823         }
1824         x = l2->x;
1825         y = l2->y;
1826         l2 = l2->next;
1827     }
1828     vec[pos].code = ART_END;
1829
1830     return vec;
1831 }
1832
1833 static ArtSVP* gfxfillToSVP(gfxline_t*line)
1834 {
1835     ArtVpath* vec = gfxline_to_ArtVpath(line);
1836     ArtSVP *svp = art_svp_from_vpath(vec);
1837     free(vec);
1838     return svp;
1839 }
1840
1841 static ArtSVP* gfxstrokeToSVP(gfxline_t*line, gfxcoord_t width, gfx_capType cap_style, gfx_joinType joint_style, double miterLimit)
1842 {
1843     ArtVpath* vec = gfxline_to_ArtVpath(line);
1844     ArtSVP *svp = art_svp_vpath_stroke (vec,
1845                         (joint_style==gfx_joinMiter)?ART_PATH_STROKE_JOIN_MITER:
1846                         ((joint_style==gfx_joinRound)?ART_PATH_STROKE_JOIN_ROUND:
1847                          ((joint_style==gfx_joinBevel)?ART_PATH_STROKE_JOIN_BEVEL:ART_PATH_STROKE_JOIN_BEVEL)),
1848                         (cap_style==gfx_capButt)?ART_PATH_STROKE_CAP_BUTT:
1849                         ((cap_style==gfx_capRound)?ART_PATH_STROKE_CAP_ROUND:
1850                          ((cap_style==gfx_capSquare)?ART_PATH_STROKE_CAP_SQUARE:ART_PATH_STROKE_CAP_SQUARE)),
1851                         width, //line_width
1852                         miterLimit, //miter_limit
1853                         0.05 //flatness
1854                         );
1855     free(vec);
1856     return svp;
1857 }
1858
1859 static gfxline_t* SVPtogfxline(ArtSVP*svp)
1860 {
1861     int size = 0;
1862     int t;
1863     int pos = 0;
1864     for(t=0;t<svp->n_segs;t++) {
1865         size += svp->segs[t].n_points + 1;
1866     }
1867     gfxline_t* lines = (gfxline_t*)rfx_alloc(sizeof(gfxline_t)*size);
1868
1869     for(t=0;t<svp->n_segs;t++) {
1870         ArtSVPSeg* seg = &svp->segs[t];
1871         int p;
1872         for(p=0;p<seg->n_points;p++) {
1873             lines[pos].type = p==0?gfx_moveTo:gfx_lineTo;
1874             ArtPoint* point = &seg->points[p];
1875             lines[pos].x = point->x;
1876             lines[pos].y = point->y;
1877             lines[pos].next = &lines[pos+1];
1878             pos++;
1879         }
1880     }
1881     if(pos) {
1882         lines[pos-1].next = 0;
1883         return lines;
1884     } else {
1885         return 0;
1886     }
1887 }
1888
1889 /* TODO */
1890 static int imageInCache(gfxdevice_t*dev, void*data, int width, int height)
1891 {
1892     return -1;
1893 }
1894 static void addImageToCache(gfxdevice_t*dev, void*data, int width, int height)
1895 {
1896 }
1897     
1898 static int add_image(swfoutput_internal*i, gfximage_t*img, int targetwidth, int targetheight, int* newwidth, int* newheight)
1899 {
1900     gfxdevice_t*dev = i->dev;
1901     RGBA*newpic = 0;
1902     RGBA*mem = (RGBA*)img->data;
1903     
1904     int sizex = img->width;
1905     int sizey = img->height;
1906     int is_jpeg = i->jpeg;
1907     i->jpeg = 0;
1908
1909     int newsizex=sizex, newsizey=sizey;
1910
1911     /// {
1912     if(is_jpeg && i->config_jpegsubpixels) {
1913         newsizex = (int)(targetwidth*i->config_jpegsubpixels+0.5);
1914         newsizey = (int)(targetheight*i->config_jpegsubpixels+0.5);
1915     } else if(!is_jpeg && i->config_ppmsubpixels) {
1916         newsizex = (int)(targetwidth*i->config_ppmsubpixels+0.5);
1917         newsizey = (int)(targetheight*i->config_ppmsubpixels+0.5);
1918     }
1919     /// }
1920
1921     if(sizex<=0 || sizey<=0 || newsizex<=0 || newsizey<=0)
1922         return -1;
1923
1924     /* TODO: cache images */
1925     *newwidth = sizex;
1926     *newheight  = sizey;
1927     
1928     if(newsizex<sizex || newsizey<sizey) {
1929         msg("<verbose> Scaling %dx%d image to %dx%d", sizex, sizey, newsizex, newsizey);
1930         newpic = swf_ImageScale(mem, sizex, sizey, newsizex, newsizey);
1931         *newwidth = sizex = newsizex;
1932         *newheight  = sizey = newsizey;
1933         mem = newpic;
1934     
1935     }
1936
1937     int num_colors = swf_ImageGetNumberOfPaletteEntries(mem,sizex,sizey,0);
1938     int has_alpha = swf_ImageHasAlpha(mem,sizex,sizey);
1939     
1940     msg("<verbose> Drawing %dx%d %s%simage at size %dx%d (%dx%d), %s%d colors",
1941             sizex, sizey, 
1942             has_alpha?(has_alpha==2?"semi-transparent ":"transparent "):"", 
1943             is_jpeg?"jpeg-":"",
1944             newsizex, newsizey,
1945             targetwidth, targetheight,
1946             /*newsizex, newsizey,*/
1947             num_colors>256?">":"", num_colors>256?256:num_colors);
1948
1949     /*RGBA* pal = (RGBA*)rfx_alloc(sizeof(RGBA)*num_colors);
1950     swf_ImageGetNumberOfPaletteEntries(mem,sizex,sizey,pal);
1951     int t;
1952     for(t=0;t<num_colors;t++) {
1953         printf("%02x%02x%02x%02x ",
1954                 pal[t].r, pal[t].g, pal[t].b, pal[t].a);
1955         if((t&7)==7)
1956             printf("\n");
1957     }
1958     printf("\n");*/
1959
1960     int bitid = -1;
1961     int cacheid = imageInCache(dev, mem, sizex, sizey);
1962
1963     if(cacheid<=0) {
1964         bitid = getNewID(dev);
1965         i->tag = swf_AddImage(i->tag, bitid, mem, sizex, sizey, i->config_jpegquality);
1966         addImageToCache(dev, mem, sizex, sizey);
1967     } else {
1968         bitid = cacheid;
1969     }
1970
1971     if(newpic)
1972         free(newpic);
1973     return bitid;
1974 }
1975
1976 static SRECT gfxline_getSWFbbox(gfxline_t*line)
1977 {
1978     gfxbbox_t bbox = gfxline_getbbox(line);
1979     SRECT r;
1980     r.xmin = (int)(bbox.xmin*20);
1981     r.ymin = (int)(bbox.ymin*20);
1982     r.xmax = (int)(bbox.xmax*20);
1983     r.ymax = (int)(bbox.ymax*20);
1984     return r;
1985 }
1986
1987 static void swf_fillbitmap(gfxdevice_t*dev, gfxline_t*line, gfximage_t*img, gfxmatrix_t*matrix, gfxcxform_t*cxform)
1988 {
1989     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
1990
1991     endshape(dev);
1992     endtext(dev);
1993
1994     int targetx = (int)(sqrt(matrix->m00*matrix->m00 + matrix->m01*matrix->m01)*img->width);
1995     int targety = (int)(sqrt(matrix->m10*matrix->m10 + matrix->m11*matrix->m11)*img->height);
1996
1997     int newwidth=0,newheight=0;
1998     int bitid = add_image(i, img, targetx, targety, &newwidth, &newheight);
1999     if(bitid<0)
2000         return;
2001     double fx = (double)img->width / (double)newwidth;
2002     double fy = (double)img->height / (double)newheight;
2003
2004     MATRIX m;
2005     float m00,m10,tx;
2006     float m01,m11,ty;
2007     m.sx = (int)(65536*20*matrix->m00*fx); m.r1 = (int)(65536*20*matrix->m10*fy);
2008     m.r0 = (int)(65536*20*matrix->m01*fx); m.sy = (int)(65536*20*matrix->m11*fy);
2009     m.tx = (int)(matrix->tx*20);
2010     m.ty = (int)(matrix->ty*20);
2011   
2012     /* shape */
2013     int myshapeid = getNewID(dev);
2014     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE);
2015     SHAPE*shape;
2016     swf_ShapeNew(&shape);
2017     int fsid = swf_ShapeAddBitmapFillStyle(shape,&m,bitid,1);
2018     swf_SetU16(i->tag, myshapeid);
2019     SRECT r = gfxline_getSWFbbox(line);
2020     swf_SetRect(i->tag,&r);
2021     swf_SetShapeStyles(i->tag,shape);
2022     swf_ShapeCountBits(shape,NULL,NULL);
2023     swf_SetShapeBits(i->tag,shape);
2024     swf_ShapeSetAll(i->tag,shape,UNDEFINED_COORD,UNDEFINED_COORD,0,fsid,0);
2025     i->swflastx = i->swflasty = UNDEFINED_COORD;
2026     drawgfxline(dev, line);
2027     swf_ShapeSetEnd(i->tag);
2028     swf_ShapeFree(shape);
2029
2030     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
2031     CXFORM cxform2 = gfxcxform_to_cxform(cxform);
2032     swf_ObjectPlace(i->tag,myshapeid,getNewDepth(dev),&i->page_matrix,&cxform2,NULL);
2033 }
2034
2035 static void swf_startclip(gfxdevice_t*dev, gfxline_t*line)
2036 {
2037     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2038
2039     endtext(dev);
2040     endshape(dev);
2041
2042     if(i->clippos >= 127)
2043     {
2044         msg("<warning> Too many clip levels.");
2045         i->clippos --;
2046     } 
2047
2048     int myshapeid = getNewID(dev);
2049     i->tag = swf_InsertTag(i->tag,ST_DEFINESHAPE);
2050     RGBA col;
2051     memset(&col, 0, sizeof(RGBA));
2052     SHAPE*shape;
2053     swf_ShapeNew(&shape);
2054     int fsid = swf_ShapeAddSolidFillStyle(shape,&col);
2055     swf_SetU16(i->tag,myshapeid);
2056     SRECT r = gfxline_getSWFbbox(line);
2057     swf_SetRect(i->tag,&r);
2058     swf_SetShapeStyles(i->tag,shape);
2059     swf_ShapeCountBits(shape,NULL,NULL);
2060     swf_SetShapeBits(i->tag,shape);
2061     swf_ShapeSetAll(i->tag,shape,UNDEFINED_COORD,UNDEFINED_COORD,0,fsid,0);
2062     i->swflastx = i->swflasty = UNDEFINED_COORD;
2063     drawgfxline(dev, line);
2064     swf_ShapeSetEnd(i->tag);
2065     swf_ShapeFree(shape);
2066
2067     /* TODO: remember the bbox, and check all shapes against it */
2068     
2069     i->tag = swf_InsertTag(i->tag,ST_PLACEOBJECT2);
2070     i->cliptags[i->clippos] = i->tag;
2071     i->clipshapes[i->clippos] = myshapeid;
2072     i->clipdepths[i->clippos] = getNewDepth(dev);
2073     i->clippos++;
2074 }
2075
2076 static void swf_endclip(gfxdevice_t*dev)
2077 {
2078     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2079     if(i->textid>=0)
2080         endtext(dev);
2081     if(i->shapeid>=0)
2082         endshape(dev);
2083
2084     if(!i->clippos) {
2085         msg("<error> Invalid end of clipping region");
2086         return;
2087     }
2088     i->clippos--;
2089     /*swf_ObjectPlaceClip(i->cliptags[i->clippos],i->clipshapes[i->clippos],i->clipdepths[i->clippos],&i->page_matrix,NULL,NULL,
2090             / * clip to depth: * / i->depth <= i->clipdepths[i->clippos]? i->depth : i->depth - 1);
2091     i->depth ++;*/
2092     swf_ObjectPlaceClip(i->cliptags[i->clippos],i->clipshapes[i->clippos],i->clipdepths[i->clippos],&i->page_matrix,NULL,NULL,i->depth);
2093 }
2094 static int gfxline_type(gfxline_t*line)
2095 {
2096     int tmplines=0;
2097     int tmpsplines=0;
2098     int lines=0;
2099     int splines=0;
2100     int haszerosegments=0;
2101     while(line) {
2102         if(line->type == gfx_moveTo) {
2103             tmplines=0;
2104             tmpsplines=0;
2105         } else if(line->type == gfx_lineTo) {
2106             tmplines++;
2107             if(tmplines>lines)
2108                 lines=tmplines;
2109         } else if(line->type == gfx_splineTo) {
2110             tmpsplines++;
2111             if(tmpsplines>lines)
2112                 splines=tmpsplines;
2113         }
2114         line = line->next;
2115     }
2116     if(lines==0 && splines==0) return 0;
2117     else if(lines==1 && splines==0) return 1;
2118     else if(lines==0 && splines==1) return 2;
2119     else if(splines==0) return 3;
2120     else return 4;
2121 }
2122
2123 static int gfxline_has_dots(gfxline_t*line)
2124 {
2125     int tmplines=0;
2126     double x,y;
2127     double dist = 0;
2128     int isline = 0;
2129     while(line) {
2130         if(line->type == gfx_moveTo) {
2131             if(isline && dist < 1) {
2132                 return 1;
2133             }
2134             dist = 0;
2135             isline = 0;
2136         } else if(line->type == gfx_lineTo) {
2137             dist += fabs(line->x - x) + fabs(line->y - y);
2138             isline = 1;
2139         } else if(line->type == gfx_splineTo) {
2140             dist += fabs(line->sx - x) + fabs(line->sy - y) + 
2141                     fabs(line->x - line->sx) + fabs(line->y - line->sy);
2142             isline = 1;
2143         }
2144         x = line->x;
2145         y = line->y;
2146         line = line->next;
2147     }
2148     if(isline && dist < 1) {
2149         return 1;
2150     }
2151     return 0;
2152 }
2153
2154 static int gfxline_fix_short_edges(gfxline_t*line)
2155 {
2156     double x,y;
2157     while(line) {
2158         if(line->type == gfx_lineTo) {
2159             if(fabs(line->x - x) + fabs(line->y - y) < 0.01) {
2160                 line->x += 0.01;
2161             }
2162         } else if(line->type == gfx_splineTo) {
2163             if(fabs(line->sx - x) + fabs(line->sy - y) + 
2164                fabs(line->x - line->sx) + fabs(line->y - line->sy) < 0.01) {
2165                 line->x += 0.01;
2166             }
2167         }
2168         x = line->x;
2169         y = line->y;
2170         line = line->next;
2171     }
2172     return 0;
2173 }
2174
2175 static char is_inside_page(gfxdevice_t*dev, gfxcoord_t x, gfxcoord_t y)
2176 {
2177     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2178     if(x<i->min_x || x>i->max_x) return 0;
2179     if(y<i->min_y || y>i->max_y) return 0;
2180     return 1;
2181 }
2182
2183 static void show_path(ArtSVP*path)
2184 {
2185     int t;
2186     printf("Segments: %d\n", path->n_segs);
2187     for(t=0;t<path->n_segs;t++) {
2188         ArtSVPSeg* seg = &path->segs[t];
2189         printf("Segment %d: %d points, %s, BBox: (%f,%f,%f,%f)\n", 
2190                 t, seg->n_points, seg->dir==0?"UP  ":"DOWN",
2191                 seg->bbox.x0, seg->bbox.y0, seg->bbox.x1, seg->bbox.y1);
2192         int p;
2193         for(p=0;p<seg->n_points;p++) {
2194             ArtPoint* point = &seg->points[p];
2195             printf("        (%f,%f)\n", point->x, point->y);
2196         }
2197     }
2198     printf("\n");
2199 }
2200
2201
2202 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)
2203 {
2204     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2205     int type = gfxline_type(line);
2206     int has_dots = gfxline_has_dots(line);
2207     gfxbbox_t r = gfxline_getbbox(line);
2208     int is_outside_page = !is_inside_page(dev, r.xmin, r.ymin) || !is_inside_page(dev, r.xmax, r.ymax);
2209
2210     /* TODO: * split line into segments, and perform this check for all segments */
2211
2212     if(!has_dots && 
2213        (width <= i->config_caplinewidth 
2214         || (cap_style == gfx_capRound && joint_style == gfx_joinRound)
2215         || (cap_style == gfx_capRound && type<=2))) {
2216         msg("<trace> draw as stroke, type=%d dots=%d", type, has_dots);
2217         endtext(dev);
2218         swfoutput_setstrokecolor(dev, color->r, color->g, color->b, color->a);
2219         swfoutput_setlinewidth(dev, width);
2220         startshape(dev);
2221         stopFill(dev);
2222         drawgfxline(dev, line);
2223     } else {
2224         msg("<trace> draw as polygon, type=%d dots=%d", type, has_dots);
2225         if(has_dots)
2226             gfxline_fix_short_edges(line);
2227         /* we need to convert the line into a polygon */
2228         ArtSVP* svp = gfxstrokeToSVP(line, width, cap_style, joint_style, miterLimit);
2229         gfxline_t*gfxline = SVPtogfxline(svp);
2230         dev->fill(dev, gfxline, color);
2231         free(gfxline);
2232         art_svp_free(svp);
2233     }
2234 }
2235 static void swf_fill(gfxdevice_t*dev, gfxline_t*line, gfxcolor_t*color)
2236 {
2237     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2238     gfxbbox_t r = gfxline_getbbox(line);
2239     int is_outside_page = !is_inside_page(dev, r.xmin, r.ymin) || !is_inside_page(dev, r.xmax, r.ymax);
2240
2241     endtext(dev);
2242     if(!i->config_ignoredraworder)
2243         endshape(dev);
2244     swfoutput_setfillcolor(dev, color->r, color->g, color->b, color->a);
2245     startshape(dev);
2246     startFill(dev);
2247     i->fill=1;
2248     drawgfxline(dev, line);
2249     msg("<trace> end of swf_fill (shapeid=%d)", i->shapeid);
2250 }
2251 static void swf_fillgradient(gfxdevice_t*dev, gfxline_t*line, gfxgradient_t*gradient, gfxgradienttype_t type, gfxmatrix_t*matrix)
2252 {
2253     msg("<error> Gradient filling not implemented yet");
2254 }
2255
2256 static SWFFONT* gfxfont_to_swffont(gfxfont_t*font, char* id)
2257 {
2258     SWFFONT*swffont = (SWFFONT*)rfx_calloc(sizeof(SWFFONT));
2259     int t;
2260     swffont->id = -1;
2261     swffont->version = 2;
2262     swffont->name = (U8*)strdup(id);
2263     swffont->layout = (SWFLAYOUT*)rfx_calloc(sizeof(SWFLAYOUT));
2264     swffont->layout->ascent = 0; /* ? */
2265     swffont->layout->descent = 0;
2266     swffont->layout->leading = 0;
2267     swffont->layout->bounds = (SRECT*)rfx_calloc(sizeof(SRECT)*font->num_glyphs);
2268     swffont->encoding = FONT_ENCODING_UNICODE;
2269     swffont->numchars = font->num_glyphs;
2270     swffont->maxascii = font->max_unicode;
2271     swffont->ascii2glyph = (int*)rfx_calloc(sizeof(int)*swffont->maxascii);
2272     swffont->glyph2ascii = (U16*)rfx_calloc(sizeof(U16)*swffont->numchars);
2273     swffont->glyph = (SWFGLYPH*)rfx_calloc(sizeof(SWFGLYPH)*swffont->numchars);
2274     swffont->glyphnames = (char**)rfx_calloc(sizeof(char*)*swffont->numchars);
2275     for(t=0;t<font->max_unicode;t++) {
2276         swffont->ascii2glyph[t] = font->unicode2glyph[t];
2277     }
2278     for(t=0;t<font->num_glyphs;t++) {
2279         drawer_t draw;
2280         gfxline_t*line;
2281         swffont->glyph2ascii[t] = font->glyphs[t].unicode;
2282         if(font->glyphs[t].name) {
2283             swffont->glyphnames[t] = strdup(font->glyphs[t].name);
2284         } else {
2285             swffont->glyphnames[t] = 0;
2286         }
2287         swffont->glyph[t].advance = (int)(font->glyphs[t].advance * 20);
2288
2289         swf_Shape01DrawerInit(&draw, 0);
2290         line = font->glyphs[t].line;
2291         while(line) {
2292             FPOINT c,to;
2293             c.x = line->sx; c.y = line->sy;
2294             to.x = line->x; to.y = line->y;
2295             if(line->type == gfx_moveTo) {
2296                 draw.moveTo(&draw, &to);
2297             } else if(line->type == gfx_lineTo) {
2298                 draw.lineTo(&draw, &to);
2299             } else if(line->type == gfx_splineTo) {
2300                 draw.splineTo(&draw, &c, &to);
2301             }
2302             line = line->next;
2303         }
2304         draw.finish(&draw);
2305         swffont->glyph[t].shape = swf_ShapeDrawerToShape(&draw);
2306         swffont->layout->bounds[t] = swf_ShapeDrawerGetBBox(&draw);
2307         draw.dealloc(&draw);
2308     }
2309     return swffont;
2310 }
2311
2312 static void swf_addfont(gfxdevice_t*dev, char*fontid, gfxfont_t*font)
2313 {
2314     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2315
2316     if(i->swffont && i->swffont->name && !strcmp((char*)i->swffont->name,fontid))
2317         return; // the requested font is the current font
2318     
2319     fontlist_t*last=0,*l = i->fontlist;
2320     while(l) {
2321         last = l;
2322         if(!strcmp((char*)l->swffont->name, fontid)) {
2323             return; // we already know this font
2324         }
2325         l = l->next;
2326     }
2327     l = (fontlist_t*)rfx_calloc(sizeof(fontlist_t));
2328     l->swffont = gfxfont_to_swffont(font, fontid);
2329     l->next = 0;
2330     if(last) {
2331         last->next = l;
2332     } else {
2333         i->fontlist = l;
2334     }
2335     swf_FontSetID(l->swffont, getNewID(i->dev));
2336
2337     if(getScreenLogLevel() >= LOGLEVEL_DEBUG)  {
2338         // print font information
2339         msg("<debug> Font %s",fontid);
2340         msg("<debug> |   ID: %d", l->swffont->id);
2341         msg("<debug> |   Version: %d", l->swffont->version);
2342         msg("<debug> |   Name: %s", l->swffont->name);
2343         msg("<debug> |   Numchars: %d", l->swffont->numchars);
2344         msg("<debug> |   Maxascii: %d", l->swffont->maxascii);
2345         msg("<debug> |   Style: %d", l->swffont->style);
2346         msg("<debug> |   Encoding: %d", l->swffont->encoding);
2347         for(int iii=0; iii<l->swffont->numchars;iii++) {
2348             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, 
2349                     l->swffont->layout->bounds[iii].xmin/20.0,
2350                     l->swffont->layout->bounds[iii].ymin/20.0,
2351                     l->swffont->layout->bounds[iii].xmax/20.0,
2352                     l->swffont->layout->bounds[iii].ymax/20.0
2353                     );
2354             int t;
2355             for(t=0;t<l->swffont->maxascii;t++) {
2356                 if(l->swffont->ascii2glyph[t] == iii)
2357                     msg("<debug> | - maps to %d",t);
2358             }
2359         }
2360     }
2361 }
2362
2363 static void swf_switchfont(gfxdevice_t*dev, char*fontid)
2364 {
2365     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2366
2367     if(i->swffont && i->swffont->name && !strcmp((char*)i->swffont->name,fontid))
2368         return; // the requested font is the current font
2369     
2370     fontlist_t*l = i->fontlist;
2371     while(l) {
2372         if(!strcmp((char*)l->swffont->name, fontid)) {
2373             i->swffont = l->swffont;
2374             return; //done!
2375         }
2376         l = l->next;
2377     }
2378     msg("<error> Unknown font id: %s", fontid);
2379     return;
2380 }
2381
2382 static void swf_drawchar(gfxdevice_t*dev, char*fontid, int glyph, gfxcolor_t*color, gfxmatrix_t*matrix)
2383 {
2384     swfoutput_internal*i = (swfoutput_internal*)dev->internal;
2385         
2386     if(!i->swffont || !i->swffont->name || strcmp((char*)i->swffont->name,fontid)) // not equal to current font
2387     {
2388         /* TODO: remove the need for this (enhance getcharacterbbox so that it can cope
2389                  with multiple fonts */
2390         endtext(dev);
2391
2392         swf_switchfont(dev, fontid); // set the current font
2393     }
2394     swfoutput_setfontmatrix(dev, matrix->m00, matrix->m01, matrix->m10, matrix->m11);
2395    
2396     swfmatrix m;
2397     m.m11 = i->fontm11;
2398     m.m12 = i->fontm12;
2399     m.m21 = i->fontm21;
2400     m.m22 = i->fontm22;
2401     m.m31 = matrix->tx;
2402     m.m32 = matrix->ty;
2403     drawchar(dev, i->swffont, 0, glyph, -1, &m, color);
2404 }