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