Merge "Renamed TextVisual::DoSetProperty to SetProperty" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / text / text-visual.cpp
1 /*
2  * Copyright (c) 2016 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 <dali-toolkit/internal/visuals/text/text-visual.h>
20
21 // INTERNAL HEADER
22 #include <dali-toolkit/devel-api/visual-factory/devel-visual-properties.h>
23 #include <dali-toolkit/devel-api/visuals/text-visual-properties.h>
24 #include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
25 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
26 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
27 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
28 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
29 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
30 #include <dali-toolkit/internal/text/text-font-style.h>
31
32 namespace Dali
33 {
34
35 namespace Toolkit
36 {
37
38 namespace Internal
39 {
40
41 namespace
42 {
43
44 // Property names.
45 const char * const TEXT_PROPERTY( "text" );
46 const char * const FONT_FAMILY_PROPERTY( "fontFamily" );
47 const char * const FONT_STYLE_PROPERTY( "fontStyle" );
48 const char * const POINT_SIZE_PROPERTY( "pointSize" );
49 const char * const MULTI_LINE_PROPERTY( "multiLine" );
50 const char * const HORIZONTAL_ALIGNMENT_PROPERTY( "horizontalAlignment" );
51 const char * const VERTICAL_ALIGNMENT_PROPERTY( "verticalAlignment" );
52 const char * const TEXT_COLOR_PROPERTY( "textColor" );
53 const char * const ENABLE_MARKUP_PROPERTY( "enableMarkup" );
54
55 const std::string PIXEL_AREA_UNIFORM_NAME = "pixelArea";
56
57 const Scripting::StringEnum HORIZONTAL_ALIGNMENT_STRING_TABLE[] =
58 {
59   { "BEGIN",  Toolkit::Text::Layout::HORIZONTAL_ALIGN_BEGIN  },
60   { "CENTER", Toolkit::Text::Layout::HORIZONTAL_ALIGN_CENTER },
61   { "END",    Toolkit::Text::Layout::HORIZONTAL_ALIGN_END    },
62 };
63 const unsigned int HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof( HORIZONTAL_ALIGNMENT_STRING_TABLE ) / sizeof( HORIZONTAL_ALIGNMENT_STRING_TABLE[0] );
64
65 const Scripting::StringEnum VERTICAL_ALIGNMENT_STRING_TABLE[] =
66 {
67   { "TOP",    Toolkit::Text::Layout::VERTICAL_ALIGN_TOP    },
68   { "CENTER", Toolkit::Text::Layout::VERTICAL_ALIGN_CENTER },
69   { "BOTTOM", Toolkit::Text::Layout::VERTICAL_ALIGN_BOTTOM },
70 };
71 const unsigned int VERTICAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof( VERTICAL_ALIGNMENT_STRING_TABLE ) / sizeof( VERTICAL_ALIGNMENT_STRING_TABLE[0] );
72
73 const Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f );
74
75 std::string GetHorizontalAlignment( Toolkit::Text::Layout::HorizontalAlignment alignment )
76 {
77   const char* name = Scripting::GetEnumerationName<Toolkit::Text::Layout::HorizontalAlignment>( alignment,
78                                                                                                 HORIZONTAL_ALIGNMENT_STRING_TABLE,
79                                                                                                 HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT );
80
81   return std::string( name );
82 }
83
84 std::string GetVerticalAlignment( Toolkit::Text::Layout::VerticalAlignment alignment )
85 {
86   const char* name = Scripting::GetEnumerationName< Toolkit::Text::Layout::VerticalAlignment >( alignment,
87                                                                                                 VERTICAL_ALIGNMENT_STRING_TABLE,
88                                                                                                 VERTICAL_ALIGNMENT_STRING_TABLE_COUNT );
89
90   return std::string( name );
91 }
92
93 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
94   attribute mediump vec2 aPosition;\n
95   uniform mediump mat4 uMvpMatrix;\n
96   uniform mediump vec3 uSize;\n
97   uniform mediump vec4 pixelArea;
98   varying mediump vec2 vTexCoord;\n
99   \n
100
101   //Visual size and offset
102   uniform mediump vec2 offset;\n
103   uniform mediump vec2 size;\n
104   uniform mediump vec4 offsetSizeMode;\n
105   uniform mediump vec2 origin;\n
106   uniform mediump vec2 anchorPoint;\n
107
108   vec4 ComputeVertexPosition()\n
109   {\n
110     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
111     vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
112     return vec4( (aPosition + anchorPoint)*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
113   }\n
114
115   void main()\n
116   {\n
117     mediump vec4 vertexPosition = uMvpMatrix *ComputeVertexPosition();\n
118     vTexCoord = pixelArea.xy+pixelArea.zw*(aPosition + vec2(0.5) );\n
119     gl_Position = vertexPosition;\n
120   }\n
121 );
122
123 const char* FRAGMENT_SHADER_ATLAS_CLAMP = DALI_COMPOSE_SHADER(
124     varying mediump vec2 vTexCoord;\n
125     uniform sampler2D sTexture;\n
126     uniform mediump vec4 uAtlasRect;\n
127     uniform lowp vec4 uColor;\n
128     \n
129     void main()\n
130     {\n
131       mediump vec2 texCoord = clamp( mix( uAtlasRect.xy, uAtlasRect.zw, vTexCoord ), uAtlasRect.xy, uAtlasRect.zw );\n
132       gl_FragColor = texture2D( sTexture, texCoord ) * uColor;\n
133     }\n
134 );
135
136 } // unnamed namespace
137
138 TextVisualPtr TextVisual::New( VisualFactoryCache& factoryCache )
139 {
140   return new TextVisual( factoryCache );
141 }
142
143 float TextVisual::GetHeightForWidth( float width ) const
144 {
145   return mController->GetHeightForWidth( width );
146 }
147
148 void TextVisual::GetNaturalSize( Vector2& naturalSize )
149 {
150   naturalSize = mController->GetNaturalSize().GetVectorXY();
151 }
152
153 void TextVisual::DoCreatePropertyMap( Property::Map& map ) const
154 {
155   Property::Value value;
156
157   map.Clear();
158   map.Insert( Toolkit::VisualProperty::TYPE, Toolkit::DevelVisual::TEXT );
159
160   std::string text;
161   mController->GetText( text );
162   map.Insert( Toolkit::TextVisual::Property::TEXT, text );
163
164   map.Insert( Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily() );
165
166   GetFontStyleProperty( mController, value, Text::FontStyle::DEFAULT );
167   map.Insert( Toolkit::TextVisual::Property::FONT_STYLE, value );
168
169   map.Insert( Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultPointSize() );
170
171   map.Insert( Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled() );
172
173   map.Insert( Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, GetHorizontalAlignment( mController->GetHorizontalAlignment() ) );
174
175   map.Insert( Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, GetVerticalAlignment( mController->GetVerticalAlignment() ) );
176
177   map.Insert( Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor() );
178
179   map.Insert( Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled() );
180 }
181
182 TextVisual::TextVisual( VisualFactoryCache& factoryCache )
183 : Visual::Base( factoryCache ),
184   mController( Text::Controller::New() ),
185   mTypesetter( Text::Typesetter::New( mController->GetTextModel() ) )
186 {
187 }
188
189 TextVisual::~TextVisual()
190 {
191 }
192
193 void TextVisual::DoSetProperties( const Property::Map& propertyMap )
194 {
195   for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
196   {
197     const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
198
199     switch( keyValue.first.type )
200     {
201       case Property::Key::INDEX:
202       {
203         if( Toolkit::VisualProperty::TYPE != keyValue.first.indexKey ) // Toolkit::VisualProperty::TYPE is not a TextVisual's property.
204         {
205           SetProperty( keyValue.first.indexKey, keyValue.second );
206         }
207         break;
208       }
209       case Property::Key::STRING:
210       {
211         if( keyValue.first.stringKey == TEXT_PROPERTY )
212         {
213           SetProperty( Toolkit::TextVisual::Property::TEXT, keyValue.second );
214         }
215         else if( keyValue.first.stringKey == FONT_FAMILY_PROPERTY )
216         {
217           SetProperty( Toolkit::TextVisual::Property::FONT_FAMILY, keyValue.second );
218         }
219         else if( keyValue.first.stringKey == FONT_STYLE_PROPERTY )
220         {
221           SetProperty( Toolkit::TextVisual::Property::FONT_STYLE, keyValue.second );
222         }
223         else if( keyValue.first.stringKey == POINT_SIZE_PROPERTY )
224         {
225           SetProperty( Toolkit::TextVisual::Property::POINT_SIZE, keyValue.second );
226         }
227         else if( keyValue.first.stringKey == MULTI_LINE_PROPERTY )
228         {
229           SetProperty( Toolkit::TextVisual::Property::MULTI_LINE, keyValue.second );
230         }
231         else if( keyValue.first.stringKey == HORIZONTAL_ALIGNMENT_PROPERTY )
232         {
233           SetProperty( Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, keyValue.second );
234         }
235         else if( keyValue.first.stringKey == VERTICAL_ALIGNMENT_PROPERTY )
236         {
237           SetProperty( Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, keyValue.second );
238         }
239         else if( keyValue.first.stringKey == TEXT_COLOR_PROPERTY )
240         {
241           SetProperty( Toolkit::TextVisual::Property::TEXT_COLOR, keyValue.second );
242         }
243         else if( keyValue.first.stringKey == ENABLE_MARKUP_PROPERTY )
244         {
245           SetProperty( Toolkit::TextVisual::Property::ENABLE_MARKUP, keyValue.second );
246         }
247         break;
248       }
249     }
250   }
251
252   // Elide the text if it exceeds the boundaries.
253   mController->SetTextElideEnabled( true );
254
255   // Retrieve the layout engine to set the cursor's width.
256   Text::Layout::Engine& engine = mController->GetLayoutEngine();
257
258   // Sets 0 as cursor's width.
259   engine.SetCursorWidth( 0u ); // Do not layout space for the cursor.
260 }
261
262 void TextVisual::DoSetOnStage( Actor& actor )
263 {
264   mControl = actor;
265
266   CreateRenderer();
267 }
268
269 void TextVisual::DoSetOffStage( Actor& actor )
270 {
271   if( mImpl->mRenderer )
272   {
273     // Removes the renderer from the actor.
274     actor.RemoveRenderer( mImpl->mRenderer );
275
276     DestroyRenderer();
277   }
278
279   // Resets the control handle.
280   mControl.Reset();
281 }
282
283 void TextVisual::SetProperty( Dali::Property::Index index, const Dali::Property::Value& propertyValue )
284 {
285   switch( index )
286   {
287     case Toolkit::TextVisual::Property::TEXT:
288     {
289       mController->SetText( propertyValue.Get<std::string>() );
290       break;
291     }
292     case Toolkit::TextVisual::Property::FONT_FAMILY:
293     {
294       SetFontFamilyProperty( mController, propertyValue );
295       break;
296     }
297     case Toolkit::TextVisual::Property::FONT_STYLE:
298     {
299       SetFontStyleProperty( mController, propertyValue, Text::FontStyle::DEFAULT );
300       break;
301     }
302     case Toolkit::TextVisual::Property::POINT_SIZE:
303     {
304       const float pointSize = propertyValue.Get<float>();
305
306       if( !Equals( mController->GetDefaultPointSize(), pointSize ) )
307       {
308         mController->SetDefaultPointSize( pointSize );
309       }
310       break;
311     }
312     case Toolkit::TextVisual::Property::MULTI_LINE:
313     {
314       mController->SetMultiLineEnabled( propertyValue.Get<bool>() );
315       break;
316     }
317     case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
318     {
319       Toolkit::Text::Layout::HorizontalAlignment alignment( Toolkit::Text::Layout::HORIZONTAL_ALIGN_BEGIN );
320       if( Scripting::GetEnumeration< Toolkit::Text::Layout::HorizontalAlignment >( propertyValue.Get< std::string >().c_str(),
321                                                                                    HORIZONTAL_ALIGNMENT_STRING_TABLE,
322                                                                                    HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT,
323                                                                                    alignment ) )
324       {
325         mController->SetHorizontalAlignment( alignment );
326       }
327       break;
328     }
329     case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
330     {
331       Toolkit::Text::Layout::VerticalAlignment alignment( Toolkit::Text::Layout::VERTICAL_ALIGN_BOTTOM );
332       if( Scripting::GetEnumeration< Toolkit::Text::Layout::VerticalAlignment >( propertyValue.Get< std::string >().c_str(),
333                                                                                  VERTICAL_ALIGNMENT_STRING_TABLE,
334                                                                                  VERTICAL_ALIGNMENT_STRING_TABLE_COUNT,
335                                                                                  alignment ) )
336       {
337         mController->SetVerticalAlignment( alignment );
338       }
339       break;
340     }
341     case Toolkit::TextVisual::Property::TEXT_COLOR:
342     {
343       const Vector4& textColor = propertyValue.Get< Vector4 >();
344       if( mController->GetDefaultColor() != textColor )
345       {
346         mController->SetDefaultColor( textColor );
347       }
348       break;
349     }
350     case Toolkit::TextVisual::Property::ENABLE_MARKUP:
351     {
352       const bool enableMarkup = propertyValue.Get<bool>();
353       mController->SetMarkupProcessorEnabled( enableMarkup );
354       break;
355     }
356     default:
357     {
358       // Should not arrive here.
359       DALI_ASSERT_DEBUG( false );
360     }
361   }
362 }
363
364 void TextVisual::OnSetTransform()
365 {
366   CreateRenderer();
367 }
368
369 void TextVisual::CreateRenderer()
370 {
371   Actor control = mControl.GetHandle();
372   if( !control )
373   {
374     // Nothing to do.
375     return;
376   }
377
378   // Calculates the size to be used to relayout.
379   Vector2 relayoutSize;
380
381   const bool isWidthRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.z ) < Math::MACHINE_EPSILON_1000;
382   const bool isHeightRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.w ) < Math::MACHINE_EPSILON_1000;
383
384   // Round the size and offset to avoid pixel alignement issues.
385   relayoutSize.width = floorf( 0.5f + ( isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width ) );
386   relayoutSize.height = floorf( 0.5f + ( isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height ) );
387
388   if( ( fabsf( relayoutSize.width ) < Math::MACHINE_EPSILON_1000 ) || ( fabsf( relayoutSize.height ) < Math::MACHINE_EPSILON_1000 ) )
389   {
390     // Remove any renderer previously set.
391     if( mImpl->mRenderer )
392     {
393       control.RemoveRenderer( mImpl->mRenderer );
394
395       DestroyRenderer();
396     }
397
398     // Nothing else to do if the relayout size is zero.
399     return;
400   }
401
402   const Text::Controller::UpdateTextType updateTextType = mController->Relayout( relayoutSize );
403
404   if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) )
405   {
406     // Remove any renderer previously set.
407     if( mImpl->mRenderer )
408     {
409       control.RemoveRenderer( mImpl->mRenderer );
410
411       DestroyRenderer();
412     }
413
414     if( ( relayoutSize.width > Math::MACHINE_EPSILON_1000 ) &&
415         ( relayoutSize.height > Math::MACHINE_EPSILON_1000 ) )
416     {
417       PixelData data = mTypesetter->Render( relayoutSize );
418
419       Geometry geometry;
420       Shader shader;
421       TextureSet textureSet;
422
423       Vector4 atlasRect;
424
425       textureSet = mFactoryCache.GetAtlasManager()->Add( atlasRect, data );
426       mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
427
428       // Filter mode needs to be set to nearest to avoid blurry text.
429       Sampler sampler = Sampler::New();
430       sampler.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
431       textureSet.SetSampler( 0u, sampler );
432
433       geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
434       if( !geometry )
435       {
436         geometry =  VisualFactoryCache::CreateQuadGeometry();
437         mFactoryCache.SaveGeometry( VisualFactoryCache::QUAD_GEOMETRY , geometry );
438       }
439
440       shader = mFactoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP );
441       if( !shader )
442       {
443         shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_ATLAS_CLAMP );
444         mFactoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP, shader );
445       }
446       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
447
448       mImpl->mRenderer = Renderer::New( geometry, shader );
449       mImpl->mRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::TEXT );
450       mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect );
451
452       mImpl->mRenderer.SetTextures( textureSet );
453
454       control.AddRenderer( mImpl->mRenderer );
455
456       //Register transform properties
457       mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
458
459       mImpl->mFlags |= Impl::IS_FROM_CACHE;
460     }
461   }
462 }
463
464 void TextVisual::DestroyRenderer()
465 {
466   // Removes the text's image from the texture atlas.
467   Vector4 atlasRect;
468
469   const Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
470   if( index != Property::INVALID_INDEX )
471   {
472     const Property::Value& atlasRectValue = mImpl->mRenderer.GetProperty( index );
473     atlasRectValue.Get( atlasRect );
474
475     const TextureSet& textureSet = mImpl->mRenderer.GetTextures();
476     mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
477   }
478
479   // Resets the renderer.
480   mImpl->mRenderer.Reset();
481 }
482
483 } // namespace Internal
484
485 } // namespace Toolkit
486
487 } // namespace Dali