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