Minor optimize for Text (Add API for length of text + Cache DPI)
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / text / text-visual.cpp
1 /*
2  * Copyright (c) 2023 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/devel-api/adaptor-framework/image-loading.h>
23 #include <dali/devel-api/images/pixel-data-devel.h>
24 #include <dali/devel-api/rendering/renderer-devel.h>
25 #include <dali/devel-api/rendering/texture-devel.h>
26 #include <dali/devel-api/text-abstraction/text-abstraction-definitions.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/integration-api/trace.h>
29 #include <string.h>
30
31 // INTERNAL HEADER
32 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
33 #include <dali-toolkit/devel-api/text/text-enumerations-devel.h>
34 #include <dali-toolkit/devel-api/visuals/text-visual-properties-devel.h>
35 #include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
36 #include <dali-toolkit/internal/text/script-run.h>
37 #include <dali-toolkit/internal/text/text-effects-style.h>
38 #include <dali-toolkit/internal/text/text-enumerations-impl.h>
39 #include <dali-toolkit/internal/text/text-font-style.h>
40 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
41 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
42 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
43 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
44 #include <dali-toolkit/public-api/visuals/text-visual-properties.h>
45 #include <dali-toolkit/public-api/visuals/visual-properties.h>
46
47 namespace Dali
48 {
49 namespace Toolkit
50 {
51 namespace Internal
52 {
53 namespace
54 {
55 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_TEXT_PERFORMANCE_MARKER, false);
56
57 const int CUSTOM_PROPERTY_COUNT(5); // anim,premul,size,offset,multicol
58
59 const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
60
61 /**
62  * Return Property index for the given string key
63  * param[in] stringKey the string index key
64  * return the key as an index
65  */
66
67 Dali::Property::Index StringKeyToIndexKey(const std::string& stringKey)
68 {
69   Dali::Property::Index result = Property::INVALID_KEY;
70
71   if(stringKey == VISUAL_TYPE)
72   {
73     result = Toolkit::Visual::Property::TYPE;
74   }
75   else if(stringKey == TEXT_PROPERTY)
76   {
77     result = Toolkit::TextVisual::Property::TEXT;
78   }
79   else if(stringKey == FONT_FAMILY_PROPERTY)
80   {
81     result = Toolkit::TextVisual::Property::FONT_FAMILY;
82   }
83   else if(stringKey == FONT_STYLE_PROPERTY)
84   {
85     result = Toolkit::TextVisual::Property::FONT_STYLE;
86   }
87   else if(stringKey == POINT_SIZE_PROPERTY)
88   {
89     result = Toolkit::TextVisual::Property::POINT_SIZE;
90   }
91   else if(stringKey == MULTI_LINE_PROPERTY)
92   {
93     result = Toolkit::TextVisual::Property::MULTI_LINE;
94   }
95   else if(stringKey == HORIZONTAL_ALIGNMENT_PROPERTY)
96   {
97     result = Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT;
98   }
99   else if(stringKey == VERTICAL_ALIGNMENT_PROPERTY)
100   {
101     result = Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT;
102   }
103   else if(stringKey == TEXT_COLOR_PROPERTY)
104   {
105     result = Toolkit::TextVisual::Property::TEXT_COLOR;
106   }
107   else if(stringKey == ENABLE_MARKUP_PROPERTY)
108   {
109     result = Toolkit::TextVisual::Property::ENABLE_MARKUP;
110   }
111   else if(stringKey == SHADOW_PROPERTY)
112   {
113     result = Toolkit::TextVisual::Property::SHADOW;
114   }
115   else if(stringKey == UNDERLINE_PROPERTY)
116   {
117     result = Toolkit::TextVisual::Property::UNDERLINE;
118   }
119   else if(stringKey == OUTLINE_PROPERTY)
120   {
121     result = Toolkit::DevelTextVisual::Property::OUTLINE;
122   }
123   else if(stringKey == BACKGROUND_PROPERTY)
124   {
125     result = Toolkit::DevelTextVisual::Property::BACKGROUND;
126   }
127
128   return result;
129 }
130
131 void TextColorConstraint(Vector4& current, const PropertyInputContainer& inputs)
132 {
133   Vector4 color = inputs[0]->GetVector4();
134   current.r     = color.r * color.a;
135   current.g     = color.g * color.a;
136   current.b     = color.b * color.a;
137   current.a     = color.a;
138 }
139
140 void OpacityConstraint(float& current, const PropertyInputContainer& inputs)
141 {
142   // Make zero if the alpha value of text color is zero to skip rendering text
143   if(EqualsZero(inputs[0]->GetVector4().a))
144   {
145     current = 0.0f;
146   }
147   else
148   {
149     current = 1.0f;
150   }
151 }
152
153 } // unnamed namespace
154
155 TextVisualPtr TextVisual::New(VisualFactoryCache& factoryCache, TextVisualShaderFactory& shaderFactory, const Property::Map& properties)
156 {
157   TextVisualPtr textVisualPtr(new TextVisual(factoryCache, shaderFactory));
158   textVisualPtr->SetProperties(properties);
159   textVisualPtr->Initialize();
160   return textVisualPtr;
161 }
162
163 Property::Map TextVisual::ConvertStringKeysToIndexKeys(const Property::Map& propertyMap)
164 {
165   Property::Map outMap;
166
167   for(Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index)
168   {
169     const KeyValuePair& keyValue = propertyMap.GetKeyValue(index);
170
171     Property::Index indexKey = keyValue.first.indexKey;
172
173     if(keyValue.first.type == Property::Key::STRING)
174     {
175       indexKey = StringKeyToIndexKey(keyValue.first.stringKey);
176     }
177
178     outMap.Insert(indexKey, keyValue.second);
179   }
180
181   return outMap;
182 }
183
184 float TextVisual::GetHeightForWidth(float width)
185 {
186   return mController->GetHeightForWidth(width);
187 }
188
189 void TextVisual::GetNaturalSize(Vector2& naturalSize)
190 {
191   naturalSize = mController->GetNaturalSize().GetVectorXY();
192 }
193
194 void TextVisual::DoCreatePropertyMap(Property::Map& map) const
195 {
196   Property::Value value;
197
198   map.Clear();
199   map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT);
200
201   std::string text;
202   mController->GetText(text);
203   map.Insert(Toolkit::TextVisual::Property::TEXT, text);
204
205   map.Insert(Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily());
206
207   GetFontStyleProperty(mController, value, Text::FontStyle::DEFAULT);
208   map.Insert(Toolkit::TextVisual::Property::FONT_STYLE, value);
209
210   map.Insert(Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultFontSize(Text::Controller::POINT_SIZE));
211
212   map.Insert(Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled());
213
214   map.Insert(Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, mController->GetHorizontalAlignment());
215
216   map.Insert(Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, mController->GetVerticalAlignment());
217
218   map.Insert(Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor());
219
220   map.Insert(Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled());
221
222   GetShadowProperties(mController, value, Text::EffectStyle::DEFAULT);
223   map.Insert(Toolkit::TextVisual::Property::SHADOW, value);
224
225   GetUnderlineProperties(mController, value, Text::EffectStyle::DEFAULT);
226   map.Insert(Toolkit::TextVisual::Property::UNDERLINE, value);
227
228   GetOutlineProperties(mController, value, Text::EffectStyle::DEFAULT);
229   map.Insert(Toolkit::DevelTextVisual::Property::OUTLINE, value);
230
231   GetBackgroundProperties(mController, value, Text::EffectStyle::DEFAULT);
232   map.Insert(Toolkit::DevelTextVisual::Property::BACKGROUND, value);
233
234   GetStrikethroughProperties(mController, value, Text::EffectStyle::DEFAULT);
235   map.Insert(Toolkit::DevelTextVisual::Property::STRIKETHROUGH, value);
236 }
237
238 void TextVisual::DoCreateInstancePropertyMap(Property::Map& map) const
239 {
240   map.Clear();
241   map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT);
242   std::string text;
243   mController->GetText(text);
244   map.Insert(Toolkit::TextVisual::Property::TEXT, text);
245 }
246
247 void TextVisual::EnablePreMultipliedAlpha(bool preMultiplied)
248 {
249   // Make always enable pre multiplied alpha whether preMultiplied value is false.
250   if(!preMultiplied)
251   {
252     DALI_LOG_WARNING("Note : TextVisual cannot disable PreMultipliedAlpha\n");
253   }
254 }
255
256 TextVisual::TextVisual(VisualFactoryCache& factoryCache, TextVisualShaderFactory& shaderFactory)
257 : Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::TEXT),
258   mController(Text::Controller::New()),
259   mTypesetter(Text::Typesetter::New(mController->GetTextModel())),
260   mTextVisualShaderFactory(shaderFactory),
261   mTextShaderFeatureCache(),
262   mAnimatableTextColorPropertyIndex(Property::INVALID_INDEX),
263   mTextColorAnimatableIndex(Property::INVALID_INDEX),
264   mRendererUpdateNeeded(false)
265 {
266   // Enable the pre-multiplied alpha to improve the text quality
267   mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
268 }
269
270 TextVisual::~TextVisual()
271 {
272 }
273
274 void TextVisual::OnInitialize()
275 {
276   Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
277   Shader   shader   = GetTextShader(mFactoryCache, TextVisualShaderFeature::FeatureBuilder());
278
279   mImpl->mRenderer = VisualRenderer::New(geometry, shader);
280   mImpl->mRenderer.ReserveCustomProperties(CUSTOM_PROPERTY_COUNT);
281 }
282
283 void TextVisual::DoSetProperties(const Property::Map& propertyMap)
284 {
285   for(Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index)
286   {
287     const KeyValuePair& keyValue = propertyMap.GetKeyValue(index);
288
289     Property::Index indexKey = keyValue.first.indexKey;
290
291     if(keyValue.first.type == Property::Key::STRING)
292     {
293       indexKey = StringKeyToIndexKey(keyValue.first.stringKey);
294     }
295
296     DoSetProperty(indexKey, keyValue.second);
297   }
298
299   // Elide the text if it exceeds the boundaries.
300   mController->SetTextElideEnabled(true);
301
302   // Retrieve the layout engine to set the cursor's width.
303   Text::Layout::Engine& engine = mController->GetLayoutEngine();
304
305   // Sets 0 as cursor's width.
306   engine.SetCursorWidth(0u); // Do not layout space for the cursor.
307 }
308
309 void TextVisual::DoSetOnScene(Actor& actor)
310 {
311   mControl = actor;
312
313   mImpl->mRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT);
314
315   const Vector4& defaultColor = mController->GetTextModel()->GetDefaultColor();
316   if(mTextColorAnimatableIndex == Property::INVALID_INDEX)
317   {
318     mTextColorAnimatableIndex = mImpl->mRenderer.RegisterUniqueProperty("uTextColorAnimatable", defaultColor);
319   }
320   else
321   {
322     mImpl->mRenderer.SetProperty(mTextColorAnimatableIndex, defaultColor);
323   }
324
325   if(mAnimatableTextColorPropertyIndex != Property::INVALID_INDEX)
326   {
327     // Create constraint for the animatable text's color Property with uTextColorAnimatable in the renderer.
328     if(mTextColorAnimatableIndex != Property::INVALID_INDEX)
329     {
330       if(!mColorConstraint)
331       {
332         mColorConstraint = Constraint::New<Vector4>(mImpl->mRenderer, mTextColorAnimatableIndex, TextColorConstraint);
333         mColorConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex));
334       }
335       mColorConstraint.Apply();
336     }
337
338     // Make zero if the alpha value of text color is zero to skip rendering text
339     if(!mOpacityConstraint)
340     {
341       // VisualRenderer::Property::OPACITY uses same animatable property internally.
342       mOpacityConstraint = Constraint::New<float>(mImpl->mRenderer, Dali::DevelRenderer::Property::OPACITY, OpacityConstraint);
343       mOpacityConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex));
344     }
345     mOpacityConstraint.Apply();
346   }
347
348   // Renderer needs textures and to be added to control
349   mRendererUpdateNeeded = true;
350
351   UpdateRenderer();
352 }
353
354 void TextVisual::RemoveRenderer(Actor& actor)
355 {
356   for(RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
357   {
358     Renderer renderer = (*iter);
359     if(renderer)
360     {
361       // Removes the renderer from the actor.
362       actor.RemoveRenderer(renderer);
363     }
364   }
365   // Clear the renderer list
366   mRendererList.clear();
367 }
368
369 void TextVisual::DoSetOffScene(Actor& actor)
370 {
371   if(mColorConstraint)
372   {
373     mColorConstraint.Remove();
374   }
375   if(mOpacityConstraint)
376   {
377     mOpacityConstraint.Remove();
378   }
379
380   RemoveRenderer(actor);
381
382   // Resets the control handle.
383   mControl.Reset();
384 }
385
386 void TextVisual::OnSetTransform()
387 {
388   UpdateRenderer();
389 }
390
391 void TextVisual::DoSetProperty(Dali::Property::Index index, const Dali::Property::Value& propertyValue)
392 {
393   switch(index)
394   {
395     case Toolkit::TextVisual::Property::ENABLE_MARKUP:
396     {
397       const bool enableMarkup = propertyValue.Get<bool>();
398       mController->SetMarkupProcessorEnabled(enableMarkup);
399       break;
400     }
401     case Toolkit::TextVisual::Property::TEXT:
402     {
403       mController->SetText(propertyValue.Get<std::string>());
404       break;
405     }
406     case Toolkit::TextVisual::Property::FONT_FAMILY:
407     {
408       SetFontFamilyProperty(mController, propertyValue);
409       break;
410     }
411     case Toolkit::TextVisual::Property::FONT_STYLE:
412     {
413       SetFontStyleProperty(mController, propertyValue, Text::FontStyle::DEFAULT);
414       break;
415     }
416     case Toolkit::TextVisual::Property::POINT_SIZE:
417     {
418       const float pointSize = propertyValue.Get<float>();
419       if(!Equals(mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize))
420       {
421         mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE);
422       }
423       break;
424     }
425     case Toolkit::TextVisual::Property::MULTI_LINE:
426     {
427       mController->SetMultiLineEnabled(propertyValue.Get<bool>());
428       break;
429     }
430     case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
431     {
432       if(mController)
433       {
434         Text::HorizontalAlignment::Type alignment(static_cast<Text::HorizontalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
435         if(Toolkit::Text::GetHorizontalAlignmentEnumeration(propertyValue, alignment))
436         {
437           mController->SetHorizontalAlignment(alignment);
438         }
439       }
440       break;
441     }
442     case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
443     {
444       if(mController)
445       {
446         Toolkit::Text::VerticalAlignment::Type alignment(static_cast<Text::VerticalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
447         if(Toolkit::Text::GetVerticalAlignmentEnumeration(propertyValue, alignment))
448         {
449           mController->SetVerticalAlignment(alignment);
450         }
451       }
452       break;
453     }
454     case Toolkit::TextVisual::Property::TEXT_COLOR:
455     {
456       const Vector4& textColor = propertyValue.Get<Vector4>();
457       if(mController->GetDefaultColor() != textColor)
458       {
459         mController->SetDefaultColor(textColor);
460       }
461       break;
462     }
463     case Toolkit::TextVisual::Property::SHADOW:
464     {
465       SetShadowProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
466       break;
467     }
468     case Toolkit::TextVisual::Property::UNDERLINE:
469     {
470       SetUnderlineProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
471       break;
472     }
473     case Toolkit::DevelTextVisual::Property::OUTLINE:
474     {
475       SetOutlineProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
476       break;
477     }
478     case Toolkit::DevelTextVisual::Property::BACKGROUND:
479     {
480       SetBackgroundProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
481       break;
482     }
483     case Toolkit::DevelTextVisual::Property::STRIKETHROUGH:
484     {
485       SetStrikethroughProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
486       break;
487     }
488   }
489 }
490
491 void TextVisual::UpdateRenderer()
492 {
493   Actor control = mControl.GetHandle();
494   if(!control)
495   {
496     // Nothing to do.
497     return;
498   }
499
500   // Calculates the size to be used to relayout.
501   Vector2 relayoutSize;
502
503   const bool isWidthRelative  = fabsf(mImpl->mTransform.mOffsetSizeMode.z) < Math::MACHINE_EPSILON_1000;
504   const bool isHeightRelative = fabsf(mImpl->mTransform.mOffsetSizeMode.w) < Math::MACHINE_EPSILON_1000;
505
506   // Round the size and offset to avoid pixel alignement issues.
507   relayoutSize.width  = floorf(0.5f + (isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width));
508   relayoutSize.height = floorf(0.5f + (isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height));
509
510   auto textLengthUtf32 = mController->GetNumberOfCharacters();
511
512   if((fabsf(relayoutSize.width) < Math::MACHINE_EPSILON_1000) || (fabsf(relayoutSize.height) < Math::MACHINE_EPSILON_1000) || textLengthUtf32 == 0u)
513   {
514     // Remove the texture set and any renderer previously set.
515     RemoveRenderer(control);
516
517     // Nothing else to do if the relayout size is zero.
518     ResourceReady(Toolkit::Visual::ResourceStatus::READY);
519     return;
520   }
521
522   Dali::LayoutDirection::Type layoutDirection = mController->GetLayoutDirection(control);
523
524   const Text::Controller::UpdateTextType updateTextType = mController->Relayout(relayoutSize, layoutDirection);
525
526   if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType) || mRendererUpdateNeeded)
527   {
528     mRendererUpdateNeeded = false;
529
530     // Remove the texture set and any renderer previously set.
531     RemoveRenderer(control);
532
533     if((relayoutSize.width > Math::MACHINE_EPSILON_1000) &&
534        (relayoutSize.height > Math::MACHINE_EPSILON_1000))
535     {
536       // Check whether it is a markup text with multiple text colors
537       const Vector4* const colorsBuffer          = mController->GetTextModel()->GetColors();
538       bool                 hasMultipleTextColors = (NULL != colorsBuffer);
539
540       // Check whether the text contains any color glyph
541       bool containsColorGlyph = false;
542
543       TextAbstraction::FontClient  fontClient     = TextAbstraction::FontClient::Get();
544       const Text::GlyphInfo* const glyphsBuffer   = mController->GetTextModel()->GetGlyphs();
545       const Text::Length           numberOfGlyphs = mController->GetTextModel()->GetNumberOfGlyphs();
546       for(Text::Length glyphIndex = 0; glyphIndex < numberOfGlyphs; glyphIndex++)
547       {
548         // Retrieve the glyph's info.
549         const Text::GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
550
551         // Whether the current glyph is a color one.
552         if(fontClient.IsColorGlyph(glyphInfo->fontId, glyphInfo->index))
553         {
554           containsColorGlyph = true;
555           break;
556         }
557       }
558
559       // Check whether the text contains any style colors (e.g. underline color, shadow color, etc.)
560
561       bool           shadowEnabled = false;
562       const Vector2& shadowOffset  = mController->GetTextModel()->GetShadowOffset();
563       if(fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1)
564       {
565         shadowEnabled = true;
566       }
567
568       const bool outlineEnabled             = (mController->GetTextModel()->GetOutlineWidth() > Math::MACHINE_EPSILON_1);
569       const bool backgroundEnabled          = mController->GetTextModel()->IsBackgroundEnabled();
570       const bool markupOrSpannedText        = mController->IsMarkupProcessorEnabled() || mController->GetTextModel()->IsSpannedTextPlaced();
571       const bool markupUnderlineEnabled     = markupOrSpannedText && mController->GetTextModel()->IsMarkupUnderlineSet();
572       const bool markupStrikethroughEnabled = markupOrSpannedText && mController->GetTextModel()->IsMarkupStrikethroughSet();
573       const bool underlineEnabled           = mController->GetTextModel()->IsUnderlineEnabled() || markupUnderlineEnabled;
574       const bool strikethroughEnabled       = mController->GetTextModel()->IsStrikethroughEnabled() || markupStrikethroughEnabled;
575       const bool backgroundMarkupSet        = mController->GetTextModel()->IsMarkupBackgroundColorSet();
576       const bool styleEnabled               = (shadowEnabled || outlineEnabled || backgroundEnabled || markupOrSpannedText || backgroundMarkupSet);
577       const bool isOverlayStyle             = underlineEnabled || strikethroughEnabled;
578
579       AddRenderer(control, relayoutSize, hasMultipleTextColors, containsColorGlyph, styleEnabled, isOverlayStyle);
580
581       // Text rendered and ready to display
582       ResourceReady(Toolkit::Visual::ResourceStatus::READY);
583     }
584   }
585 }
586
587 void TextVisual::AddTexture(TextureSet& textureSet, PixelData& data, Sampler& sampler, unsigned int textureSetIndex)
588 {
589   Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D,
590                                  data.GetPixelFormat(),
591                                  data.GetWidth(),
592                                  data.GetHeight());
593   texture.Upload(data);
594
595   textureSet.SetTexture(textureSetIndex, texture);
596   textureSet.SetSampler(textureSetIndex, sampler);
597 }
598
599 void TextVisual::AddTilingTexture(TextureSet& textureSet, TilingInfo& tilingInfo, PixelData& data, Sampler& sampler, unsigned int textureSetIndex)
600 {
601   Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D,
602                                  tilingInfo.textPixelFormat,
603                                  tilingInfo.width,
604                                  tilingInfo.height);
605   DevelTexture::UploadSubPixelData(texture, data, 0u, tilingInfo.offsetHeight, tilingInfo.width, tilingInfo.height);
606
607   textureSet.SetTexture(textureSetIndex, texture);
608   textureSet.SetSampler(textureSetIndex, sampler);
609 }
610
611 void TextVisual::CreateTextureSet(TilingInfo& info, VisualRenderer& renderer, Sampler& sampler)
612 {
613   TextureSet textureSet      = TextureSet::New();
614   uint32_t   textureSetIndex = 0u;
615
616   // Convert the buffer to pixel data to make it a texture.
617
618   if(info.textPixelData)
619   {
620     AddTilingTexture(textureSet, info, info.textPixelData, sampler, textureSetIndex);
621     ++textureSetIndex;
622   }
623
624   if(mTextShaderFeatureCache.IsEnabledStyle() && info.stylePixelData)
625   {
626     AddTilingTexture(textureSet, info, info.stylePixelData, sampler, textureSetIndex);
627     ++textureSetIndex;
628   }
629
630   if(mTextShaderFeatureCache.IsEnabledOverlay() && info.overlayStylePixelData)
631   {
632     AddTilingTexture(textureSet, info, info.overlayStylePixelData, sampler, textureSetIndex);
633     ++textureSetIndex;
634   }
635
636   if(mTextShaderFeatureCache.IsEnabledEmoji() && !mTextShaderFeatureCache.IsEnabledMultiColor() && info.maskPixelData)
637   {
638     AddTilingTexture(textureSet, info, info.maskPixelData, sampler, textureSetIndex);
639     ++textureSetIndex;
640   }
641
642   renderer.SetTextures(textureSet);
643
644   //Register transform properties
645   mImpl->mTransform.SetUniforms(renderer, Direction::LEFT_TO_RIGHT);
646
647   // Enable the pre-multiplied alpha to improve the text quality
648   renderer.SetProperty(Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, true);
649   renderer.RegisterProperty(PREMULTIPLIED_ALPHA, 1.0f);
650
651   // Set size and offset for the tiling.
652   renderer.SetProperty(VisualRenderer::Property::TRANSFORM_SIZE, Vector2(info.width, info.height));
653   renderer.SetProperty(VisualRenderer::Property::TRANSFORM_OFFSET, info.transformOffset);
654   renderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
655   renderer.RegisterProperty("uHasMultipleTextColors", static_cast<float>(mTextShaderFeatureCache.IsEnabledMultiColor()));
656
657   mRendererList.push_back(renderer);
658 }
659
660 void TextVisual::AddRenderer(Actor& actor, const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled, bool isOverlayStyle)
661 {
662   Shader shader = GetTextShader(mFactoryCache, TextVisualShaderFeature::FeatureBuilder().EnableMultiColor(hasMultipleTextColors).EnableEmoji(containsColorGlyph).EnableStyle(styleEnabled).EnableOverlay(isOverlayStyle));
663   mImpl->mRenderer.SetShader(shader);
664
665   DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_VISUAL_UPDATE_RENDERER");
666
667   // Get the maximum size.
668   const int maxTextureSize = Dali::GetMaxTextureSize();
669
670   // No tiling required. Use the default renderer.
671   if(size.height < maxTextureSize)
672   {
673     TextureSet textureSet = GetTextTexture(size);
674
675     mImpl->mRenderer.SetTextures(textureSet);
676     //Register transform properties
677     mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
678     mImpl->mRenderer.RegisterProperty("uHasMultipleTextColors", static_cast<float>(hasMultipleTextColors));
679     mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
680
681     mRendererList.push_back(mImpl->mRenderer);
682   }
683   // If the pixel data exceeds the maximum size, tiling is required.
684   else
685   {
686     // Filter mode needs to be set to linear to produce better quality while scaling.
687     Sampler sampler = Sampler::New();
688     sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR);
689
690     // Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture
691     Pixel::Format textPixelFormat = (containsColorGlyph || hasMultipleTextColors) ? Pixel::RGBA8888 : Pixel::L8;
692
693     // Check the text direction
694     Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection();
695
696     // Create a texture for the text without any styles
697     PixelData data = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat);
698
699     int verifiedWidth  = data.GetWidth();
700     int verifiedHeight = data.GetHeight();
701
702     // Set information for creating textures.
703     TilingInfo info(verifiedWidth, maxTextureSize, textPixelFormat);
704
705     // Get the pixel data of text.
706     info.textPixelData = data;
707
708     if(mTextShaderFeatureCache.IsEnabledStyle())
709     {
710       // Create RGBA texture for all the text styles (without the text itself)
711       info.stylePixelData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888);
712     }
713
714     if(mTextShaderFeatureCache.IsEnabledOverlay())
715     {
716       // Create RGBA texture for all the overlay styles
717       info.overlayStylePixelData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_OVERLAY_STYLE, false, Pixel::RGBA8888);
718     }
719
720     if(mTextShaderFeatureCache.IsEnabledEmoji() && !mTextShaderFeatureCache.IsEnabledMultiColor())
721     {
722       // Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation
723       info.maskPixelData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8);
724     }
725
726     // Get the current offset for recalculate the offset when tiling.
727     Property::Map retMap;
728     mImpl->mTransform.GetPropertyMap(retMap);
729     Property::Value* offsetValue = retMap.Find(Dali::Toolkit::Visual::Transform::Property::OFFSET);
730     if(offsetValue)
731     {
732       offsetValue->Get(info.transformOffset);
733     }
734
735     // Create a textureset in the default renderer.
736     CreateTextureSet(info, mImpl->mRenderer, sampler);
737
738     verifiedHeight -= maxTextureSize;
739
740     Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
741
742     // Create a renderer by cutting maxTextureSize.
743     while(verifiedHeight > 0)
744     {
745       VisualRenderer tilingRenderer = VisualRenderer::New(geometry, shader);
746       tilingRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT);
747       // New offset position of buffer for tiling.
748       info.offsetHeight += maxTextureSize;
749       // New height for tiling.
750       info.height = (verifiedHeight - maxTextureSize) > 0 ? maxTextureSize : verifiedHeight;
751       // New offset for tiling.
752       info.transformOffset.y += maxTextureSize;
753       // Create a textureset int the new tiling renderer.
754       CreateTextureSet(info, tilingRenderer, sampler);
755
756       verifiedHeight -= maxTextureSize;
757     }
758   }
759
760   mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
761
762   const Vector4& defaultColor = mController->GetTextModel()->GetDefaultColor();
763
764   for(RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
765   {
766     Renderer renderer = (*iter);
767     if(renderer)
768     {
769       actor.AddRenderer(renderer);
770
771       if(renderer != mImpl->mRenderer)
772       {
773         // Set constraint for text label's color for non-default renderers.
774         if(mAnimatableTextColorPropertyIndex != Property::INVALID_INDEX)
775         {
776           // Register unique property, or get property for default renderer.
777           Property::Index index = renderer.RegisterUniqueProperty("uTextColorAnimatable", defaultColor);
778
779           // Create constraint for the animatable text's color Property with uTextColorAnimatable in the renderer.
780           if(index != Property::INVALID_INDEX)
781           {
782             Constraint colorConstraint = Constraint::New<Vector4>(renderer, index, TextColorConstraint);
783             colorConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex));
784             colorConstraint.Apply();
785           }
786
787           // Make zero if the alpha value of text color is zero to skip rendering text
788           // VisualRenderer::Property::OPACITY uses same animatable property internally.
789           Constraint opacityConstraint = Constraint::New<float>(renderer, Dali::DevelRenderer::Property::OPACITY, OpacityConstraint);
790           opacityConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex));
791           opacityConstraint.Apply();
792         }
793       }
794     }
795   }
796 }
797
798 TextureSet TextVisual::GetTextTexture(const Vector2& size)
799 {
800   // Filter mode needs to be set to linear to produce better quality while scaling.
801   Sampler sampler = Sampler::New();
802   sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR);
803
804   TextureSet textureSet = TextureSet::New();
805
806   // Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture
807   Pixel::Format textPixelFormat = (mTextShaderFeatureCache.IsEnabledEmoji() || mTextShaderFeatureCache.IsEnabledMultiColor()) ? Pixel::RGBA8888 : Pixel::L8;
808
809   // Check the text direction
810   Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection();
811
812   // Create a texture for the text without any styles
813   PixelData data = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat);
814
815   uint32_t textureSetIndex = 0u;
816   AddTexture(textureSet, data, sampler, textureSetIndex);
817   ++textureSetIndex;
818
819   if(mTextShaderFeatureCache.IsEnabledStyle())
820   {
821     // Create RGBA texture for all the text styles that render in the background (without the text itself)
822     PixelData styleData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888);
823     AddTexture(textureSet, styleData, sampler, textureSetIndex);
824     ++textureSetIndex;
825   }
826
827   if(mTextShaderFeatureCache.IsEnabledOverlay())
828   {
829     // Create RGBA texture for overlay styles such as underline and strikethrough (without the text itself)
830     PixelData overlayStyleData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_OVERLAY_STYLE, false, Pixel::RGBA8888);
831     AddTexture(textureSet, overlayStyleData, sampler, textureSetIndex);
832     ++textureSetIndex;
833   }
834
835   if(mTextShaderFeatureCache.IsEnabledEmoji() && !mTextShaderFeatureCache.IsEnabledMultiColor())
836   {
837     // Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation
838     PixelData maskData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8);
839
840     AddTexture(textureSet, maskData, sampler, textureSetIndex);
841   }
842
843   return textureSet;
844 }
845
846 Shader TextVisual::GetTextShader(VisualFactoryCache& factoryCache, const TextVisualShaderFeature::FeatureBuilder& featureBuilder)
847 {
848   // Cache feature builder informations.
849   mTextShaderFeatureCache = featureBuilder;
850
851   Shader shader = mTextVisualShaderFactory.GetShader(factoryCache, mTextShaderFeatureCache);
852   shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
853   return shader;
854 }
855
856 } // namespace Internal
857
858 } // namespace Toolkit
859
860 } // namespace Dali