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