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