Font characters are now addressed by full name, not charcode
[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      return;
211     
212     swfmatrix m2=*m;    
213     m2.m11/=100;
214     m2.m21/=100;
215     m2.m12/=100;
216     m2.m22/=100;
217
218     if(shapeid<0)
219         startshape(obj);
220
221     if(!lastwasfill)
222      ShapeSetStyle(tag,shape,0x8000,fillstyleid,0);
223     lastwasfill = 1;
224
225     drawpath(outline, &m2, charname);
226 }
227
228 /* draw a curved polygon. */
229 void swfoutput_drawpath(swfoutput*output, T1_OUTLINE*outline, struct swfmatrix*m)
230 {
231     if(shapeid<0)
232         startshape(output);
233
234     if(lastwasfill && !fill)
235     {
236      ShapeSetStyle(tag,shape,linestyleid,0x8000,0);
237      lastwasfill = 0;
238     }
239     if(!lastwasfill && fill)
240     {
241      ShapeSetStyle(tag,shape,0x8000,fillstyleid,0);
242      lastwasfill = 1;
243     }
244
245     drawpath(outline,m, 0); 
246 }
247
248 SWFFont::SWFFont(char*name, int id, char*filename)
249 {
250     if(!T1_GetFontName(id))
251         T1_LoadFont(id);
252
253     this->name = strdup(T1_GetFontFileName(id));
254     this->fontid = name;
255     this->t1id = id;
256
257     char**a= T1_GetAllCharNames(id);
258     int t=0, outlinepos=0;
259     char*map[256];
260     while(a[t])
261         t++;
262  
263     this->charnum = t;
264     if(!t) 
265         return;
266     logf("<notice> Font %s(%d): Storing %d outlines.\n", name, id, t);
267     
268     outline = (T1_OUTLINE**)malloc(t*sizeof(T1_OUTLINE*));
269     charname = (char**)malloc(t*sizeof(char*));
270     
271     t=0;
272     while(*a)
273     {
274         map[t] = *a;
275         a++;
276         t++;
277         if(t==256 || !*a) {
278             int s;
279             for(s=t;s<256;s++)
280                 map[s] = ".notdef";
281
282             int ret = T1_ReencodeFont(id, map);
283             if(ret) {
284              T1_DeleteFont(id);
285              T1_LoadFont(id);
286              int ret = T1_ReencodeFont(id, map);
287              if(ret)
288                fprintf(stderr,"Can't reencode font: (%s) ret:%d\n",filename, ret);
289             }
290
291             // parsecharacters
292             for(s=0;s<t;s++)
293             {
294                 this->outline[outlinepos] = T1_CopyOutline(T1_GetCharOutline(id, s, 100.0, 0));
295                 this->charname[outlinepos] = strdup(T1_GetCharName(id, s));
296                 outlinepos++;
297             }
298             t=0;
299         }
300     }
301 }
302
303 T1_OUTLINE*SWFFont::getOutline(char*name)
304 {
305     int t;
306     for(t=0;t<this->charnum;t++) {
307         if(!strcmp(this->charname[t],name))
308             return outline[t];
309     }
310     return 0;
311 }
312
313 char*SWFFont::getName()
314 {
315     return this->name;
316 }
317
318 struct fontlist_t 
319 {
320     SWFFont * font;
321     fontlist_t*next;
322 } *fontlist = 0;
323
324 /* set's the t1 font index of the font to use for swfoutput_drawchar(). */
325 void swfoutput_setfont(struct swfoutput*obj, char*fontid, int t1id, char*filename)
326 {
327     fontlist_t*last=0,*iterator;
328     if(obj->font && !strcmp(obj->font->fontid,fontid))
329         return;
330
331     iterator = fontlist;
332     while(iterator) {
333         if(!strcmp(iterator->font->fontid,fontid))
334             break;
335         last = iterator;
336         iterator = iterator->next;
337     }
338     if(iterator) 
339     {
340         obj->font = iterator->font;
341         return ;
342     }
343
344     if(t1id<0) {
345         logf("<error> internal error: t1id:%d, fontid:%s\n", t1id,fontid);
346     }
347     
348     SWFFont*font = new SWFFont(fontid, t1id, filename);
349     iterator = new fontlist_t;
350     iterator->font = font;
351     iterator->next = 0;
352
353     if(last) 
354         last->next = iterator;
355     else 
356         fontlist = iterator;
357     obj->font = font;
358 }
359
360 int swfoutput_queryfont(struct swfoutput*obj, char*fontid)
361 {
362     fontlist_t *iterator = fontlist;
363     while(iterator) {
364         if(!strcmp(iterator->font->fontid,fontid))
365             return 1;
366         iterator = iterator->next;
367     }
368     return 0;
369 }
370
371 /* set's the matrix which is to be applied to characters drawn by
372    swfoutput_drawchar() */
373 void swfoutput_setfontmatrix(struct swfoutput*obj,double m11,double m12,
374                                                   double m21,double m22)
375 {
376     obj->fontm11 = m11;
377     obj->fontm12 = m12;
378     obj->fontm21 = m21;
379     obj->fontm22 = m22;
380 }
381
382 /* draws a character at x,y. */
383 void swfoutput_drawchar(struct swfoutput* obj,double x,double y,char*character) 
384 {
385     swfmatrix m;
386     m.m11 = obj->fontm11;
387     m.m12 = obj->fontm12;
388     m.m21 = obj->fontm21;
389     m.m22 = obj->fontm22;
390     m.m13 = x;
391     m.m23 = y;
392     drawchar(obj, obj->font, character, &m);
393 }
394
395 /* initialize the swf writer */
396 void swfoutput_init(struct swfoutput* obj, char*_filename, int _sizex, int _sizey) 
397 {
398   GLYPH *glyph;
399   RGBA rgb;
400   SRECT r;
401   memset(obj, 0, sizeof(struct swfoutput));
402   filename = _filename;
403   sizex = _sizex;
404   sizey = _sizey;
405
406   logf("<verbose> initializing swf output for size %d*%d\n", sizex,sizey);
407
408   obj->font = 0;
409   
410   memset(&swf,0x00,sizeof(SWF));
411
412   swf.FileVersion    = 4;
413 //  swf.FrameRate      = 0x1900;
414   swf.FrameRate      = 0x0040; // 1 frame per 4 seconds
415   swf.MovieSize.xmax = 20*sizex;
416   swf.MovieSize.ymax = 20*sizey;
417   
418   swf.FirstTag = InsertTag(NULL,ST_SETBACKGROUNDCOLOR);
419   tag = swf.FirstTag;
420   rgb.r = 0xff;
421   rgb.g = 0xff;
422   rgb.b = 0xff;
423   SetRGB(tag,&rgb);
424   if(flag_protected)
425     tag = InsertTag(tag, ST_PROTECT);
426   depth = 1;
427   startdepth = depth;
428 }
429
430 void swfoutput_setprotected() //write PROTECT tag
431 {
432   flag_protected = 1;
433 }
434
435 void startshape(struct swfoutput*obj)
436 {
437   RGBA rgb;
438   SRECT r;
439   tag = InsertTag(tag,ST_DEFINESHAPE);
440
441   NewShape(&shape);
442   linestyleid = ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
443   rgb.r = obj->fillrgb.r;
444   rgb.g = obj->fillrgb.g;
445   rgb.b = obj->fillrgb.b;
446   fillstyleid = ShapeAddSolidFillStyle(shape,&obj->fillrgb);
447
448   shapeid = ++shapecount;
449   SetU16(tag,shapeid);  // ID
450
451   r.xmin = 0;
452   r.ymin = 0;
453   r.xmax = 20*sizex;
454   r.ymax = 20*sizey;
455   
456   SetRect(tag,&r);
457
458   SetShapeStyles(tag,shape);
459   ShapeCountBits(shape,NULL,NULL);
460   SetShapeBits(tag,shape);
461
462   ShapeSetAll(tag,shape,/*x*/0,/*y*/0,linestyleid,0,0);
463   swflastx=swflasty=0;
464   lastwasfill = 0;
465 }
466
467 void endshape()
468 {
469     if(shapeid<0) 
470         return;
471     ShapeSetEnd(tag);
472     tag = InsertTag(tag,ST_PLACEOBJECT2);
473     ObjectPlace(tag,shapeid,/*depth*/depth++,NULL,NULL,NULL);
474     shapeid = -1;
475 }
476
477 void endpage(struct swfoutput*obj)
478 {
479     if(shapeid>=0)
480       endshape();
481     while(clippos)
482         swfoutput_endclip(obj);
483     tag = InsertTag(tag,ST_SHOWFRAME);
484 }
485
486 void swfoutput_newpage(struct swfoutput*obj)
487 {
488     endpage(obj);
489
490     for(depth--;depth>=startdepth;depth--) {
491         tag = InsertTag(tag,ST_REMOVEOBJECT2);
492         SetU16(tag,depth);
493     }
494
495     depth = 1;
496     startdepth = depth;
497 }
498
499 /* "destroy" like in (oo-terminology) "destructor". Perform cleaning
500    up, complete the swf, and write it out. */
501 void swfoutput_destroy(struct swfoutput* obj) 
502 {
503     endpage(obj);
504
505     T1_CloseLib();
506     if(!filename) 
507         return;
508     if(filename)
509      fi = open(filename, O_CREAT|O_TRUNC|O_WRONLY, 0777);
510     else
511      fi = 1; // stdout
512     
513     if(fi<=0) {
514      logf("<fatal> Could not create \"%s\". ", filename);
515      exit(1);
516     }
517  
518     tag = InsertTag(tag,ST_END);
519
520     if FAILED(WriteSWF(fi,&swf)) 
521      logf("<error> WriteSWF() failed.\n");
522     if(filename)
523      close(fi);
524     printf("SWF written\n");
525 }
526
527 void swfoutput_setdrawmode(swfoutput* obj, int mode)
528 {
529     if(mode == DRAWMODE_FILL)
530      fill = 1;
531     else if(mode == DRAWMODE_EOFILL)
532      fill = 1;
533     else if(mode == DRAWMODE_STROKE)
534      fill = 0;
535     else if(mode == DRAWMODE_CLIP)
536      fill = 1;
537     else if(mode == DRAWMODE_EOCLIP)
538      fill = 1;
539 }
540
541 void swfoutput_setfillcolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
542 {
543     if(obj->fillrgb.r == r &&
544        obj->fillrgb.g == g &&
545        obj->fillrgb.b == b &&
546        obj->fillrgb.a == a) return;
547
548     if(shape>=0)
549      endshape();
550     obj->fillrgb.r = r;
551     obj->fillrgb.g = g;
552     obj->fillrgb.b = b;
553     obj->fillrgb.a = a;
554 }
555
556 void swfoutput_setstrokecolor(swfoutput* obj, u8 r, u8 g, u8 b, u8 a)
557 {
558     if(obj->strokergb.r == r &&
559        obj->strokergb.g == g &&
560        obj->strokergb.b == b &&
561        obj->strokergb.a == a) return;
562
563     if(shape>=0)
564      endshape();
565     obj->strokergb.r = r;
566     obj->strokergb.g = g;
567     obj->strokergb.b = b;
568     obj->strokergb.a = a;
569 }
570
571 void swfoutput_setlinewidth(struct swfoutput*obj, double linewidth)
572 {
573     if(obj->linewidth == (u16)(linewidth*20))
574         return;
575
576     if(shape>=0)
577      endshape();
578     obj->linewidth = (u16)(linewidth*20);
579 }
580
581
582 void swfoutput_startclip(swfoutput*obj, T1_OUTLINE*outline, struct swfmatrix*m)
583 {
584     if(shape>=0)
585      endshape();
586
587     if(clippos >= 127)
588     {
589         logf("<warning> Too many clip levels.");
590         clippos --;
591     } 
592
593     startshape(obj);
594
595     swfoutput_setdrawmode(obj, DRAWMODE_CLIP);
596     swfoutput_drawpath(obj, outline, m);
597
598     ShapeSetEnd(tag);
599     tag = InsertTag(tag,ST_PLACEOBJECT2);
600     cliptags[clippos] = tag;
601     clipshapes[clippos] = shapeid;
602     clipdepths[clippos] = depth++;
603     clippos++;
604     shapeid = -1;
605 }
606
607 void swfoutput_endclip(swfoutput*obj)
608 {
609     if(shape>=0)
610      endshape();
611
612     if(!clippos) {
613         logf("<error> Invalid end of clipping region");
614         return;
615     }
616     clippos--;
617     PlaceObject(cliptags[clippos],clipshapes[clippos],clipdepths[clippos],NULL,NULL,NULL,depth++);
618 }
619
620 void swfoutput_drawimagefile(struct swfoutput*, char*filename, int sizex,int sizey, 
621         double x1,double y1,
622         double x2,double y2,
623         double x3,double y3,
624         double x4,double y4)
625 {
626     RGBA rgb;
627     SRECT r;
628     int lsid=0;
629     int fsid;
630     int bitid;
631     struct plotxy p1,p2,p3,p4;
632     int myshapeid;
633     double xmax=x1,ymax=y1,xmin=x1,ymin=y1;
634     if(x2>xmax) xmax=x2;
635     if(y2>ymax) ymax=y2;
636     if(x2<xmin) xmin=x2;
637     if(y2<ymin) ymin=y2;
638     if(x3>xmax) xmax=x3;
639     if(y3>ymax) ymax=y3;
640     if(x3<xmin) xmin=x3;
641     if(y3<ymin) ymin=y3;
642     if(x4>xmax) xmax=x4;
643     if(y4>ymax) ymax=y4;
644     if(x4<xmin) xmin=x4;
645     if(y4<ymin) ymin=y4;
646     p1.x=x1;
647     p1.y=y1;
648     p2.x=x2;
649     p2.y=y2;
650     p3.x=x3;
651     p3.y=y3;
652     p4.x=x4;
653     p4.y=y4;
654     
655     MATRIX m;
656     m.sx = (int)(65536*20*(x4-x1))/sizex;
657     m.r1 = -(int)(65536*20*(y4-y1))/sizex;
658     m.r0 = (int)(65536*20*(x1-x2))/sizey;
659     m.sy = -(int)(65536*20*(y1-y2))/sizey;
660
661     m.tx = (int)(x1*20);
662     m.ty = (int)(y1*20);
663     
664     if(shape>=0)
665      endshape();
666
667     bitid = ++shapecount;
668   
669     /* bitmap */
670     tag = InsertTag(tag,ST_DEFINEBITSJPEG2);
671     SetU16(tag, bitid);
672     SetJPEGBits(tag, filename, 85);
673
674     /* shape */
675     myshapeid = ++shapecount;
676     tag = InsertTag(tag,ST_DEFINESHAPE);
677     NewShape(&shape);
678     //lsid = ShapeAddLineStyle(shape,obj->linewidth,&obj->strokergb);
679     //fsid = ShapeAddSolidFillStyle(shape,&obj->fillrgb);
680     fsid = ShapeAddBitmapFillStyle(shape,&m,bitid,0);
681     SetU16(tag, myshapeid);
682     r.xmin = (int)(xmin*20);
683     r.ymin = (int)(ymin*20);
684     r.xmax = (int)(xmax*20);
685     r.ymax = (int)(ymax*20);
686     SetRect(tag,&r);
687     SetShapeStyles(tag,shape);
688     ShapeCountBits(shape,NULL,NULL);
689     SetShapeBits(tag,shape);
690     ShapeSetAll(tag,shape,/*x*/0,/*y*/0,lsid,fsid,0);
691     swflastx = swflasty = 0;
692     moveto(p1);
693     lineto(p2);
694     lineto(p3);
695     lineto(p4);
696     lineto(p1);
697     /*
698     ShapeMoveTo  (tag, shape, (int)(x1*20),(int)(y1*20));
699     ShapeSetLine (tag, shape, (int)(x1*20);
700     ShapeSetLine (tag, shape, x*20,0);
701     ShapeSetLine (tag, shape, 0,-y*20);
702     ShapeSetLine (tag, shape, -x*20,0);*/
703     ShapeSetEnd(tag);
704
705     /* instance */
706     tag = InsertTag(tag,ST_PLACEOBJECT2);
707     ObjectPlace(tag,myshapeid,/*depth*/depth++,NULL,NULL,NULL);
708 }
709