fixed a bug. (SWFFont now strdups it's font name)
[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
31 typedef unsigned char u8;
32 typedef unsigned short int u16;
33 typedef unsigned long int u32;
34
35 static int fi;
36 static int flag_protected;
37 static SWF swf;
38 static TAG *tag;
39 static int shapeid = -1;
40 static int shapecount = 0;
41 static SHAPE* shape;
42 static int fillstyleid;
43 static int linestyleid;
44 static int swflastx=0;
45 static int swflasty=0;
46 static int lastwasfill = 0;
47 static char* filename = 0;
48 static int sizex;
49 static int sizey;
50 static char fill = 0;
51 static int depth = 1;
52 static int startdepth = 1;
53 TAG* cliptags[128];
54 int clipshapes[128];
55 u32 clipdepths[128];
56 int clippos = 0;
57
58 void startshape(struct swfoutput* obj);
59
60 // matrix multiplication. changes p0
61 void transform (plotxy*p0,struct swfmatrix*m)
62 {
63     double x,y;
64     x = m->m11*p0->x+m->m12*p0->y;
65     y = m->m21*p0->x+m->m22*p0->y;
66     p0->x = x + m->m13;
67     p0->y = y + m->m23;
68 }
69
70 // write a move-to command into the swf
71 void moveto(plotxy p0)
72 {
73     int rx = (int)(p0.x*20);
74     int ry = (int)(p0.y*20);
75     if(rx!=swflastx || ry!=swflasty) {
76       ShapeSetMove (tag, shape, rx,ry);
77     }
78     swflastx=rx;
79     swflasty=ry;
80 }
81
82 // write a line-to command into the swf
83 void lineto(plotxy p0)
84 {
85     int rx = ((int)(p0.x*20)-swflastx);
86     int ry = ((int)(p0.y*20)-swflasty);
87     /* we can't skip this for rx=0,ry=0, those
88        are plots */
89     ShapeSetLine (tag, shape, rx,ry);
90     swflastx+=rx;
91     swflasty+=ry;
92 }
93
94 // write a spline-to command into the swf
95 void splineto(plotxy control,plotxy end)
96 {
97     int cx = ((int)(control.x*20)-swflastx);
98     int cy = ((int)(control.y*20)-swflasty);
99     swflastx += cx;
100     swflasty += cy;
101     int ex = ((int)(end.x*20)-swflastx);
102     int ey = ((int)(end.y*20)-swflasty);
103     swflastx += ex;
104     swflasty += ey;
105     ShapeSetCurve(tag, shape, cx,cy,ex,ey);
106 }
107
108 /* write a line, given two points and the transformation
109    matrix. */
110 void line(plotxy p0, plotxy p1, struct swfmatrix*m)
111 {
112     transform(&p0,m);
113     transform(&p1,m);
114     moveto(p0);
115     lineto(p1);
116 }
117
118 /* write a cubic (!) spline. This involves calling the approximate()
119    function out of spline.cc to convert it to a quadratic spline.  */
120 void spline(plotxy p0,plotxy p1,plotxy p2,plotxy p3,struct swfmatrix*m)
121 {
122     double d;
123     struct qspline q[16];
124     int num;
125     int t;
126     transform(&p0,m);
127     transform(&p1,m);
128     transform(&p2,m);
129     transform(&p3,m);
130
131     num = approximate(p0,p1,p2,p3,q);
132     for(t=0;t<num;t++) {
133         moveto(q[t].start);
134         splineto(q[t].control, q[t].end);
135     }
136 }
137
138 /* Adds an outline to a font. Applies only the 2x2 component of the transformation matrix. 
139  */
140 void addtofont(T1_OUTLINE*outline, struct swfmatrix*m, char*namehint)
141 {
142 }
143
144 /* draw a T1 outline. These are generated by pdf2swf and by t1lib.
145    (representing characters) */
146 void drawpath(T1_OUTLINE*outline, struct swfmatrix*m, char*namehint)
147 {
148     double x=0,y=0;
149     double lastx=0,lasty=0;
150
151     while (outline)
152     {
153         logf("<debug> Pathtype:%s",outline->type == T1_PATHTYPE_MOVE?"MOVE":
154                                                     (outline->type == T1_PATHTYPE_LINE?"LINE"
155                                                                                       :"BEZIER"));
156         logf("<debug> relative coordinates: %08x,%08x", outline->dest.x, outline->dest.y);
157         x += (outline->dest.x/(float)0xffff);
158         y += (outline->dest.y/(float)0xffff);
159         logf("<debug> coordinates: %f,%f", x, y);
160         if(outline->type == T1_PATHTYPE_MOVE)
161         {
162         }
163         else if(outline->type == T1_PATHTYPE_LINE) 
164         {
165             plotxy p0;
166             plotxy p1;
167             p0.x=lastx;
168             p0.y=lasty;
169             p1.x=x;
170             p1.y=y;
171             line(p0,p1,m);
172         }
173         else if(outline->type == T1_PATHTYPE_BEZIER)
174         {
175             plotxy p0;
176             plotxy p1;
177             plotxy p2;
178             plotxy p3;
179             T1_BEZIERSEGMENT*o2 = (T1_BEZIERSEGMENT*)outline;
180             p0.x=x; 
181             p0.y=y;
182             p1.x=o2->C.x/(float)0xffff+lastx;
183             p1.y=o2->C.y/(float)0xffff+lasty;
184             p2.x=o2->B.x/(float)0xffff+lastx;
185             p2.y=o2->B.y/(float)0xffff+lasty;
186             p3.x=lastx;
187             p3.y=lasty;
188             spline(p0,p1,p2,p3,m);
189         } 
190         else {
191          logf("<error> drawpath: unknown outline type:%d\n", outline->type);
192         }
193         lastx=x;
194         lasty=y;
195         outline = outline->link;
196     }
197 }
198     //logf("<debug> Font name is %s", T1_GetFontFileName(t1fontindex));
199     //logf("<debug> char 0x%02x is named %s\n",character,charname);
200     //logf("<debug> bbox: %d %d %d %d\n",bbox.llx,bbox.lly,bbox.urx,bbox.ury);
201     //char*charname = T1_GetCharName(t1fontindex, character);
202
203 /* process a character. */
204 void drawchar(struct swfoutput*obj, SWFFont*font, char*character, swfmatrix*m)
205 {
206     T1_OUTLINE*outline = font->getOutline(character);
207     char* charname = character;
208
209     if(!outline) {
210      logf("Didn't find %s in current charset", character);
211      return;
212     }
213     
214     swfmatrix m2=*m;    
215     m2.m11/=100;
216     m2.m21/=100;
217     m2.m12/=100;
218     m2.m22/=100;
219
220     if(shapeid<0)
221         startshape(obj);
222
223     if(!lastwasfill)
224      ShapeSetStyle(tag,shape,0x8000,fillstyleid,0);
225     lastwasfill = 1;
226
227     drawpath(outline, &m2, charname);
228 }
229
230 /* draw a curved polygon. */
231 void swfoutput_drawpath(swfoutput*output, T1_OUTLINE*outline, struct swfmatrix*m)
232 {
233     if(shapeid<0)
234         startshape(output);
235
236     if(lastwasfill && !fill)
237     {
238      ShapeSetStyle(tag,shape,linestyleid,0x8000,0);
239      lastwasfill = 0;
240     }
241     if(!lastwasfill && fill)
242     {
243      ShapeSetStyle(tag,shape,0x8000,fillstyleid,0);
244      lastwasfill = 1;
245     }
246
247     drawpath(outline,m, 0); 
248 }
249
250 SWFFont::SWFFont(char*name, int id, char*filename)
251 {
252     if(!T1_GetFontName(id))
253         T1_LoadFont(id);
254
255     this->name = strdup(T1_GetFontFileName(id));
256     this->fontid = strdup(name);
257     this->t1id = id;
258
259     char**a= T1_GetAllCharNames(id);
260     int t=0, outlinepos=0;
261     char*map[256];
262     while(a[t])
263         t++;
264  
265     this->charnum = t;
266     if(!t) 
267         return;
268     logf("<notice> Font %s(%d): Storing %d outlines.\n", name, id, t);
269     
270     outline = (T1_OUTLINE**)malloc(t*sizeof(T1_OUTLINE*));
271     charname = (char**)malloc(t*sizeof(char*));
272     
273     t=0;
274     while(*a)
275     {
276         map[t] = *a;
277         a++;
278         t++;
279         if(t==256 || !*a) {
280             int s;
281             for(s=t;s<256;s++)
282                 map[s] = ".notdef";
283
284             int ret = T1_ReencodeFont(id, map);
285             if(ret) {
286              T1_DeleteFont(id);
287              T1_LoadFont(id);
288              int ret = T1_ReencodeFont(id, map);
289              if(ret)
290                fprintf(stderr,"Can't reencode font: (%s) ret:%d\n",filename, ret);
291             }
292
293             // parsecharacters
294             for(s=0;s<t;s++)
295             {
296                 this->outline[outlinepos] = T1_CopyOutline(T1_GetCharOutline(id, s, 100.0, 0));
297                 this->charname[outlinepos] = strdup(T1_GetCharName(id, s));
298                 outlinepos++;
299             }
300             t=0;
301         }
302     }
303 }
304
305 T1_OUTLINE*SWFFont::getOutline(char*name)
306 {
307     int t;
308     for(t=0;t<this->charnum;t++) {
309         if(!strcmp(this->charname[t],name))
310             return outline[t];
311     }
312     return 0;
313 }
314
315 char*SWFFont::getName()
316 {
317     return this->name;
318 }
319
320 struct fontlist_t 
321 {
322     SWFFont * font;
323     fontlist_t*next;
324 } *fontlist = 0;
325
326 /* set's the t1 font index of the font to use for swfoutput_drawchar(). */
327 void swfoutput_setfont(struct swfoutput*obj, char*fontid, int t1id, char*filename)
328 {
329     fontlist_t*last=0,*iterator;
330     if(obj->font && !strcmp(obj->font->fontid,fontid))
331         return;
332
333     iterator = fontlist;
334     while(iterator) {
335         if(!strcmp(iterator->font->fontid,fontid))
336             break;
337         last = iterator;
338         iterator = iterator->next;
339     }
340     if(iterator) 
341     {
342         obj->font = iterator->font;
343         return ;
344     }
345
346     if(t1id<0) {
347         logf("<error> internal error: t1id:%d, fontid:%s\n", t1id,fontid);
348     }
349     
350     SWFFont*font = new SWFFont(fontid, t1id, filename);
351     iterator = new fontlist_t;
352     iterator->font = font;
353     iterator->next = 0;
354
355     if(last) 
356         last->next = iterator;
357     else 
358         fontlist = iterator;
359     obj->font = font;
360 }
361
362 int swfoutput_queryfont(struct swfoutput*obj, char*fontid)
363 {
364     fontlist_t *iterator = fontlist;
365     while(iterator) {
366         if(!strcmp(iterator->font->fontid,fontid))
367             return 1;
368         iterator = iterator->next;
369     }
370     return 0;
371 }
372
373 /* set's the matrix which is to be applied to characters drawn by
374    swfoutput_drawchar() */
375 void swfoutput_setfontmatrix(struct swfoutput*obj,double m11,double m12,
376                                                   double m21,double m22)
377 {
378     obj->fontm11 = m11;
379     obj->fontm12 = m12;
380     obj->fontm21 = m21;
381     obj->fontm22 = m22;
382 }
383
384 /* draws a character at x,y. */
385 void swfoutput_drawchar(struct swfoutput* obj,double x,double y,char*character) 
386 {
387     swfmatrix m;
388     m.m11 = obj->fontm11;
389     m.m12 = obj->fontm12;
390     m.m21 = obj->fontm21;
391     m.m22 = obj->fontm22;
392     m.m13 = x;
393     m.m23 = y;
394     drawchar(obj, obj->font, character, &m);
395 }
396
397 /* initialize the swf writer */
398 void swfoutput_init(struct swfoutput* obj, char*_filename, int _sizex, int _sizey) 
399 {
400   GLYPH *glyph;
401   RGBA rgb;
402   SRECT r;
403   memset(obj, 0, sizeof(struct swfoutput));
404   filename = _filename;
405   sizex = _sizex;
406   sizey = _sizey;
407
408   logf("<verbose> initializing swf output for size %d*%d\n", sizex,sizey);
409
410   obj->font = 0;
411   
412   memset(&swf,0x00,sizeof(SWF));
413
414   swf.FileVersion    = 4;
415 //  swf.FrameRate      = 0x1900;
416   swf.FrameRate      = 0x0040; // 1 frame per 4 seconds
417   swf.MovieSize.xmax = 20*sizex;
418   swf.MovieSize.ymax = 20*sizey;
419   
420   swf.FirstTag = InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
421   tag = swf.FirstTag;
422   rgb.r = 0xff;
423   rgb.g = 0xff;
424   rgb.b = 0xff;
425   SetRGB(tag,&rgb);
426   if(flag_protected)
427     tag = InsertTag(tag, ST_PROTECT);
428   depth = 1;
429   startdepth = depth;
430 }
431
432 void swfoutput_setprotected() //write PROTECT tag
433 {
434   flag_protected = 1;
435 }
436
437 void startshape(struct swfoutput*obj)
438 {
439   RGBA rgb;
440   SRECT r;
441   tag = InsertTag(tag,ST_DEFINESHAPE);
442
443   NewShape(&shape);
444   linestyleid = ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
445   rgb.r = obj->fillrgb.r;
446   rgb.g = obj->fillrgb.g;
447   rgb.b = obj->fillrgb.b;
448   fillstyleid = ShapeAddSolidFillStyle(shape,&obj->fillrgb);
449
450   shapeid = ++shapecount;
451   SetU16(tag,shapeid);  // ID
452
453   r.xmin = 0;
454   r.ymin = 0;
455   r.xmax = 20*sizex;
456   r.ymax = 20*sizey;
457   
458   SetRect(tag,&r);
459
460   SetShapeStyles(tag,shape);
461   ShapeCountBits(shape,NULL,NULL);
462   SetShapeBits(tag,shape);
463
464   ShapeSetAll(tag,shape,/*x*/0,/*y*/0,linestyleid,0,0);
465   swflastx=swflasty=0;
466   lastwasfill = 0;
467 }
468
469 void endshape()
470 {
471     if(shapeid<0) 
472         return;
473     ShapeSetEnd(tag);
474     tag = InsertTag(tag,ST_PLACEOBJECT2);
475     ObjectPlace(tag,shapeid,/*depth*/depth++,NULL,NULL,NULL);
476     shapeid = -1;
477 }
478
479 void endpage(struct swfoutput*obj)
480 {
481     if(shapeid>=0)
482       endshape();
483     while(clippos)
484         swfoutput_endclip(obj);
485     tag = InsertTag(tag,ST_SHOWFRAME);
486 }
487
488 void swfoutput_newpage(struct swfoutput*obj)
489 {
490     endpage(obj);
491
492     for(depth--;depth>=startdepth;depth--) {
493         tag = InsertTag(tag,ST_REMOVEOBJECT2);
494         SetU16(tag,depth);
495     }
496
497     depth = 1;
498     startdepth = depth;
499 }
500
501 /* "destroy" like in (oo-terminology) "destructor". Perform cleaning
502    up, complete the swf, and write it out. */
503 void swfoutput_destroy(struct swfoutput* obj) 
504 {
505     endpage(obj);
506
507     T1_CloseLib();
508     if(!filename) 
509         return;
510     if(filename)
511      fi = open(filename, O_CREAT|O_TRUNC|O_WRONLY, 0777);
512     else
513      fi = 1; // stdout
514     
515     if(fi<=0) {
516      logf("<fatal> Could not create \"%s\". ", filename);
517      exit(1);
518     }
519  
520     tag = InsertTag(tag,ST_END);
521
522     if FAILED(WriteSWF(fi,&swf)) 
523      logf("<error> WriteSWF() failed.\n");
524     if(filename)
525      close(fi);
526     printf("SWF written\n");
527 }
528
529 void swfoutput_setdrawmode(swfoutput* obj, int mode)
530 {
531     if(mode == DRAWMODE_FILL)
532      fill = 1;
533     else if(mode == DRAWMODE_EOFILL)
534      fill = 1;
535     else if(mode == DRAWMODE_STROKE)
536      fill = 0;
537     else if(mode == DRAWMODE_CLIP)
538      fill = 1;
539     else if(mode == DRAWMODE_EOCLIP)
540      fill = 1;
541 }
542
543 void swfoutput_setfillcolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
544 {
545     if(obj->fillrgb.r == r &&
546        obj->fillrgb.g == g &&
547        obj->fillrgb.b == b &&
548        obj->fillrgb.a == a) return;
549
550     if(shape>=0)
551      endshape();
552     obj->fillrgb.r = r;
553     obj->fillrgb.g = g;
554     obj->fillrgb.b = b;
555     obj->fillrgb.a = a;
556 }
557
558 void swfoutput_setstrokecolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
559 {
560     if(obj->strokergb.r == r &&
561        obj->strokergb.g == g &&
562        obj->strokergb.b == b &&
563        obj->strokergb.a == a) return;
564
565     if(shape>=0)
566      endshape();
567     obj->strokergb.r = r;
568     obj->strokergb.g = g;
569     obj->strokergb.b = b;
570     obj->strokergb.a = a;
571 }
572
573 void swfoutput_setlinewidth(struct swfoutput*obj, double linewidth)
574 {
575     if(obj->linewidth == (u16)(linewidth*20))
576         return;
577
578     if(shape>=0)
579      endshape();
580     obj->linewidth = (u16)(linewidth*20);
581 }
582
583
584 void swfoutput_startclip(swfoutput*obj, T1_OUTLINE*outline, struct swfmatrix*m)
585 {
586     if(shape>=0)
587      endshape();
588
589     if(clippos >= 127)
590     {
591         logf("<warning> Too many clip levels.");
592         clippos --;
593     } 
594
595     startshape(obj);
596
597     swfoutput_setdrawmode(obj, DRAWMODE_CLIP);
598     swfoutput_drawpath(obj, outline, m);
599
600     ShapeSetEnd(tag);
601     tag = InsertTag(tag,ST_PLACEOBJECT2);
602     cliptags[clippos] = tag;
603     clipshapes[clippos] = shapeid;
604     clipdepths[clippos] = depth++;
605     clippos++;
606     shapeid = -1;
607 }
608
609 void swfoutput_endclip(swfoutput*obj)
610 {
611     if(shape>=0)
612      endshape();
613
614     if(!clippos) {
615         logf("<error> Invalid end of clipping region");
616         return;
617     }
618     clippos--;
619     PlaceObject(cliptags[clippos],clipshapes[clippos],clipdepths[clippos],NULL,NULL,NULL,depth++);
620 }
621
622 void swfoutput_drawimagefile(struct swfoutput*, char*filename, int sizex,int sizey, 
623         double x1,double y1,
624         double x2,double y2,
625         double x3,double y3,
626         double x4,double y4)
627 {
628     RGBA rgb;
629     SRECT r;
630     int lsid=0;
631     int fsid;
632     int bitid;
633     struct plotxy p1,p2,p3,p4;
634     int myshapeid;
635     double xmax=x1,ymax=y1,xmin=x1,ymin=y1;
636     if(x2>xmax) xmax=x2;
637     if(y2>ymax) ymax=y2;
638     if(x2<xmin) xmin=x2;
639     if(y2<ymin) ymin=y2;
640     if(x3>xmax) xmax=x3;
641     if(y3>ymax) ymax=y3;
642     if(x3<xmin) xmin=x3;
643     if(y3<ymin) ymin=y3;
644     if(x4>xmax) xmax=x4;
645     if(y4>ymax) ymax=y4;
646     if(x4<xmin) xmin=x4;
647     if(y4<ymin) ymin=y4;
648     p1.x=x1;
649     p1.y=y1;
650     p2.x=x2;
651     p2.y=y2;
652     p3.x=x3;
653     p3.y=y3;
654     p4.x=x4;
655     p4.y=y4;
656     
657     MATRIX m;
658     m.sx = (int)(65536*20*(x4-x1))/sizex;
659     m.r1 = -(int)(65536*20*(y4-y1))/sizex;
660     m.r0 = (int)(65536*20*(x1-x2))/sizey;
661     m.sy = -(int)(65536*20*(y1-y2))/sizey;
662
663     m.tx = (int)(x1*20);
664     m.ty = (int)(y1*20);
665     
666     if(shape>=0)
667      endshape();
668
669     bitid = ++shapecount;
670   
671     /* bitmap */
672     tag = InsertTag(tag,ST_DEFINEBITSJPEG2);
673     SetU16(tag, bitid);
674     SetJPEGBits(tag, filename, 85);
675
676     /* shape */
677     myshapeid = ++shapecount;
678     tag = InsertTag(tag,ST_DEFINESHAPE);
679     NewShape(&shape);
680     //lsid = ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
681     //fsid = ShapeAddSolidFillStyle(shape,&obj->fillrgb);
682     fsid = ShapeAddBitmapFillStyle(shape,&m,bitid,0);
683     SetU16(tag, myshapeid);
684     r.xmin = (int)(xmin*20);
685     r.ymin = (int)(ymin*20);
686     r.xmax = (int)(xmax*20);
687     r.ymax = (int)(ymax*20);
688     SetRect(tag,&r);
689     SetShapeStyles(tag,shape);
690     ShapeCountBits(shape,NULL,NULL);
691     SetShapeBits(tag,shape);
692     ShapeSetAll(tag,shape,/*x*/0,/*y*/0,lsid,fsid,0);
693     swflastx = swflasty = 0;
694     moveto(p1);
695     lineto(p2);
696     lineto(p3);
697     lineto(p4);
698     lineto(p1);
699     /*
700     ShapeMoveTo  (tag, shape, (int)(x1*20),(int)(y1*20));
701     ShapeSetLine (tag, shape, (int)(x1*20);
702     ShapeSetLine (tag, shape, x*20,0);
703     ShapeSetLine (tag, shape, 0,-y*20);
704     ShapeSetLine (tag, shape, -x*20,0);*/
705     ShapeSetEnd(tag);
706
707     /* instance */
708     tag = InsertTag(tag,ST_PLACEOBJECT2);
709     ObjectPlace(tag,myshapeid,/*depth*/depth++,NULL,NULL,NULL);
710 }
711