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