Fix bugs in previous commit that caused FTBFS in synfig and ETL FTBFS with older...
[synfig.git] / synfig-core / tags / 0.61.09 / 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         origin=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(origin,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         IMPORT_AS(origin,"pos");
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(origin);
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("origin")
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("origin")
565                 .set_local_name(_("Origin"))
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 inline Color
599 Layer_Freetype::color_func(const Point &point_ __attribute__ ((unused)), int quality __attribute__ ((unused)), float supersample __attribute__ ((unused)))const
600 {
601         if (invert)
602                 return color;
603         else
604                 return Color::alpha();
605 }
606
607 Color
608 Layer_Freetype::get_color(Context context, const synfig::Point &pos)const
609 {
610         if(needs_sync_)
611                 const_cast<Layer_Freetype*>(this)->sync();
612
613         const Color color(color_func(pos,0));
614
615         if(!face)
616                 return context.get_color(pos);
617
618         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
619                 return color;
620         else
621                 return Color::blend(color,context.get_color(pos),get_amount(),get_blend_method());
622 }
623
624 bool
625 Layer_Freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
626 {
627         static synfig::RecMutex freetype_mutex;
628
629         if(needs_sync_)
630                 const_cast<Layer_Freetype*>(this)->sync();
631
632         int error;
633         Vector size(Layer_Freetype::size*2);
634
635         if(!context.accelerated_render(surface,quality,renddesc,cb))
636                 return false;
637
638         if(is_disabled() || text.empty())
639                 return true;
640
641         // If there is no font loaded, just bail
642         if(!face)
643         {
644                 if(cb)cb->warning(string("Layer_Freetype:")+_("No face loaded, no text will be rendered."));
645                 return true;
646         }
647
648         String text(Layer_Freetype::text);
649         if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
650         {
651                 text=basename(get_canvas()->get_file_name());
652         }
653
654         // Width and Height of a pixel
655         Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
656         Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
657
658     // Calculate character width and height
659         int w=abs(round_to_int(size[0]*pw));
660         int h=abs(round_to_int(size[1]*ph));
661
662     //int bx=(int)((origin[0]-renddesc.get_tl()[0])*pw*64+0.5);
663     //int by=(int)((origin[1]-renddesc.get_tl()[1])*ph*64+0.5);
664     int bx=0;
665     int by=0;
666
667     // If the font is the size of a pixel, don't bother rendering any text
668         if(w<=1 || h<=1)
669         {
670                 if(cb)cb->warning(string("Layer_Freetype:")+_("Text too small, no text will be rendered."));
671                 return true;
672         }
673
674         synfig::RecMutex::Lock lock(freetype_mutex);
675
676 #define CHAR_RESOLUTION         (64)
677         error = FT_Set_Char_Size(
678                 face,                                           // handle to face object
679                 (int)CHAR_RESOLUTION,   // char_width in 1/64th of points
680                 (int)CHAR_RESOLUTION,   // char_height in 1/64th of points
681                 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)),                                          // horizontal device resolution
682                 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) );                                                // vertical device resolution
683
684         // Here is where we can compensate for the
685         // error in freetype's rendering engine.
686         const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
687         const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
688         //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
689         const float compress(Layer_Freetype::compress*xerror);
690         const float vcompress(Layer_Freetype::vcompress*yerror);
691
692         if(error)
693         {
694                 if(cb)cb->warning(string("Layer_Freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
695         }
696
697         FT_GlyphSlot  slot = face->glyph;  // a small shortcut
698         FT_UInt       glyph_index(0);
699         FT_UInt       previous(0);
700         int u,v;
701
702         std::list<TextLine> lines;
703
704         /*
705  --     ** -- CREATE GLYPHS -------------------------------------------------------
706         */
707
708         mbstate_t ps;
709         memset(&ps, 0, sizeof(ps));
710
711         lines.push_front(TextLine());
712         string::const_iterator iter;
713         for (iter=text.begin(); iter!=text.end(); ++iter)
714         {
715                 int multiplier(1);
716                 if(*iter=='\n')
717                 {
718                         lines.push_front(TextLine());
719                         bx=0;
720                         by=0;
721                         previous=0;
722                         continue;
723                 }
724                 if(*iter=='\t')
725                 {
726                         multiplier=8;
727                         glyph_index = FT_Get_Char_Index( face, ' ' );
728                 }
729                 else
730                 {
731                         wchar_t wc;
732                         size_t converted = mbrtowc(&wc, &(*iter), text.end() - iter, &ps);
733
734                         if(converted == (size_t)(-1))
735                         {
736                                 synfig::warning("Layer_Freetype: multibyte: %s",
737                                                                 _("Invalid multibyte sequence - is the locale set?\n"));
738                                 continue;
739                         }
740
741                         if(converted == (size_t)(-2))
742                         {
743                                 synfig::warning("Layer_Freetype: multibyte: %s",
744                                                                 _("Can't parse multibyte character.\n"));
745                                 continue;
746                         }
747
748                         glyph_index = FT_Get_Char_Index( face, wc );
749
750                         if(converted > 1)
751                                 iter += converted - 1;
752                 }
753
754         // retrieve kerning distance and move pen position
755                 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
756                 {
757                         FT_Vector  delta;
758
759                         if(grid_fit)
760                                 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
761                         else
762                                 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
763
764                         if(compress<1.0f)
765                         {
766                                 bx += round_to_int(delta.x*compress);
767                                 by += round_to_int(delta.y*compress);
768                         }
769                         else
770                         {
771                                 bx += delta.x;
772                                 by += delta.y;
773                         }
774         }
775
776                 Glyph curr_glyph;
777
778         // store current pen position
779         curr_glyph.pos.x = bx;
780         curr_glyph.pos.y = by;
781
782         // load glyph image into the slot. DO NOT RENDER IT !!
783         if(grid_fit)
784                         error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
785                 else
786                         error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
787         if (error) continue;  // ignore errors, jump to next glyph
788
789         // extract glyph image and store it in our table
790         error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
791         if (error) continue;  // ignore errors, jump to next glyph
792
793         // record current glyph index
794         previous = glyph_index;
795
796                 // Update the line width
797                 lines.front().width=bx+slot->advance.x;
798
799                 // increment pen position
800                 if(multiplier>1)
801                         bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
802                 else
803                         bx += round_to_int(slot->advance.x*compress*multiplier);
804
805                 //bx += round_to_int(slot->advance.x*compress*multiplier);
806                 //by += round_to_int(slot->advance.y*compress);
807                 by += slot->advance.y*multiplier;
808
809                 lines.front().glyph_table.push_back(curr_glyph);
810
811         }
812
813         //float string_height;
814         //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
815
816         //int string_height=face->size->metrics.ascender;
817 //#define METRICS_SCALE_ONE             (65536.0f)
818 #define METRICS_SCALE_ONE               ((float)(1<<16))
819
820         float line_height;
821         line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
822
823         // This module sees to expect pixel height to be negative, as it
824         // usually is.  But rendering to .bmp format causes ph to be
825         // positive, which was causing text to be rendered upside down.
826         if (ph>0) line_height = -line_height;
827
828         int     string_height;
829         string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
830         //synfig::info("string_height=%d",string_height);
831         //synfig::info("line_height=%f",line_height);
832
833         /*
834  --     ** -- RENDER THE GLYPHS ---------------------------------------------------
835         */
836
837         Surface src_;
838         Surface *src_surface;
839
840         src_surface=surface;
841
842         if(invert)
843         {
844                 src_=*surface;
845                 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
846
847                 surface->fill(color,pen,src_.get_w(),src_.get_h());
848
849                 src_surface=&src_;
850         }
851
852         {
853                 std::list<TextLine>::iterator iter;
854                 int curr_line;
855                 for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
856                 {
857                         bx=round_to_int((origin[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
858                         // I've no idea why 1.5, but it kind of works.  Otherwise,
859                         // rendering to .bmp (which renders from bottom to top, due to
860                         // the .bmp format describing the image from bottom to top,
861                         // renders text in the wrong place.
862                         by=round_to_int((origin[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION +
863                                                         (1.0-orient[1])*string_height-line_height*curr_line +
864                                                         ((ph>0) ? line_height/1.5 : 0));
865
866                         //by=round_to_int(vcompress*((origin[1]-renddesc.get_tl()[1])*ph*64+(1.0-orient[1])*string_height-face->size->metrics.height*curr_line));
867                         //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
868
869                         std::vector<Glyph>::iterator iter2;
870                         for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
871                         {
872                                 FT_Glyph  image(iter2->glyph);
873                                 FT_Vector pen;
874                                 FT_BitmapGlyph  bit;
875
876                                 pen.x = bx + iter2->pos.x;
877                                 pen.y = by + iter2->pos.y;
878
879                                 //synfig::info("GLYPH: line %d, pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
880
881                                 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
882                                 if(error) { FT_Done_Glyph( image ); continue; }
883
884                                 bit = (FT_BitmapGlyph)image;
885
886                                 for(v=0;v<bit->bitmap.rows;v++)
887                                         for(u=0;u<bit->bitmap.width;u++)
888                                         {
889                                                 int x=u+((pen.x+32)>>6)+ bit->left;
890                                                 int y=((pen.y+32)>>6) + (bit->top - v) * ((ph<0) ? -1 : 1);
891                                                 if(     y>=0 &&
892                                                         x>=0 &&
893                                                         y<surface->get_h() &&
894                                                         x<surface->get_w())
895                                                 {
896                                                         float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
897                                                         if(invert)
898                                                                 myamount=1.0f-myamount;
899                                                         (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
900                                                 }
901                                         }
902
903                                 FT_Done_Glyph( image );
904                         }
905                         //iter->clear_and_free();
906                 }
907         }
908
909         return true;
910 }
911
912 synfig::Rect
913 Layer_Freetype::get_bounding_rect()const
914 {
915         if(needs_sync_)
916                 const_cast<Layer_Freetype*>(this)->sync();
917 //      if(!is_disabled())
918                 return synfig::Rect::full_plane();
919 }