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