Added copyright lines for files I've edited this year.
[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 Implementation of the "Text" layer
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, 2008 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 #endif
43
44 using namespace std;
45 using namespace etl;
46 using namespace synfig;
47
48 /* === M A C R O S ========================================================= */
49
50 #define MAX_GLYPHS              2000
51
52 #define PANGO_STYLE_NORMAL (0)
53 #define PANGO_STYLE_OBLIQUE (1)
54 #define PANGO_STYLE_ITALIC (2)
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(Layer_Freetype);
62 SYNFIG_LAYER_SET_NAME(Layer_Freetype,"text");
63 SYNFIG_LAYER_SET_LOCAL_NAME(Layer_Freetype,N_("Text"));
64 SYNFIG_LAYER_SET_CATEGORY(Layer_Freetype,N_("Other"));
65 SYNFIG_LAYER_SET_VERSION(Layer_Freetype,"0.2");
66 SYNFIG_LAYER_SET_CVS_ID(Layer_Freetype,"$Id$");
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 Layer_Freetype::Layer_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 Layer_Freetype::~Layer_Freetype()
115 {
116         if(face)
117                 FT_Done_Face(face);
118 }
119
120 void
121 Layer_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 Layer_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         {
149 #ifndef __APPLE__
150                 if(new_face("ariblk"))
151                         return true;
152                 else
153 #endif
154                 font_fam="sans serif";
155         }
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         if(font_fam=="sans serif" || font_fam=="luxi sans")
231         {
232                 {
233                         String luxi("luxis");
234                         if(weight>WEIGHT_NORMAL)
235                                 luxi+='b';
236                         else
237                                 luxi+='r';
238                         if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
239                                 luxi+='i';
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 Layer_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_SEPARATOR+newfont).c_str(),face_index,&face);
347                 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPARATOR+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 #endif
372
373 #ifdef WITH_FONTCONFIG
374         if(error)
375         {
376                 FcFontSet *fs;
377                 FcResult result;
378                 if( !FcInit() )
379                 {
380                         synfig::warning("Layer_Freetype: fontconfig: %s",_("unable to initialize"));
381                         error = 1;
382                 } else {
383                         FcPattern* pat = FcNameParse((FcChar8 *) newfont.c_str());
384                         FcConfigSubstitute(0, pat, FcMatchPattern);
385                         FcDefaultSubstitute(pat);
386                         FcPattern *match;
387                         fs = FcFontSetCreate();
388                         match = FcFontMatch(0, pat, &result);
389                         if (match)
390                                 FcFontSetAdd(fs, match);
391                         if (pat)
392                                 FcPatternDestroy(pat);
393                         if(fs){
394                                 FcChar8* file;
395                                 if( FcPatternGetString (fs->fonts[0], FC_FILE, 0, &file) == FcResultMatch )
396                                         error=FT_New_Face(ft_library,(const char*)file,face_index,&face);
397                                 FcFontSetDestroy(fs);
398                         } else
399                                 synfig::warning("Layer_Freetype: fontconfig: %s",_("empty font set"));
400                 }
401         }
402 #endif
403
404 #ifdef WIN32
405         if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont).c_str(),face_index,&face);
406         if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont+".ttf").c_str(),face_index,&face);
407 #else
408
409 #ifdef __APPLE__
410         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont).c_str(),face_index,&face);
411         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
412         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
413
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 #endif
418
419         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont).c_str(),face_index,&face);
420         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont+".ttf").c_str(),face_index,&face);
421
422         if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont).c_str(),face_index,&face);
423         if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
424
425         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont).c_str(),face_index,&face);
426         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont+".ttf").c_str(),face_index,&face);
427
428         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont).c_str(),face_index,&face);
429         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
430
431 #endif
432         if(error)
433         {
434                 //synfig::error(strprintf("Layer_Freetype:%s (err=%d)",_("Unable to open face."),error));
435                 return false;
436         }
437
438         font=newfont;
439
440         needs_sync_=true;
441         return true;
442 }
443
444 bool
445 Layer_Freetype::set_param(const String & param, const ValueBase &value)
446 {
447         Mutex::Lock lock(mutex);
448 /*
449         if(param=="font" && value.same_type_as(font))
450         {
451                 new_font(etl::basename(value.get(font)),style,weight);
452                 family=etl::basename(value.get(font));
453                 return true;
454         }
455 */
456         IMPORT_PLUS(family,new_font(family,style,weight));
457         IMPORT_PLUS(weight,new_font(family,style,weight));
458         IMPORT_PLUS(style,new_font(family,style,weight));
459         IMPORT_PLUS(size, if(old_version){size/=2.0;} needs_sync_=true );
460         IMPORT_PLUS(text,needs_sync_=true);
461         IMPORT_PLUS(pos,needs_sync_=true);
462         IMPORT_PLUS(color, { if (color.get_a() == 0) { if (converted_blend_) {
463                                         set_blend_method(Color::BLEND_ALPHA_OVER);
464                                         color.set_a(1); } else transparent_color_ = true; } });
465         IMPORT(invert);
466         IMPORT_PLUS(orient,needs_sync_=true);
467         IMPORT_PLUS(compress,needs_sync_=true);
468         IMPORT_PLUS(vcompress,needs_sync_=true);
469         IMPORT_PLUS(use_kerning,needs_sync_=true);
470         IMPORT_PLUS(grid_fit,needs_sync_=true);
471
472         return Layer_Composite::set_param(param,value);
473 }
474
475 ValueBase
476 Layer_Freetype::get_param(const String& param)const
477 {
478         EXPORT(font);
479         EXPORT(family);
480         EXPORT(style);
481         EXPORT(weight);
482         EXPORT(size);
483         EXPORT(text);
484         EXPORT(color);
485         EXPORT(pos);
486         EXPORT(orient);
487         EXPORT(compress);
488         EXPORT(vcompress);
489         EXPORT(use_kerning);
490         EXPORT(grid_fit);
491         EXPORT(invert);
492
493         EXPORT_NAME();
494         EXPORT_VERSION();
495
496         return Layer_Composite::get_param(param);
497 }
498
499 Layer::Vocab
500 Layer_Freetype::get_param_vocab(void)const
501 {
502         Layer::Vocab ret(Layer_Composite::get_param_vocab());
503
504         ret.push_back(ParamDesc("text")
505                 .set_local_name(_("Text"))
506                 .set_description(_("Text to Render"))
507                 .set_hint("paragraph")
508         );
509
510         ret.push_back(ParamDesc("color")
511                 .set_local_name(_("Color"))
512                 .set_description(_("Color of the text"))
513         );
514
515         ret.push_back(ParamDesc("family")
516                 .set_local_name(_("Font Family"))
517                 .set_hint("font_family")
518         );
519
520         ret.push_back(ParamDesc("style")
521                 .set_local_name(_("Style"))
522                 .set_hint("enum")
523                 .add_enum_value(PANGO_STYLE_NORMAL, "normal" ,_("Normal"))
524                 .add_enum_value(PANGO_STYLE_OBLIQUE, "oblique" ,_("Oblique"))
525                 .add_enum_value(PANGO_STYLE_ITALIC, "italic" ,_("Italic"))
526         );
527
528         ret.push_back(ParamDesc("weight")
529                 .set_local_name(_("Weight"))
530                 .set_hint("enum")
531                 .add_enum_value(200, "ultralight" ,_("Ultralight"))
532                 .add_enum_value(300, "light" ,_("light"))
533                 .add_enum_value(400, "normal" ,_("Normal"))
534                 .add_enum_value(700, "bold" ,_("Bold"))
535                 .add_enum_value(800, "ultrabold" ,_("Ultrabold"))
536                 .add_enum_value(900, "heavy" ,_("Heavy"))
537         );
538         ret.push_back(ParamDesc("compress")
539                 .set_local_name(_("Horizontal Spacing"))
540                 .set_description(_("Describes how close glyphs are horizontally"))
541         );
542
543         ret.push_back(ParamDesc("vcompress")
544                 .set_local_name(_("Vertical Spacing"))
545                 .set_description(_("Describes how close lines of text are vertically"))
546         );
547
548         ret.push_back(ParamDesc("size")
549                 .set_local_name(_("Size"))
550                 .set_description(_("Size of the text"))
551                 .set_hint("size")
552                 .set_origin("pos")
553                 .set_scalar(1)
554         );
555
556         ret.push_back(ParamDesc("orient")
557                 .set_local_name(_("Orientation"))
558                 .set_description(_("Text Orientation"))
559                 .set_invisible_duck()
560         );
561
562         ret.push_back(ParamDesc("pos")
563                 .set_local_name(_("Position"))
564                 .set_description(_("Text Position"))
565         );
566
567         ret.push_back(ParamDesc("font")
568                 .set_local_name(_("Font"))
569                 .set_description(_("Filename of the font to use"))
570                 .set_hint("filename")
571                 .not_critical()
572                 .hidden()
573         );
574
575         ret.push_back(ParamDesc("use_kerning")
576                 .set_local_name(_("Kerning"))
577                 .set_description(_("Enables/Disables font kerning (If the font supports it)"))
578         );
579
580         ret.push_back(ParamDesc("grid_fit")
581                 .set_local_name(_("Sharpen Edges"))
582                 .set_description(_("Turn this off if you are going to be animating the text"))
583         );
584         ret.push_back(ParamDesc("invert")
585                 .set_local_name(_("Invert"))
586         );
587         return ret;
588 }
589
590 void
591 Layer_Freetype::sync()
592 {
593         needs_sync_=false;
594 }
595
596 inline Color
597 Layer_Freetype::color_func(const Point &point_, int quality, float supersample)const
598 {
599         if (invert)
600                 return color;
601         else
602                 return Color::alpha();
603 }
604
605 Color
606 Layer_Freetype::get_color(Context context, const synfig::Point &pos)const
607 {
608         if(needs_sync_)
609                 const_cast<Layer_Freetype*>(this)->sync();
610
611         const Color color(color_func(pos,0));
612
613         if(!face)
614                 return context.get_color(pos);
615
616         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
617                 return color;
618         else
619                 return Color::blend(color,context.get_color(pos),get_amount(),get_blend_method());
620 }
621
622 bool
623 Layer_Freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
624 {
625         static synfig::RecMutex freetype_mutex;
626
627         if(needs_sync_)
628                 const_cast<Layer_Freetype*>(this)->sync();
629
630         int error;
631         Vector size(Layer_Freetype::size*2);
632
633         if(!context.accelerated_render(surface,quality,renddesc,cb))
634                 return false;
635
636         if(is_disabled() || text.empty())
637                 return true;
638
639         // If there is no font loaded, just bail
640         if(!face)
641         {
642                 if(cb)cb->warning(string("Layer_Freetype:")+_("No face loaded, no text will be rendered."));
643                 return true;
644         }
645
646         String text(Layer_Freetype::text);
647         if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
648         {
649                 text=basename(get_canvas()->get_file_name());
650         }
651
652         // Width and Height of a pixel
653         Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
654         Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
655
656     // Calculate character width and height
657         int w=abs(round_to_int(size[0]*pw));
658         int h=abs(round_to_int(size[1]*ph));
659
660     //int bx=(int)((pos[0]-renddesc.get_tl()[0])*pw*64+0.5);
661     //int by=(int)((pos[1]-renddesc.get_tl()[1])*ph*64+0.5);
662     int bx=0;
663     int by=0;
664
665     // If the font is the size of a pixel, don't bother rendering any text
666         if(w<=1 || h<=1)
667         {
668                 if(cb)cb->warning(string("Layer_Freetype:")+_("Text too small, no text will be rendered."));
669                 return true;
670         }
671
672         synfig::RecMutex::Lock lock(freetype_mutex);
673
674 #define CHAR_RESOLUTION         (64)
675         error = FT_Set_Char_Size(
676                 face,                                           // handle to face object
677                 (int)CHAR_RESOLUTION,   // char_width in 1/64th of points
678                 (int)CHAR_RESOLUTION,   // char_height in 1/64th of points
679                 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)),                                          // horizontal device resolution
680                 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) );                                                // vertical device resolution
681
682         // Here is where we can compensate for the
683         // error in freetype's rendering engine.
684         const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
685         const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
686         //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
687         const float compress(Layer_Freetype::compress*xerror);
688         const float vcompress(Layer_Freetype::vcompress*yerror);
689
690         if(error)
691         {
692                 if(cb)cb->warning(string("Layer_Freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
693         }
694
695         FT_GlyphSlot  slot = face->glyph;  // a small shortcut
696         FT_UInt       glyph_index(0);
697         FT_UInt       previous(0);
698         int u,v;
699
700         std::list<TextLine> lines;
701
702         /*
703  --     ** -- CREATE GLYPHS -------------------------------------------------------
704         */
705
706         mbstate_t ps;
707         memset(&ps, 0, sizeof(ps));
708
709         lines.push_front(TextLine());
710         string::const_iterator iter;
711         for (iter=text.begin(); iter!=text.end(); ++iter)
712         {
713                 int multiplier(1);
714                 if(*iter=='\n')
715                 {
716                         lines.push_front(TextLine());
717                         bx=0;
718                         by=0;
719                         previous=0;
720                         continue;
721                 }
722                 if(*iter=='\t')
723                 {
724                         multiplier=8;
725                         glyph_index = FT_Get_Char_Index( face, ' ' );
726                 }
727                 else
728                 {
729                         wchar_t wc;
730                         size_t converted = mbrtowc(&wc, &(*iter), text.end() - iter, &ps);
731
732                         if(converted == (size_t)(-1))
733                         {
734                                 synfig::warning("Layer_Freetype: multibyte: %s",
735                                                                 _("Invalid multibyte sequence - is the locale set?\n"));
736                                 continue;
737                         }
738
739                         if(converted == (size_t)(-2))
740                         {
741                                 synfig::warning("Layer_Freetype: multibyte: %s",
742                                                                 _("Can't parse multibyte character.\n"));
743                                 continue;
744                         }
745
746                         glyph_index = FT_Get_Char_Index( face, wc );
747
748                         if(converted > 1)
749                                 iter += converted - 1;
750                 }
751
752         // retrieve kerning distance and move pen position
753                 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
754                 {
755                         FT_Vector  delta;
756
757                         if(grid_fit)
758                                 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
759                         else
760                                 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
761
762                         if(compress<1.0f)
763                         {
764                                 bx += round_to_int(delta.x*compress);
765                                 by += round_to_int(delta.y*compress);
766                         }
767                         else
768                         {
769                                 bx += delta.x;
770                                 by += delta.y;
771                         }
772         }
773
774                 Glyph curr_glyph;
775
776         // store current pen position
777         curr_glyph.pos.x = bx;
778         curr_glyph.pos.y = by;
779
780         // load glyph image into the slot. DO NOT RENDER IT !!
781         if(grid_fit)
782                         error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
783                 else
784                         error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
785         if (error) continue;  // ignore errors, jump to next glyph
786
787         // extract glyph image and store it in our table
788         error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
789         if (error) continue;  // ignore errors, jump to next glyph
790
791         // record current glyph index
792         previous = glyph_index;
793
794                 // Update the line width
795                 lines.front().width=bx+slot->advance.x;
796
797                 // increment pen position
798                 if(multiplier>1)
799                         bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
800                 else
801                         bx += round_to_int(slot->advance.x*compress*multiplier);
802
803                 //bx += round_to_int(slot->advance.x*compress*multiplier);
804                 //by += round_to_int(slot->advance.y*compress);
805                 by += slot->advance.y*multiplier;
806
807                 lines.front().glyph_table.push_back(curr_glyph);
808
809         }
810
811         //float string_height;
812         //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
813
814         //int string_height=face->size->metrics.ascender;
815 //#define METRICS_SCALE_ONE             (65536.0f)
816 #define METRICS_SCALE_ONE               ((float)(1<<16))
817
818         float line_height;
819         line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
820
821         // This module sees to expect pixel height to be negative, as it
822         // usually is.  But rendering to .bmp format causes ph to be
823         // positive, which was causing text to be rendered upside down.
824         if (ph>0) line_height = -line_height;
825
826         int     string_height;
827         string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
828         //synfig::info("string_height=%d",string_height);
829         //synfig::info("line_height=%f",line_height);
830
831         /*
832  --     ** -- RENDER THE GLYPHS ---------------------------------------------------
833         */
834
835         Surface src_;
836         Surface *src_surface;
837
838         src_surface=surface;
839
840         if(invert)
841         {
842                 src_=*surface;
843                 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
844
845                 surface->fill(color,pen,src_.get_w(),src_.get_h());
846
847                 src_surface=&src_;
848         }
849
850         {
851                 std::list<TextLine>::iterator iter;
852                 int curr_line;
853                 for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
854                 {
855                         bx=round_to_int((pos[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
856                         // I've no idea why 1.5, but it kind of works.  Otherwise,
857                         // rendering to .bmp (which renders from bottom to top, due to
858                         // the .bmp format describing the image from bottom to top,
859                         // renders text in the wrong place.
860                         by=round_to_int((pos[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION +
861                                                         (1.0-orient[1])*string_height-line_height*curr_line +
862                                                         ((ph>0) ? line_height/1.5 : 0));
863
864                         //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));
865                         //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
866
867                         std::vector<Glyph>::iterator iter2;
868                         for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
869                         {
870                                 FT_Glyph  image(iter2->glyph);
871                                 FT_Vector pen;
872                                 FT_BitmapGlyph  bit;
873
874                                 pen.x = bx + iter2->pos.x;
875                                 pen.y = by + iter2->pos.y;
876
877                                 //synfig::info("GLYPH: line %d, pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
878
879                                 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
880                                 if(error) { FT_Done_Glyph( image ); continue; }
881
882                                 bit = (FT_BitmapGlyph)image;
883
884                                 for(v=0;v<bit->bitmap.rows;v++)
885                                         for(u=0;u<bit->bitmap.width;u++)
886                                         {
887                                                 int x=u+((pen.x+32)>>6)+ bit->left;
888                                                 int y=((pen.y+32)>>6) + (bit->top - v) * ((ph<0) ? -1 : 1);
889                                                 if(     y>=0 &&
890                                                         x>=0 &&
891                                                         y<surface->get_h() &&
892                                                         x<surface->get_w())
893                                                 {
894                                                         float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
895                                                         if(invert)
896                                                                 myamount=1.0f-myamount;
897                                                         (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
898                                                 }
899                                         }
900
901                                 FT_Done_Glyph( image );
902                         }
903                         //iter->clear_and_free();
904                 }
905         }
906
907         return true;
908 }
909
910 synfig::Rect
911 Layer_Freetype::get_bounding_rect()const
912 {
913         if(needs_sync_)
914                 const_cast<Layer_Freetype*>(this)->sync();
915 //      if(!is_disabled())
916                 return synfig::Rect::full_plane();
917 }