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