Merge "Fix documentation for Text::EditableControlInterface interface override functi...
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / text / text-visual.cpp
1 /*
2  * Copyright (c) 2020 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 // EXTERNAL INCLUDES
22 #include <dali/public-api/animation/constraints.h>
23 #include <dali/devel-api/rendering/renderer-devel.h>
24 #include <dali/devel-api/text-abstraction/text-abstraction-definitions.h>
25 #include <dali/devel-api/adaptor-framework/image-loading.h>
26 #include <dali/devel-api/adaptor-framework/window-devel.h>
27 #include <dali/devel-api/images/pixel-data-devel.h>
28 #include <string.h>
29
30 // INTERNAL HEADER
31 #include <dali-toolkit/public-api/visuals/text-visual-properties.h>
32 #include <dali-toolkit/devel-api/visuals/text-visual-properties-devel.h>
33 #include <dali-toolkit/public-api/visuals/visual-properties.h>
34 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
35 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
36 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
37 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
38 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
39 #include <dali-toolkit/internal/text/text-font-style.h>
40 #include <dali-toolkit/internal/text/text-effects-style.h>
41 #include <dali-toolkit/internal/text/script-run.h>
42 #include <dali-toolkit/internal/text/text-enumerations-impl.h>
43 #include <dali-toolkit/devel-api/text/text-enumerations-devel.h>
44
45 namespace Dali
46 {
47
48 namespace Toolkit
49 {
50
51 namespace Internal
52 {
53
54 namespace
55 {
56 const Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f );
57
58 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
59   attribute mediump vec2 aPosition;\n
60   uniform highp   mat4 uMvpMatrix;\n
61   uniform highp   vec3 uSize;\n
62   uniform mediump vec4 pixelArea;\n
63
64   varying mediump vec2 vTexCoord;\n
65
66   //Visual size and offset
67   uniform mediump vec2 offset;\n
68   uniform highp   vec2 size;\n
69   uniform mediump vec4 offsetSizeMode;\n
70   uniform mediump vec2 origin;\n
71   uniform mediump vec2 anchorPoint;\n
72
73   vec4 ComputeVertexPosition()\n
74   {\n
75     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
76     vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
77     return vec4( (aPosition + anchorPoint)*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
78   }\n
79
80   void main()\n
81   {\n
82     gl_Position = uMvpMatrix * ComputeVertexPosition();\n
83     vTexCoord = pixelArea.xy+pixelArea.zw*(aPosition + vec2(0.5) );\n
84   }\n
85 );
86
87 const char* FRAGMENT_SHADER_SINGLE_COLOR_TEXT = DALI_COMPOSE_SHADER(
88   varying mediump vec2 vTexCoord;\n
89   uniform sampler2D sTexture;\n
90   uniform lowp vec4 uTextColorAnimatable;\n
91   uniform lowp vec4 uColor;\n
92   uniform lowp vec3 mixColor;\n
93   \n
94   void main()\n
95   {\n
96     mediump float textTexture = texture2D( sTexture, vTexCoord ).r;\n
97
98     // Set the color of the text to what it is animated to.
99     gl_FragColor = uTextColorAnimatable * textTexture * uColor * vec4( mixColor, 1.0 );
100   }\n
101 );
102
103 const char* FRAGMENT_SHADER_MULTI_COLOR_TEXT = DALI_COMPOSE_SHADER(
104   varying mediump vec2 vTexCoord;\n
105   uniform sampler2D sTexture;\n
106   uniform lowp vec4 uColor;\n
107   uniform lowp vec3 mixColor;\n
108   \n
109   void main()\n
110   {\n
111     mediump vec4 textTexture = texture2D( sTexture, vTexCoord );\n
112
113     gl_FragColor = textTexture * uColor * vec4( mixColor, 1.0 );
114   }\n
115 );
116
117 const char* FRAGMENT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE = DALI_COMPOSE_SHADER(
118   varying mediump vec2 vTexCoord;\n
119   uniform sampler2D sTexture;\n
120   uniform sampler2D sStyle;\n
121   uniform lowp vec4 uTextColorAnimatable;\n
122   uniform lowp vec4 uColor;\n
123   uniform lowp vec3 mixColor;\n
124   \n
125   void main()\n
126   {\n
127     mediump float textTexture = texture2D( sTexture, vTexCoord ).r;\n
128     mediump vec4 styleTexture = texture2D( sStyle, vTexCoord );\n
129
130     // Draw the text as overlay above the style
131     gl_FragColor = ( uTextColorAnimatable * textTexture + styleTexture * ( 1.0 - uTextColorAnimatable.a * textTexture ) ) * uColor * vec4( mixColor, 1.0 );\n
132   }\n
133 );
134
135 const char* FRAGMENT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE = DALI_COMPOSE_SHADER(
136   varying mediump vec2 vTexCoord;\n
137   uniform sampler2D sTexture;\n
138   uniform sampler2D sStyle;\n
139   uniform lowp vec4 uColor;\n
140   uniform lowp vec3 mixColor;\n
141   \n
142   void main()\n
143   {\n
144     mediump vec4 textTexture = texture2D( sTexture, vTexCoord );\n
145     mediump vec4 styleTexture = texture2D( sStyle, vTexCoord );\n
146
147     // Draw the text as overlay above the style
148     gl_FragColor = ( textTexture + styleTexture * ( 1.0 - textTexture.a ) ) * uColor * vec4( mixColor, 1.0 );\n
149   }\n
150 );
151
152 const char* FRAGMENT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI = DALI_COMPOSE_SHADER(
153   varying mediump vec2 vTexCoord;\n
154   uniform sampler2D sTexture;\n
155   uniform sampler2D sMask;\n
156   uniform lowp vec4 uTextColorAnimatable;\n
157   uniform lowp vec4 uColor;\n
158   uniform lowp vec3 mixColor;\n
159   \n
160   void main()\n
161   {\n
162     mediump vec4 textTexture = texture2D( sTexture, vTexCoord );\n
163     mediump float maskTexture = texture2D( sMask, vTexCoord ).r;\n
164
165     // Set the color of non-transparent pixel in text to what it is animated to.
166     // Markup text with multiple text colors are not animated (but can be supported later on if required).
167     // Emoji color are not animated.
168     mediump float vstep = step( 0.0001, textTexture.a );\n
169     textTexture.rgb = mix( textTexture.rgb, uTextColorAnimatable.rgb, vstep * maskTexture );\n
170
171     // Draw the text as overlay above the style
172     gl_FragColor = textTexture * uColor * vec4( mixColor, 1.0 );\n
173   }\n
174 );
175
176 const char* FRAGMENT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI = DALI_COMPOSE_SHADER(
177   varying mediump vec2 vTexCoord;\n
178   uniform sampler2D sTexture;\n
179   uniform sampler2D sStyle;\n
180   uniform sampler2D sMask;\n
181   uniform lowp float uHasMultipleTextColors;\n
182   uniform lowp vec4 uTextColorAnimatable;\n
183   uniform lowp vec4 uColor;\n
184   uniform lowp vec3 mixColor;\n
185   \n
186   void main()\n
187   {\n
188     mediump vec4 textTexture = texture2D( sTexture, vTexCoord );\n
189     mediump vec4 styleTexture = texture2D( sStyle, vTexCoord );\n
190     mediump float maskTexture = texture2D( sMask, vTexCoord ).r;\n
191
192     // Set the color of non-transparent pixel in text to what it is animated to.
193     // Markup text with multiple text colors are not animated (but can be supported later on if required).
194     // Emoji color are not animated.
195     mediump float vstep = step( 0.0001, textTexture.a );\n
196     textTexture.rgb = mix( textTexture.rgb, uTextColorAnimatable.rgb, vstep * maskTexture * ( 1.0 - uHasMultipleTextColors ) );\n
197
198     // Draw the text as overlay above the style
199     gl_FragColor = ( textTexture + styleTexture * ( 1.0 - textTexture.a ) ) * uColor * vec4( mixColor, 1.0 );\n
200   }\n
201 );
202
203 /**
204  * Return Property index for the given string key
205  * param[in] stringKey the string index key
206  * return the key as an index
207  */
208
209 Dali::Property::Index StringKeyToIndexKey( const std::string& stringKey )
210 {
211   Dali::Property::Index result = Property::INVALID_KEY;
212
213   if( stringKey == VISUAL_TYPE )
214   {
215     result = Toolkit::Visual::Property::TYPE;
216   }
217   else if( stringKey == TEXT_PROPERTY )
218   {
219     result = Toolkit::TextVisual::Property::TEXT;
220   }
221   else if( stringKey == FONT_FAMILY_PROPERTY )
222   {
223     result = Toolkit::TextVisual::Property::FONT_FAMILY;
224   }
225   else if( stringKey == FONT_STYLE_PROPERTY )
226   {
227     result = Toolkit::TextVisual::Property::FONT_STYLE;
228   }
229   else if( stringKey == POINT_SIZE_PROPERTY )
230   {
231     result = Toolkit::TextVisual::Property::POINT_SIZE;
232   }
233   else if( stringKey == MULTI_LINE_PROPERTY )
234   {
235     result = Toolkit::TextVisual::Property::MULTI_LINE;
236   }
237   else if( stringKey == HORIZONTAL_ALIGNMENT_PROPERTY )
238   {
239     result = Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT;
240   }
241   else if( stringKey == VERTICAL_ALIGNMENT_PROPERTY )
242   {
243     result = Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT;
244   }
245   else if( stringKey == TEXT_COLOR_PROPERTY )
246   {
247     result = Toolkit::TextVisual::Property::TEXT_COLOR;
248   }
249   else if( stringKey == ENABLE_MARKUP_PROPERTY )
250   {
251     result = Toolkit::TextVisual::Property::ENABLE_MARKUP;
252   }
253   else if( stringKey == SHADOW_PROPERTY )
254   {
255     result = Toolkit::TextVisual::Property::SHADOW;
256   }
257   else if( stringKey == UNDERLINE_PROPERTY )
258   {
259     result = Toolkit::TextVisual::Property::UNDERLINE;
260   }
261   else if( stringKey == OUTLINE_PROPERTY )
262   {
263     result = Toolkit::DevelTextVisual::Property::OUTLINE;
264   }
265   else if( stringKey == BACKGROUND_PROPERTY )
266   {
267     result = Toolkit::DevelTextVisual::Property::BACKGROUND;
268   }
269
270   return result;
271 }
272
273 void TextColorConstraint( Vector4& current, const PropertyInputContainer& inputs )
274 {
275   Vector4 color = inputs[0]->GetVector4();
276   current.r = color.r * color.a;
277   current.g = color.g * color.a;
278   current.b = color.b * color.a;
279   current.a = color.a;
280 }
281
282 void OpacityConstraint( float& current, const PropertyInputContainer& inputs )
283 {
284   // Make zero if the alpha value of text color is zero to skip rendering text
285   if( EqualsZero( inputs[0]->GetVector4().a ) )
286   {
287     current = 0.0f;
288   }
289   else
290   {
291     current = 1.0f;
292   }
293 }
294
295 } // unnamed namespace
296
297 TextVisualPtr TextVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
298 {
299   TextVisualPtr TextVisualPtr( new TextVisual( factoryCache ) );
300   TextVisualPtr->SetProperties( properties );
301   return TextVisualPtr;
302 }
303
304 Property::Map TextVisual::ConvertStringKeysToIndexKeys( const Property::Map& propertyMap )
305 {
306   Property::Map outMap;
307
308   for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
309   {
310     const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
311
312     Property::Index indexKey = keyValue.first.indexKey;
313
314     if ( keyValue.first.type == Property::Key::STRING )
315     {
316       indexKey = StringKeyToIndexKey( keyValue.first.stringKey );
317     }
318
319     outMap.Insert( indexKey, keyValue.second );
320   }
321
322   return outMap;
323 }
324
325 float TextVisual::GetHeightForWidth( float width )
326 {
327   return mController->GetHeightForWidth( width );
328 }
329
330 void TextVisual::GetNaturalSize( Vector2& naturalSize )
331 {
332   naturalSize = mController->GetNaturalSize().GetVectorXY();
333 }
334
335 void TextVisual::DoCreatePropertyMap( Property::Map& map ) const
336 {
337   Property::Value value;
338
339   map.Clear();
340   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT );
341
342   std::string text;
343   mController->GetText( text );
344   map.Insert( Toolkit::TextVisual::Property::TEXT, text );
345
346   map.Insert( Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily() );
347
348   GetFontStyleProperty( mController, value, Text::FontStyle::DEFAULT );
349   map.Insert( Toolkit::TextVisual::Property::FONT_STYLE, value );
350
351   map.Insert( Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ) );
352
353   map.Insert( Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled() );
354
355   map.Insert( Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, mController->GetHorizontalAlignment() );
356
357   map.Insert( Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, mController->GetVerticalAlignment() );
358
359   map.Insert( Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor() );
360
361   map.Insert( Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled() );
362
363   GetShadowProperties( mController, value, Text::EffectStyle::DEFAULT );
364   map.Insert( Toolkit::TextVisual::Property::SHADOW, value );
365
366   GetUnderlineProperties( mController, value, Text::EffectStyle::DEFAULT );
367   map.Insert( Toolkit::TextVisual::Property::UNDERLINE, value );
368
369   GetOutlineProperties( mController, value, Text::EffectStyle::DEFAULT );
370   map.Insert( Toolkit::DevelTextVisual::Property::OUTLINE, value );
371
372   GetBackgroundProperties( mController, value, Text::EffectStyle::DEFAULT );
373   map.Insert( Toolkit::DevelTextVisual::Property::BACKGROUND, value );
374 }
375
376 void TextVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
377 {
378   map.Clear();
379   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT );
380   std::string text;
381   mController->GetText( text );
382   map.Insert( Toolkit::TextVisual::Property::TEXT, text );
383 }
384
385
386 TextVisual::TextVisual( VisualFactoryCache& factoryCache )
387 : Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::TEXT ),
388   mController( Text::Controller::New() ),
389   mTypesetter( Text::Typesetter::New( mController->GetTextModel() ) ),
390   mAnimatableTextColorPropertyIndex( Property::INVALID_INDEX ),
391   mRendererUpdateNeeded( false )
392 {
393 }
394
395 TextVisual::~TextVisual()
396 {
397 }
398
399 void TextVisual::DoSetProperties( const Property::Map& propertyMap )
400 {
401   for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
402   {
403     const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
404
405     Property::Index indexKey = keyValue.first.indexKey;
406
407     if( keyValue.first.type == Property::Key::STRING )
408     {
409       indexKey = StringKeyToIndexKey( keyValue.first.stringKey );
410     }
411
412     DoSetProperty( indexKey, keyValue.second );
413   }
414
415   // Elide the text if it exceeds the boundaries.
416   mController->SetTextElideEnabled( true );
417
418   // Retrieve the layout engine to set the cursor's width.
419   Text::Layout::Engine& engine = mController->GetLayoutEngine();
420
421   // Sets 0 as cursor's width.
422   engine.SetCursorWidth( 0u ); // Do not layout space for the cursor.
423 }
424
425 void TextVisual::DoSetOnScene( Actor& actor )
426 {
427   mControl = actor;
428
429   Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
430   Shader shader = GetTextShader(mFactoryCache, TextType::SINGLE_COLOR_TEXT, TextType::NO_EMOJI, TextType::NO_STYLES);
431
432   mImpl->mRenderer = Renderer::New( geometry, shader );
433   mImpl->mRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT );
434
435   // Enable the pre-multiplied alpha to improve the text quality
436   EnablePreMultipliedAlpha(true);
437
438   const Vector4& defaultColor = mController->GetTextModel()->GetDefaultColor();
439   Dali::Property::Index shaderTextColorIndex = mImpl->mRenderer.RegisterProperty( "uTextColorAnimatable", defaultColor );
440
441   if ( mAnimatableTextColorPropertyIndex != Property::INVALID_INDEX )
442   {
443     // Create constraint for the animatable text's color Property with uTextColorAnimatable in the renderer.
444     if( shaderTextColorIndex != Property::INVALID_INDEX )
445     {
446       Constraint colorConstraint = Constraint::New<Vector4>( mImpl->mRenderer, shaderTextColorIndex, TextColorConstraint );
447       colorConstraint.AddSource( Source( actor, mAnimatableTextColorPropertyIndex ) );
448       colorConstraint.Apply();
449
450       // Make zero if the alpha value of text color is zero to skip rendering text
451       Constraint opacityConstraint = Constraint::New< float >( mImpl->mRenderer, Dali::DevelRenderer::Property::OPACITY, OpacityConstraint );
452       opacityConstraint.AddSource( Source( actor, mAnimatableTextColorPropertyIndex ) );
453       opacityConstraint.Apply();
454     }
455   }
456
457   // Renderer needs textures and to be added to control
458   mRendererUpdateNeeded = true;
459
460   mRendererList.push_back( mImpl->mRenderer );
461
462   UpdateRenderer();
463 }
464
465 void TextVisual::RemoveRenderer( Actor& actor )
466 {
467   for( RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
468   {
469     Renderer renderer = (*iter);
470     if( renderer )
471     {
472       // Removes the renderer from the actor.
473       actor.RemoveRenderer( renderer );
474     }
475   }
476   // Clear the renderer list
477   mRendererList.clear();
478 }
479
480 void TextVisual::DoSetOffScene( Actor& actor )
481 {
482   RemoveRenderer( actor );
483
484   // Resets the renderer.
485   mImpl->mRenderer.Reset();
486
487   // Resets the control handle.
488   mControl.Reset();
489 }
490
491 void TextVisual::OnSetTransform()
492 {
493   UpdateRenderer();
494 }
495
496 void TextVisual::DoSetProperty( Dali::Property::Index index, const Dali::Property::Value& propertyValue )
497 {
498   switch( index )
499   {
500     case Toolkit::TextVisual::Property::ENABLE_MARKUP:
501     {
502       const bool enableMarkup = propertyValue.Get<bool>();
503       mController->SetMarkupProcessorEnabled( enableMarkup );
504       break;
505     }
506     case Toolkit::TextVisual::Property::TEXT:
507     {
508       mController->SetText( propertyValue.Get<std::string>() );
509       break;
510     }
511     case Toolkit::TextVisual::Property::FONT_FAMILY:
512     {
513       SetFontFamilyProperty( mController, propertyValue );
514       break;
515     }
516     case Toolkit::TextVisual::Property::FONT_STYLE:
517     {
518       SetFontStyleProperty( mController, propertyValue, Text::FontStyle::DEFAULT );
519       break;
520     }
521     case Toolkit::TextVisual::Property::POINT_SIZE:
522     {
523       const float pointSize = propertyValue.Get<float>();
524       if( !Equals( mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
525       {
526         mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE );
527       }
528       break;
529     }
530     case Toolkit::TextVisual::Property::MULTI_LINE:
531     {
532       mController->SetMultiLineEnabled( propertyValue.Get<bool>() );
533       break;
534     }
535     case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
536     {
537       if( mController )
538       {
539         Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
540         if( Toolkit::Text::GetHorizontalAlignmentEnumeration( propertyValue, alignment ) )
541         {
542           mController->SetHorizontalAlignment( alignment );
543         }
544       }
545       break;
546     }
547     case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
548     {
549       if( mController )
550       {
551         Toolkit::Text::VerticalAlignment::Type alignment( static_cast< Text::VerticalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
552         if( Toolkit::Text::GetVerticalAlignmentEnumeration( propertyValue, alignment) )
553         {
554           mController->SetVerticalAlignment( alignment );
555         }
556       }
557       break;
558     }
559     case Toolkit::TextVisual::Property::TEXT_COLOR:
560     {
561       const Vector4& textColor = propertyValue.Get< Vector4 >();
562       if( mController->GetDefaultColor() != textColor )
563       {
564         mController->SetDefaultColor( textColor );
565       }
566       break;
567     }
568     case Toolkit::TextVisual::Property::SHADOW:
569     {
570       SetShadowProperties( mController, propertyValue, Text::EffectStyle::DEFAULT );
571       break;
572     }
573     case Toolkit::TextVisual::Property::UNDERLINE:
574     {
575       SetUnderlineProperties( mController, propertyValue, Text::EffectStyle::DEFAULT );
576       break;
577     }
578     case Toolkit::DevelTextVisual::Property::OUTLINE:
579     {
580       SetOutlineProperties( mController, propertyValue, Text::EffectStyle::DEFAULT );
581       break;
582     }
583     case Toolkit::DevelTextVisual::Property::BACKGROUND:
584     {
585       SetBackgroundProperties( mController, propertyValue, Text::EffectStyle::DEFAULT );
586       break;
587     }
588   }
589 }
590
591 void TextVisual::UpdateRenderer()
592 {
593   Actor control = mControl.GetHandle();
594   if( !control )
595   {
596     // Nothing to do.
597     return;
598   }
599
600   // Calculates the size to be used to relayout.
601   Vector2 relayoutSize;
602
603   const bool isWidthRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.z ) < Math::MACHINE_EPSILON_1000;
604   const bool isHeightRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.w ) < Math::MACHINE_EPSILON_1000;
605
606   // Round the size and offset to avoid pixel alignement issues.
607   relayoutSize.width = floorf( 0.5f + ( isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width ) );
608   relayoutSize.height = floorf( 0.5f + ( isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height ) );
609
610   std::string text;
611   mController->GetText( text );
612
613   if( ( fabsf( relayoutSize.width ) < Math::MACHINE_EPSILON_1000 ) || ( fabsf( relayoutSize.height ) < Math::MACHINE_EPSILON_1000 ) || text.empty() )
614   {
615     // Remove the texture set and any renderer previously set.
616     RemoveRenderer( control );
617
618     // Nothing else to do if the relayout size is zero.
619     ResourceReady( Toolkit::Visual::ResourceStatus::READY );
620     return;
621   }
622
623
624   Dali::LayoutDirection::Type layoutDirection;
625   if( mController->IsMatchSystemLanguageDirection() )
626   {
627     layoutDirection = static_cast<Dali::LayoutDirection::Type>( DevelWindow::Get( control ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
628   }
629   else
630   {
631     layoutDirection = static_cast<Dali::LayoutDirection::Type>( control.GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
632   }
633
634   const Text::Controller::UpdateTextType updateTextType = mController->Relayout( relayoutSize, layoutDirection );
635
636   if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType )
637    || mRendererUpdateNeeded )
638   {
639     mRendererUpdateNeeded = false;
640
641     // Remove the texture set and any renderer previously set.
642     RemoveRenderer( control );
643
644     if( ( relayoutSize.width > Math::MACHINE_EPSILON_1000 ) &&
645         ( relayoutSize.height > Math::MACHINE_EPSILON_1000 ) )
646     {
647       // Check whether it is a markup text with multiple text colors
648       const Vector4* const colorsBuffer = mController->GetTextModel()->GetColors();
649       bool hasMultipleTextColors = ( NULL != colorsBuffer );
650
651       // Check whether the text contains any color glyph
652       bool containsColorGlyph = false;
653
654       TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
655       const Text::GlyphInfo* const glyphsBuffer = mController->GetTextModel()->GetGlyphs();
656       const Text::Length numberOfGlyphs = mController->GetTextModel()->GetNumberOfGlyphs();
657       for ( Text::Length glyphIndex = 0; glyphIndex < numberOfGlyphs; glyphIndex++ )
658       {
659         // Retrieve the glyph's info.
660         const Text::GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
661
662         // Whether the current glyph is a color one.
663         if( fontClient.IsColorGlyph( glyphInfo->fontId, glyphInfo->index ) )
664         {
665           containsColorGlyph = true;
666           break;
667         }
668       }
669
670       // Check whether the text contains any style colors (e.g. underline color, shadow color, etc.)
671
672       bool shadowEnabled = false;
673       const Vector2& shadowOffset = mController->GetTextModel()->GetShadowOffset();
674       if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
675       {
676         shadowEnabled = true;
677       }
678
679       const bool underlineEnabled = mController->GetTextModel()->IsUnderlineEnabled();
680       const bool outlineEnabled = ( mController->GetTextModel()->GetOutlineWidth() > Math::MACHINE_EPSILON_1 );
681       const bool backgroundEnabled = mController->GetTextModel()->IsBackgroundEnabled();;
682
683       const bool styleEnabled = ( shadowEnabled || underlineEnabled || outlineEnabled || backgroundEnabled );
684
685
686       AddRenderer( control, relayoutSize, hasMultipleTextColors, containsColorGlyph, styleEnabled );
687
688       // Text rendered and ready to display
689       ResourceReady( Toolkit::Visual::ResourceStatus::READY );
690     }
691   }
692 }
693
694 void TextVisual::AddTexture( TextureSet& textureSet, PixelData& data, Sampler& sampler, unsigned int textureSetIndex )
695 {
696   Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D,
697                                   data.GetPixelFormat(),
698                                   data.GetWidth(),
699                                   data.GetHeight() );
700   texture.Upload( data );
701
702   textureSet.SetTexture( textureSetIndex, texture );
703   textureSet.SetSampler( textureSetIndex, sampler );
704 }
705
706 PixelData TextVisual::ConvertToPixelData( unsigned char* buffer, int width, int height, int offsetPosition, const Pixel::Format textPixelFormat )
707 {
708   int bpp = Pixel::GetBytesPerPixel( textPixelFormat );
709   unsigned int bufferSize = width * height * bpp;
710   unsigned char* dstBuffer = static_cast<unsigned char*>( malloc ( bufferSize ) );
711   memcpy( dstBuffer, buffer + offsetPosition * bpp, bufferSize );
712   PixelData pixelData = Dali::PixelData::New( dstBuffer,
713                                               bufferSize,
714                                               width,
715                                               height,
716                                               textPixelFormat,
717                                               Dali::PixelData::FREE );
718   return pixelData;
719 }
720
721 void TextVisual::CreateTextureSet( TilingInfo& info, Renderer& renderer, Sampler& sampler, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled )
722 {
723
724   TextureSet textureSet = TextureSet::New();
725   unsigned int textureSetIndex = 0u;
726
727   // Convert the buffer to pixel data to make it a texture.
728   if( info.textBuffer )
729   {
730     PixelData data = ConvertToPixelData( info.textBuffer, info.width, info.height, info.offsetPosition, info.textPixelFormat );
731     AddTexture( textureSet, data, sampler, textureSetIndex );
732     ++textureSetIndex;
733   }
734
735   if( styleEnabled && info.styleBuffer )
736   {
737     PixelData styleData = ConvertToPixelData( info.styleBuffer, info.width, info.height, info.offsetPosition, Pixel::RGBA8888 );
738     AddTexture( textureSet, styleData, sampler, textureSetIndex );
739     ++textureSetIndex;
740   }
741
742   if( containsColorGlyph && !hasMultipleTextColors && info.maskBuffer )
743   {
744     PixelData maskData = ConvertToPixelData( info.maskBuffer, info.width, info.height, info.offsetPosition, Pixel::L8 );
745     AddTexture( textureSet, maskData, sampler, textureSetIndex );
746   }
747
748   renderer.SetTextures( textureSet );
749
750   //Register transform properties
751   mImpl->mTransform.RegisterUniforms( renderer, Direction::LEFT_TO_RIGHT );
752
753   // Enable the pre-multiplied alpha to improve the text quality
754   renderer.SetProperty( Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, true );
755   renderer.RegisterProperty( PREMULTIPLIED_ALPHA, 1.0f );
756
757   // Set size and offset for the tiling.
758   renderer.RegisterProperty( SIZE, Vector2( info.width, info.height ) );
759   renderer.RegisterProperty( OFFSET, Vector2( info.offSet.x, info.offSet.y ) );
760   renderer.RegisterProperty( "uHasMultipleTextColors", static_cast<float>( hasMultipleTextColors ) );
761   renderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON);
762
763   mRendererList.push_back( renderer );
764 }
765
766
767 void TextVisual::AddRenderer( Actor& actor, const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled )
768 {
769   Shader shader = GetTextShader( mFactoryCache, hasMultipleTextColors, containsColorGlyph, styleEnabled );
770   mImpl->mRenderer.SetShader( shader );
771
772   // Get the maximum size.
773   const int maxTextureSize = Dali::GetMaxTextureSize();
774
775   // No tiling required. Use the default renderer.
776   if( size.height < maxTextureSize )
777   {
778     TextureSet textureSet = GetTextTexture( size, hasMultipleTextColors, containsColorGlyph, styleEnabled );
779
780     mImpl->mRenderer.SetTextures( textureSet );
781     //Register transform properties
782     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
783     mImpl->mRenderer.RegisterProperty( "uHasMultipleTextColors", static_cast<float>( hasMultipleTextColors ) );
784     mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON);
785
786     mRendererList.push_back( mImpl->mRenderer );
787   }
788   // If the pixel data exceeds the maximum size, tiling is required.
789   else
790   {
791     // Filter mode needs to be set to linear to produce better quality while scaling.
792     Sampler sampler = Sampler::New();
793     sampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
794
795     // Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture
796     Pixel::Format textPixelFormat = ( containsColorGlyph || hasMultipleTextColors ) ? Pixel::RGBA8888 : Pixel::L8;
797
798     // Check the text direction
799     Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection();
800
801     // Create a texture for the text without any styles
802     PixelData data = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat );
803
804     int verifiedWidth = data.GetWidth();
805     int verifiedHeight = data.GetHeight();
806
807     // Set information for creating textures.
808     TilingInfo info( verifiedWidth, maxTextureSize, textPixelFormat );
809
810     // Get the buffer of text.
811     Dali::DevelPixelData::PixelDataBuffer textPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( data );
812     info.textBuffer = textPixelData.buffer;
813
814     if( styleEnabled )
815     {
816       // Create RGBA texture for all the text styles (without the text itself)
817       PixelData styleData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888 );
818       Dali::DevelPixelData::PixelDataBuffer stylePixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( styleData );
819       info.styleBuffer = stylePixelData.buffer;
820     }
821
822     if ( containsColorGlyph && !hasMultipleTextColors )
823     {
824       // Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation
825       PixelData maskData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8 );
826       Dali::DevelPixelData::PixelDataBuffer maskPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( maskData );
827       info.maskBuffer = maskPixelData.buffer;
828     }
829
830     // Get the current offset for recalculate the offset when tiling.
831     Property::Map retMap;
832     mImpl->mTransform.GetPropertyMap( retMap );
833     Property::Value* offsetValue = retMap.Find( Dali::Toolkit::Visual::Transform::Property::OFFSET );
834     if( offsetValue )
835     {
836       offsetValue->Get( info.offSet );
837     }
838
839     // Create a textureset in the default renderer.
840     CreateTextureSet( info, mImpl->mRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled );
841
842     verifiedHeight -= maxTextureSize;
843
844     Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
845
846     int offsetPosition = verifiedWidth * maxTextureSize;
847     // Create a renderer by cutting maxTextureSize.
848     while( verifiedHeight > 0 )
849     {
850       Renderer tilingRenderer = Renderer::New( geometry, shader );
851       tilingRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT );
852       // New offset position of buffer for tiling.
853       info.offsetPosition += offsetPosition;
854       // New height for tiling.
855       info.height = ( verifiedHeight - maxTextureSize ) > 0 ? maxTextureSize : verifiedHeight;
856       // New offset for tiling.
857       info.offSet.y += maxTextureSize;
858       // Create a textureset int the new tiling renderer.
859       CreateTextureSet( info, tilingRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled );
860
861       verifiedHeight -= maxTextureSize;
862     }
863   }
864
865   mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
866
867   for( RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
868   {
869     Renderer renderer = (*iter);
870     if( renderer )
871     {
872       actor.AddRenderer( renderer );
873     }
874   }
875 }
876
877
878 TextureSet TextVisual::GetTextTexture( const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled )
879 {
880   // Filter mode needs to be set to linear to produce better quality while scaling.
881   Sampler sampler = Sampler::New();
882   sampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
883
884   TextureSet textureSet = TextureSet::New();
885
886   // Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture
887   Pixel::Format textPixelFormat = ( containsColorGlyph || hasMultipleTextColors ) ? Pixel::RGBA8888 : Pixel::L8;
888
889   // Check the text direction
890   Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection();
891
892   // Create a texture for the text without any styles
893   PixelData data = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat );
894
895   // It may happen the image atlas can't handle a pixel data it exceeds the maximum size.
896   // In that case, create a texture. TODO: should tile the text.
897   unsigned int textureSetIndex = 0u;
898
899   AddTexture( textureSet, data, sampler, textureSetIndex );
900   ++textureSetIndex;
901
902   if ( styleEnabled )
903   {
904     // Create RGBA texture for all the text styles (without the text itself)
905     PixelData styleData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888 );
906
907     AddTexture( textureSet, styleData, sampler, textureSetIndex );
908     ++textureSetIndex;
909   }
910
911   if ( containsColorGlyph && !hasMultipleTextColors )
912   {
913     // Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation
914     PixelData maskData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8 );
915
916     AddTexture( textureSet, maskData, sampler, textureSetIndex );
917   }
918
919   return textureSet;
920 }
921
922 Shader TextVisual::GetTextShader( VisualFactoryCache& factoryCache, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled )
923 {
924   Shader shader;
925
926   if( hasMultipleTextColors && !styleEnabled )
927   {
928     // We don't animate text color if the text contains multiple colors
929     shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT );
930     if( !shader )
931     {
932       shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_MULTI_COLOR_TEXT );
933       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
934       factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT, shader );
935     }
936   }
937   else if( hasMultipleTextColors && styleEnabled )
938   {
939     // We don't animate text color if the text contains multiple colors
940     shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE );
941     if( !shader )
942     {
943       shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE );
944       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
945       factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE, shader );
946     }
947   }
948   else if( !hasMultipleTextColors && !containsColorGlyph && !styleEnabled )
949   {
950     shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT );
951     if( !shader )
952     {
953       shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_SINGLE_COLOR_TEXT );
954       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
955       factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT, shader );
956     }
957   }
958   else if( !hasMultipleTextColors && !containsColorGlyph && styleEnabled )
959   {
960     shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE );
961     if( !shader )
962     {
963       shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE );
964       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
965       factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE, shader );
966     }
967   }
968   else if( !hasMultipleTextColors && containsColorGlyph && !styleEnabled )
969   {
970     shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI );
971     if( !shader )
972     {
973       shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI );
974       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
975       factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI, shader );
976     }
977   }
978   else // if( !hasMultipleTextColors && containsColorGlyph && styleEnabled )
979   {
980     shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI );
981     if( !shader )
982     {
983       shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI );
984       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
985       factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI, shader );
986     }
987   }
988
989   return shader;
990 }
991
992 } // namespace Internal
993
994 } // namespace Toolkit
995
996 } // namespace Dali