1 /* === S Y N F I G ========================================================= */
2 /*! \file lyr_freetype.cpp
3 ** \brief Template Header
8 ** Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 ** Copyright (c) 2006 Paul Wise
11 ** This package is free software; you can redistribute it and/or
12 ** modify it under the terms of the GNU General Public License as
13 ** published by the Free Software Foundation; either version 2 of
14 ** the License, or (at your option) any later version.
16 ** This package is distributed in the hope that it will be useful,
17 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 ** General Public License for more details.
22 ** === N O T E S ===========================================================
24 ** ========================================================================= */
26 /* === H E A D E R S ======================================================= */
36 #ifdef WITH_FONTCONFIG
37 #include <fontconfig/fontconfig.h>
40 #include "lyr_freetype.h"
47 using namespace synfig;
49 /* === M A C R O S ========================================================= */
51 #define MAX_GLYPHS 2000
53 #define PANGO_STYLE_NORMAL (0)
54 #define PANGO_STYLE_OBLIQUE (1)
55 #define PANGO_STYLE_ITALIC (2)
58 #define WEIGHT_NORMAL (400)
59 #define WEIGHT_BOLD (700)
61 /* === G L O B A L S ======================================================= */
63 SYNFIG_LAYER_INIT(Layer_Freetype);
64 SYNFIG_LAYER_SET_NAME(Layer_Freetype,"text");
65 SYNFIG_LAYER_SET_LOCAL_NAME(Layer_Freetype,_("Simple Text"));
66 SYNFIG_LAYER_SET_CATEGORY(Layer_Freetype,_("Typography"));
67 SYNFIG_LAYER_SET_VERSION(Layer_Freetype,"0.2");
68 SYNFIG_LAYER_SET_CVS_ID(Layer_Freetype,"$Id$");
70 /* === P R O C E D U R E S ================================================= */
74 if(glyph)FT_Done_Glyph(glyph);
78 TextLine::clear_and_free()
80 std::vector<Glyph>::iterator iter;
81 for(iter=glyph_table.begin();iter!=glyph_table.end();++iter)
83 if(iter->glyph)FT_Done_Glyph(iter->glyph);
89 /* === M E T H O D S ======================================================= */
91 Layer_Freetype::Layer_Freetype()
95 size=Vector(0.25,0.25);
99 orient=Vector(0.5,0.5);
102 weight=WEIGHT_NORMAL;
103 style=PANGO_STYLE_NORMAL;
108 set_blend_method(Color::BLEND_COMPOSITE);
111 new_font(family,style,weight);
116 Layer_Freetype::~Layer_Freetype()
123 Layer_Freetype::new_font(const synfig::String &family, int style, int weight)
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)
134 new_font_("sans serif",PANGO_STYLE_NORMAL,WEIGHT_NORMAL);
138 Layer_Freetype::new_font_(const synfig::String &font_fam_, int style, int weight)
140 synfig::String font_fam(font_fam_);
142 if(new_face(font_fam_))
146 for(unsigned int i=0;i<font_fam.size();i++)font_fam[i]=tolower(font_fam[i]);
149 if(font_fam=="arial black")
151 if(new_face("ariblk"))
155 font_fam="sans serif";
157 if(font_fam=="sans serif" || font_fam=="arial")
159 String arial("arial");
160 if(weight>WEIGHT_NORMAL)
162 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
165 if(weight>WEIGHT_NORMAL) arial+='d';
170 if(new_face("Helvetica RO"))
175 if(font_fam=="comic" || font_fam=="comic sans")
177 String filename("comic");
178 if(weight>WEIGHT_NORMAL)
180 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
182 else if(weight>WEIGHT_NORMAL) filename+='d';
184 if(new_face(filename))
188 if(font_fam=="courier" || font_fam=="courier new")
190 String filename("cour");
191 if(weight>WEIGHT_NORMAL)
193 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
195 else if(weight>WEIGHT_NORMAL) filename+='d';
197 if(new_face(filename))
201 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman")
203 String filename("times");
204 if(weight>WEIGHT_NORMAL)
206 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
208 else if(weight>WEIGHT_NORMAL) filename+='d';
210 if(new_face(filename))
214 if(font_fam=="trebuchet")
216 String filename("trebuc");
217 if(weight>WEIGHT_NORMAL)
219 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
222 if(weight<=WEIGHT_NORMAL) filename+='t';
224 else if(weight>WEIGHT_NORMAL) filename+='d';
226 if(new_face(filename))
231 if(font_fam=="sans serif" || font_fam=="luxi sans")
234 String luxi("luxis");
235 if(weight>WEIGHT_NORMAL)
239 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
246 if(new_face("arial"))
248 if(new_face("Arial"))
251 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman" || font_fam=="luxi serif")
254 String luxi("luxir");
255 if(weight>WEIGHT_NORMAL)
259 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
265 if(new_face("Times New Roman"))
267 if(new_face("Times"))
273 String luxi("luxim");
274 if(weight>WEIGHT_NORMAL)
278 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
285 if(new_face("Times New Roman"))
287 if(new_face("Times"))
291 return new_face(font_fam_) || new_face(font_fam);
296 #ifdef USE_MAC_FT_FUNCS
297 void fss2path(char *path, FSSpec *fss)
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];
303 if(fss->parID != fsRtParID) //path is more than just a volume name
308 pb.dirInfo.ioNamePtr = fss->name;
309 pb.dirInfo.ioVRefNum = fss->vRefNum;
310 pb.dirInfo.ioDrParID = fss->parID;
313 pb.dirInfo.ioFDirIndex = -1; //get parent directory name
314 pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
315 if(PBGetCatInfoSync(&pb) != noErr) break;
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
322 } while(pb.dirInfo.ioDrDirID != fsRtDirID); //while more directory levels
328 Layer_Freetype::new_face(const String &newfont)
331 FT_Long face_index=0;
333 // If we are already loaded, don't bother reloading.
334 if(face && font==newfont)
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);
348 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont).c_str(),face_index,&face);
349 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont+".ttf").c_str(),face_index,&face);
352 #ifdef USE_MAC_FT_FUNCS
356 error=FT_GetFile_From_Mac_Name(newfont.c_str(),&fs_spec,&face_index);
360 fss2path(filename,&fs_spec);
361 //FSSpecToNativePathName(fs_spec,filename,sizeof(filename)-1, 0);
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);
369 synfig::info(__FILE__":%d: \"%s\" -- ft_error=%d",__LINE__,newfont.c_str(),error);
370 // Unable to generate fs_spec
376 #ifdef WITH_FONTCONFIG
383 synfig::warning("Layer_Freetype: fontconfig: %s",_("unable to initialise"));
386 FcPattern* pat = FcNameParse((FcChar8 *) newfont.c_str());
387 FcConfigSubstitute(0, pat, FcMatchPattern);
388 FcDefaultSubstitute(pat);
390 fs = FcFontSetCreate();
391 match = FcFontMatch(0, pat, &result);
393 FcFontSetAdd(fs, match);
395 FcPatternDestroy(pat);
398 if( FcPatternGetString (fs->fonts[0], FC_FILE, 0, &file) == FcResultMatch )
399 error=FT_New_Face(ft_library,(const char*)file,face_index,&face);
400 FcFontSetDestroy(fs);
402 synfig::warning("Layer_Freetype: fontconfig: %s",_("empty font set"));
408 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont).c_str(),face_index,&face);
409 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont+".ttf").c_str(),face_index,&face);
413 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont).c_str(),face_index,&face);
414 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
415 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
417 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont).c_str(),face_index,&face);
418 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
419 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
422 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont).c_str(),face_index,&face);
423 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont+".ttf").c_str(),face_index,&face);
425 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont).c_str(),face_index,&face);
426 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
428 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont).c_str(),face_index,&face);
429 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont+".ttf").c_str(),face_index,&face);
431 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont).c_str(),face_index,&face);
432 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
437 //synfig::error(strprintf("Layer_Freetype:%s (err=%d)",_("Unable to open face."),error));
448 Layer_Freetype::set_param(const String & param, const ValueBase &value)
450 Mutex::Lock lock(mutex);
452 if(param=="font" && value.same_type_as(font))
454 new_font(etl::basename(value.get(font)),style,weight);
455 family=etl::basename(value.get(font));
459 IMPORT_PLUS(family,new_font(family,style,weight));
460 IMPORT_PLUS(weight,new_font(family,style,weight));
461 IMPORT_PLUS(style,new_font(family,style,weight));
462 IMPORT_PLUS(size, if(old_version){size/=2.0;} needs_sync_=true );
463 IMPORT_PLUS(text,needs_sync_=true);
464 IMPORT_PLUS(pos,needs_sync_=true);
467 IMPORT_PLUS(orient,needs_sync_=true);
468 IMPORT_PLUS(compress,needs_sync_=true);
469 IMPORT_PLUS(vcompress,needs_sync_=true);
470 IMPORT_PLUS(use_kerning,needs_sync_=true);
471 IMPORT_PLUS(grid_fit,needs_sync_=true);
473 return Layer_Composite::set_param(param,value);
477 Layer_Freetype::get_param(const String& param)const
497 return Layer_Composite::get_param(param);
501 Layer_Freetype::get_param_vocab(void)const
503 Layer::Vocab ret(Layer_Composite::get_param_vocab());
505 ret.push_back(ParamDesc("text")
506 .set_local_name(_("Text"))
507 .set_description(_("Text to Render"))
508 .set_hint("paragraph")
511 ret.push_back(ParamDesc("color")
512 .set_local_name(_("Color"))
513 .set_description(_("Color of the text"))
516 ret.push_back(ParamDesc("family")
517 .set_local_name(_("Font Family"))
518 .set_hint("font_family")
521 ret.push_back(ParamDesc("style")
522 .set_local_name(_("Style"))
524 .add_enum_value(PANGO_STYLE_NORMAL, "normal" ,_("Normal"))
525 .add_enum_value(PANGO_STYLE_OBLIQUE, "oblique" ,_("Oblique"))
526 .add_enum_value(PANGO_STYLE_ITALIC, "italic" ,_("Italic"))
529 ret.push_back(ParamDesc("weight")
530 .set_local_name(_("Weight"))
532 .add_enum_value(200, "ultralight" ,_("Ultralight"))
533 .add_enum_value(300, "light" ,_("light"))
534 .add_enum_value(400, "normal" ,_("Normal"))
535 .add_enum_value(700, "bold" ,_("Bold"))
536 .add_enum_value(800, "ultrabold" ,_("Ultrabold"))
537 .add_enum_value(900, "heavy" ,_("Heavy"))
539 ret.push_back(ParamDesc("compress")
540 .set_local_name(_("Horizontal Spacing"))
541 .set_description(_("Describes how close glyphs are horizontally"))
544 ret.push_back(ParamDesc("vcompress")
545 .set_local_name(_("Vertical Spacing"))
546 .set_description(_("Describes how close lines of text are vertically"))
549 ret.push_back(ParamDesc("size")
550 .set_local_name(_("Size"))
551 .set_description(_("Size of the text"))
557 ret.push_back(ParamDesc("orient")
558 .set_local_name(_("Orientation"))
559 .set_description(_("Text Orientation"))
560 .set_invisible_duck()
563 ret.push_back(ParamDesc("pos")
564 .set_local_name(_("Position"))
565 .set_description(_("Text Position"))
568 ret.push_back(ParamDesc("font")
569 .set_local_name(_("Font"))
570 .set_description(_("Filename of the font to use"))
571 .set_hint("filename")
576 ret.push_back(ParamDesc("use_kerning")
577 .set_local_name(_("Kerning"))
578 .set_description(_("Enables/Disables font kerning (If the font supports it)"))
581 ret.push_back(ParamDesc("grid_fit")
582 .set_local_name(_("Sharpen Edges"))
583 .set_description(_("Turn this off if you are going to be animating the text"))
585 ret.push_back(ParamDesc("invert")
586 .set_local_name(_("Invert"))
592 Layer_Freetype::sync()
602 Layer_Freetype::get_color(Context context, const synfig::Point &pos)const
605 const_cast<Layer_Freetype*>(this)->sync();
608 return context.get_color(pos);
609 return context.get_color(pos);
613 Layer_Freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
615 static synfig::RecMutex freetype_mutex;
618 const_cast<Layer_Freetype*>(this)->sync();
624 Vector size(Layer_Freetype::size*2);
626 if(!context.accelerated_render(surface,quality,renddesc,cb))
629 if(is_disabled() || text.empty())
632 // If there is no font loaded, just bail
635 if(cb)cb->warning(string("Layer_Freetype:")+_("No face loaded, no text will be rendered."));
639 String text(Layer_Freetype::text);
640 if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
642 text=basename(get_canvas()->get_file_name());
645 // Width and Height of a pixel
646 Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
647 Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
649 // Calculate character width and height
650 int w=abs(round_to_int(size[0]*pw));
651 int h=abs(round_to_int(size[1]*ph));
653 //int bx=(int)((pos[0]-renddesc.get_tl()[0])*pw*64+0.5);
654 //int by=(int)((pos[1]-renddesc.get_tl()[1])*ph*64+0.5);
658 // If the font is the size of a pixel, don't bother rendering any text
661 if(cb)cb->warning(string("Layer_Freetype:")+_("Text too small, no text will be rendered."));
665 synfig::RecMutex::Lock lock(freetype_mutex);
667 #define CHAR_RESOLUTION (64)
668 error = FT_Set_Char_Size(
669 face, // handle to face object
670 (int)CHAR_RESOLUTION, // char_width in 1/64th of points
671 (int)CHAR_RESOLUTION, // char_height in 1/64th of points
672 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)), // horizontal device resolution
673 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) ); // vertical device resolution
675 // Here is where we can compensate for the
676 // error in freetype's rendering engine.
677 const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
678 const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
679 //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
680 const float compress(Layer_Freetype::compress*xerror);
681 const float vcompress(Layer_Freetype::vcompress*yerror);
685 if(cb)cb->warning(string("Layer_Freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
688 FT_GlyphSlot slot = face->glyph; // a small shortcut
689 FT_UInt glyph_index(0);
693 std::list<TextLine> lines;
696 -- ** -- CREATE GLYPHS -------------------------------------------------------
699 lines.push_front(TextLine());
700 string::const_iterator iter;
701 for (iter=text.begin(); iter!=text.end(); ++iter)
706 lines.push_front(TextLine());
715 glyph_index = FT_Get_Char_Index( face, ' ' );
718 glyph_index = FT_Get_Char_Index( face, *iter );
720 // retrieve kerning distance and move pen position
721 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
726 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
728 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
732 bx += round_to_int(delta.x*compress);
733 by += round_to_int(delta.y*compress);
744 // store current pen position
745 curr_glyph.pos.x = bx;
746 curr_glyph.pos.y = by;
748 // load glyph image into the slot. DO NOT RENDER IT !!
750 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
752 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
753 if (error) continue; // ignore errors, jump to next glyph
755 // extract glyph image and store it in our table
756 error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
757 if (error) continue; // ignore errors, jump to next glyph
759 // record current glyph index
760 previous = glyph_index;
762 // Update the line width
763 lines.front().width=bx+slot->advance.x;
765 // increment pen position
767 bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
769 bx += round_to_int(slot->advance.x*compress*multiplier);
771 //bx += round_to_int(slot->advance.x*compress*multiplier);
772 //by += round_to_int(slot->advance.y*compress);
773 by += slot->advance.y*multiplier;
775 lines.front().glyph_table.push_back(curr_glyph);
780 //float string_height;
781 //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
783 //int string_height=face->size->metrics.ascender;
784 //#define METRICS_SCALE_ONE (65536.0f)
785 #define METRICS_SCALE_ONE ((float)(1<<16))
788 line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
791 string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
792 //synfig::info("string_height=%d",string_height);
793 //synfig::info("line_height=%f",line_height);
796 -- ** -- RENDER THE GLYPHS ---------------------------------------------------
800 Surface *src_surface;
807 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
809 surface->fill(color,pen,src_.get_w(),src_.get_h());
815 std::list<TextLine>::iterator iter;
817 for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
819 bx=round_to_int((pos[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
820 by=round_to_int((pos[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION+(1.0-orient[1])*string_height-line_height*curr_line);
821 //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));
822 //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
824 std::vector<Glyph>::iterator iter2;
825 for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
827 FT_Glyph image(iter2->glyph);
831 pen.x = bx + iter2->pos.x;
832 pen.y = by + iter2->pos.y;
834 //synfig::info("GLYPH: pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
836 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
837 if(error) { FT_Done_Glyph( image ); continue; }
839 bit = (FT_BitmapGlyph)image;
841 for(v=0;v<bit->bitmap.rows;v++)
842 for(u=0;u<bit->bitmap.width;u++)
844 int x=u+((pen.x+32)>>6)+ bit->left;
845 int y=v+((pen.y+32)>>6)- bit->top;
848 y<surface->get_h() &&
851 float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
853 myamount=1.0f-myamount;
854 (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
858 FT_Done_Glyph( image );
860 //iter->clear_and_free();
869 Layer_Freetype::get_bounding_rect()const
872 const_cast<Layer_Freetype*>(this)->sync();
873 // if(!is_disabled())
874 return synfig::Rect::full_plane();