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