The image routines don't try to insert broken images into the swf stream
[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 <string.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include "swfoutput.h"
25 #include "spline.h"
26 extern "C" {
27 #include "../lib/log.h"
28 #include "../lib/rfxswf.h"
29 }
30 #define standardEncodingSize 335
31 extern char *standardEncodingNames[standardEncodingSize];
32
33 int opennewwindow=0;
34 int ignoredraworder=0;
35 int drawonlyshapes=0;
36 int jpegquality=85;
37 int storeallcharacters=0;
38 static int flag_protected = 0;
39
40 typedef unsigned char u8;
41 typedef unsigned short int u16;
42 typedef unsigned long int u32;
43
44 static int fi;
45 static char* filename = 0;
46 static SWF swf;
47 static TAG *tag;
48 static int currentswfid = 0;
49 static int depth = 1;
50 static int startdepth = 1;
51
52 static SHAPE* shape;
53 static int shapeid = -1;
54 static int textid = -1;
55
56 static int drawmode = -1;
57 static char storefont = 0;
58 static int fillstyleid;
59 static int linestyleid;
60 static int swflastx=0;
61 static int swflasty=0;
62 static int lastwasfill = 0;
63 static char fill = 0;
64 static int sizex;
65 static int sizey;
66 TAG* cliptags[128];
67 int clipshapes[128];
68 u32 clipdepths[128];
69 int clippos = 0;
70
71 int CHARMIDX = 0;
72 int CHARMIDY = 0;
73
74 void startshape(struct swfoutput* obj);
75 void starttext(struct swfoutput* obj);
76 void endshape();
77 void endtext();
78
79 // matrix multiplication. changes p0
80 void transform (plotxy*p0,struct swfmatrix*m)
81 {
82     double x,y;
83     x = m->m11*p0->x+m->m12*p0->y;
84     y = m->m21*p0->x+m->m22*p0->y;
85     p0->x = x + m->m13;
86     p0->y = y + m->m23;
87 }
88
89 // write a move-to command into the swf
90 void moveto(TAG*tag, plotxy p0)
91 {
92     int rx = (int)(p0.x*20);
93     int ry = (int)(p0.y*20);
94     if(rx!=swflastx || ry!=swflasty) {
95       swf_ShapeSetMove (tag, shape, rx,ry);
96     }
97     swflastx=rx;
98     swflasty=ry;
99 }
100
101 // write a line-to command into the swf
102 void lineto(TAG*tag, plotxy p0)
103 {
104     int rx = ((int)(p0.x*20)-swflastx);
105     int ry = ((int)(p0.y*20)-swflasty);
106     /* we can't skip this for rx=0,ry=0, those
107        are plots */
108     swf_ShapeSetLine (tag, shape, rx,ry);
109     swflastx+=rx;
110     swflasty+=ry;
111 }
112
113 // write a spline-to command into the swf
114 void splineto(TAG*tag, plotxy control,plotxy end)
115 {
116     int cx = ((int)(control.x*20)-swflastx);
117     int cy = ((int)(control.y*20)-swflasty);
118     swflastx += cx;
119     swflasty += cy;
120     int ex = ((int)(end.x*20)-swflastx);
121     int ey = ((int)(end.y*20)-swflasty);
122     swflastx += ex;
123     swflasty += ey;
124     swf_ShapeSetCurve(tag, shape, cx,cy,ex,ey);
125 }
126
127 /* write a line, given two points and the transformation
128    matrix. */
129 void line(TAG*tag, plotxy p0, plotxy p1, struct swfmatrix*m)
130 {
131     transform(&p0,m);
132     transform(&p1,m);
133     moveto(tag, p0);
134     lineto(tag, p1);
135 }
136
137 /* write a cubic (!) spline. This involves calling the approximate()
138    function out of spline.cc to convert it to a quadratic spline.  */
139 void spline(TAG*tag,plotxy p0,plotxy p1,plotxy p2,plotxy p3,struct swfmatrix*m)
140 {
141     double d;
142     struct qspline q[16];
143     int num;
144     int t;
145     transform(&p0,m);
146     transform(&p1,m);
147     transform(&p2,m);
148     transform(&p3,m);
149
150     num = approximate(p0,p1,p2,p3,q);
151     for(t=0;t<num;t++) {
152         moveto(tag,q[t].start);
153         splineto(tag,q[t].control, q[t].end);
154     }
155 }
156
157 /* draw a T1 outline. These are generated by pdf2swf and by t1lib.
158    (representing characters) */
159 void drawpath(TAG*tag, T1_OUTLINE*outline, struct swfmatrix*m)
160 {
161     if(tag->id != ST_DEFINEFONT &&
162         tag->id != ST_DEFINESHAPE &&
163         tag->id != ST_DEFINESHAPE2 &&
164         tag->id != ST_DEFINESHAPE3)
165     {
166         logf("<error> internal error: drawpath needs a shape tag, not %d\n",tag->id);
167         exit(1);
168     }
169     int log = 0;
170
171     double x=0,y=0;
172     double lastx=0,lasty=0;
173     double firstx=0,firsty=0;
174     int init=1;
175
176     while (outline)
177     {
178         x += (outline->dest.x/(float)0xffff);
179         y += (outline->dest.y/(float)0xffff);
180         if(outline->type == T1_PATHTYPE_MOVE)
181         {
182             if(((int)(lastx*20) != (int)(firstx*20) ||
183                 (int)(lasty*20) != (int)(firsty*20)) &&
184                      fill && !init)
185             {
186                 plotxy p0;
187                 plotxy p1;
188                 p0.x=lastx;
189                 p0.y=lasty;
190                 p1.x=firstx;
191                 p1.y=firsty;
192                 if(log) printf("fix: %f,%f -> %f,%f\n",p0.x,p0.y,p1.x,p1.y);
193                 line(tag, p0, p1, m);
194             }
195             firstx=x;
196             firsty=y;
197             init = 0;
198         }
199         else if(outline->type == T1_PATHTYPE_LINE) 
200         {
201             plotxy p0;
202             plotxy p1;
203             p0.x=lastx;
204             p0.y=lasty;
205             p1.x=x;
206             p1.y=y;
207             if(log) printf("line: %f,%f -> %f,%f\n",p0.x,p0.y,p1.x,p1.y);
208             line(tag, p0,p1,m);
209         }
210         else if(outline->type == T1_PATHTYPE_BEZIER)
211         {
212             plotxy p0;
213             plotxy p1;
214             plotxy p2;
215             plotxy p3;
216             T1_BEZIERSEGMENT*o2 = (T1_BEZIERSEGMENT*)outline;
217             p0.x=x; 
218             p0.y=y;
219             p1.x=o2->C.x/(float)0xffff+lastx;
220             p1.y=o2->C.y/(float)0xffff+lasty;
221             p2.x=o2->B.x/(float)0xffff+lastx;
222             p2.y=o2->B.y/(float)0xffff+lasty;
223             p3.x=lastx;
224             p3.y=lasty;
225             if(log) printf("spline: %f,%f -> %f,%f\n",p3.x,p3.y,p0.x,p0.y);
226             spline(tag,p0,p1,p2,p3,m);
227         } 
228         else {
229          logf("<error> drawpath: unknown outline type:%d\n", outline->type);
230         }
231         lastx=x;
232         lasty=y;
233         outline = outline->link;
234     }
235     if(((int)(lastx*20) != (int)(firstx*20) ||
236         (int)(lasty*20) != (int)(firsty*20)) &&
237              fill)
238     {
239         plotxy p0;
240         plotxy p1;
241         p0.x=lastx;
242         p0.y=lasty;
243         p1.x=firstx;
244         p1.y=firsty;
245         if(log) printf("fix: %f,%f -> %f,%f\n",p0.x,p0.y,p1.x,p1.y);
246         line(tag, p0, p1, m);
247     }
248 }
249
250 int colorcompare(RGBA*a,RGBA*b)
251 {
252
253     if(a->r!=b->r ||
254        a->g!=b->g ||
255        a->b!=b->b ||
256        a->a!=b->a) {
257         return 0;
258     }
259     return 1;
260 }
261
262 static const int CHARDATAMAX = 1024;
263 struct chardata {
264     int charid;
265     int fontid;
266     int x;
267     int y;
268     int size;
269     RGBA color;
270 } chardata[CHARDATAMAX];
271 int chardatapos = 0;
272
273 void putcharacters(TAG*tag)
274 {
275     int t;
276     SWFFONT font;
277     RGBA color;
278     color.r = chardata[0].color.r^255;
279     color.g = 0;
280     color.b = 0;
281     color.a = 0;
282     int lastfontid;
283     int lastx;
284     int lasty;
285     int lastsize;
286     int charids[128];
287     int charadvance[128];
288     int charstorepos;
289     int pass;
290     int glyphbits=1; //TODO: can this be zero?
291     int advancebits=1;
292
293     if(tag->id != ST_DEFINETEXT &&
294         tag->id != ST_DEFINETEXT2) {
295         logf("<error> internal error: putcharacters needs an text tag, not %d\n",tag->id);
296         exit(1);
297     }
298     if(!chardatapos) {
299         logf("<warning> putcharacters called with zero characters");
300     }
301
302     for(pass = 0; pass < 2; pass++)
303     {
304         charstorepos = 0;
305         lastfontid = -1;
306         lastx = CHARMIDX;
307         lasty = CHARMIDY;
308         lastsize = -1;
309
310         if(pass==1)
311         {
312             advancebits++; // add sign bit
313             swf_SetU8(tag, glyphbits);
314             swf_SetU8(tag, advancebits);
315         }
316
317         for(t=0;t<=chardatapos;t++)
318         {
319             if(lastfontid != chardata[t].fontid || 
320                     lastx!=chardata[t].x ||
321                     lasty!=chardata[t].y ||
322                     !colorcompare(&color, &chardata[t].color) ||
323                     charstorepos==127 ||
324                     lastsize != chardata[t].size ||
325                     t == chardatapos)
326             {
327                 if(charstorepos && pass==0)
328                 {
329                     int s;
330                     for(s=0;s<charstorepos;s++)
331                     {
332                         while(charids[s]>=(1<<glyphbits))
333                             glyphbits++;
334                         while(charadvance[s]>=(1<<advancebits))
335                             advancebits++;
336                     }
337                 }
338                 if(charstorepos && pass==1)
339                 {
340                     tag->writeBit = 0; // Q&D
341                     swf_SetBits(tag, 0, 1); // GLYPH Record
342                     swf_SetBits(tag, charstorepos, 7); // number of glyphs
343                     int s;
344                     for(s=0;s<charstorepos;s++)
345                     {
346                         swf_SetBits(tag, charids[s], glyphbits);
347                         swf_SetBits(tag, charadvance[s], advancebits);
348                     }
349                 }
350                 charstorepos = 0;
351
352                 if(pass == 1 && t<chardatapos)
353                 {
354                     RGBA*newcolor=0;
355                     SWFFONT*newfont=0;
356                     int newx = 0;
357                     int newy = 0;
358                     if(lastx != chardata[t].x ||
359                        lasty != chardata[t].y)
360                     {
361                         newx=chardata[t].x;
362                         newy=chardata[t].y;
363                     }
364                     if(!colorcompare(&color, &chardata[t].color)) 
365                     {
366                         color = chardata[t].color;
367                         newcolor = &color;
368                     }
369                     font.id = chardata[t].fontid;
370                     if(lastfontid != chardata[t].fontid || lastsize != chardata[t].size)
371                         newfont = &font;
372
373                     tag->writeBit = 0; // Q&D
374                     swf_TextSetInfoRecord(tag, newfont, chardata[t].size, newcolor, newx,newy);
375                 }
376
377                 lastfontid = chardata[t].fontid;
378                 lastx = chardata[t].x;
379                 lasty = chardata[t].y;
380                 lastsize = chardata[t].size;
381             }
382
383             if(t==chardatapos)
384                     break;
385
386             int advance;
387             int nextt = t==chardatapos-1?t:t+1;
388             int rel = chardata[nextt].x-chardata[t].x;
389             if(rel>=0 && (rel<(1<<(advancebits-1)) || pass==0)) {
390                advance = rel;
391                lastx=chardata[nextt].x;
392             }
393             else {
394                advance = 0;
395                lastx=chardata[t].x;
396             }
397             charids[charstorepos] = chardata[t].charid;
398             charadvance[charstorepos] = advance;
399             charstorepos ++;
400         }
401     }
402     chardatapos = 0;
403 }
404
405 void putcharacter(struct swfoutput*obj, int fontid, int charid, 
406                     int x,int y, int size)
407 {
408     if(chardatapos == CHARDATAMAX)
409     {
410         endtext();
411         starttext(obj);
412     }
413     chardata[chardatapos].fontid = fontid;
414     chardata[chardatapos].charid = charid;
415     chardata[chardatapos].x = x;
416     chardata[chardatapos].y = y;
417     chardata[chardatapos].color = obj->fillrgb;
418     chardata[chardatapos].size = size;
419     chardatapos++;
420 }
421
422
423 /* process a character. */
424 void drawchar(struct swfoutput*obj, SWFFont*font, char*character, int charnr, swfmatrix*m)
425 {
426     int usefonts=1;
427     if(m->m12!=0 || m->m21!=0)
428         usefonts=0;
429     if(m->m11 != m->m22)
430         usefonts=0;
431
432     if(usefonts && ! drawonlyshapes)
433     {
434         int charid = font->getSWFCharID(character, charnr);
435         if(shapeid>=0)
436             endshape();
437         if(textid<0)
438             starttext(obj);
439         putcharacter(obj, font->swfid, charid,(int)(m->m13*20),(int)(m->m23*20),
440                 (int)(m->m11*20/2+0.5)); //where does the /2 come from?
441     }
442     else
443     {
444         T1_OUTLINE*outline = font->getOutline(character);
445         char* charname = character;
446
447         if(!outline) {
448          logf("<warning> Didn't find %s in current charset (%s)", 
449                  character,font->getName());
450          return;
451         }
452         
453         swfmatrix m2=*m;    
454         m2.m11/=100;
455         m2.m21/=100;
456         m2.m12/=100;
457         m2.m22/=100;
458
459         if(textid>=0)
460             endtext();
461         if(shapeid<0)
462             startshape(obj);
463
464         if(!lastwasfill)
465          swf_ShapeSetStyle(tag,shape,0x8000,fillstyleid,0);
466         lastwasfill = 1;
467
468         int lf = fill;
469         fill = 1;
470         drawpath(tag, outline, &m2);
471         fill = lf;
472     }
473 }
474
475 /* draw a curved polygon. */
476 void swfoutput_drawpath(swfoutput*output, T1_OUTLINE*outline, 
477                             struct swfmatrix*m)
478 {
479     if(textid>=0)
480         endtext();
481     if(shapeid<0)
482         startshape(output);
483
484     if(lastwasfill && !fill)
485     {
486      swf_ShapeSetStyle(tag,shape,linestyleid,0x8000,0);
487      lastwasfill = 0;
488     }
489     if(!lastwasfill && fill)
490     {
491      swf_ShapeSetStyle(tag,shape,0x8000,fillstyleid,0);
492      lastwasfill = 1;
493     }
494
495     drawpath(tag, outline,m); 
496 }
497
498 /* SWFFont: copy all t1 font outlines to a local 
499    array. */
500 SWFFont::SWFFont(char*name, int id, char*filename)
501 {
502     if(!T1_GetFontName(id))
503         T1_LoadFont(id);
504
505     this->name = strdup(T1_GetFontFileName(id));
506     this->fontid = strdup(name);
507     this->t1id = id;
508     
509     char**a= T1_GetAllCharNames(id);
510     int t, outlinepos=0;
511     char*map[256];
512
513     t=0;
514     while(a[t])
515         t++;
516     this->charnum = t;
517
518     if(!charnum) 
519         return;
520     logf("<verbose> Font %s(%d): Storing %d outlines.\n", name, id, charnum);
521
522     this->standardtablesize = 256;
523     if(this->charnum < this->standardtablesize)
524         this->standardtablesize = this->charnum;
525     this->standardtable = (char**)malloc(standardtablesize*sizeof(char*));
526
527     for(t = 0; t < this->standardtablesize; t++) {
528         char*name = T1_GetCharName(id,t);
529         if(!name)
530             name = "";
531         standardtable[t] = strdup(name);
532     }
533     
534     outline = (T1_OUTLINE**)malloc(charnum*sizeof(T1_OUTLINE*));
535     charname = (char**)malloc(charnum*sizeof(char*));
536     width = (int*)malloc(charnum*sizeof(int));
537     memset(width, 0, charnum*sizeof(int));
538     memset(charname, 0, charnum*sizeof(char*));
539     used = (char*)malloc(charnum*sizeof(char));
540     char2swfcharid = (U16*)malloc(charnum*2);
541     swfcharid2char = (U16*)malloc(charnum*2);
542     swfcharpos = 0;
543
544     memset(used,0,charnum*sizeof(char));
545
546     this->swfid = ++currentswfid;
547     
548     t=0;
549     while(*a)
550     {
551         map[t] = *a;
552         a++;
553         t++;
554         if(t==256 || !*a) {
555             int s;
556             for(s=t;s<256;s++)
557                 map[s] = ".notdef";
558
559             int ret = T1_ReencodeFont(id, map);
560             if(ret) {
561              T1_DeleteFont(id);
562              T1_LoadFont(id);
563              int ret = T1_ReencodeFont(id, map);
564              if(ret)
565                fprintf(stderr,"Can't reencode font: (%s) ret:%d\n",filename, ret);
566             }
567
568             // parsecharacters
569             for(s=0;s<t;s++)
570             {
571                 char* name = T1_GetCharName(id, s);
572                 if(!name) name = "";
573                 this->outline[outlinepos] = T1_CopyOutline(T1_GetCharOutline(id, s, 100.0, 0));
574                 this->width[outlinepos] = T1_GetCharWidth(id, s);
575                 this->charname[outlinepos] = strdup(name);
576                 outlinepos++;
577             }
578             t=0;
579         }
580     }
581 }
582
583 /* free all tables, write out definefont tags */
584 SWFFont::~SWFFont()
585 {
586     int t,usednum=0;
587     int*ptr; 
588
589     if(storeallcharacters)
590     {
591         int t;
592         for(t=0;t<this->charnum;t++) 
593         {
594             if(this->charname[t])
595               getSWFCharID(this->charname[t], -1);
596         }
597     }
598     
599     ptr = (int*)malloc(swfcharpos*sizeof(int));
600
601     for(t=0;t<charnum;t++)
602         if(used[t]) usednum++;
603
604     if(usednum && !drawonlyshapes)
605     {
606         logf("<verbose> Font %s has %d used characters",fontid, usednum);
607         TAG*ftag = swf_InsertTag(swf.firstTag,ST_DEFINEFONT);
608         swf_SetU16(ftag, this->swfid);
609         int initpos = swf_GetDataSize(ftag);
610         swfmatrix m;
611         m.m11 = m.m22 = 1;
612         m.m21 = m.m12 = 0;
613         m.m13 = CHARMIDX;
614         m.m23 = CHARMIDY;
615
616         for(t=0;t<swfcharpos;t++) 
617         {
618             ptr[t] = swf_GetDataSize(ftag);
619             swf_SetU16(ftag, 0x1234);
620         }
621         for(t=0;t<swfcharpos;t++)
622         {
623             *(U16*)&ftag->data[ptr[t]] = swf_GetDataSize(ftag)-initpos;
624             swflastx=0;
625             swflasty=0;
626             swf_SetU8(ftag,0x10); //0 fill bits, 0 linestyle bits
627             SHAPE s;
628             s.bits.fill = 1;
629             s.bits.line = 0;
630             swf_ShapeSetStyle(ftag,&s,0,1,0);
631             int lastfill = fill;
632             fill = 1;
633             storefont = 1;
634             drawpath(ftag, outline[swfcharid2char[t]],&m);
635             storefont = 0;
636             fill = lastfill;
637             swf_ShapeSetEnd(ftag);
638         }
639         ftag = swf_InsertTag(ftag,ST_DEFINEFONTINFO);
640         swf_SetU16(ftag, this->swfid);
641         if(this->fontid) {
642             swf_SetU8(ftag, strlen(this->fontid));
643             swf_SetBlock(ftag, (U8*)this->fontid, strlen(this->fontid));
644         } else {
645             swf_SetU8(ftag, 0);
646         }
647         swf_SetU8(ftag, 0); //flags
648         for(t=0;t<swfcharpos;t++)
649         {
650             int s;
651             char * name = this->charname[this->swfcharid2char[t]];
652             for(s=0;s<256;s++) {
653                 if(standardEncodingNames[s] && 
654                         !strcmp(name,standardEncodingNames[s]))
655                     break;
656             }
657             swf_SetU8(ftag, (U8)s);
658         }
659     }
660
661     free(ptr);
662     free(outline);
663     for(t=0;t<charnum;t++)
664         free(charname[t]);
665     for(t=0;t<standardtablesize;t++)
666         if(standardtable[t]) {
667             free(standardtable[t]);
668         }
669     free(standardtable);
670     free(charname);
671     free(width);
672     free(used);
673     free(swfcharid2char);
674     free(char2swfcharid);
675 }
676
677 T1_OUTLINE*SWFFont::getOutline(char*name)
678 {
679     int t;
680     for(t=0;t<this->charnum;t++) {
681         if(!strcmp(this->charname[t],name)) {
682             if(!used[t])
683             {
684                 swfcharid2char[swfcharpos] = t;
685                 char2swfcharid[t] = swfcharpos;
686                 swfcharpos++;
687                 used[t] = 1;
688             }
689             return outline[t];
690         }
691     }
692     return 0;
693 }
694
695 int SWFFont::getSWFCharID(char*name, int charnr)
696 {
697     int t;
698     for(t=0;t<this->charnum;t++) {
699         if(!strcmp(this->charname[t],name)) {
700             if(!used[t])
701             {
702                 swfcharid2char[swfcharpos] = t;
703                 char2swfcharid[t] = swfcharpos++;
704                 used[t] = 1;
705             }
706             return char2swfcharid[t];
707         }
708     }
709     if(this->standardtable && charnr>=0 && charnr < this->standardtablesize) {
710         return getSWFCharID(this->standardtable[charnr], -1);
711     }
712     logf("<warning> Didn't find character '%s' in font '%s'", name, this->name);
713     return 0;
714 }
715
716 char*SWFFont::getName()
717 {
718     return this->name;
719 }
720
721 struct fontlist_t 
722 {
723     SWFFont * font;
724     fontlist_t*next;
725 } *fontlist = 0;
726
727 /* set's the t1 font index of the font to use for swfoutput_drawchar(). */
728 void swfoutput_setfont(struct swfoutput*obj, char*fontid, int t1id, char*filename)
729 {
730     fontlist_t*last=0,*iterator;
731     if(obj->font && !strcmp(obj->font->fontid,fontid))
732         return;
733
734     iterator = fontlist;
735     while(iterator) {
736         if(!strcmp(iterator->font->fontid,fontid))
737             break;
738         last = iterator;
739         iterator = iterator->next;
740     }
741     if(iterator) 
742     {
743         obj->font = iterator->font;
744         return ;
745     }
746
747     if(t1id<0) {
748         logf("<error> internal error: t1id:%d, fontid:%s\n", t1id,fontid);
749     }
750     
751     SWFFont*font = new SWFFont(fontid, t1id, filename);
752     iterator = new fontlist_t;
753     iterator->font = font;
754     iterator->next = 0;
755
756     if(last) 
757         last->next = iterator;
758     else 
759         fontlist = iterator;
760     obj->font = font;
761 }
762
763 int swfoutput_queryfont(struct swfoutput*obj, char*fontid)
764 {
765     fontlist_t *iterator = fontlist;
766     while(iterator) {
767         if(!strcmp(iterator->font->fontid,fontid))
768             return 1;
769         iterator = iterator->next;
770     }
771     return 0;
772 }
773
774 /* set's the matrix which is to be applied to characters drawn by
775    swfoutput_drawchar() */
776 void swfoutput_setfontmatrix(struct swfoutput*obj,double m11,double m12,
777                                                   double m21,double m22)
778 {
779     if(obj->fontm11 == m11 &&
780        obj->fontm12 == m12 &&
781        obj->fontm21 == m21 &&
782        obj->fontm22 == m22)
783         return;
784 //    if(textid>=0)
785 //      endtext();
786     obj->fontm11 = m11;
787     obj->fontm12 = m12;
788     obj->fontm21 = m21;
789     obj->fontm22 = m22;
790 }
791
792 /* draws a character at x,y. */
793 void swfoutput_drawchar(struct swfoutput* obj,double x,double y,char*character, int charnr) 
794 {
795     swfmatrix m;
796     m.m11 = obj->fontm11;
797     m.m12 = obj->fontm12;
798     m.m21 = obj->fontm21;
799     m.m22 = obj->fontm22;
800     m.m13 = x;
801     m.m23 = y;
802     drawchar(obj, obj->font, character, charnr, &m);
803 }
804
805 /* initialize the swf writer */
806 void swfoutput_init(struct swfoutput* obj, char*_filename, int _sizex, int _sizey) 
807 {
808   GLYPH *glyph;
809   RGBA rgb;
810   SRECT r;
811   memset(obj, 0, sizeof(struct swfoutput));
812   filename = _filename;
813   sizex = _sizex;
814   sizey = _sizey;
815
816   logf("<verbose> initializing swf output for size %d*%d\n", sizex,sizey);
817
818   obj->font = 0;
819   
820   memset(&swf,0x00,sizeof(SWF));
821
822   swf.fileVersion    = 4;
823   swf.frameRate      = 0x0040; // 1 frame per 4 seconds
824   swf.movieSize.xmax = 20*sizex;
825   swf.movieSize.ymax = 20*sizey;
826   
827   swf.firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
828   tag = swf.firstTag;
829   rgb.r = 0xff;
830   rgb.g = 0xff;
831   rgb.b = 0xff;
832   swf_SetRGB(tag,&rgb);
833   if(flag_protected)  // good practice! /r
834     tag = swf_InsertTag(tag, ST_PROTECT);
835   depth = 1;
836   startdepth = depth;
837 }
838
839 void swfoutput_setprotected() //write PROTECT tag
840 {
841   flag_protected = 1;
842 }
843
844 void startshape(struct swfoutput*obj)
845 {
846   RGBA rgb;
847   SRECT r;
848
849   if(textid>=0)
850       endtext();
851
852   tag = swf_InsertTag(tag,ST_DEFINESHAPE);
853
854   swf_ShapeNew(&shape);
855   linestyleid = swf_ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
856   rgb.r = obj->fillrgb.r;
857   rgb.g = obj->fillrgb.g;
858   rgb.b = obj->fillrgb.b;
859   fillstyleid = swf_ShapeAddSolidFillStyle(shape,&obj->fillrgb);
860
861   shapeid = ++currentswfid;
862   swf_SetU16(tag,shapeid);  // ID
863
864   r.xmin = 0;
865   r.ymin = 0;
866   r.xmax = 20*sizex;
867   r.ymax = 20*sizey;
868   
869   swf_SetRect(tag,&r);
870
871   swf_SetShapeStyles(tag,shape);
872   swf_ShapeCountBits(shape,NULL,NULL);
873   swf_SetShapeBits(tag,shape);
874
875   swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,linestyleid,0,0);
876   swflastx=swflasty=0;
877   lastwasfill = 0;
878 }
879
880 void starttext(struct swfoutput*obj)
881 {
882   SRECT r;
883   MATRIX m;
884   if(shapeid>=0)
885       endshape();
886   tag = swf_InsertTag(tag,ST_DEFINETEXT);
887   textid = ++currentswfid;
888   swf_SetU16(tag, textid);
889
890   r.xmin = 0;
891   r.ymin = 0;
892   r.xmax = 20*sizex;
893   r.ymax = 20*sizey;
894   
895   swf_SetRect(tag,&r);
896
897   m.sx = 65536;
898   m.sy = 65536;
899   m.r0 = 0;
900   m.r1 = 0;
901   m.tx = 0;
902   m.ty = 0;
903  
904   swf_SetMatrix(tag,&m);
905   swflastx=swflasty=0;
906 }
907
908 void endshape()
909 {
910     if(shapeid<0) 
911         return;
912     swf_ShapeSetEnd(tag);
913     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
914     swf_ObjectPlace(tag,shapeid,/*depth*/depth++,NULL,NULL,NULL);
915     shapeid = -1;
916 }
917
918 void endtext()
919 {
920     if(textid<0)
921         return;
922     putcharacters(tag);
923     swf_SetU8(tag,0);
924     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
925     swf_ObjectPlace(tag,textid,/*depth*/depth++,NULL,NULL,NULL);
926     textid = -1;
927 }
928
929 void endpage(struct swfoutput*obj)
930 {
931     if(shapeid>=0)
932       endshape();
933     if(textid>=0)
934       endtext();
935     while(clippos)
936         swfoutput_endclip(obj);
937     tag = swf_InsertTag(tag,ST_SHOWFRAME);
938 }
939
940 void swfoutput_newpage(struct swfoutput*obj)
941 {
942     endpage(obj);
943
944     for(depth--;depth>=startdepth;depth--) {
945         tag = swf_InsertTag(tag,ST_REMOVEOBJECT2);
946         swf_SetU16(tag,depth);
947     }
948
949     depth = 1;
950     startdepth = depth;
951 }
952
953 /* "destroy" like in (oo-terminology) "destructor". Perform cleaning
954    up, complete the swf, and write it out. */
955 void swfoutput_destroy(struct swfoutput* obj) 
956 {
957     endpage(obj);
958     fontlist_t *tmp,*iterator = fontlist;
959     while(iterator) {
960         delete iterator->font;
961         iterator->font = 0;
962         tmp = iterator;
963         iterator = iterator->next;
964         delete tmp;
965     }
966
967     T1_CloseLib();
968     if(!filename) 
969         return;
970     if(filename)
971      fi = open(filename, O_CREAT|O_TRUNC|O_WRONLY, 0777);
972     else
973      fi = 1; // stdout
974     
975     if(fi<=0) {
976      logf("<fatal> Could not create \"%s\". ", filename);
977      exit(1);
978     }
979  
980     tag = swf_InsertTag(tag,ST_END);
981
982     if FAILED(swf_WriteSWF(fi,&swf)) 
983      logf("<error> WriteSWF() failed.\n");
984     if(filename)
985      close(fi);
986     logf("<notice> SWF written\n");
987 }
988
989 void swfoutput_setdrawmode(swfoutput* obj, int mode)
990 {
991     drawmode = mode;
992     if(mode == DRAWMODE_FILL)
993      fill = 1;
994     else if(mode == DRAWMODE_EOFILL)
995      fill = 1;
996     else if(mode == DRAWMODE_STROKE)
997      fill = 0;
998     else if(mode == DRAWMODE_CLIP)
999      fill = 1;
1000     else if(mode == DRAWMODE_EOCLIP)
1001      fill = 1;
1002 }
1003
1004 void swfoutput_setfillcolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
1005 {
1006     if(obj->fillrgb.r == r &&
1007        obj->fillrgb.g == g &&
1008        obj->fillrgb.b == b &&
1009        obj->fillrgb.a == a) return;
1010
1011     if(shapeid>=0)
1012      endshape();
1013     obj->fillrgb.r = r;
1014     obj->fillrgb.g = g;
1015     obj->fillrgb.b = b;
1016     obj->fillrgb.a = a;
1017 }
1018
1019 void swfoutput_setstrokecolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
1020 {
1021     if(obj->strokergb.r == r &&
1022        obj->strokergb.g == g &&
1023        obj->strokergb.b == b &&
1024        obj->strokergb.a == a) return;
1025
1026     if(shapeid>=0)
1027      endshape();
1028     obj->strokergb.r = r;
1029     obj->strokergb.g = g;
1030     obj->strokergb.b = b;
1031     obj->strokergb.a = a;
1032 }
1033
1034 void swfoutput_setlinewidth(struct swfoutput*obj, double linewidth)
1035 {
1036     if(obj->linewidth == (u16)(linewidth*20))
1037         return;
1038
1039     if(shapeid>=0)
1040      endshape();
1041     obj->linewidth = (u16)(linewidth*20);
1042 }
1043
1044
1045 void swfoutput_startclip(swfoutput*obj, T1_OUTLINE*outline, struct swfmatrix*m)
1046 {
1047     if(textid>=0)
1048      endtext();
1049     if(shapeid>=0)
1050      endshape();
1051
1052     if(clippos >= 127)
1053     {
1054         logf("<warning> Too many clip levels.");
1055         clippos --;
1056     } 
1057     
1058     startshape(obj);
1059     int olddrawmode = drawmode;
1060     swfoutput_setdrawmode(obj, DRAWMODE_CLIP);
1061     swfoutput_drawpath(obj, outline, m);
1062     swf_ShapeSetEnd(tag);
1063     swfoutput_setdrawmode(obj, olddrawmode);
1064
1065     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1066     cliptags[clippos] = tag;
1067     clipshapes[clippos] = shapeid;
1068     clipdepths[clippos] = depth++;
1069     clippos++;
1070     shapeid = -1;
1071 }
1072
1073 void swfoutput_endclip(swfoutput*obj)
1074 {
1075     if(textid>=0)
1076      endtext();
1077     if(shapeid>=0)
1078      endshape();
1079
1080     if(!clippos) {
1081         logf("<error> Invalid end of clipping region");
1082         return;
1083     }
1084     clippos--;
1085     swf_ObjectPlaceClip(cliptags[clippos],clipshapes[clippos],clipdepths[clippos],NULL,NULL,NULL,depth++);
1086 }
1087
1088 void drawlink(struct swfoutput*obj, ActionTAG*, swfcoord*points);
1089
1090 void swfoutput_linktourl(struct swfoutput*obj, char*url, swfcoord*points)
1091 {
1092     ActionTAG* actions;
1093     
1094     if(shapeid>=0)
1095      endshape();
1096     if(textid>=0)
1097      endtext();
1098     
1099     actions = swf_ActionStart();
1100     if(opennewwindow)
1101       action_GetUrl(url, "_parent");
1102     else
1103       action_GetUrl(url, "_this");
1104       action_End();
1105     swf_ActionEnd();
1106     
1107     drawlink(obj, actions, points);
1108 }
1109 void swfoutput_linktopage(struct swfoutput*obj, int page, swfcoord*points)
1110 {
1111     ActionTAG* actions;
1112
1113     if(shapeid>=0)
1114      endshape();
1115     if(textid>=0)
1116      endtext();
1117    
1118     actions = swf_ActionStart();
1119       action_GotoFrame(page);
1120       action_End();
1121     swf_ActionEnd();
1122
1123     drawlink(obj, actions, points);
1124 }
1125
1126 void drawlink(struct swfoutput*obj, ActionTAG*actions, swfcoord*points)
1127 {
1128     RGBA rgb;
1129     SRECT r;
1130     int lsid=0;
1131     int fsid;
1132     struct plotxy p1,p2,p3,p4;
1133     int myshapeid;
1134     int myshapeid2;
1135     double xmin,ymin;
1136     double xmax=xmin=points[0].x,ymax=ymin=points[0].y;
1137     int t;
1138     int buttonid = ++currentswfid;
1139     for(t=1;t<4;t++)
1140     {
1141         if(points[t].x>xmax) xmax=points[t].x;
1142         if(points[t].y>ymax) ymax=points[t].y;
1143         if(points[t].x<xmin) xmin=points[t].x;
1144         if(points[t].y<ymin) ymin=points[t].y;
1145     }
1146     p1.x=points[0].x; p1.y=points[0].y; p2.x=points[1].x; p2.y=points[1].y; 
1147     p3.x=points[2].x; p3.y=points[2].y; p4.x=points[3].x; p4.y=points[3].y;
1148     
1149     /* shape */
1150     myshapeid = ++currentswfid;
1151     tag = swf_InsertTag(tag,ST_DEFINESHAPE3);
1152     swf_ShapeNew(&shape);
1153     rgb.r = rgb.b = rgb.a = rgb.g = 0; 
1154     fsid = swf_ShapeAddSolidFillStyle(shape,&rgb);
1155     swf_SetU16(tag, myshapeid);
1156     r.xmin = (int)(xmin*20);
1157     r.ymin = (int)(ymin*20);
1158     r.xmax = (int)(xmax*20);
1159     r.ymax = (int)(ymax*20);
1160     swf_SetRect(tag,&r);
1161     swf_SetShapeStyles(tag,shape);
1162     swf_ShapeCountBits(shape,NULL,NULL);
1163     swf_SetShapeBits(tag,shape);
1164     swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,0,fsid,0);
1165     swflastx = swflasty = 0;
1166     moveto(tag, p1);
1167     lineto(tag, p2);
1168     lineto(tag, p3);
1169     lineto(tag, p4);
1170     lineto(tag, p1);
1171     swf_ShapeSetEnd(tag);
1172
1173     /* shape2 */
1174     myshapeid2 = ++currentswfid;
1175     tag = swf_InsertTag(tag,ST_DEFINESHAPE3);
1176     swf_ShapeNew(&shape);
1177     rgb.r = rgb.b = rgb.a = rgb.g = 255;
1178     rgb.a = 40;
1179     fsid = swf_ShapeAddSolidFillStyle(shape,&rgb);
1180     swf_SetU16(tag, myshapeid2);
1181     r.xmin = (int)(xmin*20);
1182     r.ymin = (int)(ymin*20);
1183     r.xmax = (int)(xmax*20);
1184     r.ymax = (int)(ymax*20);
1185     swf_SetRect(tag,&r);
1186     swf_SetShapeStyles(tag,shape);
1187     swf_ShapeCountBits(shape,NULL,NULL);
1188     swf_SetShapeBits(tag,shape);
1189     swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,0,fsid,0);
1190     swflastx = swflasty = 0;
1191     moveto(tag, p1);
1192     lineto(tag, p2);
1193     lineto(tag, p3);
1194     lineto(tag, p4);
1195     lineto(tag, p1);
1196     swf_ShapeSetEnd(tag);
1197
1198     tag = swf_InsertTag(tag,ST_DEFINEBUTTON);
1199     swf_SetU16(tag,buttonid); //id
1200     swf_ButtonSetFlags(tag, 0); //menu=no
1201     swf_ButtonSetRecord(tag,0x01,myshapeid,depth,0,0);
1202     swf_ButtonSetRecord(tag,0x02,myshapeid2,depth,0,0);
1203     swf_ButtonSetRecord(tag,0x04,myshapeid2,depth,0,0);
1204     swf_ButtonSetRecord(tag,0x08,myshapeid,depth,0,0);
1205     swf_SetU8(tag,0);
1206     swf_ActionSet(tag,actions);
1207     swf_SetU8(tag,0);
1208     
1209     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1210     swf_ObjectPlace(tag, buttonid, depth++,0,0,0);
1211 }
1212
1213 void drawimage(struct swfoutput*obj, int bitid, int sizex,int sizey, 
1214         double x1,double y1,
1215         double x2,double y2,
1216         double x3,double y3,
1217         double x4,double y4)
1218 {
1219     RGBA rgb;
1220     SRECT r;
1221     int lsid=0;
1222     int fsid;
1223     struct plotxy p1,p2,p3,p4;
1224     int myshapeid;
1225     double xmax=x1,ymax=y1,xmin=x1,ymin=y1;
1226     if(x2>xmax) xmax=x2;
1227     if(y2>ymax) ymax=y2;
1228     if(x2<xmin) xmin=x2;
1229     if(y2<ymin) ymin=y2;
1230     if(x3>xmax) xmax=x3;
1231     if(y3>ymax) ymax=y3;
1232     if(x3<xmin) xmin=x3;
1233     if(y3<ymin) ymin=y3;
1234     if(x4>xmax) xmax=x4;
1235     if(y4>ymax) ymax=y4;
1236     if(x4<xmin) xmin=x4;
1237     if(y4<ymin) ymin=y4;
1238     p1.x=x1;
1239     p1.y=y1;
1240     p2.x=x2;
1241     p2.y=y2;
1242     p3.x=x3;
1243     p3.y=y3;
1244     p4.x=x4;
1245     p4.y=y4;
1246     
1247     MATRIX m;
1248     m.sx = (int)(65536*20*(x4-x1))/sizex;
1249     m.r1 = -(int)(65536*20*(y4-y1))/sizex;
1250     m.r0 = (int)(65536*20*(x1-x2))/sizey;
1251     m.sy = -(int)(65536*20*(y1-y2))/sizey;
1252
1253     m.tx = (int)(x1*20);
1254     m.ty = (int)(y1*20);
1255   
1256     /* shape */
1257     myshapeid = ++currentswfid;
1258     tag = swf_InsertTag(tag,ST_DEFINESHAPE);
1259     swf_ShapeNew(&shape);
1260     //lsid = ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
1261     //fsid = ShapeAddSolidFillStyle(shape,&obj->fillrgb);
1262     fsid = swf_ShapeAddBitmapFillStyle(shape,&m,bitid,0);
1263     swf_SetU16(tag, myshapeid);
1264     r.xmin = (int)(xmin*20);
1265     r.ymin = (int)(ymin*20);
1266     r.xmax = (int)(xmax*20);
1267     r.ymax = (int)(ymax*20);
1268     swf_SetRect(tag,&r);
1269     swf_SetShapeStyles(tag,shape);
1270     swf_ShapeCountBits(shape,NULL,NULL);
1271     swf_SetShapeBits(tag,shape);
1272     swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,lsid,fsid,0);
1273     swflastx = swflasty = 0;
1274     moveto(tag, p1);
1275     lineto(tag, p2);
1276     lineto(tag, p3);
1277     lineto(tag, p4);
1278     lineto(tag, p1);
1279     /*
1280     ShapeMoveTo  (tag, shape, (int)(x1*20),(int)(y1*20));
1281     ShapeSetLine (tag, shape, (int)(x1*20);
1282     ShapeSetLine (tag, shape, x*20,0);
1283     ShapeSetLine (tag, shape, 0,-y*20);
1284     ShapeSetLine (tag, shape, -x*20,0);*/
1285     swf_ShapeSetEnd(tag);
1286
1287     /* instance */
1288     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1289     swf_ObjectPlace(tag,myshapeid,/*depth*/depth++,NULL,NULL,NULL);
1290 }
1291
1292 int swfoutput_drawimagejpeg(struct swfoutput*obj, char*filename, int sizex,int sizey, 
1293         double x1,double y1,
1294         double x2,double y2,
1295         double x3,double y3,
1296         double x4,double y4)
1297 {
1298     TAG*oldtag;
1299     if(shapeid>=0)
1300      endshape();
1301     if(textid>=0)
1302      endtext();
1303
1304     int bitid = ++currentswfid;
1305     oldtag = tag;
1306     tag = swf_InsertTag(tag,ST_DEFINEBITSJPEG2);
1307     swf_SetU16(tag, bitid);
1308     if(swf_SetJPEGBits(tag, filename, jpegquality)<0) {
1309         swf_DeleteTag(tag);
1310         tag = oldtag;
1311         return -1;
1312     }
1313
1314     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1315     return bitid;
1316 }
1317
1318 int swfoutput_drawimagelossless(struct swfoutput*obj, RGBA*mem, int sizex,int sizey, 
1319         double x1,double y1,
1320         double x2,double y2,
1321         double x3,double y3,
1322         double x4,double y4)
1323 {
1324     TAG*oldtag;
1325     if(shapeid>=0)
1326      endshape();
1327     if(textid>=0)
1328      endtext();
1329
1330     int bitid = ++currentswfid;
1331     oldtag = tag;
1332     tag = swf_InsertTag(tag,ST_DEFINEBITSLOSSLESS);
1333     swf_SetU16(tag, bitid);
1334     if(swf_SetLosslessBits(tag,sizex,sizey,mem, BMF_32BIT)<0) {
1335         swf_DeleteTag(tag);
1336         tag = oldtag;
1337         return -1;
1338     }
1339     
1340     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1341     return bitid;
1342 }
1343
1344 int swfoutput_drawimagelossless256(struct swfoutput*obj, U8*mem, RGBA*pal, int sizex,int sizey, 
1345         double x1,double y1,
1346         double x2,double y2,
1347         double x3,double y3,
1348         double x4,double y4)
1349 {
1350     TAG*oldtag;
1351     if(shapeid>=0)
1352      endshape();
1353     if(textid>=0)
1354      endtext();
1355
1356     int bitid = ++currentswfid;
1357     oldtag = tag;
1358     tag = swf_InsertTag(tag,ST_DEFINEBITSLOSSLESS2);
1359     swf_SetU16(tag, bitid);
1360     if(swf_SetLosslessBitsIndexed(tag,sizex,sizey,mem, pal, 256)<0) {
1361         swf_DeleteTag(tag);
1362         tag = oldtag;
1363         return -1;
1364     }
1365   
1366     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1367     return bitid;
1368 }
1369
1370 void swfoutput_drawimageagain(struct swfoutput*obj, int id, int sizex,int sizey, 
1371         double x1,double y1,
1372         double x2,double y2,
1373         double x3,double y3,
1374         double x4,double y4)
1375 {
1376     if(id<0) return;
1377     if(shapeid>=0)
1378      endshape();
1379     if(textid>=0)
1380      endtext();
1381
1382     drawimage(obj, id, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1383 }
1384