COMMON script added.
[platform/core/uifw/dali-adaptor.git] / text / dali / internal / text-abstraction / shaping-impl.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS  HEADER
19 #include "shaping-impl.h"
20
21 // INTERNAL INCLUDES
22 #include <singleton-service-impl.h>
23 #include <dali/devel-api/text-abstraction/font-client.h>
24 #include <dali/devel-api/text-abstraction/glyph-info.h>
25 #include <dali/integration-api/debug.h>
26
27 // EXTERNAL INCLUDES
28 #include <harfbuzz/hb.h>
29 #include <harfbuzz/hb-ft.h>
30
31 #include <ft2build.h>
32
33 namespace Dali
34 {
35
36 namespace TextAbstraction
37 {
38
39 namespace Internal
40 {
41
42 const char*        DEFAULT_LANGUAGE = "en";
43 const unsigned int DEFAULT_LANGUAGE_LENGTH = 2u;
44 const float        FROM_266 = 1.0f / 64.0f;
45
46 const hb_script_t SCRIPT_TO_HARFBUZZ[] =
47 {
48   HB_SCRIPT_COMMON,
49
50   HB_SCRIPT_CYRILLIC,
51   HB_SCRIPT_GREEK,
52   HB_SCRIPT_LATIN,
53
54   HB_SCRIPT_ARABIC,
55   HB_SCRIPT_HEBREW,
56
57   HB_SCRIPT_ARMENIAN,
58   HB_SCRIPT_GEORGIAN,
59
60   HB_SCRIPT_HAN,
61   HB_SCRIPT_HANGUL,
62   HB_SCRIPT_HIRAGANA,
63   HB_SCRIPT_KATAKANA,
64
65   HB_SCRIPT_BENGALI,
66   HB_SCRIPT_MYANMAR,
67   HB_SCRIPT_DEVANAGARI,
68   HB_SCRIPT_GUJARATI,
69   HB_SCRIPT_GURMUKHI,
70   HB_SCRIPT_KANNADA,
71   HB_SCRIPT_MALAYALAM,
72   HB_SCRIPT_ORIYA,
73   HB_SCRIPT_SINHALA,
74   HB_SCRIPT_TAMIL,
75   HB_SCRIPT_TELUGU,
76
77   HB_SCRIPT_LAO,
78   HB_SCRIPT_THAI,
79   HB_SCRIPT_KHMER,
80
81   HB_SCRIPT_UNKNOWN, // EMOJI
82   HB_SCRIPT_UNKNOWN
83 };
84
85 struct Shaping::Plugin
86 {
87   Plugin()
88   : mFreeTypeLibrary( NULL ),
89     mIndices(),
90     mAdvance(),
91     mCharacterMap(),
92     mFontId( 0u )
93   {
94   }
95
96   ~Plugin()
97   {
98     FT_Done_FreeType( mFreeTypeLibrary );
99   }
100
101   void Initialize()
102   {
103     int error = FT_Init_FreeType( &mFreeTypeLibrary );
104     if( FT_Err_Ok != error )
105     {
106       DALI_LOG_ERROR( "FreeType Init error: %d\n", error );
107     }
108   }
109
110   Length Shape( const Character* const text,
111                 Length numberOfCharacters,
112                 FontId fontId,
113                 Script script )
114   {
115     // Clear previoursly shaped texts.
116     mIndices.Clear();
117     mAdvance.Clear();
118     mCharacterMap.Clear();
119     mOffset.Clear();
120     mFontId = fontId;
121
122     // Reserve some space to avoid reallocations.
123     const Length numberOfGlyphs = static_cast<Length>( 1.3f * static_cast<float>( numberOfCharacters ) );
124     mIndices.Reserve( numberOfGlyphs );
125     mAdvance.Reserve( numberOfGlyphs );
126     mCharacterMap.Reserve( numberOfGlyphs );
127     mOffset.Reserve( 2u * numberOfGlyphs );
128
129     TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
130
131     // Get the font's path file name from the font Id.
132     FontDescription fontDescription;
133     fontClient.GetDescription( fontId, fontDescription );
134
135     // Create a FreeType font's face.
136     FT_Face face;
137     FT_Error retVal = FT_New_Face( mFreeTypeLibrary, fontDescription.path.c_str(), 0u, &face );
138     if( FT_Err_Ok != retVal )
139     {
140       DALI_LOG_ERROR( "Failed to open face: %s\n", fontDescription.path.c_str() );
141       return 0u;
142     }
143
144     unsigned int horizontalDpi = 0u;
145     unsigned int verticalDpi = 0u;
146     fontClient.GetDpi( horizontalDpi, verticalDpi );
147
148     FT_Set_Char_Size( face,
149                       0u,
150                       fontClient.GetPointSize( fontId ),
151                       horizontalDpi,
152                       verticalDpi );
153
154     /* Get our harfbuzz font struct */
155     hb_font_t* harfBuzzFont;
156     harfBuzzFont = hb_ft_font_create( face, NULL );
157
158     /* Create a buffer for harfbuzz to use */
159     hb_buffer_t* harfBuzzBuffer = hb_buffer_create();
160
161     const bool rtlDirection = IsRightToLeftScript( script );
162     hb_buffer_set_direction( harfBuzzBuffer,
163                              rtlDirection ? HB_DIRECTION_RTL : HB_DIRECTION_LTR ); /* or LTR */
164
165     hb_buffer_set_script( harfBuzzBuffer,
166                           SCRIPT_TO_HARFBUZZ[ script ] ); /* see hb-unicode.h */
167
168     hb_buffer_set_language( harfBuzzBuffer,
169                             hb_language_from_string( DEFAULT_LANGUAGE,
170                                                      DEFAULT_LANGUAGE_LENGTH ) );
171
172     /* Layout the text */
173     hb_buffer_add_utf32( harfBuzzBuffer, text, numberOfCharacters, 0u, numberOfCharacters );
174
175     hb_shape( harfBuzzFont, harfBuzzBuffer, NULL, 0u );
176
177     /* Get glyph data */
178     unsigned int glyphCount;
179     hb_glyph_info_t* glyphInfo = hb_buffer_get_glyph_infos( harfBuzzBuffer, &glyphCount );
180     hb_glyph_position_t *glyphPositions = hb_buffer_get_glyph_positions( harfBuzzBuffer, &glyphCount );
181     const GlyphIndex lastGlyphIndex = glyphCount - 1u;
182     for( GlyphIndex i = 0u; i < glyphCount; )
183     {
184       if( rtlDirection )
185       {
186         // If the direction is right to left, Harfbuzz retrieves the glyphs in the visual order.
187         // The glyphs are needed in the logical order to layout the text in lines.
188         // Do not change the order of the glyphs if they belong to the same cluster.
189         GlyphIndex rtlIndex = lastGlyphIndex - i;
190
191         unsigned int cluster = glyphInfo[rtlIndex].cluster;
192         unsigned int previousCluster = cluster;
193         Length numberOfGlyphsInCluster = 0u;
194
195         while( ( cluster == previousCluster ) )
196         {
197           ++numberOfGlyphsInCluster;
198           previousCluster = cluster;
199
200           if( rtlIndex > 0u )
201           {
202             --rtlIndex;
203
204             cluster = glyphInfo[rtlIndex].cluster;
205           }
206           else
207           {
208             break;
209           }
210         }
211
212         rtlIndex = lastGlyphIndex - ( i + ( numberOfGlyphsInCluster - 1u ) );
213
214         for( GlyphIndex j = 0u; j < numberOfGlyphsInCluster; ++j )
215         {
216           const GlyphIndex index = rtlIndex + j;
217
218           mIndices.PushBack( glyphInfo[index].codepoint );
219           mAdvance.PushBack( floor( glyphPositions[index].x_advance * FROM_266 ) );
220           mCharacterMap.PushBack( glyphInfo[index].cluster );
221           mOffset.PushBack( floor( glyphPositions[index].x_offset * FROM_266 ) );
222           mOffset.PushBack( floor( glyphPositions[index].y_offset * FROM_266 ) );
223         }
224
225         i += numberOfGlyphsInCluster;
226       }
227       else
228       {
229         mIndices.PushBack( glyphInfo[i].codepoint );
230         mAdvance.PushBack( floor( glyphPositions[i].x_advance * FROM_266 ) );
231         mCharacterMap.PushBack( glyphInfo[i].cluster );
232         mOffset.PushBack( floor( glyphPositions[i].x_offset * FROM_266 ) );
233         mOffset.PushBack( floor( glyphPositions[i].y_offset * FROM_266 ) );
234
235         ++i;
236       }
237     }
238
239     /* Cleanup */
240     hb_buffer_destroy( harfBuzzBuffer );
241     hb_font_destroy( harfBuzzFont );
242     FT_Done_Face( face );
243
244     return mIndices.Count();
245   }
246
247   void GetGlyphs( GlyphInfo* glyphInfo,
248                   CharacterIndex* glyphToCharacterMap )
249   {
250     Vector<CharacterIndex>::ConstIterator indicesIt = mIndices.Begin();
251     Vector<float>::ConstIterator advanceIt = mAdvance.Begin();
252     Vector<float>::ConstIterator offsetIt = mOffset.Begin();
253     Vector<CharacterIndex>::ConstIterator characterMapIt = mCharacterMap.Begin();
254
255     for( GlyphIndex index = 0u, size = mIndices.Count(); index < size; ++index )
256     {
257       GlyphInfo& glyph = *( glyphInfo + index );
258       CharacterIndex& glyphToCharacter = *( glyphToCharacterMap + index );
259
260       glyph.fontId = mFontId;
261       glyph.index = *( indicesIt + index );
262       glyph.advance = *( advanceIt + index );
263
264       const GlyphIndex offsetIndex = 2u * index;
265       glyph.xBearing = *( offsetIt + offsetIndex );
266       glyph.yBearing = *( offsetIt + offsetIndex + 1u );
267
268       glyphToCharacter = *( characterMapIt + index );
269     }
270   }
271
272   FT_Library             mFreeTypeLibrary;
273
274   Vector<CharacterIndex> mIndices;
275   Vector<float>          mAdvance;
276   Vector<float>          mOffset;
277   Vector<CharacterIndex> mCharacterMap;
278   FontId                 mFontId;
279 };
280
281 Shaping::Shaping()
282 : mPlugin( NULL )
283 {
284 }
285
286 Shaping::~Shaping()
287 {
288   delete mPlugin;
289 }
290
291 TextAbstraction::Shaping Shaping::Get()
292 {
293   TextAbstraction::Shaping shapingHandle;
294
295   SingletonService service( SingletonService::Get() );
296   if( service )
297   {
298     // Check whether the singleton is already created
299     Dali::BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::Shaping ) );
300     if( handle )
301     {
302       // If so, downcast the handle
303       Shaping* impl = dynamic_cast< Internal::Shaping* >( handle.GetObjectPtr() );
304       shapingHandle = TextAbstraction::Shaping( impl );
305     }
306     else // create and register the object
307     {
308       shapingHandle = TextAbstraction::Shaping( new Shaping );
309       service.Register( typeid( shapingHandle ), shapingHandle );
310     }
311   }
312
313   return shapingHandle;
314 }
315
316 Length Shaping::Shape( const Character* const text,
317                        Length numberOfCharacters,
318                        FontId fontId,
319                        Script script )
320 {
321   CreatePlugin();
322
323   return mPlugin->Shape( text,
324                          numberOfCharacters,
325                          fontId,
326                          script );
327 }
328
329 void Shaping::GetGlyphs( GlyphInfo* glyphInfo,
330                          CharacterIndex* glyphToCharacterMap )
331 {
332   CreatePlugin();
333
334   mPlugin->GetGlyphs( glyphInfo,
335                       glyphToCharacterMap );
336 }
337
338 void Shaping::CreatePlugin()
339 {
340   if( !mPlugin )
341   {
342     mPlugin = new Plugin();
343     mPlugin->Initialize();
344   }
345 }
346
347 } // namespace Internal
348
349 } // namespace TextAbstraction
350
351 } // namespace Dali