b67617abc47626da49f796314efd0cb8eb8784b6
[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           DoSetProperty( keyValue.first.indexKey, keyValue.second );
206         }
207         break;
208       }
209       case Property::Key::STRING:
210       {
211         if( keyValue.first.stringKey == TEXT_PROPERTY )
212         {
213           DoSetProperty( Toolkit::TextVisual::Property::TEXT, keyValue.second );
214         }
215         else if( keyValue.first.stringKey == FONT_FAMILY_PROPERTY )
216         {
217           DoSetProperty( Toolkit::TextVisual::Property::FONT_FAMILY, keyValue.second );
218         }
219         else if( keyValue.first.stringKey == FONT_STYLE_PROPERTY )
220         {
221           DoSetProperty( Toolkit::TextVisual::Property::FONT_STYLE, keyValue.second );
222         }
223         else if( keyValue.first.stringKey == POINT_SIZE_PROPERTY )
224         {
225           DoSetProperty( Toolkit::TextVisual::Property::POINT_SIZE, keyValue.second );
226         }
227         else if( keyValue.first.stringKey == MULTI_LINE_PROPERTY )
228         {
229           DoSetProperty( Toolkit::TextVisual::Property::MULTI_LINE, keyValue.second );
230         }
231         else if( keyValue.first.stringKey == HORIZONTAL_ALIGNMENT_PROPERTY )
232         {
233           DoSetProperty( Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, keyValue.second );
234         }
235         else if( keyValue.first.stringKey == VERTICAL_ALIGNMENT_PROPERTY )
236         {
237           DoSetProperty( Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, keyValue.second );
238         }
239         else if( keyValue.first.stringKey == TEXT_COLOR_PROPERTY )
240         {
241           DoSetProperty( Toolkit::TextVisual::Property::TEXT_COLOR, keyValue.second );
242         }
243         else if( keyValue.first.stringKey == ENABLE_MARKUP_PROPERTY )
244         {
245           DoSetProperty( 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::DoSetProperty( 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 Dali::Property::Value TextVisual::DoGetProperty( Dali::Property::Index index )
365 {
366   Dali::Property::Value value;
367
368   switch( index )
369   {
370     case Toolkit::TextVisual::Property::TEXT:
371     {
372       std::string text;
373       mController->GetText( text );
374       value = text;
375       break;
376     }
377     case Toolkit::TextVisual::Property::FONT_FAMILY:
378     {
379       value = mController->GetDefaultFontFamily();
380       break;
381     }
382     case Toolkit::TextVisual::Property::FONT_STYLE:
383     {
384       GetFontStyleProperty( mController, value, Text::FontStyle::DEFAULT );
385       break;
386     }
387     case Toolkit::TextVisual::Property::POINT_SIZE:
388     {
389       value = mController->GetDefaultPointSize();
390       break;
391     }
392     case Toolkit::TextVisual::Property::MULTI_LINE:
393     {
394       value = mController->IsMultiLineEnabled();
395       break;
396     }
397     case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
398     {
399       const char* name = Scripting::GetEnumerationName< Toolkit::Text::Layout::HorizontalAlignment >( mController->GetHorizontalAlignment(),
400                                                                                                       HORIZONTAL_ALIGNMENT_STRING_TABLE,
401                                                                                                       HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT );
402       if( name )
403       {
404         value = std::string( name );
405       }
406       break;
407     }
408     case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
409     {
410       const char* name = Scripting::GetEnumerationName< Toolkit::Text::Layout::VerticalAlignment >( mController->GetVerticalAlignment(),
411                                                                                                     VERTICAL_ALIGNMENT_STRING_TABLE,
412                                                                                                     VERTICAL_ALIGNMENT_STRING_TABLE_COUNT );
413       if( name )
414       {
415         value = std::string( name );
416       }
417       break;
418     }
419     case Toolkit::TextVisual::Property::TEXT_COLOR:
420     {
421       value = mController->GetDefaultColor();
422       break;
423     }
424     case Toolkit::TextVisual::Property::ENABLE_MARKUP:
425     {
426       value = mController->IsMarkupProcessorEnabled();
427       break;
428     }
429     default:
430     {
431       // Should not arrive here.
432       DALI_ASSERT_DEBUG( false );
433     }
434   }
435
436   return value;
437 }
438
439 void TextVisual::OnSetTransform()
440 {
441   CreateRenderer();
442 }
443
444 void TextVisual::CreateRenderer()
445 {
446   Actor control = mControl.GetHandle();
447   if( !control )
448   {
449     // Nothing to do.
450     return;
451   }
452
453   // Calculates the size to be used to relayout.
454   Vector2 relayoutSize;
455
456   const bool isWidthRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.z ) < Math::MACHINE_EPSILON_1000;
457   const bool isHeightRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.w ) < Math::MACHINE_EPSILON_1000;
458
459   // Round the size and offset to avoid pixel alignement issues.
460   relayoutSize.width = floorf( 0.5f + ( isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width ) );
461   relayoutSize.height = floorf( 0.5f + ( isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height ) );
462
463   if( ( fabsf( relayoutSize.width ) < Math::MACHINE_EPSILON_1000 ) || ( fabsf( relayoutSize.height ) < Math::MACHINE_EPSILON_1000 ) )
464   {
465     // Remove any renderer previously set.
466     if( mImpl->mRenderer )
467     {
468       control.RemoveRenderer( mImpl->mRenderer );
469
470       DestroyRenderer();
471     }
472
473     // Nothing else to do if the relayout size is zero.
474     return;
475   }
476
477   const Text::Controller::UpdateTextType updateTextType = mController->Relayout( relayoutSize );
478
479   if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) )
480   {
481     // Remove any renderer previously set.
482     if( mImpl->mRenderer )
483     {
484       control.RemoveRenderer( mImpl->mRenderer );
485
486       DestroyRenderer();
487     }
488
489     if( ( relayoutSize.width > Math::MACHINE_EPSILON_1000 ) &&
490         ( relayoutSize.height > Math::MACHINE_EPSILON_1000 ) )
491     {
492       PixelData data = mTypesetter->Render( relayoutSize );
493
494       Geometry geometry;
495       Shader shader;
496       TextureSet textureSet;
497
498       Vector4 atlasRect;
499
500       textureSet = mFactoryCache.GetAtlasManager()->Add( atlasRect, data );
501       mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
502
503       // Filter mode needs to be set to nearest to avoid blurry text.
504       Sampler sampler = Sampler::New();
505       sampler.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
506       textureSet.SetSampler( 0u, sampler );
507
508       geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
509       if( !geometry )
510       {
511         geometry =  VisualFactoryCache::CreateQuadGeometry();
512         mFactoryCache.SaveGeometry( VisualFactoryCache::QUAD_GEOMETRY , geometry );
513       }
514
515       shader = mFactoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP );
516       if( !shader )
517       {
518         shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_ATLAS_CLAMP );
519         mFactoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP, shader );
520       }
521       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
522
523       mImpl->mRenderer = Renderer::New( geometry, shader );
524       mImpl->mRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::TEXT );
525       mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect );
526
527       mImpl->mRenderer.SetTextures( textureSet );
528
529       control.AddRenderer( mImpl->mRenderer );
530
531       //Register transform properties
532       mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
533
534       mImpl->mFlags |= Impl::IS_FROM_CACHE;
535     }
536   }
537 }
538
539 void TextVisual::DestroyRenderer()
540 {
541   // Removes the text's image from the texture atlas.
542   Vector4 atlasRect;
543
544   const Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
545   if( index != Property::INVALID_INDEX )
546   {
547     const Property::Value& atlasRectValue = mImpl->mRenderer.GetProperty( index );
548     atlasRectValue.Get( atlasRect );
549
550     const TextureSet& textureSet = mImpl->mRenderer.GetTextures();
551     mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
552   }
553
554   // Resets the renderer.
555   mImpl->mRenderer.Reset();
556 }
557
558 } // namespace Internal
559
560 } // namespace Toolkit
561
562 } // namespace Dali