Fix bugs in previous commit that caused FTBFS in synfig and ETL FTBFS with older...
[synfig.git] / synfig-core / tags / synfig_0_61_06 / src / modules / lyr_freetype / lyr_freetype.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file lyr_freetype.cpp
3 **      \brief Template Header
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2006 Paul Wise
10 **
11 **      This package is free software; you can redistribute it and/or
12 **      modify it under the terms of the GNU General Public License as
13 **      published by the Free Software Foundation; either version 2 of
14 **      the License, or (at your option) any later version.
15 **
16 **      This package is distributed in the hope that it will be useful,
17 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
18 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 **      General Public License for more details.
20 **      \endlegal
21 **
22 ** === N O T E S ===========================================================
23 **
24 ** ========================================================================= */
25
26 /* === H E A D E R S ======================================================= */
27
28 #define SYNFIG_LAYER
29
30 #ifdef USING_PCH
31 #       include "pch.h"
32 #else
33 #ifdef HAVE_CONFIG_H
34 #       include <config.h>
35 #endif
36 #ifdef WITH_FONTCONFIG
37 #include <fontconfig/fontconfig.h>
38 #endif
39
40 #include "lyr_freetype.h"
41
42
43 #endif
44
45 using namespace std;
46 using namespace etl;
47 using namespace synfig;
48
49 /* === M A C R O S ========================================================= */
50
51 #define MAX_GLYPHS              2000
52
53 #define PANGO_STYLE_NORMAL (0)
54 #define PANGO_STYLE_OBLIQUE (1)
55 #define PANGO_STYLE_ITALIC (2)
56
57
58 #define WEIGHT_NORMAL (400)
59 #define WEIGHT_BOLD (700)
60
61 /* === G L O B A L S ======================================================= */
62
63 SYNFIG_LAYER_INIT(lyr_freetype);
64 SYNFIG_LAYER_SET_NAME(lyr_freetype,"text");
65 SYNFIG_LAYER_SET_LOCAL_NAME(lyr_freetype,_("Simple Text"));
66 SYNFIG_LAYER_SET_CATEGORY(lyr_freetype,_("Typography"));
67 SYNFIG_LAYER_SET_VERSION(lyr_freetype,"0.2");
68 SYNFIG_LAYER_SET_CVS_ID(lyr_freetype,"$Id$");
69
70 /* === P R O C E D U R E S ================================================= */
71
72 /*Glyph::~Glyph()
73 {
74         if(glyph)FT_Done_Glyph(glyph);
75 }
76 */
77 void
78 TextLine::clear_and_free()
79 {
80         std::vector<Glyph>::iterator iter;
81         for(iter=glyph_table.begin();iter!=glyph_table.end();++iter)
82         {
83                 if(iter->glyph)FT_Done_Glyph(iter->glyph);
84                 iter->glyph=0;
85         }
86         glyph_table.clear();
87 }
88
89 /* === M E T H O D S ======================================================= */
90
91 lyr_freetype::lyr_freetype()
92 {
93         face=0;
94
95         size=Vector(0.25,0.25);
96         text=_("Text Layer");
97         color=Color::black();
98         pos=Vector(0,0);
99         orient=Vector(0.5,0.5);
100         compress=1.0;
101         vcompress=1.0;
102         weight=WEIGHT_NORMAL;
103         style=PANGO_STYLE_NORMAL;
104         family="Sans Serif";
105         use_kerning=true;
106         grid_fit=false;
107         old_version=false;
108         set_blend_method(Color::BLEND_COMPOSITE);
109         needs_sync_=true;
110
111         new_font(family,style,weight);
112
113         invert=false;
114 }
115
116 lyr_freetype::~lyr_freetype()
117 {
118         if(face)
119                 FT_Done_Face(face);
120 }
121
122 void
123 lyr_freetype::new_font(const synfig::String &family, int style, int weight)
124 {
125         if(
126                 !new_font_(family,style,weight) &&
127                 !new_font_(family,style,WEIGHT_NORMAL) &&
128                 !new_font_(family,PANGO_STYLE_NORMAL,weight) &&
129                 !new_font_(family,PANGO_STYLE_NORMAL,WEIGHT_NORMAL) &&
130                 !new_font_("sans serif",style,weight) &&
131                 !new_font_("sans serif",style,WEIGHT_NORMAL) &&
132                 !new_font_("sans serif",PANGO_STYLE_NORMAL,weight)
133         )
134                 new_font_("sans serif",PANGO_STYLE_NORMAL,WEIGHT_NORMAL);
135 }
136
137 bool
138 lyr_freetype::new_font_(const synfig::String &font_fam_, int style, int weight)
139 {
140         synfig::String font_fam(font_fam_);
141
142         if(new_face(font_fam_))
143                 return true;
144
145         //start evil hack
146         for(unsigned int i=0;i<font_fam.size();i++)font_fam[i]=tolower(font_fam[i]);
147         //end evil hack
148
149         if(font_fam=="arial black")
150 #ifndef __APPLE__
151         if(new_face("ariblk"))
152                         return true;
153                 else
154 #endif
155                 font_fam="sans serif";
156
157         if(font_fam=="sans serif" || font_fam=="arial")
158         {
159                 String arial("arial");
160                 if(weight>WEIGHT_NORMAL)
161                         arial+='b';
162                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
163                         arial+='i';
164                 else
165                         if(weight>WEIGHT_NORMAL) arial+='d';
166
167                 if(new_face(arial))
168                         return true;
169 #ifdef __APPLE__
170                 if(new_face("Helvetica RO"))
171                         return true;
172 #endif
173         }
174
175         if(font_fam=="comic" || font_fam=="comic sans")
176         {
177                 String filename("comic");
178                 if(weight>WEIGHT_NORMAL)
179                         filename+='b';
180                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
181                         filename+='i';
182                 else if(weight>WEIGHT_NORMAL) filename+='d';
183
184                 if(new_face(filename))
185                         return true;
186         }
187
188         if(font_fam=="courier" || font_fam=="courier new")
189         {
190                 String filename("cour");
191                 if(weight>WEIGHT_NORMAL)
192                         filename+='b';
193                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
194                         filename+='i';
195                 else if(weight>WEIGHT_NORMAL) filename+='d';
196
197                 if(new_face(filename))
198                         return true;
199         }
200
201         if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman")
202         {
203                 String filename("times");
204                 if(weight>WEIGHT_NORMAL)
205                         filename+='b';
206                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
207                         filename+='i';
208                 else if(weight>WEIGHT_NORMAL) filename+='d';
209
210                 if(new_face(filename))
211                         return true;
212         }
213
214         if(font_fam=="trebuchet")
215         {
216                 String filename("trebuc");
217                 if(weight>WEIGHT_NORMAL)
218                         filename+='b';
219                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
220                 {
221                         filename+='i';
222                         if(weight<=WEIGHT_NORMAL) filename+='t';
223                 }
224                 else if(weight>WEIGHT_NORMAL) filename+='d';
225
226                 if(new_face(filename))
227                         return true;
228         }
229
230
231         if(font_fam=="sans serif" || font_fam=="luxi sans")
232         {
233                 {
234                         String luxi("luxis");
235                         if(weight>WEIGHT_NORMAL)
236                                 luxi+='b';
237                         else
238                                 luxi+='r';
239                         if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
240                                 luxi+='i';
241
242
243                         if(new_face(luxi))
244                                 return true;
245                 }
246                 if(new_face("arial"))
247                         return true;
248                 if(new_face("Arial"))
249                         return true;
250         }
251         if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman" || font_fam=="luxi serif")
252         {
253                 {
254                         String luxi("luxir");
255                         if(weight>WEIGHT_NORMAL)
256                                 luxi+='b';
257                         else
258                                 luxi+='r';
259                         if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
260                                 luxi+='i';
261
262                         if(new_face(luxi))
263                                 return true;
264                 }
265                 if(new_face("Times New Roman"))
266                         return true;
267                 if(new_face("Times"))
268                         return true;
269         }
270         if(font_fam=="luxi")
271         {
272                 {
273                         String luxi("luxim");
274                         if(weight>WEIGHT_NORMAL)
275                                 luxi+='b';
276                         else
277                                 luxi+='r';
278                         if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
279                                 luxi+='i';
280
281                         if(new_face(luxi))
282                                 return true;
283                 }
284
285                 if(new_face("Times New Roman"))
286                         return true;
287                 if(new_face("Times"))
288                         return true;
289         }
290
291         return new_face(font_fam_) || new_face(font_fam);
292
293         return false;
294 }
295
296 #ifdef USE_MAC_FT_FUNCS
297 void fss2path(char *path, FSSpec *fss)
298 {
299   int l;             //fss->name contains name of last item in path
300   for(l=0; l<(fss->name[0]); l++) path[l] = fss->name[l + 1];
301   path[l] = 0;
302
303   if(fss->parID != fsRtParID) //path is more than just a volume name
304   {
305     int i, len;
306     CInfoPBRec pb;
307
308     pb.dirInfo.ioNamePtr = fss->name;
309     pb.dirInfo.ioVRefNum = fss->vRefNum;
310     pb.dirInfo.ioDrParID = fss->parID;
311     do
312     {
313       pb.dirInfo.ioFDirIndex = -1;  //get parent directory name
314       pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
315       if(PBGetCatInfoSync(&pb) != noErr) break;
316
317       len = fss->name[0] + 1;
318       for(i=l; i>=0;  i--) path[i + len] = path[i];
319       for(i=1; i<len; i++) path[i - 1] = fss->name[i]; //add to start of path
320       path[i - 1] = ':';
321       l += len;
322 } while(pb.dirInfo.ioDrDirID != fsRtDirID); //while more directory levels
323   }
324 }
325 #endif
326
327 bool
328 lyr_freetype::new_face(const String &newfont)
329 {
330         int error;
331         FT_Long face_index=0;
332
333         // If we are already loaded, don't bother reloading.
334         if(face && font==newfont)
335                 return true;
336
337         if(face)
338         {
339                 FT_Done_Face(face);
340                 face=0;
341         }
342
343         error=FT_New_Face(ft_library,newfont.c_str(),face_index,&face);
344         if(error)error=FT_New_Face(ft_library,(newfont+".ttf").c_str(),face_index,&face);
345
346         if(get_canvas())
347         {
348                 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont).c_str(),face_index,&face);
349                 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont+".ttf").c_str(),face_index,&face);
350         }
351
352 #ifdef USE_MAC_FT_FUNCS
353         if(error)
354         {
355                 FSSpec fs_spec;
356                 error=FT_GetFile_From_Mac_Name(newfont.c_str(),&fs_spec,&face_index);
357                 if(!error)
358                 {
359                         char filename[512];
360                         fss2path(filename,&fs_spec);
361                         //FSSpecToNativePathName(fs_spec,filename,sizeof(filename)-1, 0);
362
363                         error=FT_New_Face(ft_library, filename, face_index,&face);
364                         //error=FT_New_Face_From_FSSpec(ft_library, &fs_spec, face_index,&face);
365                         synfig::info(__FILE__":%d: \"%s\" (%s) -- ft_error=%d",__LINE__,newfont.c_str(),filename,error);
366                 }
367                 else
368                 {
369                         synfig::info(__FILE__":%d: \"%s\" -- ft_error=%d",__LINE__,newfont.c_str(),error);
370                         // Unable to generate fs_spec
371                 }
372
373         }
374 #endif
375
376 #ifdef WITH_FONTCONFIG
377         if(error)
378         {
379                 FcFontSet *fs;
380                 FcResult result;
381                 if( !FcInit() )
382                 {
383                         synfig::warning("lyr_freetype: fontconfig: %s",_("unable to initialise"));
384                         error = 1;
385                 } else {
386                         FcPattern* pat = FcNameParse((FcChar8 *) newfont.c_str());
387                         FcConfigSubstitute(0, pat, FcMatchPattern);
388                         FcDefaultSubstitute(pat);
389                         FcPattern *match;
390                         fs = FcFontSetCreate();
391                         match = FcFontMatch(0, pat, &result);
392                         if (match)
393                                 FcFontSetAdd(fs, match);
394                         if (pat)
395                                 FcPatternDestroy(pat);
396                         if(fs){
397                                 FcChar8* file;
398                                 if( FcPatternGetString (fs->fonts[0], FC_FILE, 0, &file) == FcResultMatch )
399                                         error=FT_New_Face(ft_library,(const char*)file,face_index,&face);
400                                 FcFontSetDestroy(fs);
401                         } else
402                                 synfig::warning("lyr_freetype: fontconfig: %s",_("empty font set"));
403                 }
404         }
405 #endif
406
407 #ifdef WIN32
408         if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont).c_str(),face_index,&face);
409         if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont+".ttf").c_str(),face_index,&face);
410 #else
411
412 #ifdef __APPLE__
413         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont).c_str(),face_index,&face);
414         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
415         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
416
417         if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont).c_str(),face_index,&face);
418         if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
419         if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
420 #endif
421
422         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont).c_str(),face_index,&face);
423         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont+".ttf").c_str(),face_index,&face);
424
425         if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont).c_str(),face_index,&face);
426         if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
427
428         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont).c_str(),face_index,&face);
429         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont+".ttf").c_str(),face_index,&face);
430
431         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont).c_str(),face_index,&face);
432         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
433
434 #endif
435         if(error)
436         {
437                 //synfig::error(strprintf("lyr_freetype:%s (err=%d)",_("Unable to open face."),error));
438                 return false;
439         }
440
441         font=newfont;
442
443         needs_sync_=true;
444         return true;
445 }
446
447 bool
448 lyr_freetype::set_param(const String & param, const ValueBase &value)
449 {
450         Mutex::Lock lock(mutex);
451 /*
452         if(param=="font" && value.same_as(font))
453         {
454                 new_font(etl::basename(value.get(font)),style,weight);
455                 family=etl::basename(value.get(font));
456                 return true;
457         }
458 */
459         IMPORT_PLUS(family,new_font(family,style,weight));
460         IMPORT_PLUS(weight,new_font(family,style,weight));
461         IMPORT_PLUS(style,new_font(family,style,weight));
462         IMPORT_PLUS(size, if(old_version){size/=2.0;} needs_sync_=true );
463         IMPORT_PLUS(text,needs_sync_=true);
464         IMPORT_PLUS(pos,needs_sync_=true);
465         IMPORT(color);
466         IMPORT(invert);
467         IMPORT_PLUS(orient,needs_sync_=true);
468         IMPORT_PLUS(compress,needs_sync_=true);
469         IMPORT_PLUS(vcompress,needs_sync_=true);
470         IMPORT_PLUS(use_kerning,needs_sync_=true);
471         IMPORT_PLUS(grid_fit,needs_sync_=true);
472
473         return Layer_Composite::set_param(param,value);
474 }
475
476 ValueBase
477 lyr_freetype::get_param(const String& param)const
478 {
479         EXPORT(font);
480         EXPORT(family);
481         EXPORT(style);
482         EXPORT(weight);
483         EXPORT(size);
484         EXPORT(text);
485         EXPORT(color);
486         EXPORT(pos);
487         EXPORT(orient);
488         EXPORT(compress);
489         EXPORT(vcompress);
490         EXPORT(use_kerning);
491         EXPORT(grid_fit);
492         EXPORT(invert);
493
494         EXPORT_NAME();
495         EXPORT_VERSION();
496
497         return Layer_Composite::get_param(param);
498 }
499
500 Layer::Vocab
501 lyr_freetype::get_param_vocab(void)const
502 {
503         Layer::Vocab ret(Layer_Composite::get_param_vocab());
504
505         ret.push_back(ParamDesc("text")
506                 .set_local_name(_("Text"))
507                 .set_description(_("Text to Render"))
508                 .set_hint("paragraph")
509         );
510
511         ret.push_back(ParamDesc("color")
512                 .set_local_name(_("Color"))
513                 .set_description(_("Color of the text"))
514         );
515
516         ret.push_back(ParamDesc("family")
517                 .set_local_name(_("Font Family"))
518                 .set_hint("font_family")
519         );
520
521         ret.push_back(ParamDesc("style")
522                 .set_local_name(_("Style"))
523                 .set_hint("enum")
524                 .add_enum_value(PANGO_STYLE_NORMAL, "normal" ,_("Normal"))
525                 .add_enum_value(PANGO_STYLE_OBLIQUE, "oblique" ,_("Oblique"))
526                 .add_enum_value(PANGO_STYLE_ITALIC, "italic" ,_("Italic"))
527         );
528
529         ret.push_back(ParamDesc("weight")
530                 .set_local_name(_("Weight"))
531                 .set_hint("enum")
532                 .add_enum_value(200, "ultralight" ,_("Ultralight"))
533                 .add_enum_value(300, "light" ,_("light"))
534                 .add_enum_value(400, "normal" ,_("Normal"))
535                 .add_enum_value(700, "bold" ,_("Bold"))
536                 .add_enum_value(800, "ultrabold" ,_("Ultrabold"))
537                 .add_enum_value(900, "heavy" ,_("Heavy"))
538         );
539         ret.push_back(ParamDesc("compress")
540                 .set_local_name(_("Hozontal Spacing"))
541                 .set_description(_("Describes how close glyphs are horizontally"))
542         );
543
544         ret.push_back(ParamDesc("vcompress")
545                 .set_local_name(_("Vertical Spacing"))
546                 .set_description(_("Describes how close lines of text are vertically"))
547         );
548
549         ret.push_back(ParamDesc("size")
550                 .set_local_name(_("Size"))
551                 .set_description(_("Size of the text"))
552                 .set_hint("size")
553                 .set_origin("pos")
554                 .set_scalar(1)
555         );
556
557         ret.push_back(ParamDesc("orient")
558                 .set_local_name(_("Orientation"))
559                 .set_description(_("Text Orientation"))
560                 .set_invisible_duck()
561         );
562
563         ret.push_back(ParamDesc("pos")
564                 .set_local_name(_("Position"))
565                 .set_description(_("Text Position"))
566         );
567
568         ret.push_back(ParamDesc("font")
569                 .set_local_name(_("Font"))
570                 .set_description(_("Filename of the font to use"))
571                 .set_hint("filename")
572                 .not_critical()
573                 .hidden()
574         );
575
576         ret.push_back(ParamDesc("use_kerning")
577                 .set_local_name(_("Kerning"))
578                 .set_description(_("Enables/Disables font kerning (If the font supports it)"))
579         );
580
581         ret.push_back(ParamDesc("grid_fit")
582                 .set_local_name(_("Sharpen Edges"))
583                 .set_description(_("Turn this off if you are going to be animating the text"))
584         );
585         ret.push_back(ParamDesc("invert")
586                 .set_local_name(_("Invert"))
587         );
588         return ret;
589 }
590
591 void
592 lyr_freetype::sync()
593 {
594         needs_sync_=false;
595
596
597
598
599 }
600
601 Color
602 lyr_freetype::get_color(Context context, const synfig::Point &pos)const
603 {
604         if(needs_sync_)
605                 const_cast<lyr_freetype*>(this)->sync();
606
607         if(!face)
608                 return context.get_color(pos);
609         return context.get_color(pos);
610 }
611
612 bool
613 lyr_freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
614 {
615         static synfig::RecMutex freetype_mutex;
616
617         if(needs_sync_)
618                 const_cast<lyr_freetype*>(this)->sync();
619
620
621
622
623         int error;
624         Vector size(lyr_freetype::size*2);
625
626         if(!context.accelerated_render(surface,quality,renddesc,cb))
627                 return false;
628
629         if(is_disabled() || text.empty())
630                 return true;
631
632         // If there is no font loaded, just bail
633         if(!face)
634         {
635                 if(cb)cb->warning(string("lyr_freetype:")+_("No face loaded, no text will be rendered."));
636                 return true;
637         }
638
639         String text(lyr_freetype::text);
640         if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
641         {
642                 text=basename(get_canvas()->get_file_name());
643         }
644
645         // Width and Height of a pixel
646         Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
647         Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
648
649     // Calculate character width and height
650         int w=abs(round_to_int(size[0]*pw));
651         int h=abs(round_to_int(size[1]*ph));
652
653     //int bx=(int)((pos[0]-renddesc.get_tl()[0])*pw*64+0.5);
654     //int by=(int)((pos[1]-renddesc.get_tl()[1])*ph*64+0.5);
655     int bx=0;
656     int by=0;
657
658     // If the font is the size of a pixel, don't bother rendering any text
659         if(w<=1 || h<=1)
660         {
661                 if(cb)cb->warning(string("lyr_freetype:")+_("Text too small, no text will be rendered."));
662                 return true;
663         }
664
665         synfig::RecMutex::Lock lock(freetype_mutex);
666
667 #define CHAR_RESOLUTION         (64)
668         error = FT_Set_Char_Size(
669                 face,                                           // handle to face object
670                 (int)CHAR_RESOLUTION,   // char_width in 1/64th of points
671                 (int)CHAR_RESOLUTION,   // char_height in 1/64th of points
672                 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)),                                          // horizontal device resolution
673                 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) );                                                // vertical device resolution
674
675         // Here is where we can compensate for the
676         // error in freetype's rendering engine.
677         const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
678         const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
679         //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
680         const float compress(lyr_freetype::compress*xerror);
681         const float vcompress(lyr_freetype::vcompress*yerror);
682
683         if(error)
684         {
685                 if(cb)cb->warning(string("lyr_freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
686         }
687
688         FT_GlyphSlot  slot = face->glyph;  // a small shortcut
689         FT_UInt       glyph_index(0);
690         FT_UInt       previous(0);
691         int u,v;
692
693         std::list<TextLine> lines;
694
695         /*
696  --     ** -- CREATE GLYPHS -------------------------------------------------------
697         */
698
699         lines.push_front(TextLine());
700         string::const_iterator iter;
701         for (iter=text.begin(); iter!=text.end(); ++iter)
702         {
703                 int multiplier(1);
704                 if(*iter=='\n')
705                 {
706                         lines.push_front(TextLine());
707                         bx=0;
708                         by=0;
709                         previous=0;
710                         continue;
711                 }
712                 if(*iter=='\t')
713                 {
714                         multiplier=8;
715                         glyph_index = FT_Get_Char_Index( face, ' ' );
716                 }
717                 else
718                         glyph_index = FT_Get_Char_Index( face, *iter );
719
720         // retrieve kerning distance and move pen position
721                 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
722                 {
723                         FT_Vector  delta;
724
725                         if(grid_fit)
726                                 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
727                         else
728                                 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
729
730                         if(compress<1.0f)
731                         {
732                                 bx += round_to_int(delta.x*compress);
733                                 by += round_to_int(delta.y*compress);
734                         }
735                         else
736                         {
737                                 bx += delta.x;
738                                 by += delta.y;
739                         }
740         }
741
742                 Glyph curr_glyph;
743
744         // store current pen position
745         curr_glyph.pos.x = bx;
746         curr_glyph.pos.y = by;
747
748         // load glyph image into the slot. DO NOT RENDER IT !!
749         if(grid_fit)
750                         error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
751                 else
752                         error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
753         if (error) continue;  // ignore errors, jump to next glyph
754
755         // extract glyph image and store it in our table
756         error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
757         if (error) continue;  // ignore errors, jump to next glyph
758
759         // record current glyph index
760         previous = glyph_index;
761
762                 // Update the line width
763                 lines.front().width=bx+slot->advance.x;
764
765                 // increment pen position
766                 if(multiplier>1)
767                         bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
768                 else
769                         bx += round_to_int(slot->advance.x*compress*multiplier);
770
771                 //bx += round_to_int(slot->advance.x*compress*multiplier);
772                 //by += round_to_int(slot->advance.y*compress);
773                 by += slot->advance.y*multiplier;
774
775                 lines.front().glyph_table.push_back(curr_glyph);
776
777         }
778
779
780         //float string_height;
781         //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
782
783         //int string_height=face->size->metrics.ascender;
784 //#define METRICS_SCALE_ONE             (65536.0f)
785 #define METRICS_SCALE_ONE               ((float)(1<<16))
786
787         float line_height;
788         line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
789
790         int     string_height;
791         string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
792         //synfig::info("string_height=%d",string_height);
793         //synfig::info("line_height=%f",line_height);
794
795         /*
796  --     ** -- RENDER THE GLYPHS ---------------------------------------------------
797         */
798
799         Surface src_;
800         Surface *src_surface;
801
802         src_surface=surface;
803
804         if(invert)
805         {
806                 src_=*surface;
807                 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
808
809                 surface->fill(color,pen,src_.get_w(),src_.get_h());
810
811                 src_surface=&src_;
812         }
813
814         {
815         std::list<TextLine>::iterator iter;
816         int curr_line;
817         for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
818         {
819                 bx=round_to_int((pos[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
820                 by=round_to_int((pos[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION+(1.0-orient[1])*string_height-line_height*curr_line);
821                 //by=round_to_int(vcompress*((pos[1]-renddesc.get_tl()[1])*ph*64+(1.0-orient[1])*string_height-face->size->metrics.height*curr_line));
822                 //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
823
824                 std::vector<Glyph>::iterator iter2;
825                 for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
826                 {
827                         FT_Glyph  image(iter2->glyph);
828                         FT_Vector pen;
829                         FT_BitmapGlyph  bit;
830
831                         pen.x = bx + iter2->pos.x;
832                         pen.y = by + iter2->pos.y;
833
834                         //synfig::info("GLYPH: pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
835
836                         error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
837                         if(error) { FT_Done_Glyph( image ); continue; }
838
839                         bit = (FT_BitmapGlyph)image;
840
841                         for(v=0;v<bit->bitmap.rows;v++)
842                                 for(u=0;u<bit->bitmap.width;u++)
843                                 {
844                                         int x=u+((pen.x+32)>>6)+ bit->left;
845                                         int y=v+((pen.y+32)>>6)- bit->top;
846                                         if(     y>=0 &&
847                                                 x>=0 &&
848                                                 y<surface->get_h() &&
849                                                 x<surface->get_w())
850                                         {
851                                                 float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
852                                                 if(invert)
853                                                         myamount=1.0f-myamount;
854                                                 (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
855                                         }
856                                 }
857
858                         FT_Done_Glyph( image );
859                 }
860                 //iter->clear_and_free();
861         }
862         }
863
864
865         return true;
866 }
867
868 synfig::Rect
869 lyr_freetype::get_bounding_rect()const
870 {
871         if(needs_sync_)
872                 const_cast<lyr_freetype*>(this)->sync();
873 //      if(!is_disabled())
874                 return synfig::Rect::full_plane();
875 }