added optional storing of full font sets in the .swf. (option -f)
[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, 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);
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=0, outlinepos=0;
511     char*map[256];
512     while(a[t])
513         t++;
514  
515     this->charnum = t;
516     if(!t) 
517         return;
518     logf("<verbose> Font %s(%d): Storing %d outlines.\n", name, id, t);
519     
520     outline = (T1_OUTLINE**)malloc(t*sizeof(T1_OUTLINE*));
521     charname = (char**)malloc(t*sizeof(char*));
522     memset(charname, t*sizeof(char*), 0);
523     used = (char*)malloc(t*sizeof(char));
524     char2swfcharid = (U16*)malloc(t*2);
525     swfcharid2char = (U16*)malloc(t*2);
526     swfcharpos = 0;
527
528     memset(used,0,t*sizeof(char));
529
530     this->swfid = ++currentswfid;
531
532     
533     t=0;
534     while(*a)
535     {
536         map[t] = *a;
537         a++;
538         t++;
539         if(t==256 || !*a) {
540             int s;
541             for(s=t;s<256;s++)
542                 map[s] = ".notdef";
543
544             int ret = T1_ReencodeFont(id, map);
545             if(ret) {
546              T1_DeleteFont(id);
547              T1_LoadFont(id);
548              int ret = T1_ReencodeFont(id, map);
549              if(ret)
550                fprintf(stderr,"Can't reencode font: (%s) ret:%d\n",filename, ret);
551             }
552
553             // parsecharacters
554             for(s=0;s<t;s++)
555             {
556                 this->outline[outlinepos] = T1_CopyOutline(T1_GetCharOutline(id, s, 100.0, 0));
557                 this->charname[outlinepos] = strdup(T1_GetCharName(id, s));
558                 outlinepos++;
559             }
560             t=0;
561         }
562     }
563 }
564
565 /* free all tables, write out definefont tags */
566 SWFFont::~SWFFont()
567 {
568     int t,usednum=0;
569     int*ptr; 
570
571     if(storeallcharacters)
572     {
573         int t;
574         for(t=0;t<this->charnum;t++) 
575         {
576             if(this->charname[t])
577               getSWFCharID(this->charname[t]);
578         }
579     }
580     
581     ptr = (int*)malloc(swfcharpos*sizeof(int));
582
583     for(t=0;t<charnum;t++)
584         if(used[t]) usednum++;
585
586     if(usednum && !drawonlyshapes)
587     {
588         logf("<verbose> Font %s has %d used characters",fontid, usednum);
589         TAG*ftag = swf_InsertTag(swf.firstTag,ST_DEFINEFONT);
590         swf_SetU16(ftag, this->swfid);
591         int initpos = swf_GetDataSize(ftag);
592         swfmatrix m;
593         m.m11 = m.m22 = 1;
594         m.m21 = m.m12 = 0;
595         m.m13 = CHARMIDX;
596         m.m23 = CHARMIDY;
597
598         for(t=0;t<swfcharpos;t++) 
599         {
600             ptr[t] = swf_GetDataSize(ftag);
601             swf_SetU16(ftag, 0x1234);
602         }
603         for(t=0;t<swfcharpos;t++)
604         {
605             *(U16*)&ftag->data[ptr[t]] = swf_GetDataSize(ftag)-initpos;
606             swflastx=0;
607             swflasty=0;
608             swf_SetU8(ftag,0x10); //0 fill bits, 0 linestyle bits
609             SHAPE s;
610             s.bits.fill = 1;
611             s.bits.line = 0;
612             swf_ShapeSetStyle(ftag,&s,0,1,0);
613             int lastfill = fill;
614             fill = 1;
615             storefont = 1;
616             drawpath(ftag, outline[swfcharid2char[t]],&m);
617             storefont = 0;
618             fill = lastfill;
619             swf_ShapeSetEnd(ftag);
620         }
621         ftag = swf_InsertTag(ftag,ST_DEFINEFONTINFO);
622         swf_SetU16(ftag, this->swfid);
623         if(this->fontid) {
624             swf_SetU8(ftag, strlen(this->fontid));
625             swf_SetBlock(ftag, (U8*)this->fontid, strlen(this->fontid));
626         } else {
627             swf_SetU8(ftag, 0);
628         }
629         swf_SetU8(ftag, 0); //flags
630         for(t=0;t<swfcharpos;t++)
631         {
632             int s;
633             char * name = this->charname[this->swfcharid2char[t]];
634             for(s=0;s<256;s++) {
635                 if(standardEncodingNames[s] && 
636                         !strcmp(name,standardEncodingNames[s]))
637                     break;
638             }
639             swf_SetU8(ftag, (U8)s);
640         }
641     }
642
643     free(ptr);
644     free(outline);
645     for(t=0;t<charnum;t++)
646         free(charname[t]);
647     free(charname);
648     free(used);
649     free(swfcharid2char);
650     free(char2swfcharid);
651 }
652
653 T1_OUTLINE*SWFFont::getOutline(char*name)
654 {
655     int t;
656     for(t=0;t<this->charnum;t++) {
657         if(!strcmp(this->charname[t],name)) {
658             if(!used[t])
659             {
660                 swfcharid2char[swfcharpos] = t;
661                 char2swfcharid[t] = swfcharpos;
662                 swfcharpos++;
663                 used[t] = 1;
664             }
665             return outline[t];
666         }
667     }
668     return 0;
669 }
670
671 int SWFFont::getSWFCharID(char*name)
672 {
673     int t;
674     for(t=0;t<this->charnum;t++) {
675         if(!strcmp(this->charname[t],name)) {
676             if(!used[t])
677             {
678                 swfcharid2char[swfcharpos] = t;
679                 char2swfcharid[t] = swfcharpos++;
680                 used[t] = 1;
681             }
682             return char2swfcharid[t];
683         }
684     }
685     logf("<warning> Didn't find character '%s' in font '%s'", name, this->name);
686     return 0;
687 }
688
689 char*SWFFont::getName()
690 {
691     return this->name;
692 }
693
694 struct fontlist_t 
695 {
696     SWFFont * font;
697     fontlist_t*next;
698 } *fontlist = 0;
699
700 /* set's the t1 font index of the font to use for swfoutput_drawchar(). */
701 void swfoutput_setfont(struct swfoutput*obj, char*fontid, int t1id, char*filename)
702 {
703     fontlist_t*last=0,*iterator;
704     if(obj->font && !strcmp(obj->font->fontid,fontid))
705         return;
706
707     iterator = fontlist;
708     while(iterator) {
709         if(!strcmp(iterator->font->fontid,fontid))
710             break;
711         last = iterator;
712         iterator = iterator->next;
713     }
714     if(iterator) 
715     {
716         obj->font = iterator->font;
717         return ;
718     }
719
720     if(t1id<0) {
721         logf("<error> internal error: t1id:%d, fontid:%s\n", t1id,fontid);
722     }
723     
724     SWFFont*font = new SWFFont(fontid, t1id, filename);
725     iterator = new fontlist_t;
726     iterator->font = font;
727     iterator->next = 0;
728
729     if(last) 
730         last->next = iterator;
731     else 
732         fontlist = iterator;
733     obj->font = font;
734 }
735
736 int swfoutput_queryfont(struct swfoutput*obj, char*fontid)
737 {
738     fontlist_t *iterator = fontlist;
739     while(iterator) {
740         if(!strcmp(iterator->font->fontid,fontid))
741             return 1;
742         iterator = iterator->next;
743     }
744     return 0;
745 }
746
747 /* set's the matrix which is to be applied to characters drawn by
748    swfoutput_drawchar() */
749 void swfoutput_setfontmatrix(struct swfoutput*obj,double m11,double m12,
750                                                   double m21,double m22)
751 {
752     if(obj->fontm11 == m11 &&
753        obj->fontm12 == m12 &&
754        obj->fontm21 == m21 &&
755        obj->fontm22 == m22)
756         return;
757 //    if(textid>=0)
758 //      endtext();
759     obj->fontm11 = m11;
760     obj->fontm12 = m12;
761     obj->fontm21 = m21;
762     obj->fontm22 = m22;
763 }
764
765 /* draws a character at x,y. */
766 void swfoutput_drawchar(struct swfoutput* obj,double x,double y,char*character) 
767 {
768     swfmatrix m;
769     m.m11 = obj->fontm11;
770     m.m12 = obj->fontm12;
771     m.m21 = obj->fontm21;
772     m.m22 = obj->fontm22;
773     m.m13 = x;
774     m.m23 = y;
775     drawchar(obj, obj->font, character, &m);
776 }
777
778 /* initialize the swf writer */
779 void swfoutput_init(struct swfoutput* obj, char*_filename, int _sizex, int _sizey) 
780 {
781   GLYPH *glyph;
782   RGBA rgb;
783   SRECT r;
784   memset(obj, 0, sizeof(struct swfoutput));
785   filename = _filename;
786   sizex = _sizex;
787   sizey = _sizey;
788
789   logf("<verbose> initializing swf output for size %d*%d\n", sizex,sizey);
790
791   obj->font = 0;
792   
793   memset(&swf,0x00,sizeof(SWF));
794
795   swf.fileVersion    = 4;
796   swf.frameRate      = 0x0040; // 1 frame per 4 seconds
797   swf.movieSize.xmax = 20*sizex;
798   swf.movieSize.ymax = 20*sizey;
799   
800   swf.firstTag = swf_InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
801   tag = swf.firstTag;
802   rgb.r = 0xff;
803   rgb.g = 0xff;
804   rgb.b = 0xff;
805   swf_SetRGB(tag,&rgb);
806   if(flag_protected)  // good practice! /r
807     tag = swf_InsertTag(tag, ST_PROTECT);
808   depth = 1;
809   startdepth = depth;
810 }
811
812 void swfoutput_setprotected() //write PROTECT tag
813 {
814   flag_protected = 1;
815 }
816
817 void startshape(struct swfoutput*obj)
818 {
819   RGBA rgb;
820   SRECT r;
821
822   if(textid>=0)
823       endtext();
824
825   tag = swf_InsertTag(tag,ST_DEFINESHAPE);
826
827   swf_ShapeNew(&shape);
828   linestyleid = swf_ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
829   rgb.r = obj->fillrgb.r;
830   rgb.g = obj->fillrgb.g;
831   rgb.b = obj->fillrgb.b;
832   fillstyleid = swf_ShapeAddSolidFillStyle(shape,&obj->fillrgb);
833
834   shapeid = ++currentswfid;
835   swf_SetU16(tag,shapeid);  // ID
836
837   r.xmin = 0;
838   r.ymin = 0;
839   r.xmax = 20*sizex;
840   r.ymax = 20*sizey;
841   
842   swf_SetRect(tag,&r);
843
844   swf_SetShapeStyles(tag,shape);
845   swf_ShapeCountBits(shape,NULL,NULL);
846   swf_SetShapeBits(tag,shape);
847
848   swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,linestyleid,0,0);
849   swflastx=swflasty=0;
850   lastwasfill = 0;
851 }
852
853 void starttext(struct swfoutput*obj)
854 {
855   SRECT r;
856   MATRIX m;
857   if(shapeid>=0)
858       endshape();
859   tag = swf_InsertTag(tag,ST_DEFINETEXT);
860   textid = ++currentswfid;
861   swf_SetU16(tag, textid);
862
863   r.xmin = 0;
864   r.ymin = 0;
865   r.xmax = 20*sizex;
866   r.ymax = 20*sizey;
867   
868   swf_SetRect(tag,&r);
869
870   m.sx = 65536;
871   m.sy = 65536;
872   m.r0 = 0;
873   m.r1 = 0;
874   m.tx = 0;
875   m.ty = 0;
876  
877   swf_SetMatrix(tag,&m);
878   swflastx=swflasty=0;
879 }
880
881 void endshape()
882 {
883     if(shapeid<0) 
884         return;
885     swf_ShapeSetEnd(tag);
886     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
887     swf_ObjectPlace(tag,shapeid,/*depth*/depth++,NULL,NULL,NULL);
888     shapeid = -1;
889 }
890
891 void endtext()
892 {
893     if(textid<0)
894         return;
895     putcharacters(tag);
896     swf_SetU8(tag,0);
897     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
898     swf_ObjectPlace(tag,textid,/*depth*/depth++,NULL,NULL,NULL);
899     textid = -1;
900 }
901
902 void endpage(struct swfoutput*obj)
903 {
904     if(shapeid>=0)
905       endshape();
906     if(textid>=0)
907       endtext();
908     while(clippos)
909         swfoutput_endclip(obj);
910     tag = swf_InsertTag(tag,ST_SHOWFRAME);
911 }
912
913 void swfoutput_newpage(struct swfoutput*obj)
914 {
915     endpage(obj);
916
917     for(depth--;depth>=startdepth;depth--) {
918         tag = swf_InsertTag(tag,ST_REMOVEOBJECT2);
919         swf_SetU16(tag,depth);
920     }
921
922     depth = 1;
923     startdepth = depth;
924 }
925
926 /* "destroy" like in (oo-terminology) "destructor". Perform cleaning
927    up, complete the swf, and write it out. */
928 void swfoutput_destroy(struct swfoutput* obj) 
929 {
930     endpage(obj);
931     fontlist_t *tmp,*iterator = fontlist;
932     while(iterator) {
933         delete iterator->font;
934         iterator->font = 0;
935         tmp = iterator;
936         iterator = iterator->next;
937         delete tmp;
938     }
939
940     T1_CloseLib();
941     if(!filename) 
942         return;
943     if(filename)
944      fi = open(filename, O_CREAT|O_TRUNC|O_WRONLY, 0777);
945     else
946      fi = 1; // stdout
947     
948     if(fi<=0) {
949      logf("<fatal> Could not create \"%s\". ", filename);
950      exit(1);
951     }
952  
953     tag = swf_InsertTag(tag,ST_END);
954
955     if FAILED(swf_WriteSWF(fi,&swf)) 
956      logf("<error> WriteSWF() failed.\n");
957     if(filename)
958      close(fi);
959     logf("<notice> SWF written\n");
960 }
961
962 void swfoutput_setdrawmode(swfoutput* obj, int mode)
963 {
964     drawmode = mode;
965     if(mode == DRAWMODE_FILL)
966      fill = 1;
967     else if(mode == DRAWMODE_EOFILL)
968      fill = 1;
969     else if(mode == DRAWMODE_STROKE)
970      fill = 0;
971     else if(mode == DRAWMODE_CLIP)
972      fill = 1;
973     else if(mode == DRAWMODE_EOCLIP)
974      fill = 1;
975 }
976
977 void swfoutput_setfillcolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
978 {
979     if(obj->fillrgb.r == r &&
980        obj->fillrgb.g == g &&
981        obj->fillrgb.b == b &&
982        obj->fillrgb.a == a) return;
983
984     if(shapeid>=0)
985      endshape();
986     obj->fillrgb.r = r;
987     obj->fillrgb.g = g;
988     obj->fillrgb.b = b;
989     obj->fillrgb.a = a;
990 }
991
992 void swfoutput_setstrokecolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
993 {
994     if(obj->strokergb.r == r &&
995        obj->strokergb.g == g &&
996        obj->strokergb.b == b &&
997        obj->strokergb.a == a) return;
998
999     if(shapeid>=0)
1000      endshape();
1001     obj->strokergb.r = r;
1002     obj->strokergb.g = g;
1003     obj->strokergb.b = b;
1004     obj->strokergb.a = a;
1005 }
1006
1007 void swfoutput_setlinewidth(struct swfoutput*obj, double linewidth)
1008 {
1009     if(obj->linewidth == (u16)(linewidth*20))
1010         return;
1011
1012     if(shapeid>=0)
1013      endshape();
1014     obj->linewidth = (u16)(linewidth*20);
1015 }
1016
1017
1018 void swfoutput_startclip(swfoutput*obj, T1_OUTLINE*outline, struct swfmatrix*m)
1019 {
1020     if(textid>=0)
1021      endtext();
1022     if(shapeid>=0)
1023      endshape();
1024
1025     if(clippos >= 127)
1026     {
1027         logf("<warning> Too many clip levels.");
1028         clippos --;
1029     } 
1030     
1031     startshape(obj);
1032     int olddrawmode = drawmode;
1033     swfoutput_setdrawmode(obj, DRAWMODE_CLIP);
1034     swfoutput_drawpath(obj, outline, m);
1035     swf_ShapeSetEnd(tag);
1036     swfoutput_setdrawmode(obj, olddrawmode);
1037
1038     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1039     cliptags[clippos] = tag;
1040     clipshapes[clippos] = shapeid;
1041     clipdepths[clippos] = depth++;
1042     clippos++;
1043     shapeid = -1;
1044 }
1045
1046 void swfoutput_endclip(swfoutput*obj)
1047 {
1048     if(textid>=0)
1049      endtext();
1050     if(shapeid>=0)
1051      endshape();
1052
1053     if(!clippos) {
1054         logf("<error> Invalid end of clipping region");
1055         return;
1056     }
1057     clippos--;
1058     swf_ObjectPlaceClip(cliptags[clippos],clipshapes[clippos],clipdepths[clippos],NULL,NULL,NULL,depth++);
1059 }
1060
1061 void drawlink(struct swfoutput*obj, ActionTAG*, swfcoord*points);
1062
1063 void swfoutput_linktourl(struct swfoutput*obj, char*url, swfcoord*points)
1064 {
1065     ActionTAG* actions;
1066     
1067     if(shapeid>=0)
1068      endshape();
1069     if(textid>=0)
1070      endtext();
1071     
1072     actions = swf_ActionStart();
1073     if(opennewwindow)
1074       action_GetUrl(url, "_parent");
1075     else
1076       action_GetUrl(url, "_this");
1077       action_End();
1078     swf_ActionEnd();
1079     
1080     drawlink(obj, actions, points);
1081 }
1082 void swfoutput_linktopage(struct swfoutput*obj, int page, swfcoord*points)
1083 {
1084     ActionTAG* actions;
1085
1086     if(shapeid>=0)
1087      endshape();
1088     if(textid>=0)
1089      endtext();
1090    
1091     actions = swf_ActionStart();
1092       action_GotoFrame(page);
1093       action_End();
1094     swf_ActionEnd();
1095
1096     drawlink(obj, actions, points);
1097 }
1098
1099 void drawlink(struct swfoutput*obj, ActionTAG*actions, swfcoord*points)
1100 {
1101     RGBA rgb;
1102     SRECT r;
1103     int lsid=0;
1104     int fsid;
1105     struct plotxy p1,p2,p3,p4;
1106     int myshapeid;
1107     int myshapeid2;
1108     double xmin,ymin;
1109     double xmax=xmin=points[0].x,ymax=ymin=points[0].y;
1110     int t;
1111     int buttonid = ++currentswfid;
1112     for(t=1;t<4;t++)
1113     {
1114         if(points[t].x>xmax) xmax=points[t].x;
1115         if(points[t].y>ymax) ymax=points[t].y;
1116         if(points[t].x<xmin) xmin=points[t].x;
1117         if(points[t].y<ymin) ymin=points[t].y;
1118     }
1119     p1.x=points[0].x; p1.y=points[0].y; p2.x=points[1].x; p2.y=points[1].y; 
1120     p3.x=points[2].x; p3.y=points[2].y; p4.x=points[3].x; p4.y=points[3].y;
1121     
1122     /* shape */
1123     myshapeid = ++currentswfid;
1124     tag = swf_InsertTag(tag,ST_DEFINESHAPE3);
1125     swf_ShapeNew(&shape);
1126     rgb.r = rgb.b = rgb.a = rgb.g = 0; 
1127     fsid = swf_ShapeAddSolidFillStyle(shape,&rgb);
1128     swf_SetU16(tag, myshapeid);
1129     r.xmin = (int)(xmin*20);
1130     r.ymin = (int)(ymin*20);
1131     r.xmax = (int)(xmax*20);
1132     r.ymax = (int)(ymax*20);
1133     swf_SetRect(tag,&r);
1134     swf_SetShapeStyles(tag,shape);
1135     swf_ShapeCountBits(shape,NULL,NULL);
1136     swf_SetShapeBits(tag,shape);
1137     swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,0,fsid,0);
1138     swflastx = swflasty = 0;
1139     moveto(tag, p1);
1140     lineto(tag, p2);
1141     lineto(tag, p3);
1142     lineto(tag, p4);
1143     lineto(tag, p1);
1144     swf_ShapeSetEnd(tag);
1145
1146     /* shape2 */
1147     myshapeid2 = ++currentswfid;
1148     tag = swf_InsertTag(tag,ST_DEFINESHAPE3);
1149     swf_ShapeNew(&shape);
1150     rgb.r = rgb.b = rgb.a = rgb.g = 255;
1151     rgb.a = 40;
1152     fsid = swf_ShapeAddSolidFillStyle(shape,&rgb);
1153     swf_SetU16(tag, myshapeid2);
1154     r.xmin = (int)(xmin*20);
1155     r.ymin = (int)(ymin*20);
1156     r.xmax = (int)(xmax*20);
1157     r.ymax = (int)(ymax*20);
1158     swf_SetRect(tag,&r);
1159     swf_SetShapeStyles(tag,shape);
1160     swf_ShapeCountBits(shape,NULL,NULL);
1161     swf_SetShapeBits(tag,shape);
1162     swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,0,fsid,0);
1163     swflastx = swflasty = 0;
1164     moveto(tag, p1);
1165     lineto(tag, p2);
1166     lineto(tag, p3);
1167     lineto(tag, p4);
1168     lineto(tag, p1);
1169     swf_ShapeSetEnd(tag);
1170
1171     tag = swf_InsertTag(tag,ST_DEFINEBUTTON);
1172     swf_SetU16(tag,buttonid); //id
1173     swf_ButtonSetFlags(tag, 0); //menu=no
1174     swf_ButtonSetRecord(tag,0x01,myshapeid,depth,0,0);
1175     swf_ButtonSetRecord(tag,0x02,myshapeid2,depth,0,0);
1176     swf_ButtonSetRecord(tag,0x04,myshapeid2,depth,0,0);
1177     swf_ButtonSetRecord(tag,0x08,myshapeid,depth,0,0);
1178     swf_SetU8(tag,0);
1179     swf_SetActions(tag,actions);
1180     swf_SetU8(tag,0);
1181     
1182     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1183     swf_ObjectPlace(tag, buttonid, depth++,0,0,0);
1184 }
1185
1186 void drawimage(struct swfoutput*obj, int bitid, int sizex,int sizey, 
1187         double x1,double y1,
1188         double x2,double y2,
1189         double x3,double y3,
1190         double x4,double y4)
1191 {
1192     RGBA rgb;
1193     SRECT r;
1194     int lsid=0;
1195     int fsid;
1196     struct plotxy p1,p2,p3,p4;
1197     int myshapeid;
1198     double xmax=x1,ymax=y1,xmin=x1,ymin=y1;
1199     if(x2>xmax) xmax=x2;
1200     if(y2>ymax) ymax=y2;
1201     if(x2<xmin) xmin=x2;
1202     if(y2<ymin) ymin=y2;
1203     if(x3>xmax) xmax=x3;
1204     if(y3>ymax) ymax=y3;
1205     if(x3<xmin) xmin=x3;
1206     if(y3<ymin) ymin=y3;
1207     if(x4>xmax) xmax=x4;
1208     if(y4>ymax) ymax=y4;
1209     if(x4<xmin) xmin=x4;
1210     if(y4<ymin) ymin=y4;
1211     p1.x=x1;
1212     p1.y=y1;
1213     p2.x=x2;
1214     p2.y=y2;
1215     p3.x=x3;
1216     p3.y=y3;
1217     p4.x=x4;
1218     p4.y=y4;
1219     
1220     MATRIX m;
1221     m.sx = (int)(65536*20*(x4-x1))/sizex;
1222     m.r1 = -(int)(65536*20*(y4-y1))/sizex;
1223     m.r0 = (int)(65536*20*(x1-x2))/sizey;
1224     m.sy = -(int)(65536*20*(y1-y2))/sizey;
1225
1226     m.tx = (int)(x1*20);
1227     m.ty = (int)(y1*20);
1228   
1229     /* shape */
1230     myshapeid = ++currentswfid;
1231     tag = swf_InsertTag(tag,ST_DEFINESHAPE);
1232     swf_ShapeNew(&shape);
1233     //lsid = ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
1234     //fsid = ShapeAddSolidFillStyle(shape,&obj->fillrgb);
1235     fsid = swf_ShapeAddBitmapFillStyle(shape,&m,bitid,0);
1236     swf_SetU16(tag, myshapeid);
1237     r.xmin = (int)(xmin*20);
1238     r.ymin = (int)(ymin*20);
1239     r.xmax = (int)(xmax*20);
1240     r.ymax = (int)(ymax*20);
1241     swf_SetRect(tag,&r);
1242     swf_SetShapeStyles(tag,shape);
1243     swf_ShapeCountBits(shape,NULL,NULL);
1244     swf_SetShapeBits(tag,shape);
1245     swf_ShapeSetAll(tag,shape,/*x*/0,/*y*/0,lsid,fsid,0);
1246     swflastx = swflasty = 0;
1247     moveto(tag, p1);
1248     lineto(tag, p2);
1249     lineto(tag, p3);
1250     lineto(tag, p4);
1251     lineto(tag, p1);
1252     /*
1253     ShapeMoveTo  (tag, shape, (int)(x1*20),(int)(y1*20));
1254     ShapeSetLine (tag, shape, (int)(x1*20);
1255     ShapeSetLine (tag, shape, x*20,0);
1256     ShapeSetLine (tag, shape, 0,-y*20);
1257     ShapeSetLine (tag, shape, -x*20,0);*/
1258     swf_ShapeSetEnd(tag);
1259
1260     /* instance */
1261     tag = swf_InsertTag(tag,ST_PLACEOBJECT2);
1262     swf_ObjectPlace(tag,myshapeid,/*depth*/depth++,NULL,NULL,NULL);
1263 }
1264
1265 int swfoutput_drawimagejpeg(struct swfoutput*obj, char*filename, int sizex,int sizey, 
1266         double x1,double y1,
1267         double x2,double y2,
1268         double x3,double y3,
1269         double x4,double y4)
1270 {
1271     if(shapeid>=0)
1272      endshape();
1273     if(textid>=0)
1274      endtext();
1275
1276     int bitid = ++currentswfid;
1277     tag = swf_InsertTag(tag,ST_DEFINEBITSJPEG2);
1278     swf_SetU16(tag, bitid);
1279     swf_SetJPEGBits(tag, filename, jpegquality);
1280
1281     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1282     return bitid;
1283 }
1284
1285 int swfoutput_drawimagelossless(struct swfoutput*obj, RGBA*mem, int sizex,int sizey, 
1286         double x1,double y1,
1287         double x2,double y2,
1288         double x3,double y3,
1289         double x4,double y4)
1290 {
1291     if(shapeid>=0)
1292      endshape();
1293     if(textid>=0)
1294      endtext();
1295
1296     int bitid = ++currentswfid;
1297     tag = swf_InsertTag(tag,ST_DEFINEBITSLOSSLESS);
1298     swf_SetU16(tag, bitid);
1299     swf_SetLosslessBits(tag,sizex,sizey,mem, BMF_32BIT);
1300     
1301     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1302     return bitid;
1303 }
1304
1305 int swfoutput_drawimagelossless256(struct swfoutput*obj, U8*mem, RGBA*pal, int sizex,int sizey, 
1306         double x1,double y1,
1307         double x2,double y2,
1308         double x3,double y3,
1309         double x4,double y4)
1310 {
1311     if(shapeid>=0)
1312      endshape();
1313     if(textid>=0)
1314      endtext();
1315
1316     int bitid = ++currentswfid;
1317     tag = swf_InsertTag(tag,ST_DEFINEBITSLOSSLESS2);
1318     swf_SetU16(tag, bitid);
1319     swf_SetLosslessBitsIndexed(tag,sizex,sizey,mem, pal, 256);
1320   
1321     drawimage(obj, bitid, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1322     return bitid;
1323 }
1324
1325 void swfoutput_drawimageagain(struct swfoutput*obj, int id, int sizex,int sizey, 
1326         double x1,double y1,
1327         double x2,double y2,
1328         double x3,double y3,
1329         double x4,double y4)
1330 {
1331     if(shapeid>=0)
1332      endshape();
1333     if(textid>=0)
1334      endtext();
1335
1336     drawimage(obj, id, sizex, sizey, x1,y1,x2,y2,x3,y3,x4,y4);
1337 }
1338