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