2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/internal/text-abstraction/font-client-plugin-impl.h>
22 #include <dali/public-api/common/vector-wrapper.h>
23 #include <dali/public-api/text-abstraction/glyph-info.h>
24 #include <dali/integration-api/debug.h>
27 #include <fontconfig/fontconfig.h>
30 * Conversion from Fractional26.6 to float
34 const float FROM_266 = 1.0f / 64.0f;
36 const std::string FONT_FORMAT( "TrueType" );
37 const std::string DEFAULT_FONT_FAMILY_NAME( "Tizen" );
38 const std::string DEFAULT_FONT_STYLE( "Regular" );
44 namespace TextAbstraction
50 FontClient::Plugin::FontDescriptionCacheItem::FontDescriptionCacheItem( const FontFamily& fontFamily,
51 const FontStyle& fontStyle,
52 FontDescriptionId index )
53 : fontFamily( fontFamily ),
54 fontStyle( fontStyle ),
58 FontClient::Plugin::FontIdCacheItem::FontIdCacheItem( FontDescriptionId validatedFontId,
59 PointSize26Dot6 pointSize,
61 : validatedFontId( validatedFontId ),
62 pointSize( pointSize ),
66 FontClient::Plugin::CacheItem::CacheItem( FT_Face ftFace,
68 PointSize26Dot6 pointSize,
70 const FontMetrics& metrics )
71 : mFreeTypeFace( ftFace ),
73 mPointSize( pointSize ),
78 FontClient::Plugin::Plugin( unsigned int horizontalDpi,
79 unsigned int verticalDpi )
80 : mFreeTypeLibrary( NULL ),
81 mDpiHorizontal( horizontalDpi ),
82 mDpiVertical( verticalDpi ),
86 mValidatedFontCache(),
87 mFontDescriptionCache( 1u ),
90 int error = FT_Init_FreeType( &mFreeTypeLibrary );
91 if( FT_Err_Ok != error )
93 DALI_LOG_ERROR( "FreeType Init error: %d\n", error );
97 FontClient::Plugin::~Plugin()
99 FT_Done_FreeType( mFreeTypeLibrary );
102 void FontClient::Plugin::SetDpi( unsigned int horizontalDpi,
103 unsigned int verticalDpi )
105 mDpiHorizontal = horizontalDpi;
106 mDpiVertical = verticalDpi;
109 void FontClient::Plugin::SetDefaultFontFamily( const FontFamily& fontFamilyName,
110 const FontStyle& fontStyle )
112 mDefaultFonts.clear();
114 FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontFamilyName,
117 FcResult result = FcResultMatch;
119 // Match the pattern.
120 FcFontSet* fontSet = FcFontSort( NULL /* use default configure */,
122 false /* don't trim */,
126 if( NULL != fontSet )
128 // Reserve some space to avoid reallocations.
129 mDefaultFonts.reserve( fontSet->nfont );
131 for( int i = 0u; i < fontSet->nfont; ++i )
133 FcPattern* fontPattern = fontSet->fonts[i];
137 // Skip fonts with no path
138 if( GetFcString( fontPattern, FC_FILE, path ) )
140 mDefaultFonts.push_back( FontDescription() );
141 FontDescription& fontDescription = mDefaultFonts.back();
143 fontDescription.path = path;
145 GetFcString( fontPattern, FC_FAMILY, fontDescription.family );
146 GetFcString( fontPattern, FC_STYLE, fontDescription.style );
150 FcFontSetDestroy( fontSet );
153 FcPatternDestroy( fontFamilyPattern );
156 void FontClient::Plugin::GetDefaultFonts( FontList& defaultFonts )
158 if( mDefaultFonts.empty() )
160 SetDefaultFontFamily( DEFAULT_FONT_FAMILY_NAME,
161 DEFAULT_FONT_STYLE );
164 defaultFonts = mDefaultFonts;
167 void FontClient::Plugin::GetSystemFonts( FontList& systemFonts )
169 if( mSystemFonts.empty() )
174 systemFonts = mSystemFonts;
177 void FontClient::Plugin::GetDescription( FontId id,
178 FontDescription& fontDescription ) const
180 for( std::vector<FontIdCacheItem>::const_iterator it = mFontIdCache.begin(),
181 endIt = mFontIdCache.end();
185 const FontIdCacheItem& item = *it;
187 if( item.fontId == id )
189 fontDescription = *( mFontDescriptionCache.begin() + item.validatedFontId );
194 DALI_LOG_ERROR( "FontClient::Plugin::GetDescription. No description found for the font ID %d\n", id );
197 PointSize26Dot6 FontClient::Plugin::GetPointSize( FontId id )
199 const FontId index = id - 1u;
202 index < mFontCache.size() )
204 return ( *( mFontCache.begin() + index ) ).mPointSize;
208 DALI_LOG_ERROR( "FontClient::Plugin::GetPointSize. Invalid font ID %d\n", id );
211 return TextAbstraction::FontClient::DEFAULT_POINT_SIZE;
214 FontId FontClient::Plugin::FindDefaultFont( Character charcode,
215 PointSize26Dot6 pointSize )
217 // Create the list of default fonts if it has not been created.
218 if( mDefaultFonts.empty() )
220 SetDefaultFontFamily( DEFAULT_FONT_FAMILY_NAME,
221 DEFAULT_FONT_STYLE );
224 // Traverse the list of default fonts.
225 // Check for each default font if supports the character.
227 for( FontList::const_iterator it = mDefaultFonts.begin(),
228 endIt = mDefaultFonts.end();
232 const FontDescription& description = *it;
234 FcPattern* pattern = CreateFontFamilyPattern( description.family,
237 FcResult result = FcResultMatch;
238 FcPattern* match = FcFontMatch( NULL /* use default configure */, pattern, &result );
240 FcCharSet* charSet = NULL;
241 FcPatternGetCharSet( match, FC_CHARSET, 0u, &charSet );
243 if( FcCharSetHasChar( charSet, charcode ) )
245 return GetFontId( description.family,
255 FontId FontClient::Plugin::GetFontId( const FontPath& path,
256 PointSize26Dot6 pointSize,
258 bool cacheDescription )
262 if( NULL != mFreeTypeLibrary )
265 if( FindFont( path, pointSize, faceIndex, foundId ) )
271 id = CreateFont( path, pointSize, faceIndex, cacheDescription );
278 FontId FontClient::Plugin::GetFontId( const FontFamily& fontFamily,
279 const FontStyle& fontStyle,
280 PointSize26Dot6 pointSize,
281 FaceIndex faceIndex )
283 // This method uses three vectors which caches:
284 // * Pairs of non validated 'fontFamily, fontStyle' and an index to a vector with paths to font file names.
285 // * The path to font file names.
286 // * The font ids of pairs 'font point size, index to the vector with paths to font file names'.
288 // 1) Checks in the cache if the pair 'fontFamily, fontStyle' has been validated before.
289 // If it was it gets an index to the vector with paths to font file names. Otherwise,
290 // retrieves using font config a path to a font file name which matches with the pair
291 // 'fontFamily, fontStyle'. The path is stored in the chache.
293 // 2) Checks in the cache if the pair 'font point size, index to the vector with paths to
294 // fon file names' exists. If exists, it gets the font id. If it doesn't it calls
295 // the GetFontId() method with the path to the font file name and the point size to
298 // The font id to be returned.
301 // Check first if the pair font family and style have been validated before.
302 FontDescriptionId validatedFontId = 0u;
304 if( !FindValidatedFont( fontFamily,
308 // Use font config to validate the font family name and font style.
310 // Create a font pattern.
311 FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontFamily,
314 FcResult result = FcResultMatch;
317 FcPattern* match = FcFontMatch( NULL /* use default configure */, fontFamilyPattern, &result );
321 // Get the path to the font file name.
322 FontDescription description;
323 GetFcString( match, FC_FILE, description.path );
324 GetFcString( match, FC_FAMILY, description.family );
325 GetFcString( match, FC_STYLE, description.style );
327 // Set the index to the vector of paths to font file names.
328 validatedFontId = mFontDescriptionCache.size();
330 // Add the path to the cache.
331 mFontDescriptionCache.push_back( description );
333 // Cache the index and the pair font family name, font style.
334 FontDescriptionCacheItem item( fontFamily, fontStyle, validatedFontId );
335 mValidatedFontCache.push_back( item );
337 // destroyed the matched pattern
338 FcPatternDestroy( match );
342 DALI_LOG_ERROR( "FontClient::Plugin::GetFontId failed for font %s %s\n", fontFamily.c_str(), fontStyle.c_str() );
345 // destroy the pattern
346 FcPatternDestroy( fontFamilyPattern );
349 // Check if exists a pair 'validatedFontId, pointSize' in the cache.
350 if( !FindFont( validatedFontId, pointSize, fontId ) )
352 // Retrieve the font file name path.
353 const FontDescription& description = *( mFontDescriptionCache.begin() + validatedFontId );
355 // Retrieve the font id. Do not cache the description as it has been already cached.
356 fontId = GetFontId( description.path,
361 // Cache the pair 'validatedFontId, pointSize' to improve the following queries.
362 mFontIdCache.push_back( FontIdCacheItem( validatedFontId,
370 void FontClient::Plugin::GetFontMetrics( FontId fontId,
371 FontMetrics& metrics )
374 fontId-1 < mFontCache.size() )
376 metrics = mFontCache[fontId-1].mMetrics;
380 DALI_LOG_ERROR( "Invalid font ID %d\n", fontId );
384 GlyphIndex FontClient::Plugin::GetGlyphIndex( FontId fontId,
387 GlyphIndex index( 0 );
390 fontId-1 < mFontCache.size() )
392 FT_Face ftFace = mFontCache[fontId-1].mFreeTypeFace;
394 index = FT_Get_Char_Index( ftFace, charcode );
400 bool FontClient::Plugin::GetGlyphMetrics( GlyphInfo* array,
404 bool success( true );
406 for( unsigned int i=0; i<size; ++i )
408 FontId fontId = array[i].fontId;
411 fontId-1 < mFontCache.size() )
413 FT_Face ftFace = mFontCache[fontId-1].mFreeTypeFace;
415 int error = FT_Load_Glyph( ftFace, array[i].index, FT_LOAD_DEFAULT );
417 if( FT_Err_Ok == error )
419 array[i].width = static_cast< float >( ftFace->glyph->metrics.width ) * FROM_266;
420 array[i].height = static_cast< float >( ftFace->glyph->metrics.height ) * FROM_266 ;
423 array[i].xBearing = static_cast< float >( ftFace->glyph->metrics.horiBearingX ) * FROM_266;
424 array[i].yBearing = static_cast< float >( ftFace->glyph->metrics.horiBearingY ) * FROM_266;
425 array[i].advance = static_cast< float >( ftFace->glyph->metrics.horiAdvance ) * FROM_266;
429 array[i].xBearing = static_cast< float >( ftFace->glyph->metrics.vertBearingX ) * FROM_266;
430 array[i].yBearing = static_cast< float >( ftFace->glyph->metrics.vertBearingY ) * FROM_266;
431 array[i].advance = static_cast< float >( ftFace->glyph->metrics.vertAdvance ) * FROM_266;
448 BitmapImage FontClient::Plugin::CreateBitmap( FontId fontId,
449 GlyphIndex glyphIndex )
454 fontId-1 < mFontCache.size() )
456 FT_Face ftFace = mFontCache[fontId-1].mFreeTypeFace;
458 FT_Error error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_DEFAULT );
459 if( FT_Err_Ok == error )
462 error = FT_Get_Glyph( ftFace->glyph, &glyph );
464 // Convert to bitmap if necessary
465 if ( FT_Err_Ok == error )
467 if( glyph->format != FT_GLYPH_FORMAT_BITMAP )
469 error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL, 0, 1 );
473 DALI_LOG_ERROR( "FT_Glyph_To_Bitmap Failed with error: %d\n", error );
478 DALI_LOG_ERROR( "FT_Get_Glyph Failed with error: %d\n", error );
481 if( FT_Err_Ok == error )
483 // Access the underlying bitmap data
484 FT_BitmapGlyph bitmapGlyph = (FT_BitmapGlyph)glyph;
485 ConvertBitmap( bitmap, bitmapGlyph->bitmap );
488 // Created FT_Glyph object must be released with FT_Done_Glyph
489 FT_Done_Glyph( glyph );
493 DALI_LOG_ERROR( "FT_Load_Glyph Failed with error: %d\n", error );
500 void FontClient::Plugin::InitSystemFonts()
502 FcFontSet* fontSet = GetFcFontSet();
506 // Reserve some space to avoid reallocations.
507 mSystemFonts.reserve( fontSet->nfont );
509 for( int i = 0u; i < fontSet->nfont; ++i )
511 FcPattern* fontPattern = fontSet->fonts[i];
515 // Skip fonts with no path
516 if( GetFcString( fontPattern, FC_FILE, path ) )
518 mSystemFonts.push_back( FontDescription() );
519 FontDescription& fontDescription = mSystemFonts.back();
521 fontDescription.path = path;
523 GetFcString( fontPattern, FC_FAMILY, fontDescription.family );
524 GetFcString( fontPattern, FC_STYLE, fontDescription.style );
528 FcFontSetDestroy( fontSet );
532 FcPattern* FontClient::Plugin::CreateFontFamilyPattern( const FontFamily& fontFamily,
533 const FontStyle& fontStyle )
535 // create the cached font family lookup pattern
536 // a pattern holds a set of names, each name refers to a property of the font
537 FcPattern* fontFamilyPattern = FcPatternCreate();
539 // add a property to the pattern for the font family
540 FcPatternAddString( fontFamilyPattern, FC_FAMILY, reinterpret_cast<const FcChar8*>( fontFamily.c_str() ) );
542 // add a property to the pattern for the font family
543 FcPatternAddString( fontFamilyPattern, FC_STYLE, reinterpret_cast<const FcChar8*>( fontStyle.c_str() ) );
545 // Add a property of the pattern, to say we want to match TrueType fonts
546 FcPatternAddString( fontFamilyPattern , FC_FONTFORMAT, reinterpret_cast<const FcChar8*>( FONT_FORMAT.c_str() ) );
548 // modify the config, with the mFontFamilyPatterm
549 FcConfigSubstitute( NULL /* use default configure */, fontFamilyPattern, FcMatchPattern );
551 // provide default values for unspecified properties in the font pattern
552 // e.g. patterns without a specified style or weight are set to Medium
553 FcDefaultSubstitute( fontFamilyPattern );
555 return fontFamilyPattern;
558 _FcFontSet* FontClient::Plugin::GetFcFontSet() const
560 // create a new pattern.
561 // a pattern holds a set of names, each name refers to a property of the font
562 FcPattern* pattern = FcPatternCreate();
564 // create an object set used to define which properties are to be returned in the patterns from FcFontList.
565 FcObjectSet* objectSet = FcObjectSetCreate();
567 // build an object set from a list of property names
568 FcObjectSetAdd( objectSet, FC_FILE );
569 FcObjectSetAdd( objectSet, FC_FAMILY );
570 FcObjectSetAdd( objectSet, FC_STYLE );
572 // get a list of fonts
573 // creates patterns from those fonts containing only the objects in objectSet and returns the set of unique such patterns
574 FcFontSet* fontset = FcFontList( NULL /* the default configuration is checked to be up to date, and used */, pattern, objectSet );
576 // clear up the object set
579 FcObjectSetDestroy( objectSet );
581 // clear up the pattern
584 FcPatternDestroy( pattern );
590 bool FontClient::Plugin::GetFcString( const FcPattern* const pattern,
592 std::string& string )
594 FcChar8* file = NULL;
595 const FcResult retVal = FcPatternGetString( pattern, n, 0u, &file );
597 if( FcResultMatch == retVal )
599 // Have to use reinterpret_cast because FcChar8 is unsigned char*, not a const char*.
600 string.assign( reinterpret_cast<const char*>( file ) );
608 FontId FontClient::Plugin::CreateFont( const FontPath& path,
609 PointSize26Dot6 pointSize,
611 bool cacheDescription )
615 // Create & cache new font face
617 int error = FT_New_Face( mFreeTypeLibrary,
622 if( FT_Err_Ok == error )
624 error = FT_Set_Char_Size( ftFace,
630 if( FT_Err_Ok == error )
632 id = mFontCache.size() + 1;
634 FT_Size_Metrics& ftMetrics = ftFace->size->metrics;
636 FontMetrics metrics( static_cast< float >( ftMetrics.ascender ) * FROM_266,
637 static_cast< float >( ftMetrics.descender ) * FROM_266,
638 static_cast< float >( ftMetrics.height ) * FROM_266 );
640 mFontCache.push_back( CacheItem( ftFace, path, pointSize, faceIndex, metrics ) );
642 if( cacheDescription )
644 FontDescription description;
645 description.path = path;
646 description.family = FontFamily( ftFace->family_name );
647 description.style = FontStyle( ftFace->style_name );
649 mFontDescriptionCache.push_back( description );
654 DALI_LOG_ERROR( "FreeType Set_Char_Size error: %d for pointSize %d\n", pointSize );
659 DALI_LOG_ERROR( "FreeType New_Face error: %d for %s\n", error, path.c_str() );
665 void FontClient::Plugin::ConvertBitmap( BitmapImage& destBitmap,
666 FT_Bitmap srcBitmap )
668 if( srcBitmap.width*srcBitmap.rows > 0 )
670 // TODO - Support all pixel modes
671 if( FT_PIXEL_MODE_GRAY == srcBitmap.pixel_mode )
673 if( srcBitmap.pitch == srcBitmap.width )
675 destBitmap = BitmapImage::New( srcBitmap.width, srcBitmap.rows, Pixel::L8 );
677 PixelBuffer* destBuffer = destBitmap.GetBuffer();
678 memcpy( destBuffer, srcBitmap.buffer, srcBitmap.width*srcBitmap.rows );
684 bool FontClient::Plugin::FindFont( const FontPath& path,
685 PointSize26Dot6 pointSize,
687 FontId& fontId ) const
690 for( std::vector<CacheItem>::const_iterator it = mFontCache.begin(),
691 endIt = mFontCache.end();
695 const CacheItem& cacheItem = *it;
697 if( cacheItem.mPointSize == pointSize &&
698 cacheItem.mFaceIndex == faceIndex &&
699 cacheItem.mPath == path )
709 bool FontClient::Plugin::FindValidatedFont( const FontFamily& fontFamily,
710 const FontStyle& fontStyle,
711 FontDescriptionId& validatedFontId )
713 validatedFontId = 0u;
715 for( std::vector<FontDescriptionCacheItem>::const_iterator it = mValidatedFontCache.begin(),
716 endIt = mValidatedFontCache.end();
720 const FontDescriptionCacheItem& item = *it;
722 if( ( fontFamily == item.fontFamily ) &&
723 ( fontStyle == item.fontStyle ) )
725 validatedFontId = item.index;
734 bool FontClient::Plugin::FindFont( FontDescriptionId validatedFontId,
735 PointSize26Dot6 pointSize,
740 for( std::vector<FontIdCacheItem>::const_iterator it = mFontIdCache.begin(),
741 endIt = mFontIdCache.end();
745 const FontIdCacheItem& item = *it;
747 if( ( validatedFontId == item.validatedFontId ) &&
748 ( pointSize == item.pointSize ) )
750 fontId = item.fontId;
758 } // namespace Internal
760 } // namespace TextAbstraction