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