1 /*! ========================================================================
4 ** $Id: lyr_freetype.cpp,v 1.5 2005/01/24 05:00:18 darco Exp $
6 ** Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
8 ** This package is free software; you can redistribute it and/or
9 ** modify it under the terms of the GNU General Public License as
10 ** published by the Free Software Foundation; either version 2 of
11 ** the License, or (at your option) any later version.
13 ** This package is distributed in the hope that it will be useful,
14 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ** General Public License for more details.
18 ** === N O T E S ===========================================================
20 ** ========================================================================= */
22 /* === H E A D E R S ======================================================= */
33 #include "lyr_freetype.h"
40 using namespace synfig;
42 /* === M A C R O S ========================================================= */
44 #define MAX_GLYPHS 2000
46 #define PANGO_STYLE_NORMAL (0)
47 #define PANGO_STYLE_OBLIQUE (1)
48 #define PANGO_STYLE_ITALIC (2)
51 #define WEIGHT_NORMAL (400)
52 #define WEIGHT_BOLD (700)
54 /* === G L O B A L S ======================================================= */
56 SYNFIG_LAYER_INIT(lyr_freetype);
57 SYNFIG_LAYER_SET_NAME(lyr_freetype,"text");
58 SYNFIG_LAYER_SET_LOCAL_NAME(lyr_freetype,_("Simple Text"));
59 SYNFIG_LAYER_SET_CATEGORY(lyr_freetype,_("Typography"));
60 SYNFIG_LAYER_SET_VERSION(lyr_freetype,"0.2");
61 SYNFIG_LAYER_SET_CVS_ID(lyr_freetype,"$Id: lyr_freetype.cpp,v 1.5 2005/01/24 05:00:18 darco Exp $");
63 /* === P R O C E D U R E S ================================================= */
67 if(glyph)FT_Done_Glyph(glyph);
71 TextLine::clear_and_free()
73 std::vector<Glyph>::iterator iter;
74 for(iter=glyph_table.begin();iter!=glyph_table.end();++iter)
76 if(iter->glyph)FT_Done_Glyph(iter->glyph);
82 /* === M E T H O D S ======================================================= */
84 lyr_freetype::lyr_freetype()
88 size=Vector(0.25,0.25);
92 orient=Vector(0.5,0.5);
96 style=PANGO_STYLE_NORMAL;
101 set_blend_method(Color::BLEND_COMPOSITE);
104 new_font(family,style,weight);
109 lyr_freetype::~lyr_freetype()
116 lyr_freetype::new_font(const synfig::String &family, int style, int weight)
119 !new_font_(family,style,weight) &&
120 !new_font_(family,style,WEIGHT_NORMAL) &&
121 !new_font_(family,PANGO_STYLE_NORMAL,weight) &&
122 !new_font_(family,PANGO_STYLE_NORMAL,WEIGHT_NORMAL) &&
123 !new_font_("sans serif",style,weight) &&
124 !new_font_("sans serif",style,WEIGHT_NORMAL) &&
125 !new_font_("sans serif",PANGO_STYLE_NORMAL,weight)
127 new_font_("sans serif",PANGO_STYLE_NORMAL,WEIGHT_NORMAL);
131 lyr_freetype::new_font_(const synfig::String &font_fam_, int style, int weight)
133 synfig::String font_fam(font_fam_);
135 if(new_face(font_fam_))
139 for(unsigned int i=0;i<font_fam.size();i++)font_fam[i]=tolower(font_fam[i]);
142 if(font_fam=="arial black")
144 if(new_face("ariblk"))
148 font_fam="sans serif";
150 if(font_fam=="sans serif" || font_fam=="arial")
152 String arial("arial");
153 if(weight>WEIGHT_NORMAL)
155 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
158 if(weight>WEIGHT_NORMAL) arial+='d';
163 if(new_face("Helvetica RO"))
168 if(font_fam=="comic" || font_fam=="comic sans")
170 String filename("comic");
171 if(weight>WEIGHT_NORMAL)
173 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
175 else if(weight>WEIGHT_NORMAL) filename+='d';
177 if(new_face(filename))
181 if(font_fam=="courier" || font_fam=="courier new")
183 String filename("cour");
184 if(weight>WEIGHT_NORMAL)
186 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
188 else if(weight>WEIGHT_NORMAL) filename+='d';
190 if(new_face(filename))
194 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman")
196 String filename("times");
197 if(weight>WEIGHT_NORMAL)
199 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
201 else if(weight>WEIGHT_NORMAL) filename+='d';
203 if(new_face(filename))
207 if(font_fam=="trebuchet")
209 String filename("trebuc");
210 if(weight>WEIGHT_NORMAL)
212 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
215 if(weight<=WEIGHT_NORMAL) filename+='t';
217 else if(weight>WEIGHT_NORMAL) filename+='d';
219 if(new_face(filename))
224 if(font_fam=="sans serif" || font_fam=="luxi sans")
227 String luxi("luxis");
228 if(weight>WEIGHT_NORMAL)
232 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
239 if(new_face("arial"))
241 if(new_face("Arial"))
244 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman" || font_fam=="luxi serif")
247 String luxi("luxir");
248 if(weight>WEIGHT_NORMAL)
252 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
258 if(new_face("Times New Roman"))
260 if(new_face("Times"))
266 String luxi("luxim");
267 if(weight>WEIGHT_NORMAL)
271 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
278 if(new_face("Times New Roman"))
280 if(new_face("Times"))
284 return new_face(font_fam_) || new_face(font_fam);
289 #ifdef USE_MAC_FT_FUNCS
290 void fss2path(char *path, FSSpec *fss)
292 int l; //fss->name contains name of last item in path
293 for(l=0; l<(fss->name[0]); l++) path[l] = fss->name[l + 1];
296 if(fss->parID != fsRtParID) //path is more than just a volume name
301 pb.dirInfo.ioNamePtr = fss->name;
302 pb.dirInfo.ioVRefNum = fss->vRefNum;
303 pb.dirInfo.ioDrParID = fss->parID;
306 pb.dirInfo.ioFDirIndex = -1; //get parent directory name
307 pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
308 if(PBGetCatInfoSync(&pb) != noErr) break;
310 len = fss->name[0] + 1;
311 for(i=l; i>=0; i--) path[i + len] = path[i];
312 for(i=1; i<len; i++) path[i - 1] = fss->name[i]; //add to start of path
315 } while(pb.dirInfo.ioDrDirID != fsRtDirID); //while more directory levels
321 lyr_freetype::new_face(const String &newfont)
324 FT_Long face_index=0;
326 // If we are already loaded, don't bother reloading.
327 if(face && font==newfont)
336 error=FT_New_Face(ft_library,newfont.c_str(),face_index,&face);
337 if(error)error=FT_New_Face(ft_library,(newfont+".ttf").c_str(),face_index,&face);
341 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont).c_str(),face_index,&face);
342 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont+".ttf").c_str(),face_index,&face);
345 #ifdef USE_MAC_FT_FUNCS
349 error=FT_GetFile_From_Mac_Name(newfont.c_str(),&fs_spec,&face_index);
353 fss2path(filename,&fs_spec);
354 //FSSpecToNativePathName(fs_spec,filename,sizeof(filename)-1, 0);
356 error=FT_New_Face(ft_library, filename, face_index,&face);
357 //error=FT_New_Face_From_FSSpec(ft_library, &fs_spec, face_index,&face);
358 synfig::info(__FILE__":%d: \"%s\" (%s) -- ft_error=%d",__LINE__,newfont.c_str(),filename,error);
362 synfig::info(__FILE__":%d: \"%s\" -- ft_error=%d",__LINE__,newfont.c_str(),error);
363 // Unable to generate fs_spec
370 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont).c_str(),face_index,&face);
371 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont+".ttf").c_str(),face_index,&face);
375 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont).c_str(),face_index,&face);
376 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
377 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
379 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont).c_str(),face_index,&face);
380 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
381 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
384 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont).c_str(),face_index,&face);
385 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont+".ttf").c_str(),face_index,&face);
387 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont).c_str(),face_index,&face);
388 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
390 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont).c_str(),face_index,&face);
391 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont+".ttf").c_str(),face_index,&face);
393 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont).c_str(),face_index,&face);
394 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
399 //synfig::error(strprintf("lyr_freetype:%s (err=%d)",_("Unable to open face."),error));
410 lyr_freetype::set_param(const String & param, const ValueBase &value)
412 Mutex::Lock lock(mutex);
414 if(param=="font" && value.same_as(font))
416 new_font(etl::basename(value.get(font)),style,weight);
417 family=etl::basename(value.get(font));
421 IMPORT_PLUS(family,new_font(family,style,weight));
422 IMPORT_PLUS(weight,new_font(family,style,weight));
423 IMPORT_PLUS(style,new_font(family,style,weight));
424 IMPORT_PLUS(size, if(old_version){size/=2.0;} needs_sync_=true );
425 IMPORT_PLUS(text,needs_sync_=true);
426 IMPORT_PLUS(pos,needs_sync_=true);
429 IMPORT_PLUS(orient,needs_sync_=true);
430 IMPORT_PLUS(compress,needs_sync_=true);
431 IMPORT_PLUS(vcompress,needs_sync_=true);
432 IMPORT_PLUS(use_kerning,needs_sync_=true);
433 IMPORT_PLUS(grid_fit,needs_sync_=true);
435 return Layer_Composite::set_param(param,value);
439 lyr_freetype::get_param(const String& param)const
459 return Layer_Composite::get_param(param);
463 lyr_freetype::get_param_vocab(void)const
465 Layer::Vocab ret(Layer_Composite::get_param_vocab());
467 ret.push_back(ParamDesc("text")
468 .set_local_name(_("Text"))
469 .set_description(_("Text to Render"))
470 .set_hint("paragraph")
473 ret.push_back(ParamDesc("color")
474 .set_local_name(_("Color"))
475 .set_description(_("Color of the text"))
478 ret.push_back(ParamDesc("family")
479 .set_local_name(_("Font Family"))
480 .set_hint("font_family")
483 ret.push_back(ParamDesc("style")
484 .set_local_name(_("Style"))
486 .add_enum_value(PANGO_STYLE_NORMAL, "normal" ,_("Normal"))
487 .add_enum_value(PANGO_STYLE_OBLIQUE, "oblique" ,_("Oblique"))
488 .add_enum_value(PANGO_STYLE_ITALIC, "italic" ,_("Italic"))
491 ret.push_back(ParamDesc("weight")
492 .set_local_name(_("Weight"))
494 .add_enum_value(200, "ultralight" ,_("Ultralight"))
495 .add_enum_value(300, "light" ,_("light"))
496 .add_enum_value(400, "normal" ,_("Normal"))
497 .add_enum_value(700, "bold" ,_("Bold"))
498 .add_enum_value(800, "ultrabold" ,_("Ultrabold"))
499 .add_enum_value(900, "heavy" ,_("Heavy"))
501 ret.push_back(ParamDesc("compress")
502 .set_local_name(_("Hozontal Spacing"))
503 .set_description(_("Describes how close glyphs are horizontally"))
506 ret.push_back(ParamDesc("vcompress")
507 .set_local_name(_("Vertical Spacing"))
508 .set_description(_("Describes how close lines of text are vertically"))
511 ret.push_back(ParamDesc("size")
512 .set_local_name(_("Size"))
513 .set_description(_("Size of the text"))
519 ret.push_back(ParamDesc("orient")
520 .set_local_name(_("Orientation"))
521 .set_description(_("Text Orientation"))
522 .set_invisible_duck()
525 ret.push_back(ParamDesc("pos")
526 .set_local_name(_("Position"))
527 .set_description(_("Text Position"))
530 ret.push_back(ParamDesc("font")
531 .set_local_name(_("Font"))
532 .set_description(_("Filename of the font to use"))
533 .set_hint("filename")
538 ret.push_back(ParamDesc("use_kerning")
539 .set_local_name(_("Kerning"))
540 .set_description(_("Enables/Disables font kerning (If the font supports it)"))
543 ret.push_back(ParamDesc("grid_fit")
544 .set_local_name(_("Sharpen Edges"))
545 .set_description(_("Turn this off if you are going to be animating the text"))
547 ret.push_back(ParamDesc("invert")
548 .set_local_name(_("Invert"))
564 lyr_freetype::get_color(Context context, const synfig::Point &pos)const
567 const_cast<lyr_freetype*>(this)->sync();
570 return context.get_color(pos);
571 return context.get_color(pos);
575 lyr_freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
577 static synfig::RecMutex freetype_mutex;
580 const_cast<lyr_freetype*>(this)->sync();
586 Vector size(lyr_freetype::size*2);
588 if(!context.accelerated_render(surface,quality,renddesc,cb))
591 if(is_disabled() || text.empty())
594 // If there is no font loaded, just bail
597 if(cb)cb->warning(string("lyr_freetype:")+_("No face loaded, no text will be rendered."));
601 String text(lyr_freetype::text);
602 if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
604 text=basename(get_canvas()->get_file_name());
607 // Width and Height of a pixel
608 Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
609 Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
611 // Calculate character width and height
612 int w=abs(round_to_int(size[0]*pw));
613 int h=abs(round_to_int(size[1]*ph));
615 //int bx=(int)((pos[0]-renddesc.get_tl()[0])*pw*64+0.5);
616 //int by=(int)((pos[1]-renddesc.get_tl()[1])*ph*64+0.5);
620 // If the font is the size of a pixel, don't bother rendering any text
623 if(cb)cb->warning(string("lyr_freetype:")+_("Text too small, no text will be rendered."));
627 synfig::RecMutex::Lock lock(freetype_mutex);
629 #define CHAR_RESOLUTION (64)
630 error = FT_Set_Char_Size(
631 face, // handle to face object
632 (int)CHAR_RESOLUTION, // char_width in 1/64th of points
633 (int)CHAR_RESOLUTION, // char_height in 1/64th of points
634 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)), // horizontal device resolution
635 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) ); // vertical device resolution
637 // Here is where we can compensate for the
638 // error in freetype's rendering engine.
639 const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
640 const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
641 //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
642 const float compress(lyr_freetype::compress*xerror);
643 const float vcompress(lyr_freetype::vcompress*yerror);
647 if(cb)cb->error(string("lyr_freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
651 FT_GlyphSlot slot = face->glyph; // a small shortcut
652 FT_UInt glyph_index(0);
656 std::list<TextLine> lines;
659 -- ** -- CREATE GLYPHS -------------------------------------------------------
662 lines.push_front(TextLine());
663 string::const_iterator iter;
664 for (iter=text.begin(); iter!=text.end(); ++iter)
669 lines.push_front(TextLine());
678 glyph_index = FT_Get_Char_Index( face, ' ' );
681 glyph_index = FT_Get_Char_Index( face, *iter );
683 // retrieve kerning distance and move pen position
684 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
689 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
691 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
695 bx += round_to_int(delta.x*compress);
696 by += round_to_int(delta.y*compress);
707 // store current pen position
708 curr_glyph.pos.x = bx;
709 curr_glyph.pos.y = by;
711 // load glyph image into the slot. DO NOT RENDER IT !!
713 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
715 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
716 if (error) continue; // ignore errors, jump to next glyph
718 // extract glyph image and store it in our table
719 error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
720 if (error) continue; // ignore errors, jump to next glyph
722 // record current glyph index
723 previous = glyph_index;
725 // Update the line width
726 lines.front().width=bx+slot->advance.x;
728 // increment pen position
730 bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
732 bx += round_to_int(slot->advance.x*compress*multiplier);
734 //bx += round_to_int(slot->advance.x*compress*multiplier);
735 //by += round_to_int(slot->advance.y*compress);
736 by += slot->advance.y*multiplier;
738 lines.front().glyph_table.push_back(curr_glyph);
743 //float string_height;
744 //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
746 //int string_height=face->size->metrics.ascender;
747 //#define METRICS_SCALE_ONE (65536.0f)
748 #define METRICS_SCALE_ONE ((float)(1<<16))
751 line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
754 string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
755 //synfig::info("string_height=%d",string_height);
756 //synfig::info("line_height=%f",line_height);
759 -- ** -- RENDER THE GLYPHS ---------------------------------------------------
763 Surface *src_surface;
770 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
772 surface->fill(color,pen,src_.get_w(),src_.get_h());
778 std::list<TextLine>::iterator iter;
780 for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
782 bx=round_to_int((pos[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
783 by=round_to_int((pos[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION+(1.0-orient[1])*string_height-line_height*curr_line);
784 //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));
785 //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
787 std::vector<Glyph>::iterator iter2;
788 for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
790 FT_Glyph image(iter2->glyph);
794 pen.x = bx + iter2->pos.x;
795 pen.y = by + iter2->pos.y;
797 //synfig::info("GLYPH: pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
799 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
800 if(error) { FT_Done_Glyph( image ); continue; }
802 bit = (FT_BitmapGlyph)image;
804 for(v=0;v<bit->bitmap.rows;v++)
805 for(u=0;u<bit->bitmap.width;u++)
807 int x=u+((pen.x+32)>>6)+ bit->left;
808 int y=v+((pen.y+32)>>6)- bit->top;
811 y<surface->get_h() &&
814 float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
816 myamount=1.0f-myamount;
817 (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
821 FT_Done_Glyph( image );
823 //iter->clear_and_free();
832 lyr_freetype::get_bounding_rect()const
835 const_cast<lyr_freetype*>(this)->sync();
836 // if(!is_disabled())
837 return synfig::Rect::full_plane();