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
10 ** Copyright (c) 2007 Chris Moore
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.
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.
23 ** === N O T E S ===========================================================
25 ** ========================================================================= */
27 /* === H E A D E R S ======================================================= */
37 #ifdef WITH_FONTCONFIG
38 #include <fontconfig/fontconfig.h>
41 #include "lyr_freetype.h"
48 using namespace synfig;
50 /* === M A C R O S ========================================================= */
52 #define MAX_GLYPHS 2000
54 #define PANGO_STYLE_NORMAL (0)
55 #define PANGO_STYLE_OBLIQUE (1)
56 #define PANGO_STYLE_ITALIC (2)
59 #define WEIGHT_NORMAL (400)
60 #define WEIGHT_BOLD (700)
62 /* === G L O B A L S ======================================================= */
64 SYNFIG_LAYER_INIT(Layer_Freetype);
65 SYNFIG_LAYER_SET_NAME(Layer_Freetype,"text");
66 SYNFIG_LAYER_SET_LOCAL_NAME(Layer_Freetype,_("Text"));
67 SYNFIG_LAYER_SET_CATEGORY(Layer_Freetype,_("Other"));
68 SYNFIG_LAYER_SET_VERSION(Layer_Freetype,"0.2");
69 SYNFIG_LAYER_SET_CVS_ID(Layer_Freetype,"$Id$");
71 /* === P R O C E D U R E S ================================================= */
75 if(glyph)FT_Done_Glyph(glyph);
79 TextLine::clear_and_free()
81 std::vector<Glyph>::iterator iter;
82 for(iter=glyph_table.begin();iter!=glyph_table.end();++iter)
84 if(iter->glyph)FT_Done_Glyph(iter->glyph);
90 /* === M E T H O D S ======================================================= */
92 Layer_Freetype::Layer_Freetype()
96 size=Vector(0.25,0.25);
100 orient=Vector(0.5,0.5);
103 weight=WEIGHT_NORMAL;
104 style=PANGO_STYLE_NORMAL;
109 set_blend_method(Color::BLEND_COMPOSITE);
112 new_font(family,style,weight);
117 Layer_Freetype::~Layer_Freetype()
124 Layer_Freetype::new_font(const synfig::String &family, int style, int weight)
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)
135 new_font_("sans serif",PANGO_STYLE_NORMAL,WEIGHT_NORMAL);
139 Layer_Freetype::new_font_(const synfig::String &font_fam_, int style, int weight)
141 synfig::String font_fam(font_fam_);
143 if(new_face(font_fam_))
147 for(unsigned int i=0;i<font_fam.size();i++)font_fam[i]=tolower(font_fam[i]);
150 if(font_fam=="arial black")
152 if(new_face("ariblk"))
156 font_fam="sans serif";
158 if(font_fam=="sans serif" || font_fam=="arial")
160 String arial("arial");
161 if(weight>WEIGHT_NORMAL)
163 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
166 if(weight>WEIGHT_NORMAL) arial+='d';
171 if(new_face("Helvetica RO"))
176 if(font_fam=="comic" || font_fam=="comic sans")
178 String filename("comic");
179 if(weight>WEIGHT_NORMAL)
181 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
183 else if(weight>WEIGHT_NORMAL) filename+='d';
185 if(new_face(filename))
189 if(font_fam=="courier" || font_fam=="courier new")
191 String filename("cour");
192 if(weight>WEIGHT_NORMAL)
194 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
196 else if(weight>WEIGHT_NORMAL) filename+='d';
198 if(new_face(filename))
202 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman")
204 String filename("times");
205 if(weight>WEIGHT_NORMAL)
207 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
209 else if(weight>WEIGHT_NORMAL) filename+='d';
211 if(new_face(filename))
215 if(font_fam=="trebuchet")
217 String filename("trebuc");
218 if(weight>WEIGHT_NORMAL)
220 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
223 if(weight<=WEIGHT_NORMAL) filename+='t';
225 else if(weight>WEIGHT_NORMAL) filename+='d';
227 if(new_face(filename))
232 if(font_fam=="sans serif" || font_fam=="luxi sans")
235 String luxi("luxis");
236 if(weight>WEIGHT_NORMAL)
240 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
247 if(new_face("arial"))
249 if(new_face("Arial"))
252 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman" || font_fam=="luxi serif")
255 String luxi("luxir");
256 if(weight>WEIGHT_NORMAL)
260 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
266 if(new_face("Times New Roman"))
268 if(new_face("Times"))
274 String luxi("luxim");
275 if(weight>WEIGHT_NORMAL)
279 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
286 if(new_face("Times New Roman"))
288 if(new_face("Times"))
292 return new_face(font_fam_) || new_face(font_fam);
297 #ifdef USE_MAC_FT_FUNCS
298 void fss2path(char *path, FSSpec *fss)
300 int l; //fss->name contains name of last item in path
301 for(l=0; l<(fss->name[0]); l++) path[l] = fss->name[l + 1];
304 if(fss->parID != fsRtParID) //path is more than just a volume name
309 pb.dirInfo.ioNamePtr = fss->name;
310 pb.dirInfo.ioVRefNum = fss->vRefNum;
311 pb.dirInfo.ioDrParID = fss->parID;
314 pb.dirInfo.ioFDirIndex = -1; //get parent directory name
315 pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
316 if(PBGetCatInfoSync(&pb) != noErr) break;
318 len = fss->name[0] + 1;
319 for(i=l; i>=0; i--) path[i + len] = path[i];
320 for(i=1; i<len; i++) path[i - 1] = fss->name[i]; //add to start of path
323 } while(pb.dirInfo.ioDrDirID != fsRtDirID); //while more directory levels
329 Layer_Freetype::new_face(const String &newfont)
332 FT_Long face_index=0;
334 // If we are already loaded, don't bother reloading.
335 if(face && font==newfont)
344 error=FT_New_Face(ft_library,newfont.c_str(),face_index,&face);
345 if(error)error=FT_New_Face(ft_library,(newfont+".ttf").c_str(),face_index,&face);
349 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPARATOR+newfont).c_str(),face_index,&face);
350 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPARATOR+newfont+".ttf").c_str(),face_index,&face);
353 #ifdef USE_MAC_FT_FUNCS
357 error=FT_GetFile_From_Mac_Name(newfont.c_str(),&fs_spec,&face_index);
361 fss2path(filename,&fs_spec);
362 //FSSpecToNativePathName(fs_spec,filename,sizeof(filename)-1, 0);
364 error=FT_New_Face(ft_library, filename, face_index,&face);
365 //error=FT_New_Face_From_FSSpec(ft_library, &fs_spec, face_index,&face);
366 synfig::info(__FILE__":%d: \"%s\" (%s) -- ft_error=%d",__LINE__,newfont.c_str(),filename,error);
370 synfig::info(__FILE__":%d: \"%s\" -- ft_error=%d",__LINE__,newfont.c_str(),error);
371 // Unable to generate fs_spec
377 #ifdef WITH_FONTCONFIG
384 synfig::warning("Layer_Freetype: fontconfig: %s",_("unable to initialise"));
387 FcPattern* pat = FcNameParse((FcChar8 *) newfont.c_str());
388 FcConfigSubstitute(0, pat, FcMatchPattern);
389 FcDefaultSubstitute(pat);
391 fs = FcFontSetCreate();
392 match = FcFontMatch(0, pat, &result);
394 FcFontSetAdd(fs, match);
396 FcPatternDestroy(pat);
399 if( FcPatternGetString (fs->fonts[0], FC_FILE, 0, &file) == FcResultMatch )
400 error=FT_New_Face(ft_library,(const char*)file,face_index,&face);
401 FcFontSetDestroy(fs);
403 synfig::warning("Layer_Freetype: fontconfig: %s",_("empty font set"));
409 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont).c_str(),face_index,&face);
410 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont+".ttf").c_str(),face_index,&face);
414 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont).c_str(),face_index,&face);
415 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
416 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
418 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont).c_str(),face_index,&face);
419 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
420 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
423 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont).c_str(),face_index,&face);
424 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont+".ttf").c_str(),face_index,&face);
426 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont).c_str(),face_index,&face);
427 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
429 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont).c_str(),face_index,&face);
430 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont+".ttf").c_str(),face_index,&face);
432 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont).c_str(),face_index,&face);
433 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
438 //synfig::error(strprintf("Layer_Freetype:%s (err=%d)",_("Unable to open face."),error));
449 Layer_Freetype::set_param(const String & param, const ValueBase &value)
451 Mutex::Lock lock(mutex);
453 if(param=="font" && value.same_type_as(font))
455 new_font(etl::basename(value.get(font)),style,weight);
456 family=etl::basename(value.get(font));
460 IMPORT_PLUS(family,new_font(family,style,weight));
461 IMPORT_PLUS(weight,new_font(family,style,weight));
462 IMPORT_PLUS(style,new_font(family,style,weight));
463 IMPORT_PLUS(size, if(old_version){size/=2.0;} needs_sync_=true );
464 IMPORT_PLUS(text,needs_sync_=true);
465 IMPORT_PLUS(pos,needs_sync_=true);
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);
474 return Layer_Composite::set_param(param,value);
478 Layer_Freetype::get_param(const String& param)const
498 return Layer_Composite::get_param(param);
502 Layer_Freetype::get_param_vocab(void)const
504 Layer::Vocab ret(Layer_Composite::get_param_vocab());
506 ret.push_back(ParamDesc("text")
507 .set_local_name(_("Text"))
508 .set_description(_("Text to Render"))
509 .set_hint("paragraph")
512 ret.push_back(ParamDesc("color")
513 .set_local_name(_("Color"))
514 .set_description(_("Color of the text"))
517 ret.push_back(ParamDesc("family")
518 .set_local_name(_("Font Family"))
519 .set_hint("font_family")
522 ret.push_back(ParamDesc("style")
523 .set_local_name(_("Style"))
525 .add_enum_value(PANGO_STYLE_NORMAL, "normal" ,_("Normal"))
526 .add_enum_value(PANGO_STYLE_OBLIQUE, "oblique" ,_("Oblique"))
527 .add_enum_value(PANGO_STYLE_ITALIC, "italic" ,_("Italic"))
530 ret.push_back(ParamDesc("weight")
531 .set_local_name(_("Weight"))
533 .add_enum_value(200, "ultralight" ,_("Ultralight"))
534 .add_enum_value(300, "light" ,_("light"))
535 .add_enum_value(400, "normal" ,_("Normal"))
536 .add_enum_value(700, "bold" ,_("Bold"))
537 .add_enum_value(800, "ultrabold" ,_("Ultrabold"))
538 .add_enum_value(900, "heavy" ,_("Heavy"))
540 ret.push_back(ParamDesc("compress")
541 .set_local_name(_("Horizontal Spacing"))
542 .set_description(_("Describes how close glyphs are horizontally"))
545 ret.push_back(ParamDesc("vcompress")
546 .set_local_name(_("Vertical Spacing"))
547 .set_description(_("Describes how close lines of text are vertically"))
550 ret.push_back(ParamDesc("size")
551 .set_local_name(_("Size"))
552 .set_description(_("Size of the text"))
558 ret.push_back(ParamDesc("orient")
559 .set_local_name(_("Orientation"))
560 .set_description(_("Text Orientation"))
561 .set_invisible_duck()
564 ret.push_back(ParamDesc("pos")
565 .set_local_name(_("Position"))
566 .set_description(_("Text Position"))
569 ret.push_back(ParamDesc("font")
570 .set_local_name(_("Font"))
571 .set_description(_("Filename of the font to use"))
572 .set_hint("filename")
577 ret.push_back(ParamDesc("use_kerning")
578 .set_local_name(_("Kerning"))
579 .set_description(_("Enables/Disables font kerning (If the font supports it)"))
582 ret.push_back(ParamDesc("grid_fit")
583 .set_local_name(_("Sharpen Edges"))
584 .set_description(_("Turn this off if you are going to be animating the text"))
586 ret.push_back(ParamDesc("invert")
587 .set_local_name(_("Invert"))
593 Layer_Freetype::sync()
603 Layer_Freetype::get_color(Context context, const synfig::Point &pos)const
606 const_cast<Layer_Freetype*>(this)->sync();
609 return context.get_color(pos);
610 return context.get_color(pos);
614 Layer_Freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
616 static synfig::RecMutex freetype_mutex;
619 const_cast<Layer_Freetype*>(this)->sync();
625 Vector size(Layer_Freetype::size*2);
627 if(!context.accelerated_render(surface,quality,renddesc,cb))
630 if(is_disabled() || text.empty())
633 // If there is no font loaded, just bail
636 if(cb)cb->warning(string("Layer_Freetype:")+_("No face loaded, no text will be rendered."));
640 String text(Layer_Freetype::text);
641 if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
643 text=basename(get_canvas()->get_file_name());
646 // Width and Height of a pixel
647 Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
648 Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
650 // Calculate character width and height
651 int w=abs(round_to_int(size[0]*pw));
652 int h=abs(round_to_int(size[1]*ph));
654 //int bx=(int)((pos[0]-renddesc.get_tl()[0])*pw*64+0.5);
655 //int by=(int)((pos[1]-renddesc.get_tl()[1])*ph*64+0.5);
659 // If the font is the size of a pixel, don't bother rendering any text
662 if(cb)cb->warning(string("Layer_Freetype:")+_("Text too small, no text will be rendered."));
666 synfig::RecMutex::Lock lock(freetype_mutex);
668 #define CHAR_RESOLUTION (64)
669 error = FT_Set_Char_Size(
670 face, // handle to face object
671 (int)CHAR_RESOLUTION, // char_width in 1/64th of points
672 (int)CHAR_RESOLUTION, // char_height in 1/64th of points
673 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)), // horizontal device resolution
674 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) ); // vertical device resolution
676 // Here is where we can compensate for the
677 // error in freetype's rendering engine.
678 const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
679 const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
680 //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
681 const float compress(Layer_Freetype::compress*xerror);
682 const float vcompress(Layer_Freetype::vcompress*yerror);
686 if(cb)cb->warning(string("Layer_Freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
689 FT_GlyphSlot slot = face->glyph; // a small shortcut
690 FT_UInt glyph_index(0);
694 std::list<TextLine> lines;
697 -- ** -- CREATE GLYPHS -------------------------------------------------------
700 lines.push_front(TextLine());
701 string::const_iterator iter;
702 for (iter=text.begin(); iter!=text.end(); ++iter)
707 lines.push_front(TextLine());
716 glyph_index = FT_Get_Char_Index( face, ' ' );
719 glyph_index = FT_Get_Char_Index( face, *iter );
721 // retrieve kerning distance and move pen position
722 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
727 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
729 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
733 bx += round_to_int(delta.x*compress);
734 by += round_to_int(delta.y*compress);
745 // store current pen position
746 curr_glyph.pos.x = bx;
747 curr_glyph.pos.y = by;
749 // load glyph image into the slot. DO NOT RENDER IT !!
751 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
753 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
754 if (error) continue; // ignore errors, jump to next glyph
756 // extract glyph image and store it in our table
757 error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
758 if (error) continue; // ignore errors, jump to next glyph
760 // record current glyph index
761 previous = glyph_index;
763 // Update the line width
764 lines.front().width=bx+slot->advance.x;
766 // increment pen position
768 bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
770 bx += round_to_int(slot->advance.x*compress*multiplier);
772 //bx += round_to_int(slot->advance.x*compress*multiplier);
773 //by += round_to_int(slot->advance.y*compress);
774 by += slot->advance.y*multiplier;
776 lines.front().glyph_table.push_back(curr_glyph);
781 //float string_height;
782 //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
784 //int string_height=face->size->metrics.ascender;
785 //#define METRICS_SCALE_ONE (65536.0f)
786 #define METRICS_SCALE_ONE ((float)(1<<16))
789 line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
792 string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
793 //synfig::info("string_height=%d",string_height);
794 //synfig::info("line_height=%f",line_height);
797 -- ** -- RENDER THE GLYPHS ---------------------------------------------------
801 Surface *src_surface;
808 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
810 surface->fill(color,pen,src_.get_w(),src_.get_h());
816 std::list<TextLine>::iterator iter;
818 for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
820 bx=round_to_int((pos[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
821 by=round_to_int((pos[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION+(1.0-orient[1])*string_height-line_height*curr_line);
822 //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));
823 //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
825 std::vector<Glyph>::iterator iter2;
826 for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
828 FT_Glyph image(iter2->glyph);
832 pen.x = bx + iter2->pos.x;
833 pen.y = by + iter2->pos.y;
835 //synfig::info("GLYPH: pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
837 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
838 if(error) { FT_Done_Glyph( image ); continue; }
840 bit = (FT_BitmapGlyph)image;
842 for(v=0;v<bit->bitmap.rows;v++)
843 for(u=0;u<bit->bitmap.width;u++)
845 int x=u+((pen.x+32)>>6)+ bit->left;
846 int y=v+((pen.y+32)>>6)- bit->top;
849 y<surface->get_h() &&
852 float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
854 myamount=1.0f-myamount;
855 (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
859 FT_Done_Glyph( image );
861 //iter->clear_and_free();
870 Layer_Freetype::get_bounding_rect()const
873 const_cast<Layer_Freetype*>(this)->sync();
874 // if(!is_disabled())
875 return synfig::Rect::full_plane();