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