Add parameter static option for rest of layers.
[synfig.git] / synfig-core / 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         Layer::Vocab voc(get_param_vocab());
113         Layer::fill_static(voc);
114 }
115
116 Layer_Freetype::~Layer_Freetype()
117 {
118         if(face)
119                 FT_Done_Face(face);
120 }
121
122 void
123 Layer_Freetype::new_font(const synfig::String &family, int style, int weight)
124 {
125         if(
126                 !new_font_(family,style,weight) &&
127                 !new_font_(family,style,WEIGHT_NORMAL) &&
128                 !new_font_(family,PANGO_STYLE_NORMAL,weight) &&
129                 !new_font_(family,PANGO_STYLE_NORMAL,WEIGHT_NORMAL) &&
130                 !new_font_("sans serif",style,weight) &&
131                 !new_font_("sans serif",style,WEIGHT_NORMAL) &&
132                 !new_font_("sans serif",PANGO_STYLE_NORMAL,weight)
133         )
134                 new_font_("sans serif",PANGO_STYLE_NORMAL,WEIGHT_NORMAL);
135 }
136
137 bool
138 Layer_Freetype::new_font_(const synfig::String &font_fam_, int style, int weight)
139 {
140         synfig::String font_fam(font_fam_);
141
142         if(new_face(font_fam_))
143                 return true;
144
145         //start evil hack
146         for(unsigned int i=0;i<font_fam.size();i++)font_fam[i]=tolower(font_fam[i]);
147         //end evil hack
148
149         if(font_fam=="arial black")
150         {
151 #ifndef __APPLE__
152                 if(new_face("ariblk"))
153                         return true;
154                 else
155 #endif
156                 font_fam="sans serif";
157         }
158
159         if(font_fam=="sans serif" || font_fam=="arial")
160         {
161                 String arial("arial");
162                 if(weight>WEIGHT_NORMAL)
163                         arial+='b';
164                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
165                         arial+='i';
166                 else
167                         if(weight>WEIGHT_NORMAL) arial+='d';
168
169                 if(new_face(arial))
170                         return true;
171 #ifdef __APPLE__
172                 if(new_face("Helvetica RO"))
173                         return true;
174 #endif
175         }
176
177         if(font_fam=="comic" || font_fam=="comic sans")
178         {
179                 String filename("comic");
180                 if(weight>WEIGHT_NORMAL)
181                         filename+='b';
182                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
183                         filename+='i';
184                 else if(weight>WEIGHT_NORMAL) filename+='d';
185
186                 if(new_face(filename))
187                         return true;
188         }
189
190         if(font_fam=="courier" || font_fam=="courier new")
191         {
192                 String filename("cour");
193                 if(weight>WEIGHT_NORMAL)
194                         filename+='b';
195                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
196                         filename+='i';
197                 else if(weight>WEIGHT_NORMAL) filename+='d';
198
199                 if(new_face(filename))
200                         return true;
201         }
202
203         if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman")
204         {
205                 String filename("times");
206                 if(weight>WEIGHT_NORMAL)
207                         filename+='b';
208                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
209                         filename+='i';
210                 else if(weight>WEIGHT_NORMAL) filename+='d';
211
212                 if(new_face(filename))
213                         return true;
214         }
215
216         if(font_fam=="trebuchet")
217         {
218                 String filename("trebuc");
219                 if(weight>WEIGHT_NORMAL)
220                         filename+='b';
221                 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
222                 {
223                         filename+='i';
224                         if(weight<=WEIGHT_NORMAL) filename+='t';
225                 }
226                 else if(weight>WEIGHT_NORMAL) filename+='d';
227
228                 if(new_face(filename))
229                         return true;
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                         if(new_face(luxi))
244                                 return true;
245                 }
246                 if(new_face("arial"))
247                         return true;
248                 if(new_face("Arial"))
249                         return true;
250         }
251         if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman" || font_fam=="luxi serif")
252         {
253                 {
254                         String luxi("luxir");
255                         if(weight>WEIGHT_NORMAL)
256                                 luxi+='b';
257                         else
258                                 luxi+='r';
259                         if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
260                                 luxi+='i';
261
262                         if(new_face(luxi))
263                                 return true;
264                 }
265                 if(new_face("Times New Roman"))
266                         return true;
267                 if(new_face("Times"))
268                         return true;
269         }
270         if(font_fam=="luxi")
271         {
272                 {
273                         String luxi("luxim");
274                         if(weight>WEIGHT_NORMAL)
275                                 luxi+='b';
276                         else
277                                 luxi+='r';
278                         if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
279                                 luxi+='i';
280
281                         if(new_face(luxi))
282                                 return true;
283                 }
284
285                 if(new_face("Times New Roman"))
286                         return true;
287                 if(new_face("Times"))
288                         return true;
289         }
290
291         return new_face(font_fam_) || new_face(font_fam);
292
293         return false;
294 }
295
296 #ifdef USE_MAC_FT_FUNCS
297 void fss2path(char *path, FSSpec *fss)
298 {
299   int l;             //fss->name contains name of last item in path
300   for(l=0; l<(fss->name[0]); l++) path[l] = fss->name[l + 1];
301   path[l] = 0;
302
303   if(fss->parID != fsRtParID) //path is more than just a volume name
304   {
305     int i, len;
306     CInfoPBRec pb;
307
308     pb.dirInfo.ioNamePtr = fss->name;
309     pb.dirInfo.ioVRefNum = fss->vRefNum;
310     pb.dirInfo.ioDrParID = fss->parID;
311     do
312     {
313       pb.dirInfo.ioFDirIndex = -1;  //get parent directory name
314       pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
315       if(PBGetCatInfoSync(&pb) != noErr) break;
316
317       len = fss->name[0] + 1;
318       for(i=l; i>=0;  i--) path[i + len] = path[i];
319       for(i=1; i<len; i++) path[i - 1] = fss->name[i]; //add to start of path
320       path[i - 1] = ':';
321       l += len;
322 } while(pb.dirInfo.ioDrDirID != fsRtDirID); //while more directory levels
323   }
324 }
325 #endif
326
327 bool
328 Layer_Freetype::new_face(const String &newfont)
329 {
330         int error;
331         FT_Long face_index=0;
332
333         // If we are already loaded, don't bother reloading.
334         if(face && font==newfont)
335                 return true;
336
337         if(face)
338         {
339                 FT_Done_Face(face);
340                 face=0;
341         }
342
343         error=FT_New_Face(ft_library,newfont.c_str(),face_index,&face);
344         if(error)error=FT_New_Face(ft_library,(newfont+".ttf").c_str(),face_index,&face);
345
346         if(get_canvas())
347         {
348                 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPARATOR+newfont).c_str(),face_index,&face);
349                 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPARATOR+newfont+".ttf").c_str(),face_index,&face);
350         }
351
352 #ifdef USE_MAC_FT_FUNCS
353         if(error)
354         {
355                 FSSpec fs_spec;
356                 error=FT_GetFile_From_Mac_Name(newfont.c_str(),&fs_spec,&face_index);
357                 if(!error)
358                 {
359                         char filename[512];
360                         fss2path(filename,&fs_spec);
361                         //FSSpecToNativePathName(fs_spec,filename,sizeof(filename)-1, 0);
362
363                         error=FT_New_Face(ft_library, filename, face_index,&face);
364                         //error=FT_New_Face_From_FSSpec(ft_library, &fs_spec, face_index,&face);
365                         synfig::info(__FILE__":%d: \"%s\" (%s) -- ft_error=%d",__LINE__,newfont.c_str(),filename,error);
366                 }
367                 else
368                 {
369                         synfig::info(__FILE__":%d: \"%s\" -- ft_error=%d",__LINE__,newfont.c_str(),error);
370                         // Unable to generate fs_spec
371                 }
372         }
373 #endif
374
375 #ifdef WITH_FONTCONFIG
376         if(error)
377         {
378                 FcFontSet *fs;
379                 FcResult result;
380                 if( !FcInit() )
381                 {
382                         synfig::warning("Layer_Freetype: fontconfig: %s",_("unable to initialize"));
383                         error = 1;
384                 } else {
385                         FcPattern* pat = FcNameParse((FcChar8 *) newfont.c_str());
386                         FcConfigSubstitute(0, pat, FcMatchPattern);
387                         FcDefaultSubstitute(pat);
388                         FcPattern *match;
389                         fs = FcFontSetCreate();
390                         match = FcFontMatch(0, pat, &result);
391                         if (match)
392                                 FcFontSetAdd(fs, match);
393                         if (pat)
394                                 FcPatternDestroy(pat);
395                         if(fs){
396                                 FcChar8* file;
397                                 if( FcPatternGetString (fs->fonts[0], FC_FILE, 0, &file) == FcResultMatch )
398                                         error=FT_New_Face(ft_library,(const char*)file,face_index,&face);
399                                 FcFontSetDestroy(fs);
400                         } else
401                                 synfig::warning("Layer_Freetype: fontconfig: %s",_("empty font set"));
402                 }
403         }
404 #endif
405
406 #ifdef WIN32
407         if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont).c_str(),face_index,&face);
408         if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont+".ttf").c_str(),face_index,&face);
409 #else
410
411 #ifdef __APPLE__
412         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont).c_str(),face_index,&face);
413         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
414         if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
415
416         if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont).c_str(),face_index,&face);
417         if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
418         if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
419 #endif
420
421         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont).c_str(),face_index,&face);
422         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont+".ttf").c_str(),face_index,&face);
423
424         if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont).c_str(),face_index,&face);
425         if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
426
427         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont).c_str(),face_index,&face);
428         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont+".ttf").c_str(),face_index,&face);
429
430         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont).c_str(),face_index,&face);
431         if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
432
433 #endif
434         if(error)
435         {
436                 //synfig::error(strprintf("Layer_Freetype:%s (err=%d)",_("Unable to open face."),error));
437                 return false;
438         }
439
440         font=newfont;
441
442         needs_sync_=true;
443         return true;
444 }
445
446 bool
447 Layer_Freetype::set_param(const String & param, const ValueBase &value)
448 {
449         Mutex::Lock lock(mutex);
450 /*
451         if(param=="font" && value.same_type_as(font))
452         {
453                 new_font(etl::basename(value.get(font)),style,weight);
454                 family=etl::basename(value.get(font));
455                 return true;
456         }
457 */
458         IMPORT_PLUS(family,new_font(family,style,weight));
459         IMPORT_PLUS(weight,new_font(family,style,weight));
460         IMPORT_PLUS(style,new_font(family,style,weight));
461         IMPORT_PLUS(size, if(old_version){size/=2.0;} needs_sync_=true );
462         IMPORT_PLUS(text,needs_sync_=true);
463         IMPORT_PLUS(origin,needs_sync_=true);
464         IMPORT_PLUS(color, { if (color.get_a() == 0) { if (converted_blend_) {
465                                         set_blend_method(Color::BLEND_ALPHA_OVER);
466                                         color.set_a(1); } else transparent_color_ = true; } });
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         IMPORT_AS(origin,"pos");
475
476         return Layer_Composite::set_param(param,value);
477 }
478
479 ValueBase
480 Layer_Freetype::get_param(const String& param)const
481 {
482         EXPORT(font);
483         EXPORT(family);
484         EXPORT(style);
485         EXPORT(weight);
486         EXPORT(size);
487         EXPORT(text);
488         EXPORT(color);
489         EXPORT(origin);
490         EXPORT(orient);
491         EXPORT(compress);
492         EXPORT(vcompress);
493         EXPORT(use_kerning);
494         EXPORT(grid_fit);
495         EXPORT(invert);
496
497         EXPORT_NAME();
498         EXPORT_VERSION();
499
500         return Layer_Composite::get_param(param);
501 }
502
503 Layer::Vocab
504 Layer_Freetype::get_param_vocab(void)const
505 {
506         Layer::Vocab ret(Layer_Composite::get_param_vocab());
507
508         ret.push_back(ParamDesc("text")
509                 .set_local_name(_("Text"))
510                 .set_description(_("Text to Render"))
511                 .set_hint("paragraph")
512         );
513
514         ret.push_back(ParamDesc("color")
515                 .set_local_name(_("Color"))
516                 .set_description(_("Color of the text"))
517         );
518
519         ret.push_back(ParamDesc("family")
520                 .set_local_name(_("Font Family"))
521                 .set_hint("font_family")
522         );
523
524         ret.push_back(ParamDesc("style")
525                 .set_local_name(_("Style"))
526                 .set_hint("enum")
527                 .add_enum_value(PANGO_STYLE_NORMAL, "normal" ,_("Normal"))
528                 .add_enum_value(PANGO_STYLE_OBLIQUE, "oblique" ,_("Oblique"))
529                 .add_enum_value(PANGO_STYLE_ITALIC, "italic" ,_("Italic"))
530         );
531
532         ret.push_back(ParamDesc("weight")
533                 .set_local_name(_("Weight"))
534                 .set_hint("enum")
535                 .add_enum_value(200, "ultralight" ,_("Ultralight"))
536                 .add_enum_value(300, "light" ,_("light"))
537                 .add_enum_value(400, "normal" ,_("Normal"))
538                 .add_enum_value(700, "bold" ,_("Bold"))
539                 .add_enum_value(800, "ultrabold" ,_("Ultrabold"))
540                 .add_enum_value(900, "heavy" ,_("Heavy"))
541         );
542         ret.push_back(ParamDesc("compress")
543                 .set_local_name(_("Horizontal Spacing"))
544                 .set_description(_("Describes how close glyphs are horizontally"))
545         );
546
547         ret.push_back(ParamDesc("vcompress")
548                 .set_local_name(_("Vertical Spacing"))
549                 .set_description(_("Describes how close lines of text are vertically"))
550         );
551
552         ret.push_back(ParamDesc("size")
553                 .set_local_name(_("Size"))
554                 .set_description(_("Size of the text"))
555                 .set_hint("size")
556                 .set_origin("origin")
557                 .set_scalar(1)
558         );
559
560         ret.push_back(ParamDesc("orient")
561                 .set_local_name(_("Orientation"))
562                 .set_description(_("Text Orientation"))
563                 .set_invisible_duck()
564         );
565
566         ret.push_back(ParamDesc("origin")
567                 .set_local_name(_("Origin"))
568                 .set_description(_("Text Position"))
569         );
570
571         ret.push_back(ParamDesc("font")
572                 .set_local_name(_("Font"))
573                 .set_description(_("Filename of the font to use"))
574                 .set_hint("filename")
575                 .not_critical()
576                 .hidden()
577         );
578
579         ret.push_back(ParamDesc("use_kerning")
580                 .set_local_name(_("Kerning"))
581                 .set_description(_("Enables/Disables font kerning (If the font supports it)"))
582         );
583
584         ret.push_back(ParamDesc("grid_fit")
585                 .set_local_name(_("Sharpen Edges"))
586                 .set_description(_("Turn this off if you are going to be animating the text"))
587         );
588         ret.push_back(ParamDesc("invert")
589                 .set_local_name(_("Invert"))
590         );
591         return ret;
592 }
593
594 void
595 Layer_Freetype::sync()
596 {
597         needs_sync_=false;
598 }
599
600 inline Color
601 Layer_Freetype::color_func(const Point &point_ __attribute__ ((unused)), int quality __attribute__ ((unused)), float supersample __attribute__ ((unused)))const
602 {
603         if (invert)
604                 return color;
605         else
606                 return Color::alpha();
607 }
608
609 Color
610 Layer_Freetype::get_color(Context context, const synfig::Point &pos)const
611 {
612         if(needs_sync_)
613                 const_cast<Layer_Freetype*>(this)->sync();
614
615         const Color color(color_func(pos,0));
616
617         if(!face)
618                 return context.get_color(pos);
619
620         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
621                 return color;
622         else
623                 return Color::blend(color,context.get_color(pos),get_amount(),get_blend_method());
624 }
625
626 bool
627 Layer_Freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
628 {
629         static synfig::RecMutex freetype_mutex;
630
631         if(needs_sync_)
632                 const_cast<Layer_Freetype*>(this)->sync();
633
634         int error;
635         Vector size(Layer_Freetype::size*2);
636
637         if(!context.accelerated_render(surface,quality,renddesc,cb))
638                 return false;
639
640         if(is_disabled() || text.empty())
641                 return true;
642
643         // If there is no font loaded, just bail
644         if(!face)
645         {
646                 if(cb)cb->warning(string("Layer_Freetype:")+_("No face loaded, no text will be rendered."));
647                 return true;
648         }
649
650         String text(Layer_Freetype::text);
651         if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
652         {
653                 text=basename(get_canvas()->get_file_name());
654         }
655
656         // Width and Height of a pixel
657         Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
658         Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
659
660     // Calculate character width and height
661         int w=abs(round_to_int(size[0]*pw));
662         int h=abs(round_to_int(size[1]*ph));
663
664     //int bx=(int)((origin[0]-renddesc.get_tl()[0])*pw*64+0.5);
665     //int by=(int)((origin[1]-renddesc.get_tl()[1])*ph*64+0.5);
666     int bx=0;
667     int by=0;
668
669     // If the font is the size of a pixel, don't bother rendering any text
670         if(w<=1 || h<=1)
671         {
672                 if(cb)cb->warning(string("Layer_Freetype:")+_("Text too small, no text will be rendered."));
673                 return true;
674         }
675
676         synfig::RecMutex::Lock lock(freetype_mutex);
677
678 #define CHAR_RESOLUTION         (64)
679         error = FT_Set_Char_Size(
680                 face,                                           // handle to face object
681                 (int)CHAR_RESOLUTION,   // char_width in 1/64th of points
682                 (int)CHAR_RESOLUTION,   // char_height in 1/64th of points
683                 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)),                                          // horizontal device resolution
684                 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) );                                                // vertical device resolution
685
686         // Here is where we can compensate for the
687         // error in freetype's rendering engine.
688         const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
689         const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
690         //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
691         const float compress(Layer_Freetype::compress*xerror);
692         const float vcompress(Layer_Freetype::vcompress*yerror);
693
694         if(error)
695         {
696                 if(cb)cb->warning(string("Layer_Freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
697         }
698
699         FT_GlyphSlot  slot = face->glyph;  // a small shortcut
700         FT_UInt       glyph_index(0);
701         FT_UInt       previous(0);
702         int u,v;
703
704         std::list<TextLine> lines;
705
706         /*
707  --     ** -- CREATE GLYPHS -------------------------------------------------------
708         */
709
710         mbstate_t ps;
711         memset(&ps, 0, sizeof(ps));
712
713         lines.push_front(TextLine());
714         string::const_iterator iter;
715         for (iter=text.begin(); iter!=text.end(); ++iter)
716         {
717                 int multiplier(1);
718                 if(*iter=='\n')
719                 {
720                         lines.push_front(TextLine());
721                         bx=0;
722                         by=0;
723                         previous=0;
724                         continue;
725                 }
726                 if(*iter=='\t')
727                 {
728                         multiplier=8;
729                         glyph_index = FT_Get_Char_Index( face, ' ' );
730                 }
731                 else
732                 {
733                         wchar_t wc;
734                         size_t converted = mbrtowc(&wc, &(*iter), text.end() - iter, &ps);
735
736                         if(converted == (size_t)(-1))
737                         {
738                                 synfig::warning("Layer_Freetype: multibyte: %s",
739                                                                 _("Invalid multibyte sequence - is the locale set?\n"));
740                                 continue;
741                         }
742
743                         if(converted == (size_t)(-2))
744                         {
745                                 synfig::warning("Layer_Freetype: multibyte: %s",
746                                                                 _("Can't parse multibyte character.\n"));
747                                 continue;
748                         }
749
750                         glyph_index = FT_Get_Char_Index( face, wc );
751
752                         if(converted > 1)
753                                 iter += converted - 1;
754                 }
755
756         // retrieve kerning distance and move pen position
757                 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
758                 {
759                         FT_Vector  delta;
760
761                         if(grid_fit)
762                                 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
763                         else
764                                 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
765
766                         if(compress<1.0f)
767                         {
768                                 bx += round_to_int(delta.x*compress);
769                                 by += round_to_int(delta.y*compress);
770                         }
771                         else
772                         {
773                                 bx += delta.x;
774                                 by += delta.y;
775                         }
776         }
777
778                 Glyph curr_glyph;
779
780         // store current pen position
781         curr_glyph.pos.x = bx;
782         curr_glyph.pos.y = by;
783
784         // load glyph image into the slot. DO NOT RENDER IT !!
785         if(grid_fit)
786                         error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
787                 else
788                         error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
789         if (error) continue;  // ignore errors, jump to next glyph
790
791         // extract glyph image and store it in our table
792         error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
793         if (error) continue;  // ignore errors, jump to next glyph
794
795         // record current glyph index
796         previous = glyph_index;
797
798                 // Update the line width
799                 lines.front().width=bx+slot->advance.x;
800
801                 // increment pen position
802                 if(multiplier>1)
803                         bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
804                 else
805                         bx += round_to_int(slot->advance.x*compress*multiplier);
806
807                 //bx += round_to_int(slot->advance.x*compress*multiplier);
808                 //by += round_to_int(slot->advance.y*compress);
809                 by += slot->advance.y*multiplier;
810
811                 lines.front().glyph_table.push_back(curr_glyph);
812
813         }
814
815         //float string_height;
816         //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
817
818         //int string_height=face->size->metrics.ascender;
819 //#define METRICS_SCALE_ONE             (65536.0f)
820 #define METRICS_SCALE_ONE               ((float)(1<<16))
821
822         float line_height;
823         line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
824
825         // This module sees to expect pixel height to be negative, as it
826         // usually is.  But rendering to .bmp format causes ph to be
827         // positive, which was causing text to be rendered upside down.
828         if (ph>0) line_height = -line_height;
829
830         int     string_height;
831         string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
832         //synfig::info("string_height=%d",string_height);
833         //synfig::info("line_height=%f",line_height);
834
835         /*
836  --     ** -- RENDER THE GLYPHS ---------------------------------------------------
837         */
838
839         Surface src_;
840         Surface *src_surface;
841
842         src_surface=surface;
843
844         if(invert)
845         {
846                 src_=*surface;
847                 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
848
849                 surface->fill(color,pen,src_.get_w(),src_.get_h());
850
851                 src_surface=&src_;
852         }
853
854         {
855                 std::list<TextLine>::iterator iter;
856                 int curr_line;
857                 for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
858                 {
859                         bx=round_to_int((origin[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
860                         // I've no idea why 1.5, but it kind of works.  Otherwise,
861                         // rendering to .bmp (which renders from bottom to top, due to
862                         // the .bmp format describing the image from bottom to top,
863                         // renders text in the wrong place.
864                         by=round_to_int((origin[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION +
865                                                         (1.0-orient[1])*string_height-line_height*curr_line +
866                                                         ((ph>0) ? line_height/1.5 : 0));
867
868                         //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));
869                         //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
870
871                         std::vector<Glyph>::iterator iter2;
872                         for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
873                         {
874                                 FT_Glyph  image(iter2->glyph);
875                                 FT_Vector pen;
876                                 FT_BitmapGlyph  bit;
877
878                                 pen.x = bx + iter2->pos.x;
879                                 pen.y = by + iter2->pos.y;
880
881                                 //synfig::info("GLYPH: line %d, pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
882
883                                 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
884                                 if(error) { FT_Done_Glyph( image ); continue; }
885
886                                 bit = (FT_BitmapGlyph)image;
887
888                                 for(v=0;v<bit->bitmap.rows;v++)
889                                         for(u=0;u<bit->bitmap.width;u++)
890                                         {
891                                                 int x=u+((pen.x+32)>>6)+ bit->left;
892                                                 int y=((pen.y+32)>>6) + (bit->top - v) * ((ph<0) ? -1 : 1);
893                                                 if(     y>=0 &&
894                                                         x>=0 &&
895                                                         y<surface->get_h() &&
896                                                         x<surface->get_w())
897                                                 {
898                                                         float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
899                                                         if(invert)
900                                                                 myamount=1.0f-myamount;
901                                                         (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
902                                                 }
903                                         }
904
905                                 FT_Done_Glyph( image );
906                         }
907                         //iter->clear_and_free();
908                 }
909         }
910
911         return true;
912 }
913
914 synfig::Rect
915 Layer_Freetype::get_bounding_rect()const
916 {
917         if(needs_sync_)
918                 const_cast<Layer_Freetype*>(this)->sync();
919 //      if(!is_disabled())
920                 return synfig::Rect::full_plane();
921 }