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