1 /* === S Y N F I G ========================================================= */
2 /*! \file lyr_freetype.cpp
3 ** \brief Template Header
6 ** Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
7 ** Copyright (c) 2006 Paul Wise
9 ** This package is free software; you can redistribute it and/or
10 ** modify it under the terms of the GNU General Public License as
11 ** published by the Free Software Foundation; either version 2 of
12 ** the License, or (at your option) any later version.
14 ** This package is distributed in the hope that it will be useful,
15 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 ** General Public License for more details.
20 ** === N O T E S ===========================================================
22 ** ========================================================================= */
24 /* === H E A D E R S ======================================================= */
34 #ifdef WITH_FONTCONFIG
35 #include <fontconfig/fontconfig.h>
38 #include "lyr_freetype.h"
45 using namespace synfig;
47 /* === M A C R O S ========================================================= */
49 #define MAX_GLYPHS 2000
51 #define PANGO_STYLE_NORMAL (0)
52 #define PANGO_STYLE_OBLIQUE (1)
53 #define PANGO_STYLE_ITALIC (2)
56 #define WEIGHT_NORMAL (400)
57 #define WEIGHT_BOLD (700)
59 /* === G L O B A L S ======================================================= */
61 SYNFIG_LAYER_INIT(lyr_freetype);
62 SYNFIG_LAYER_SET_NAME(lyr_freetype,"text");
63 SYNFIG_LAYER_SET_LOCAL_NAME(lyr_freetype,_("Simple Text"));
64 SYNFIG_LAYER_SET_CATEGORY(lyr_freetype,_("Typography"));
65 SYNFIG_LAYER_SET_VERSION(lyr_freetype,"0.2");
66 SYNFIG_LAYER_SET_CVS_ID(lyr_freetype,"$Id: lyr_freetype.cpp,v 1.5 2005/01/24 05:00:18 darco Exp $");
68 /* === P R O C E D U R E S ================================================= */
72 if(glyph)FT_Done_Glyph(glyph);
76 TextLine::clear_and_free()
78 std::vector<Glyph>::iterator iter;
79 for(iter=glyph_table.begin();iter!=glyph_table.end();++iter)
81 if(iter->glyph)FT_Done_Glyph(iter->glyph);
87 /* === M E T H O D S ======================================================= */
89 lyr_freetype::lyr_freetype()
93 size=Vector(0.25,0.25);
97 orient=Vector(0.5,0.5);
100 weight=WEIGHT_NORMAL;
101 style=PANGO_STYLE_NORMAL;
106 set_blend_method(Color::BLEND_COMPOSITE);
109 new_font(family,style,weight);
114 lyr_freetype::~lyr_freetype()
121 lyr_freetype::new_font(const synfig::String &family, int style, int weight)
124 !new_font_(family,style,weight) &&
125 !new_font_(family,style,WEIGHT_NORMAL) &&
126 !new_font_(family,PANGO_STYLE_NORMAL,weight) &&
127 !new_font_(family,PANGO_STYLE_NORMAL,WEIGHT_NORMAL) &&
128 !new_font_("sans serif",style,weight) &&
129 !new_font_("sans serif",style,WEIGHT_NORMAL) &&
130 !new_font_("sans serif",PANGO_STYLE_NORMAL,weight)
132 new_font_("sans serif",PANGO_STYLE_NORMAL,WEIGHT_NORMAL);
136 lyr_freetype::new_font_(const synfig::String &font_fam_, int style, int weight)
138 synfig::String font_fam(font_fam_);
140 if(new_face(font_fam_))
144 for(unsigned int i=0;i<font_fam.size();i++)font_fam[i]=tolower(font_fam[i]);
147 if(font_fam=="arial black")
149 if(new_face("ariblk"))
153 font_fam="sans serif";
155 if(font_fam=="sans serif" || font_fam=="arial")
157 String arial("arial");
158 if(weight>WEIGHT_NORMAL)
160 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
163 if(weight>WEIGHT_NORMAL) arial+='d';
168 if(new_face("Helvetica RO"))
173 if(font_fam=="comic" || font_fam=="comic sans")
175 String filename("comic");
176 if(weight>WEIGHT_NORMAL)
178 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
180 else if(weight>WEIGHT_NORMAL) filename+='d';
182 if(new_face(filename))
186 if(font_fam=="courier" || font_fam=="courier new")
188 String filename("cour");
189 if(weight>WEIGHT_NORMAL)
191 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
193 else if(weight>WEIGHT_NORMAL) filename+='d';
195 if(new_face(filename))
199 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman")
201 String filename("times");
202 if(weight>WEIGHT_NORMAL)
204 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
206 else if(weight>WEIGHT_NORMAL) filename+='d';
208 if(new_face(filename))
212 if(font_fam=="trebuchet")
214 String filename("trebuc");
215 if(weight>WEIGHT_NORMAL)
217 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
220 if(weight<=WEIGHT_NORMAL) filename+='t';
222 else if(weight>WEIGHT_NORMAL) filename+='d';
224 if(new_face(filename))
229 if(font_fam=="sans serif" || font_fam=="luxi sans")
232 String luxi("luxis");
233 if(weight>WEIGHT_NORMAL)
237 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
244 if(new_face("arial"))
246 if(new_face("Arial"))
249 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman" || font_fam=="luxi serif")
252 String luxi("luxir");
253 if(weight>WEIGHT_NORMAL)
257 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
263 if(new_face("Times New Roman"))
265 if(new_face("Times"))
271 String luxi("luxim");
272 if(weight>WEIGHT_NORMAL)
276 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
283 if(new_face("Times New Roman"))
285 if(new_face("Times"))
289 return new_face(font_fam_) || new_face(font_fam);
294 #ifdef USE_MAC_FT_FUNCS
295 void fss2path(char *path, FSSpec *fss)
297 int l; //fss->name contains name of last item in path
298 for(l=0; l<(fss->name[0]); l++) path[l] = fss->name[l + 1];
301 if(fss->parID != fsRtParID) //path is more than just a volume name
306 pb.dirInfo.ioNamePtr = fss->name;
307 pb.dirInfo.ioVRefNum = fss->vRefNum;
308 pb.dirInfo.ioDrParID = fss->parID;
311 pb.dirInfo.ioFDirIndex = -1; //get parent directory name
312 pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
313 if(PBGetCatInfoSync(&pb) != noErr) break;
315 len = fss->name[0] + 1;
316 for(i=l; i>=0; i--) path[i + len] = path[i];
317 for(i=1; i<len; i++) path[i - 1] = fss->name[i]; //add to start of path
320 } while(pb.dirInfo.ioDrDirID != fsRtDirID); //while more directory levels
326 lyr_freetype::new_face(const String &newfont)
329 FT_Long face_index=0;
331 // If we are already loaded, don't bother reloading.
332 if(face && font==newfont)
341 error=FT_New_Face(ft_library,newfont.c_str(),face_index,&face);
342 if(error)error=FT_New_Face(ft_library,(newfont+".ttf").c_str(),face_index,&face);
346 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont).c_str(),face_index,&face);
347 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont+".ttf").c_str(),face_index,&face);
350 #ifdef USE_MAC_FT_FUNCS
354 error=FT_GetFile_From_Mac_Name(newfont.c_str(),&fs_spec,&face_index);
358 fss2path(filename,&fs_spec);
359 //FSSpecToNativePathName(fs_spec,filename,sizeof(filename)-1, 0);
361 error=FT_New_Face(ft_library, filename, face_index,&face);
362 //error=FT_New_Face_From_FSSpec(ft_library, &fs_spec, face_index,&face);
363 synfig::info(__FILE__":%d: \"%s\" (%s) -- ft_error=%d",__LINE__,newfont.c_str(),filename,error);
367 synfig::info(__FILE__":%d: \"%s\" -- ft_error=%d",__LINE__,newfont.c_str(),error);
368 // Unable to generate fs_spec
374 #ifdef WITH_FONTCONFIG
381 synfig::warning("lyr_freetype: fontconfig: %s",_("unable to initialise"));
384 FcPattern* pat = FcNameParse((FcChar8 *) newfont.c_str());
385 FcConfigSubstitute(0, pat, FcMatchPattern);
386 FcDefaultSubstitute(pat);
388 fs = FcFontSetCreate();
389 match = FcFontMatch(0, pat, &result);
391 FcFontSetAdd(fs, match);
393 FcPatternDestroy(pat);
396 if( FcPatternGetString (fs->fonts[0], FC_FILE, 0, &file) == FcResultMatch )
397 error=FT_New_Face(ft_library,(const char*)file,face_index,&face);
398 FcFontSetDestroy(fs);
400 synfig::warning("lyr_freetype: fontconfig: %s",_("empty font set"));
406 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont).c_str(),face_index,&face);
407 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont+".ttf").c_str(),face_index,&face);
411 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont).c_str(),face_index,&face);
412 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
413 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
415 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont).c_str(),face_index,&face);
416 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
417 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
420 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont).c_str(),face_index,&face);
421 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont+".ttf").c_str(),face_index,&face);
423 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont).c_str(),face_index,&face);
424 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
426 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont).c_str(),face_index,&face);
427 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont+".ttf").c_str(),face_index,&face);
429 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont).c_str(),face_index,&face);
430 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
435 //synfig::error(strprintf("lyr_freetype:%s (err=%d)",_("Unable to open face."),error));
446 lyr_freetype::set_param(const String & param, const ValueBase &value)
448 Mutex::Lock lock(mutex);
450 if(param=="font" && value.same_as(font))
452 new_font(etl::basename(value.get(font)),style,weight);
453 family=etl::basename(value.get(font));
457 IMPORT_PLUS(family,new_font(family,style,weight));
458 IMPORT_PLUS(weight,new_font(family,style,weight));
459 IMPORT_PLUS(style,new_font(family,style,weight));
460 IMPORT_PLUS(size, if(old_version){size/=2.0;} needs_sync_=true );
461 IMPORT_PLUS(text,needs_sync_=true);
462 IMPORT_PLUS(pos,needs_sync_=true);
465 IMPORT_PLUS(orient,needs_sync_=true);
466 IMPORT_PLUS(compress,needs_sync_=true);
467 IMPORT_PLUS(vcompress,needs_sync_=true);
468 IMPORT_PLUS(use_kerning,needs_sync_=true);
469 IMPORT_PLUS(grid_fit,needs_sync_=true);
471 return Layer_Composite::set_param(param,value);
475 lyr_freetype::get_param(const String& param)const
495 return Layer_Composite::get_param(param);
499 lyr_freetype::get_param_vocab(void)const
501 Layer::Vocab ret(Layer_Composite::get_param_vocab());
503 ret.push_back(ParamDesc("text")
504 .set_local_name(_("Text"))
505 .set_description(_("Text to Render"))
506 .set_hint("paragraph")
509 ret.push_back(ParamDesc("color")
510 .set_local_name(_("Color"))
511 .set_description(_("Color of the text"))
514 ret.push_back(ParamDesc("family")
515 .set_local_name(_("Font Family"))
516 .set_hint("font_family")
519 ret.push_back(ParamDesc("style")
520 .set_local_name(_("Style"))
522 .add_enum_value(PANGO_STYLE_NORMAL, "normal" ,_("Normal"))
523 .add_enum_value(PANGO_STYLE_OBLIQUE, "oblique" ,_("Oblique"))
524 .add_enum_value(PANGO_STYLE_ITALIC, "italic" ,_("Italic"))
527 ret.push_back(ParamDesc("weight")
528 .set_local_name(_("Weight"))
530 .add_enum_value(200, "ultralight" ,_("Ultralight"))
531 .add_enum_value(300, "light" ,_("light"))
532 .add_enum_value(400, "normal" ,_("Normal"))
533 .add_enum_value(700, "bold" ,_("Bold"))
534 .add_enum_value(800, "ultrabold" ,_("Ultrabold"))
535 .add_enum_value(900, "heavy" ,_("Heavy"))
537 ret.push_back(ParamDesc("compress")
538 .set_local_name(_("Hozontal Spacing"))
539 .set_description(_("Describes how close glyphs are horizontally"))
542 ret.push_back(ParamDesc("vcompress")
543 .set_local_name(_("Vertical Spacing"))
544 .set_description(_("Describes how close lines of text are vertically"))
547 ret.push_back(ParamDesc("size")
548 .set_local_name(_("Size"))
549 .set_description(_("Size of the text"))
555 ret.push_back(ParamDesc("orient")
556 .set_local_name(_("Orientation"))
557 .set_description(_("Text Orientation"))
558 .set_invisible_duck()
561 ret.push_back(ParamDesc("pos")
562 .set_local_name(_("Position"))
563 .set_description(_("Text Position"))
566 ret.push_back(ParamDesc("font")
567 .set_local_name(_("Font"))
568 .set_description(_("Filename of the font to use"))
569 .set_hint("filename")
574 ret.push_back(ParamDesc("use_kerning")
575 .set_local_name(_("Kerning"))
576 .set_description(_("Enables/Disables font kerning (If the font supports it)"))
579 ret.push_back(ParamDesc("grid_fit")
580 .set_local_name(_("Sharpen Edges"))
581 .set_description(_("Turn this off if you are going to be animating the text"))
583 ret.push_back(ParamDesc("invert")
584 .set_local_name(_("Invert"))
600 lyr_freetype::get_color(Context context, const synfig::Point &pos)const
603 const_cast<lyr_freetype*>(this)->sync();
606 return context.get_color(pos);
607 return context.get_color(pos);
611 lyr_freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
613 static synfig::RecMutex freetype_mutex;
616 const_cast<lyr_freetype*>(this)->sync();
622 Vector size(lyr_freetype::size*2);
624 if(!context.accelerated_render(surface,quality,renddesc,cb))
627 if(is_disabled() || text.empty())
630 // If there is no font loaded, just bail
633 if(cb)cb->warning(string("lyr_freetype:")+_("No face loaded, no text will be rendered."));
637 String text(lyr_freetype::text);
638 if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
640 text=basename(get_canvas()->get_file_name());
643 // Width and Height of a pixel
644 Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
645 Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
647 // Calculate character width and height
648 int w=abs(round_to_int(size[0]*pw));
649 int h=abs(round_to_int(size[1]*ph));
651 //int bx=(int)((pos[0]-renddesc.get_tl()[0])*pw*64+0.5);
652 //int by=(int)((pos[1]-renddesc.get_tl()[1])*ph*64+0.5);
656 // If the font is the size of a pixel, don't bother rendering any text
659 if(cb)cb->warning(string("lyr_freetype:")+_("Text too small, no text will be rendered."));
663 synfig::RecMutex::Lock lock(freetype_mutex);
665 #define CHAR_RESOLUTION (64)
666 error = FT_Set_Char_Size(
667 face, // handle to face object
668 (int)CHAR_RESOLUTION, // char_width in 1/64th of points
669 (int)CHAR_RESOLUTION, // char_height in 1/64th of points
670 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)), // horizontal device resolution
671 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) ); // vertical device resolution
673 // Here is where we can compensate for the
674 // error in freetype's rendering engine.
675 const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
676 const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
677 //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
678 const float compress(lyr_freetype::compress*xerror);
679 const float vcompress(lyr_freetype::vcompress*yerror);
683 if(cb)cb->warning(string("lyr_freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
686 FT_GlyphSlot slot = face->glyph; // a small shortcut
687 FT_UInt glyph_index(0);
691 std::list<TextLine> lines;
694 -- ** -- CREATE GLYPHS -------------------------------------------------------
697 lines.push_front(TextLine());
698 string::const_iterator iter;
699 for (iter=text.begin(); iter!=text.end(); ++iter)
704 lines.push_front(TextLine());
713 glyph_index = FT_Get_Char_Index( face, ' ' );
716 glyph_index = FT_Get_Char_Index( face, *iter );
718 // retrieve kerning distance and move pen position
719 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
724 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
726 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
730 bx += round_to_int(delta.x*compress);
731 by += round_to_int(delta.y*compress);
742 // store current pen position
743 curr_glyph.pos.x = bx;
744 curr_glyph.pos.y = by;
746 // load glyph image into the slot. DO NOT RENDER IT !!
748 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
750 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
751 if (error) continue; // ignore errors, jump to next glyph
753 // extract glyph image and store it in our table
754 error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
755 if (error) continue; // ignore errors, jump to next glyph
757 // record current glyph index
758 previous = glyph_index;
760 // Update the line width
761 lines.front().width=bx+slot->advance.x;
763 // increment pen position
765 bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
767 bx += round_to_int(slot->advance.x*compress*multiplier);
769 //bx += round_to_int(slot->advance.x*compress*multiplier);
770 //by += round_to_int(slot->advance.y*compress);
771 by += slot->advance.y*multiplier;
773 lines.front().glyph_table.push_back(curr_glyph);
778 //float string_height;
779 //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
781 //int string_height=face->size->metrics.ascender;
782 //#define METRICS_SCALE_ONE (65536.0f)
783 #define METRICS_SCALE_ONE ((float)(1<<16))
786 line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
789 string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
790 //synfig::info("string_height=%d",string_height);
791 //synfig::info("line_height=%f",line_height);
794 -- ** -- RENDER THE GLYPHS ---------------------------------------------------
798 Surface *src_surface;
805 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
807 surface->fill(color,pen,src_.get_w(),src_.get_h());
813 std::list<TextLine>::iterator iter;
815 for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
817 bx=round_to_int((pos[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
818 by=round_to_int((pos[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION+(1.0-orient[1])*string_height-line_height*curr_line);
819 //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));
820 //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
822 std::vector<Glyph>::iterator iter2;
823 for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
825 FT_Glyph image(iter2->glyph);
829 pen.x = bx + iter2->pos.x;
830 pen.y = by + iter2->pos.y;
832 //synfig::info("GLYPH: pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
834 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
835 if(error) { FT_Done_Glyph( image ); continue; }
837 bit = (FT_BitmapGlyph)image;
839 for(v=0;v<bit->bitmap.rows;v++)
840 for(u=0;u<bit->bitmap.width;u++)
842 int x=u+((pen.x+32)>>6)+ bit->left;
843 int y=v+((pen.y+32)>>6)- bit->top;
846 y<surface->get_h() &&
849 float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
851 myamount=1.0f-myamount;
852 (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
856 FT_Done_Glyph( image );
858 //iter->clear_and_free();
867 lyr_freetype::get_bounding_rect()const
870 const_cast<lyr_freetype*>(this)->sync();
871 // if(!is_disabled())
872 return synfig::Rect::full_plane();