Fix SVACE issue
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / text / text-visual.cpp
1 /*
2  * Copyright (c) 2017 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   if( name )
78   {
79     return std::string( name );
80   }
81   return std::string();
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   if( name )
91   {
92     return std::string( name );
93   }
94   return std::string();
95 }
96
97 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
98   attribute mediump vec2 aPosition;\n
99   uniform mediump mat4 uMvpMatrix;\n
100   uniform mediump vec3 uSize;\n
101   uniform mediump vec4 pixelArea;
102
103   uniform mediump mat4 uModelMatrix;\n
104   uniform mediump mat4 uViewMatrix;\n
105   uniform mediump mat4 uProjection;\n
106
107   varying mediump vec2 vTexCoord;\n
108   \n
109   //Visual size and offset
110   uniform mediump vec2 offset;\n
111   uniform mediump vec2 size;\n
112   uniform mediump vec4 offsetSizeMode;\n
113   uniform mediump vec2 origin;\n
114   uniform mediump vec2 anchorPoint;\n
115
116   vec4 ComputeVertexPosition()\n
117   {\n
118     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
119     vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
120     return vec4( (aPosition + anchorPoint)*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
121   }\n
122
123   void main()\n
124   {\n
125     mediump vec4 nonAlignedVertex = uViewMatrix*uModelMatrix*ComputeVertexPosition();\n
126     mediump vec4 pixelAlignedVertex = vec4 ( floor(nonAlignedVertex.xyz), 1.0 );\n
127     mediump vec4 vertexPosition = uProjection*pixelAlignedVertex;\n
128
129     vTexCoord = pixelArea.xy+pixelArea.zw*(aPosition + vec2(0.5) );\n
130     gl_Position = vertexPosition;\n
131   }\n
132 );
133
134 const char* FRAGMENT_SHADER_ATLAS_CLAMP = DALI_COMPOSE_SHADER(
135     varying mediump vec2 vTexCoord;\n
136     uniform sampler2D sTexture;\n
137     uniform mediump vec4 uAtlasRect;\n
138     uniform lowp vec4 uColor;\n
139     uniform lowp vec3 mixColor;\n
140     uniform lowp float opacity;\n
141     \n
142     void main()\n
143     {\n
144       mediump vec2 texCoord = clamp( mix( uAtlasRect.xy, uAtlasRect.zw, vTexCoord ), uAtlasRect.xy, uAtlasRect.zw );\n
145       gl_FragColor = texture2D( sTexture, texCoord ) * uColor * vec4( mixColor, opacity );\n
146     }\n
147 );
148
149 /**
150  * Return Property index for the given string key
151  * param[in] stringKey the string index key
152  * return the key as an index
153  */
154
155 Dali::Property::Index StringKeyToIndexKey( const std::string& stringKey )
156 {
157   Dali::Property::Index result = Property::INVALID_KEY;
158
159   if( stringKey == VISUAL_TYPE )
160   {
161     result = Toolkit::Visual::Property::TYPE;
162   }
163   else if( stringKey == TEXT_PROPERTY )
164   {
165     result = Toolkit::TextVisual::Property::TEXT;
166   }
167   else if( stringKey == FONT_FAMILY_PROPERTY )
168   {
169     result = Toolkit::TextVisual::Property::FONT_FAMILY;
170   }
171   else if( stringKey == FONT_STYLE_PROPERTY )
172   {
173     result = Toolkit::TextVisual::Property::FONT_STYLE;
174   }
175   else if( stringKey == POINT_SIZE_PROPERTY )
176   {
177     result = Toolkit::TextVisual::Property::POINT_SIZE;
178   }
179   else if( stringKey == MULTI_LINE_PROPERTY )
180   {
181     result = Toolkit::TextVisual::Property::MULTI_LINE;
182   }
183   else if( stringKey == HORIZONTAL_ALIGNMENT_PROPERTY )
184   {
185     result = Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT;
186   }
187   else if( stringKey == VERTICAL_ALIGNMENT_PROPERTY )
188   {
189     result = Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT;
190   }
191   else if( stringKey == TEXT_COLOR_PROPERTY )
192   {
193     result = Toolkit::TextVisual::Property::TEXT_COLOR;
194   }
195   else if( stringKey == ENABLE_MARKUP_PROPERTY )
196   {
197     result = Toolkit::TextVisual::Property::ENABLE_MARKUP;
198   }
199
200   return result;
201 }
202
203 } // unnamed namespace
204
205 TextVisualPtr TextVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
206 {
207   TextVisualPtr TextVisualPtr( new TextVisual( factoryCache ) );
208   TextVisualPtr->SetProperties( properties );
209   return TextVisualPtr;
210 }
211
212 void TextVisual::ConvertStringKeysToIndexKeys( Property::Map& propertyMap )
213 {
214   Property::Map outMap;
215
216   for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
217   {
218     const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
219
220     Property::Index indexKey = keyValue.first.indexKey;
221
222     if ( keyValue.first.type == Property::Key::STRING )
223     {
224       indexKey = StringKeyToIndexKey( keyValue.first.stringKey );
225     }
226
227     outMap.Insert( indexKey, keyValue.second );
228   }
229
230   propertyMap = outMap;
231 }
232
233 float TextVisual::GetHeightForWidth( float width )
234 {
235   return mController->GetHeightForWidth( width );
236 }
237
238 void TextVisual::GetNaturalSize( Vector2& naturalSize )
239 {
240   naturalSize = mController->GetNaturalSize().GetVectorXY();
241 }
242
243 void TextVisual::DoCreatePropertyMap( Property::Map& map ) const
244 {
245   Property::Value value;
246
247   map.Clear();
248   map.Insert( Toolkit::DevelVisual::Property::TYPE, Toolkit::DevelVisual::TEXT );
249
250   std::string text;
251   mController->GetText( text );
252   map.Insert( Toolkit::TextVisual::Property::TEXT, text );
253
254   map.Insert( Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily() );
255
256   GetFontStyleProperty( mController, value, Text::FontStyle::DEFAULT );
257   map.Insert( Toolkit::TextVisual::Property::FONT_STYLE, value );
258
259   map.Insert( Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ) );
260
261   map.Insert( Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled() );
262
263   map.Insert( Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, GetHorizontalAlignment( mController->GetHorizontalAlignment() ) );
264
265   map.Insert( Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, GetVerticalAlignment( mController->GetVerticalAlignment() ) );
266
267   map.Insert( Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor() );
268
269   map.Insert( Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled() );
270 }
271
272 void TextVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
273 {
274   map.Clear();
275   map.Insert( Toolkit::DevelVisual::Property::TYPE, Toolkit::DevelVisual::TEXT );
276   std::string text;
277   mController->GetText( text );
278   map.Insert( Toolkit::TextVisual::Property::TEXT, text );
279 }
280
281
282 TextVisual::TextVisual( VisualFactoryCache& factoryCache )
283 : Visual::Base( factoryCache ),
284   mController( Text::Controller::New() ),
285   mTypesetter( Text::Typesetter::New( mController->GetTextModel() ) )
286 {
287 }
288
289 TextVisual::~TextVisual()
290 {
291 }
292
293 void TextVisual::DoSetProperties( const Property::Map& propertyMap )
294 {
295   for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
296   {
297     const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
298
299     Property::Index indexKey = keyValue.first.indexKey;
300
301     if( keyValue.first.type == Property::Key::STRING )
302     {
303       indexKey = StringKeyToIndexKey( keyValue.first.stringKey );
304     }
305
306     DoSetProperty( indexKey, keyValue.second );
307   }
308
309   // Elide the text if it exceeds the boundaries.
310   mController->SetTextElideEnabled( true );
311
312   // Retrieve the layout engine to set the cursor's width.
313   Text::Layout::Engine& engine = mController->GetLayoutEngine();
314
315   // Sets 0 as cursor's width.
316   engine.SetCursorWidth( 0u ); // Do not layout space for the cursor.
317 }
318
319 void TextVisual::DoSetOnStage( Actor& actor )
320 {
321   mControl = actor;
322
323   Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
324
325   Shader shader = mFactoryCache.GetShader( VisualFactoryCache::TEXT_SHADER );
326   if( ! shader )
327   {
328     shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_ATLAS_CLAMP );
329     shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
330
331     mFactoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER, shader );
332   }
333
334   mImpl->mRenderer = Renderer::New( geometry, shader );
335   mImpl->mRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT );
336
337   UpdateRenderer( true ); // Renderer needs textures and to be added to control
338 }
339
340 void TextVisual::DoSetOffStage( Actor& actor )
341 {
342   if( mImpl->mRenderer )
343   {
344     // Removes the renderer from the actor.
345     actor.RemoveRenderer( mImpl->mRenderer );
346
347     RemoveTextureSet();
348
349     // Resets the renderer.
350     mImpl->mRenderer.Reset();
351   }
352
353   // Resets the control handle.
354   mControl.Reset();
355 }
356
357 void TextVisual::OnSetTransform()
358 {
359   UpdateRenderer( false );
360 }
361
362 void TextVisual::DoSetProperty( Dali::Property::Index index, const Dali::Property::Value& propertyValue )
363 {
364   switch( index )
365   {
366     case Toolkit::TextVisual::Property::ENABLE_MARKUP:
367     {
368       const bool enableMarkup = propertyValue.Get<bool>();
369       mController->SetMarkupProcessorEnabled( enableMarkup );
370       break;
371     }
372     case Toolkit::TextVisual::Property::TEXT:
373     {
374       mController->SetText( propertyValue.Get<std::string>() );
375       break;
376     }
377     case Toolkit::TextVisual::Property::FONT_FAMILY:
378     {
379       SetFontFamilyProperty( mController, propertyValue );
380       break;
381     }
382     case Toolkit::TextVisual::Property::FONT_STYLE:
383     {
384       SetFontStyleProperty( mController, propertyValue, Text::FontStyle::DEFAULT );
385       break;
386     }
387     case Toolkit::TextVisual::Property::POINT_SIZE:
388     {
389       const float pointSize = propertyValue.Get<float>();
390       if( !Equals( mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
391       {
392         mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE );
393       }
394       break;
395     }
396     case Toolkit::TextVisual::Property::MULTI_LINE:
397     {
398       mController->SetMultiLineEnabled( propertyValue.Get<bool>() );
399       break;
400     }
401     case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
402     {
403       Toolkit::Text::Layout::HorizontalAlignment alignment( Toolkit::Text::Layout::HORIZONTAL_ALIGN_BEGIN );
404       if( Scripting::GetEnumeration< Toolkit::Text::Layout::HorizontalAlignment >( propertyValue.Get< std::string >().c_str(),
405                                                                                    HORIZONTAL_ALIGNMENT_STRING_TABLE,
406                                                                                    HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT,
407                                                                                    alignment ) )
408       {
409         mController->SetHorizontalAlignment( alignment );
410       }
411       break;
412     }
413     case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
414     {
415       Toolkit::Text::Layout::VerticalAlignment alignment( Toolkit::Text::Layout::VERTICAL_ALIGN_BOTTOM );
416       if( Scripting::GetEnumeration< Toolkit::Text::Layout::VerticalAlignment >( propertyValue.Get< std::string >().c_str(),
417                                                                                  VERTICAL_ALIGNMENT_STRING_TABLE,
418                                                                                  VERTICAL_ALIGNMENT_STRING_TABLE_COUNT,
419                                                                                  alignment ) )
420       {
421         mController->SetVerticalAlignment( alignment );
422       }
423       break;
424     }
425     case Toolkit::TextVisual::Property::TEXT_COLOR:
426     {
427       const Vector4& textColor = propertyValue.Get< Vector4 >();
428       if( mController->GetDefaultColor() != textColor )
429       {
430         mController->SetDefaultColor( textColor );
431       }
432       break;
433     }
434   }
435 }
436
437 void TextVisual::UpdateRenderer( bool initializeRendererAndTexture )
438 {
439   Actor control = mControl.GetHandle();
440   if( !control )
441   {
442     // Nothing to do.
443     return;
444   }
445
446   // Calculates the size to be used to relayout.
447   Vector2 relayoutSize;
448
449   const bool isWidthRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.z ) < Math::MACHINE_EPSILON_1000;
450   const bool isHeightRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.w ) < Math::MACHINE_EPSILON_1000;
451
452   // Round the size and offset to avoid pixel alignement issues.
453   relayoutSize.width = floorf( 0.5f + ( isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width ) );
454   relayoutSize.height = floorf( 0.5f + ( isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height ) );
455
456   if( ( fabsf( relayoutSize.width ) < Math::MACHINE_EPSILON_1000 ) || ( fabsf( relayoutSize.height ) < Math::MACHINE_EPSILON_1000 ) )
457   {
458     // Removes the texture set.
459     RemoveTextureSet();
460
461     // Remove any renderer previously set.
462     if( mImpl->mRenderer )
463     {
464       control.RemoveRenderer( mImpl->mRenderer );
465     }
466
467     // Nothing else to do if the relayout size is zero.
468     ResourceReady();
469     return;
470   }
471
472   const Text::Controller::UpdateTextType updateTextType = mController->Relayout( relayoutSize );
473
474   if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) || initializeRendererAndTexture )
475   {
476     // Removes the texture set.
477     RemoveTextureSet();
478
479     // Remove any renderer previously set.
480     if( mImpl->mRenderer )
481     {
482       control.RemoveRenderer( mImpl->mRenderer );
483     }
484
485     if( ( relayoutSize.width > Math::MACHINE_EPSILON_1000 ) &&
486         ( relayoutSize.height > Math::MACHINE_EPSILON_1000 ) )
487     {
488       PixelData data = mTypesetter->Render( relayoutSize );
489
490       Vector4 atlasRect = FULL_TEXTURE_RECT;
491
492       // Texture set not retrieved from Atlas Manager whilst pixel offset visible.
493
494       // It may happen the image atlas can't handle a pixel data it exceeds the maximum size.
495       // In that case, create a texture. TODO: should tile the text.
496
497       Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D,
498                                       data.GetPixelFormat(),
499                                       data.GetWidth(),
500                                       data.GetHeight() );
501
502       texture.Upload( data );
503
504       TextureSet textureSet = TextureSet::New();
505       textureSet.SetTexture( 0u, texture );
506
507       mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
508
509       mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect );
510
511       //Register transform properties
512       mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
513
514       // Filter mode needs to be set to nearest to avoid blurry text.
515       Sampler sampler = Sampler::New();
516       sampler.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
517       textureSet.SetSampler( 0u, sampler );
518
519       mImpl->mRenderer.SetTextures( textureSet );
520
521       control.AddRenderer( mImpl->mRenderer );
522
523       // Text rendered and ready to display
524       ResourceReady();
525     }
526   }
527 }
528
529 void TextVisual::RemoveTextureSet()
530 {
531   if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
532   {
533     // Removes the text's image from the texture atlas.
534     Vector4 atlasRect;
535
536     const Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
537     if( index != Property::INVALID_INDEX )
538     {
539       const Property::Value& atlasRectValue = mImpl->mRenderer.GetProperty( index );
540       atlasRectValue.Get( atlasRect );
541
542       const TextureSet& textureSet = mImpl->mRenderer.GetTextures();
543       mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
544     }
545   }
546 }
547
548 } // namespace Internal
549
550 } // namespace Toolkit
551
552 } // namespace Dali