1 /*! ========================================================================
4 ** $Id: lyr_freetype.cpp,v 1.5 2005/01/24 05:00:18 darco Exp $
6 ** Copyright (c) 2002 Robert B. Quattlebaum Jr.
8 ** This software and associated documentation
9 ** are CONFIDENTIAL and PROPRIETARY property of
10 ** the above-mentioned copyright holder.
12 ** You may not copy, print, publish, or in any
13 ** other way distribute this software without
14 ** a prior written agreement with
15 ** the copyright holder.
17 ** === N O T E S ===========================================================
19 ** ========================================================================= */
21 /* === H E A D E R S ======================================================= */
32 #include "lyr_freetype.h"
39 using namespace synfig;
41 /* === M A C R O S ========================================================= */
43 #define MAX_GLYPHS 2000
45 #define PANGO_STYLE_NORMAL (0)
46 #define PANGO_STYLE_OBLIQUE (1)
47 #define PANGO_STYLE_ITALIC (2)
50 #define WEIGHT_NORMAL (400)
51 #define WEIGHT_BOLD (700)
53 /* === G L O B A L S ======================================================= */
55 SYNFIG_LAYER_INIT(lyr_freetype);
56 SYNFIG_LAYER_SET_NAME(lyr_freetype,"text");
57 SYNFIG_LAYER_SET_LOCAL_NAME(lyr_freetype,_("Simple Text"));
58 SYNFIG_LAYER_SET_CATEGORY(lyr_freetype,_("Typography"));
59 SYNFIG_LAYER_SET_VERSION(lyr_freetype,"0.2");
60 SYNFIG_LAYER_SET_CVS_ID(lyr_freetype,"$Id: lyr_freetype.cpp,v 1.5 2005/01/24 05:00:18 darco Exp $");
62 /* === P R O C E D U R E S ================================================= */
66 if(glyph)FT_Done_Glyph(glyph);
70 TextLine::clear_and_free()
72 std::vector<Glyph>::iterator iter;
73 for(iter=glyph_table.begin();iter!=glyph_table.end();++iter)
75 if(iter->glyph)FT_Done_Glyph(iter->glyph);
81 /* === M E T H O D S ======================================================= */
83 lyr_freetype::lyr_freetype()
87 size=Vector(0.25,0.25);
91 orient=Vector(0.5,0.5);
95 style=PANGO_STYLE_NORMAL;
100 set_blend_method(Color::BLEND_COMPOSITE);
103 new_font(family,style,weight);
108 lyr_freetype::~lyr_freetype()
115 lyr_freetype::new_font(const synfig::String &family, int style, int weight)
118 !new_font_(family,style,weight) &&
119 !new_font_(family,style,WEIGHT_NORMAL) &&
120 !new_font_(family,PANGO_STYLE_NORMAL,weight) &&
121 !new_font_(family,PANGO_STYLE_NORMAL,WEIGHT_NORMAL) &&
122 !new_font_("sans serif",style,weight) &&
123 !new_font_("sans serif",style,WEIGHT_NORMAL) &&
124 !new_font_("sans serif",PANGO_STYLE_NORMAL,weight)
126 new_font_("sans serif",PANGO_STYLE_NORMAL,WEIGHT_NORMAL);
130 lyr_freetype::new_font_(const synfig::String &font_fam_, int style, int weight)
132 synfig::String font_fam(font_fam_);
134 if(new_face(font_fam_))
138 for(unsigned int i=0;i<font_fam.size();i++)font_fam[i]=tolower(font_fam[i]);
141 if(font_fam=="arial black")
143 if(new_face("ariblk"))
147 font_fam="sans serif";
149 if(font_fam=="sans serif" || font_fam=="arial")
151 String arial("arial");
152 if(weight>WEIGHT_NORMAL)
154 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
157 if(weight>WEIGHT_NORMAL) arial+='d';
162 if(new_face("Helvetica RO"))
167 if(font_fam=="comic" || font_fam=="comic sans")
169 String filename("comic");
170 if(weight>WEIGHT_NORMAL)
172 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
174 else if(weight>WEIGHT_NORMAL) filename+='d';
176 if(new_face(filename))
180 if(font_fam=="courier" || font_fam=="courier new")
182 String filename("cour");
183 if(weight>WEIGHT_NORMAL)
185 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
187 else if(weight>WEIGHT_NORMAL) filename+='d';
189 if(new_face(filename))
193 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman")
195 String filename("times");
196 if(weight>WEIGHT_NORMAL)
198 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
200 else if(weight>WEIGHT_NORMAL) filename+='d';
202 if(new_face(filename))
206 if(font_fam=="trebuchet")
208 String filename("trebuc");
209 if(weight>WEIGHT_NORMAL)
211 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
214 if(weight<=WEIGHT_NORMAL) filename+='t';
216 else if(weight>WEIGHT_NORMAL) filename+='d';
218 if(new_face(filename))
223 if(font_fam=="sans serif" || font_fam=="luxi sans")
226 String luxi("luxis");
227 if(weight>WEIGHT_NORMAL)
231 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
238 if(new_face("arial"))
240 if(new_face("Arial"))
243 if(font_fam=="serif" || font_fam=="times" || font_fam=="times new roman" || font_fam=="luxi serif")
246 String luxi("luxir");
247 if(weight>WEIGHT_NORMAL)
251 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
257 if(new_face("Times New Roman"))
259 if(new_face("Times"))
265 String luxi("luxim");
266 if(weight>WEIGHT_NORMAL)
270 if(style==PANGO_STYLE_ITALIC||style==PANGO_STYLE_OBLIQUE)
277 if(new_face("Times New Roman"))
279 if(new_face("Times"))
283 return new_face(font_fam_) || new_face(font_fam);
288 #ifdef USE_MAC_FT_FUNCS
289 void fss2path(char *path, FSSpec *fss)
291 int l; //fss->name contains name of last item in path
292 for(l=0; l<(fss->name[0]); l++) path[l] = fss->name[l + 1];
295 if(fss->parID != fsRtParID) //path is more than just a volume name
300 pb.dirInfo.ioNamePtr = fss->name;
301 pb.dirInfo.ioVRefNum = fss->vRefNum;
302 pb.dirInfo.ioDrParID = fss->parID;
305 pb.dirInfo.ioFDirIndex = -1; //get parent directory name
306 pb.dirInfo.ioDrDirID = pb.dirInfo.ioDrParID;
307 if(PBGetCatInfoSync(&pb) != noErr) break;
309 len = fss->name[0] + 1;
310 for(i=l; i>=0; i--) path[i + len] = path[i];
311 for(i=1; i<len; i++) path[i - 1] = fss->name[i]; //add to start of path
314 } while(pb.dirInfo.ioDrDirID != fsRtDirID); //while more directory levels
320 lyr_freetype::new_face(const String &newfont)
323 FT_Long face_index=0;
325 // If we are already loaded, don't bother reloading.
326 if(face && font==newfont)
335 error=FT_New_Face(ft_library,newfont.c_str(),face_index,&face);
336 if(error)error=FT_New_Face(ft_library,(newfont+".ttf").c_str(),face_index,&face);
340 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont).c_str(),face_index,&face);
341 if(error)error=FT_New_Face(ft_library,(get_canvas()->get_file_path()+ETL_DIRECTORY_SEPERATOR+newfont+".ttf").c_str(),face_index,&face);
344 #ifdef USE_MAC_FT_FUNCS
348 error=FT_GetFile_From_Mac_Name(newfont.c_str(),&fs_spec,&face_index);
352 fss2path(filename,&fs_spec);
353 //FSSpecToNativePathName(fs_spec,filename,sizeof(filename)-1, 0);
355 error=FT_New_Face(ft_library, filename, face_index,&face);
356 //error=FT_New_Face_From_FSSpec(ft_library, &fs_spec, face_index,&face);
357 synfig::info(__FILE__":%d: \"%s\" (%s) -- ft_error=%d",__LINE__,newfont.c_str(),filename,error);
361 synfig::info(__FILE__":%d: \"%s\" -- ft_error=%d",__LINE__,newfont.c_str(),error);
362 // Unable to generate fs_spec
369 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont).c_str(),face_index,&face);
370 if(error)error=FT_New_Face(ft_library,("C:\\WINDOWS\\FONTS\\"+newfont+".ttf").c_str(),face_index,&face);
374 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont).c_str(),face_index,&face);
375 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
376 if(error)error=FT_New_Face(ft_library,("~/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
378 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont).c_str(),face_index,&face);
379 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".ttf").c_str(),face_index,&face);
380 if(error)error=FT_New_Face(ft_library,("/Library/Fonts/"+newfont+".dfont").c_str(),face_index,&face);
383 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont).c_str(),face_index,&face);
384 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/type1/"+newfont+".ttf").c_str(),face_index,&face);
386 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont).c_str(),face_index,&face);
387 if(error)error=FT_New_Face(ft_library,("/usr/share/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
389 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont).c_str(),face_index,&face);
390 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/TTF/"+newfont+".ttf").c_str(),face_index,&face);
392 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont).c_str(),face_index,&face);
393 if(error)error=FT_New_Face(ft_library,("/usr/X11R6/lib/X11/fonts/truetype/"+newfont+".ttf").c_str(),face_index,&face);
398 //synfig::error(strprintf("lyr_freetype:%s (err=%d)",_("Unable to open face."),error));
409 lyr_freetype::set_param(const String & param, const ValueBase &value)
411 Mutex::Lock lock(mutex);
413 if(param=="font" && value.same_as(font))
415 new_font(etl::basename(value.get(font)),style,weight);
416 family=etl::basename(value.get(font));
420 IMPORT_PLUS(family,new_font(family,style,weight));
421 IMPORT_PLUS(weight,new_font(family,style,weight));
422 IMPORT_PLUS(style,new_font(family,style,weight));
423 IMPORT_PLUS(size, if(old_version){size/=2.0;} needs_sync_=true );
424 IMPORT_PLUS(text,needs_sync_=true);
425 IMPORT_PLUS(pos,needs_sync_=true);
428 IMPORT_PLUS(orient,needs_sync_=true);
429 IMPORT_PLUS(compress,needs_sync_=true);
430 IMPORT_PLUS(vcompress,needs_sync_=true);
431 IMPORT_PLUS(use_kerning,needs_sync_=true);
432 IMPORT_PLUS(grid_fit,needs_sync_=true);
434 return Layer_Composite::set_param(param,value);
438 lyr_freetype::get_param(const String& param)const
458 return Layer_Composite::get_param(param);
462 lyr_freetype::get_param_vocab(void)const
464 Layer::Vocab ret(Layer_Composite::get_param_vocab());
466 ret.push_back(ParamDesc("text")
467 .set_local_name(_("Text"))
468 .set_description(_("Text to Render"))
469 .set_hint("paragraph")
472 ret.push_back(ParamDesc("color")
473 .set_local_name(_("Color"))
474 .set_description(_("Color of the text"))
477 ret.push_back(ParamDesc("family")
478 .set_local_name(_("Font Family"))
479 .set_hint("font_family")
482 ret.push_back(ParamDesc("style")
483 .set_local_name(_("Style"))
485 .add_enum_value(PANGO_STYLE_NORMAL, "normal" ,_("Normal"))
486 .add_enum_value(PANGO_STYLE_OBLIQUE, "oblique" ,_("Oblique"))
487 .add_enum_value(PANGO_STYLE_ITALIC, "italic" ,_("Italic"))
490 ret.push_back(ParamDesc("weight")
491 .set_local_name(_("Weight"))
493 .add_enum_value(200, "ultralight" ,_("Ultralight"))
494 .add_enum_value(300, "light" ,_("light"))
495 .add_enum_value(400, "normal" ,_("Normal"))
496 .add_enum_value(700, "bold" ,_("Bold"))
497 .add_enum_value(800, "ultrabold" ,_("Ultrabold"))
498 .add_enum_value(900, "heavy" ,_("Heavy"))
500 ret.push_back(ParamDesc("compress")
501 .set_local_name(_("Hozontal Spacing"))
502 .set_description(_("Describes how close glyphs are horizontally"))
505 ret.push_back(ParamDesc("vcompress")
506 .set_local_name(_("Vertical Spacing"))
507 .set_description(_("Describes how close lines of text are vertically"))
510 ret.push_back(ParamDesc("size")
511 .set_local_name(_("Size"))
512 .set_description(_("Size of the text"))
518 ret.push_back(ParamDesc("orient")
519 .set_local_name(_("Orientation"))
520 .set_description(_("Text Orientation"))
521 .set_invisible_duck()
524 ret.push_back(ParamDesc("pos")
525 .set_local_name(_("Position"))
526 .set_description(_("Text Position"))
529 ret.push_back(ParamDesc("font")
530 .set_local_name(_("Font"))
531 .set_description(_("Filename of the font to use"))
532 .set_hint("filename")
537 ret.push_back(ParamDesc("use_kerning")
538 .set_local_name(_("Kerning"))
539 .set_description(_("Enables/Disables font kerning (If the font supports it)"))
542 ret.push_back(ParamDesc("grid_fit")
543 .set_local_name(_("Sharpen Edges"))
544 .set_description(_("Turn this off if you are going to be animating the text"))
546 ret.push_back(ParamDesc("invert")
547 .set_local_name(_("Invert"))
563 lyr_freetype::get_color(Context context, const synfig::Point &pos)const
566 const_cast<lyr_freetype*>(this)->sync();
569 return context.get_color(pos);
570 return context.get_color(pos);
574 lyr_freetype::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
576 static synfig::RecMutex freetype_mutex;
579 const_cast<lyr_freetype*>(this)->sync();
585 Vector size(lyr_freetype::size*2);
587 if(!context.accelerated_render(surface,quality,renddesc,cb))
590 if(is_disabled() || text.empty())
593 // If there is no font loaded, just bail
596 if(cb)cb->warning(string("lyr_freetype:")+_("No face loaded, no text will be rendered."));
600 String text(lyr_freetype::text);
601 if(text=="@_FILENAME_@" && get_canvas() && !get_canvas()->get_file_name().empty())
603 text=basename(get_canvas()->get_file_name());
606 // Width and Height of a pixel
607 Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
608 Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
610 // Calculate character width and height
611 int w=abs(round_to_int(size[0]*pw));
612 int h=abs(round_to_int(size[1]*ph));
614 //int bx=(int)((pos[0]-renddesc.get_tl()[0])*pw*64+0.5);
615 //int by=(int)((pos[1]-renddesc.get_tl()[1])*ph*64+0.5);
619 // If the font is the size of a pixel, don't bother rendering any text
622 if(cb)cb->warning(string("lyr_freetype:")+_("Text too small, no text will be rendered."));
626 synfig::RecMutex::Lock lock(freetype_mutex);
628 #define CHAR_RESOLUTION (64)
629 error = FT_Set_Char_Size(
630 face, // handle to face object
631 (int)CHAR_RESOLUTION, // char_width in 1/64th of points
632 (int)CHAR_RESOLUTION, // char_height in 1/64th of points
633 round_to_int(abs(size[0]*pw*CHAR_RESOLUTION)), // horizontal device resolution
634 round_to_int(abs(size[1]*ph*CHAR_RESOLUTION)) ); // vertical device resolution
636 // Here is where we can compensate for the
637 // error in freetype's rendering engine.
638 const float xerror(abs(size[0]*pw)/(float)face->size->metrics.x_ppem/1.13f/0.996);
639 const float yerror(abs(size[1]*ph)/(float)face->size->metrics.y_ppem/1.13f/0.996);
640 //synfig::info("xerror=%f, yerror=%f",xerror,yerror);
641 const float compress(lyr_freetype::compress*xerror);
642 const float vcompress(lyr_freetype::vcompress*yerror);
646 if(cb)cb->error(string("lyr_freetype:")+_("Unable to set face size.")+strprintf(" (err=%d)",error));
650 FT_GlyphSlot slot = face->glyph; // a small shortcut
651 FT_UInt glyph_index(0);
655 std::list<TextLine> lines;
658 -- ** -- CREATE GLYPHS -------------------------------------------------------
661 lines.push_front(TextLine());
662 string::const_iterator iter;
663 for (iter=text.begin(); iter!=text.end(); ++iter)
668 lines.push_front(TextLine());
677 glyph_index = FT_Get_Char_Index( face, ' ' );
680 glyph_index = FT_Get_Char_Index( face, *iter );
682 // retrieve kerning distance and move pen position
683 if ( FT_HAS_KERNING(face) && use_kerning && previous && glyph_index )
688 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_default, &delta );
690 FT_Get_Kerning( face, previous, glyph_index, ft_kerning_unfitted, &delta );
694 bx += round_to_int(delta.x*compress);
695 by += round_to_int(delta.y*compress);
706 // store current pen position
707 curr_glyph.pos.x = bx;
708 curr_glyph.pos.y = by;
710 // load glyph image into the slot. DO NOT RENDER IT !!
712 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT);
714 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_DEFAULT|FT_LOAD_NO_HINTING );
715 if (error) continue; // ignore errors, jump to next glyph
717 // extract glyph image and store it in our table
718 error = FT_Get_Glyph( face->glyph, &curr_glyph.glyph );
719 if (error) continue; // ignore errors, jump to next glyph
721 // record current glyph index
722 previous = glyph_index;
724 // Update the line width
725 lines.front().width=bx+slot->advance.x;
727 // increment pen position
729 bx += round_to_int(slot->advance.x*multiplier*compress)-bx%round_to_int(slot->advance.x*multiplier*compress);
731 bx += round_to_int(slot->advance.x*compress*multiplier);
733 //bx += round_to_int(slot->advance.x*compress*multiplier);
734 //by += round_to_int(slot->advance.y*compress);
735 by += slot->advance.y*multiplier;
737 lines.front().glyph_table.push_back(curr_glyph);
742 //float string_height;
743 //string_height=(((lines.size()-1)*face->size->metrics.height+lines.back().actual_height()));
745 //int string_height=face->size->metrics.ascender;
746 //#define METRICS_SCALE_ONE (65536.0f)
747 #define METRICS_SCALE_ONE ((float)(1<<16))
750 line_height=vcompress*((float)face->height*(((float)face->size->metrics.y_scale/METRICS_SCALE_ONE)));
753 string_height=round_to_int(((lines.size()-1)*line_height+lines.back().actual_height()));
754 //synfig::info("string_height=%d",string_height);
755 //synfig::info("line_height=%f",line_height);
758 -- ** -- RENDER THE GLYPHS ---------------------------------------------------
762 Surface *src_surface;
769 Surface::alpha_pen pen(surface->begin(),get_amount(),get_blend_method());
771 surface->fill(color,pen,src_.get_w(),src_.get_h());
777 std::list<TextLine>::iterator iter;
779 for(curr_line=0,iter=lines.begin();iter!=lines.end();++iter,curr_line++)
781 bx=round_to_int((pos[0]-renddesc.get_tl()[0])*pw*CHAR_RESOLUTION-orient[0]*iter->width);
782 by=round_to_int((pos[1]-renddesc.get_tl()[1])*ph*CHAR_RESOLUTION+(1.0-orient[1])*string_height-line_height*curr_line);
783 //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));
784 //synfig::info("curr_line=%d, bx=%d, by=%d",curr_line,bx,by);
786 std::vector<Glyph>::iterator iter2;
787 for(iter2=iter->glyph_table.begin();iter2!=iter->glyph_table.end();++iter2)
789 FT_Glyph image(iter2->glyph);
793 pen.x = bx + iter2->pos.x;
794 pen.y = by + iter2->pos.y;
796 //synfig::info("GLYPH: pen.x=%d, pen,y=%d",curr_line,(pen.x+32)>>6,(pen.y+32)>>6);
798 error = FT_Glyph_To_Bitmap( &image, ft_render_mode_normal,0/*&pen*/, 1 );
799 if(error) { FT_Done_Glyph( image ); continue; }
801 bit = (FT_BitmapGlyph)image;
803 for(v=0;v<bit->bitmap.rows;v++)
804 for(u=0;u<bit->bitmap.width;u++)
806 int x=u+((pen.x+32)>>6)+ bit->left;
807 int y=v+((pen.y+32)>>6)- bit->top;
810 y<surface->get_h() &&
813 float myamount=(float)bit->bitmap.buffer[v*bit->bitmap.pitch+u]/255.0f;
815 myamount=1.0f-myamount;
816 (*surface)[y][x]=Color::blend(color,(*src_surface)[y][x],myamount*get_amount(),get_blend_method());
820 FT_Done_Glyph( image );
822 //iter->clear_and_free();
831 lyr_freetype::get_bounding_rect()const
834 const_cast<lyr_freetype*>(this)->sync();
835 // if(!is_disabled())
836 return synfig::Rect::full_plane();