Merge "Add null check for currentFocusActor" into devel/master
[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   GetStrikethroughProperties(mController, value, Text::EffectStyle::DEFAULT);
228   map.Insert(Toolkit::DevelTextVisual::Property::STRIKETHROUGH, value);
229 }
230
231 void TextVisual::DoCreateInstancePropertyMap(Property::Map& map) const
232 {
233   map.Clear();
234   map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT);
235   std::string text;
236   mController->GetText(text);
237   map.Insert(Toolkit::TextVisual::Property::TEXT, text);
238 }
239
240 TextVisual::TextVisual(VisualFactoryCache& factoryCache)
241 : Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::TEXT),
242   mController(Text::Controller::New()),
243   mTypesetter(Text::Typesetter::New(mController->GetTextModel())),
244   mAnimatableTextColorPropertyIndex(Property::INVALID_INDEX),
245   mTextColorAnimatableIndex(Property::INVALID_INDEX),
246   mRendererUpdateNeeded(false)
247 {
248 }
249
250 TextVisual::~TextVisual()
251 {
252 }
253
254 void TextVisual::OnInitialize()
255 {
256   Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
257   Shader   shader   = GetTextShader(mFactoryCache, TextType::SINGLE_COLOR_TEXT, TextType::NO_EMOJI, TextType::NO_STYLES);
258
259   mImpl->mRenderer = Renderer::New(geometry, shader);
260 }
261
262 void TextVisual::DoSetProperties(const Property::Map& propertyMap)
263 {
264   for(Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index)
265   {
266     const KeyValuePair& keyValue = propertyMap.GetKeyValue(index);
267
268     Property::Index indexKey = keyValue.first.indexKey;
269
270     if(keyValue.first.type == Property::Key::STRING)
271     {
272       indexKey = StringKeyToIndexKey(keyValue.first.stringKey);
273     }
274
275     DoSetProperty(indexKey, keyValue.second);
276   }
277
278   // Elide the text if it exceeds the boundaries.
279   mController->SetTextElideEnabled(true);
280
281   // Retrieve the layout engine to set the cursor's width.
282   Text::Layout::Engine& engine = mController->GetLayoutEngine();
283
284   // Sets 0 as cursor's width.
285   engine.SetCursorWidth(0u); // Do not layout space for the cursor.
286 }
287
288 void TextVisual::DoSetOnScene(Actor& actor)
289 {
290   mControl = actor;
291
292   mImpl->mRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT);
293
294   // Enable the pre-multiplied alpha to improve the text quality
295   EnablePreMultipliedAlpha(true);
296
297   const Vector4& defaultColor = mController->GetTextModel()->GetDefaultColor();
298   if(mTextColorAnimatableIndex == Property::INVALID_INDEX)
299   {
300     mTextColorAnimatableIndex = mImpl->mRenderer.RegisterProperty("uTextColorAnimatable", defaultColor);
301   }
302   else
303   {
304     mImpl->mRenderer.SetProperty(mTextColorAnimatableIndex, defaultColor);
305   }
306
307   if(mAnimatableTextColorPropertyIndex != Property::INVALID_INDEX)
308   {
309     // Create constraint for the animatable text's color Property with uTextColorAnimatable in the renderer.
310     if(mTextColorAnimatableIndex != Property::INVALID_INDEX)
311     {
312       if(!mColorConstraint)
313       {
314         mColorConstraint = Constraint::New<Vector4>(mImpl->mRenderer, mTextColorAnimatableIndex, TextColorConstraint);
315         mColorConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex));
316       }
317       mColorConstraint.Apply();
318     }
319
320     // Make zero if the alpha value of text color is zero to skip rendering text
321     if(!mOpacityConstraint)
322     {
323       mOpacityConstraint = Constraint::New<float>(mImpl->mRenderer, Dali::DevelRenderer::Property::OPACITY, OpacityConstraint);
324       mOpacityConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex));
325     }
326     mOpacityConstraint.Apply();
327   }
328
329   // Renderer needs textures and to be added to control
330   mRendererUpdateNeeded = true;
331
332   mRendererList.push_back(mImpl->mRenderer);
333
334   UpdateRenderer();
335 }
336
337 void TextVisual::RemoveRenderer(Actor& actor)
338 {
339   for(RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
340   {
341     Renderer renderer = (*iter);
342     if(renderer)
343     {
344       // Removes the renderer from the actor.
345       actor.RemoveRenderer(renderer);
346     }
347   }
348   // Clear the renderer list
349   mRendererList.clear();
350 }
351
352 void TextVisual::DoSetOffScene(Actor& actor)
353 {
354   if(mColorConstraint)
355   {
356     mColorConstraint.Remove();
357   }
358   if(mOpacityConstraint)
359   {
360     mOpacityConstraint.Remove();
361   }
362
363   RemoveRenderer(actor);
364
365   // Resets the control handle.
366   mControl.Reset();
367 }
368
369 void TextVisual::OnSetTransform()
370 {
371   UpdateRenderer();
372 }
373
374 void TextVisual::DoSetProperty(Dali::Property::Index index, const Dali::Property::Value& propertyValue)
375 {
376   switch(index)
377   {
378     case Toolkit::TextVisual::Property::ENABLE_MARKUP:
379     {
380       const bool enableMarkup = propertyValue.Get<bool>();
381       mController->SetMarkupProcessorEnabled(enableMarkup);
382       break;
383     }
384     case Toolkit::TextVisual::Property::TEXT:
385     {
386       mController->SetText(propertyValue.Get<std::string>());
387       break;
388     }
389     case Toolkit::TextVisual::Property::FONT_FAMILY:
390     {
391       SetFontFamilyProperty(mController, propertyValue);
392       break;
393     }
394     case Toolkit::TextVisual::Property::FONT_STYLE:
395     {
396       SetFontStyleProperty(mController, propertyValue, Text::FontStyle::DEFAULT);
397       break;
398     }
399     case Toolkit::TextVisual::Property::POINT_SIZE:
400     {
401       const float pointSize = propertyValue.Get<float>();
402       if(!Equals(mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize))
403       {
404         mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE);
405       }
406       break;
407     }
408     case Toolkit::TextVisual::Property::MULTI_LINE:
409     {
410       mController->SetMultiLineEnabled(propertyValue.Get<bool>());
411       break;
412     }
413     case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
414     {
415       if(mController)
416       {
417         Text::HorizontalAlignment::Type alignment(static_cast<Text::HorizontalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
418         if(Toolkit::Text::GetHorizontalAlignmentEnumeration(propertyValue, alignment))
419         {
420           mController->SetHorizontalAlignment(alignment);
421         }
422       }
423       break;
424     }
425     case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
426     {
427       if(mController)
428       {
429         Toolkit::Text::VerticalAlignment::Type alignment(static_cast<Text::VerticalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
430         if(Toolkit::Text::GetVerticalAlignmentEnumeration(propertyValue, alignment))
431         {
432           mController->SetVerticalAlignment(alignment);
433         }
434       }
435       break;
436     }
437     case Toolkit::TextVisual::Property::TEXT_COLOR:
438     {
439       const Vector4& textColor = propertyValue.Get<Vector4>();
440       if(mController->GetDefaultColor() != textColor)
441       {
442         mController->SetDefaultColor(textColor);
443       }
444       break;
445     }
446     case Toolkit::TextVisual::Property::SHADOW:
447     {
448       SetShadowProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
449       break;
450     }
451     case Toolkit::TextVisual::Property::UNDERLINE:
452     {
453       SetUnderlineProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
454       break;
455     }
456     case Toolkit::DevelTextVisual::Property::OUTLINE:
457     {
458       SetOutlineProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
459       break;
460     }
461     case Toolkit::DevelTextVisual::Property::BACKGROUND:
462     {
463       SetBackgroundProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
464       break;
465     }
466     case Toolkit::DevelTextVisual::Property::STRIKETHROUGH:
467     {
468       SetStrikethroughProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
469       break;
470     }
471   }
472 }
473
474 void TextVisual::UpdateRenderer()
475 {
476   Actor control = mControl.GetHandle();
477   if(!control)
478   {
479     // Nothing to do.
480     return;
481   }
482
483   // Calculates the size to be used to relayout.
484   Vector2 relayoutSize;
485
486   const bool isWidthRelative  = fabsf(mImpl->mTransform.mOffsetSizeMode.z) < Math::MACHINE_EPSILON_1000;
487   const bool isHeightRelative = fabsf(mImpl->mTransform.mOffsetSizeMode.w) < Math::MACHINE_EPSILON_1000;
488
489   // Round the size and offset to avoid pixel alignement issues.
490   relayoutSize.width  = floorf(0.5f + (isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width));
491   relayoutSize.height = floorf(0.5f + (isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height));
492
493   std::string text;
494   mController->GetText(text);
495
496   if((fabsf(relayoutSize.width) < Math::MACHINE_EPSILON_1000) || (fabsf(relayoutSize.height) < Math::MACHINE_EPSILON_1000) || text.empty())
497   {
498     // Remove the texture set and any renderer previously set.
499     RemoveRenderer(control);
500
501     // Nothing else to do if the relayout size is zero.
502     ResourceReady(Toolkit::Visual::ResourceStatus::READY);
503     return;
504   }
505
506   Dali::LayoutDirection::Type layoutDirection = mController->GetLayoutDirection(control);
507
508   const Text::Controller::UpdateTextType updateTextType = mController->Relayout(relayoutSize, layoutDirection);
509
510   if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType) || mRendererUpdateNeeded)
511   {
512     mRendererUpdateNeeded = false;
513
514     // Remove the texture set and any renderer previously set.
515     RemoveRenderer(control);
516
517     if((relayoutSize.width > Math::MACHINE_EPSILON_1000) &&
518        (relayoutSize.height > Math::MACHINE_EPSILON_1000))
519     {
520       // Check whether it is a markup text with multiple text colors
521       const Vector4* const colorsBuffer          = mController->GetTextModel()->GetColors();
522       bool                 hasMultipleTextColors = (NULL != colorsBuffer);
523
524       // Check whether the text contains any color glyph
525       bool containsColorGlyph = false;
526
527       TextAbstraction::FontClient  fontClient     = TextAbstraction::FontClient::Get();
528       const Text::GlyphInfo* const glyphsBuffer   = mController->GetTextModel()->GetGlyphs();
529       const Text::Length           numberOfGlyphs = mController->GetTextModel()->GetNumberOfGlyphs();
530       for(Text::Length glyphIndex = 0; glyphIndex < numberOfGlyphs; glyphIndex++)
531       {
532         // Retrieve the glyph's info.
533         const Text::GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
534
535         // Whether the current glyph is a color one.
536         if(fontClient.IsColorGlyph(glyphInfo->fontId, glyphInfo->index))
537         {
538           containsColorGlyph = true;
539           break;
540         }
541       }
542
543       // Check whether the text contains any style colors (e.g. underline color, shadow color, etc.)
544
545       bool           shadowEnabled = false;
546       const Vector2& shadowOffset  = mController->GetTextModel()->GetShadowOffset();
547       if(fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1)
548       {
549         shadowEnabled = true;
550       }
551
552       const bool underlineEnabled       = mController->GetTextModel()->IsUnderlineEnabled();
553       const bool outlineEnabled         = (mController->GetTextModel()->GetOutlineWidth() > Math::MACHINE_EPSILON_1);
554       const bool backgroundEnabled      = mController->GetTextModel()->IsBackgroundEnabled();
555       const bool markupProcessorEnabled = mController->IsMarkupProcessorEnabled();
556       const bool strikethroughEnabled   = mController->GetTextModel()->IsStrikethroughEnabled();
557
558       const bool styleEnabled = (shadowEnabled || underlineEnabled || outlineEnabled || backgroundEnabled || markupProcessorEnabled || strikethroughEnabled);
559       const bool isOverlayStyle = underlineEnabled || strikethroughEnabled;
560
561       AddRenderer(control, relayoutSize, hasMultipleTextColors, containsColorGlyph, styleEnabled, isOverlayStyle);
562
563       // Text rendered and ready to display
564       ResourceReady(Toolkit::Visual::ResourceStatus::READY);
565     }
566   }
567 }
568
569 void TextVisual::AddTexture(TextureSet& textureSet, PixelData& data, Sampler& sampler, unsigned int textureSetIndex)
570 {
571   Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D,
572                                  data.GetPixelFormat(),
573                                  data.GetWidth(),
574                                  data.GetHeight());
575   texture.Upload(data);
576
577   textureSet.SetTexture(textureSetIndex, texture);
578   textureSet.SetSampler(textureSetIndex, sampler);
579 }
580
581 PixelData TextVisual::ConvertToPixelData(unsigned char* buffer, int width, int height, int offsetPosition, const Pixel::Format textPixelFormat)
582 {
583   int            bpp        = Pixel::GetBytesPerPixel(textPixelFormat);
584   unsigned int   bufferSize = width * height * bpp;
585   unsigned char* dstBuffer  = static_cast<unsigned char*>(malloc(bufferSize));
586   memcpy(dstBuffer, buffer + offsetPosition * bpp, bufferSize);
587   PixelData pixelData = Dali::PixelData::New(dstBuffer,
588                                              bufferSize,
589                                              width,
590                                              height,
591                                              textPixelFormat,
592                                              Dali::PixelData::FREE);
593   return pixelData;
594 }
595
596 void TextVisual::CreateTextureSet(TilingInfo& info, Renderer& renderer, Sampler& sampler, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled, bool isOverlayStyle)
597 {
598   TextureSet   textureSet      = TextureSet::New();
599   unsigned int textureSetIndex = 0u;
600
601   // Convert the buffer to pixel data to make it a texture.
602
603   if(info.textBuffer)
604   {
605     PixelData data = ConvertToPixelData(info.textBuffer, info.width, info.height, info.offsetPosition, info.textPixelFormat);
606     AddTexture(textureSet, data, sampler, textureSetIndex);
607     ++textureSetIndex;
608   }
609
610   if(styleEnabled && info.styleBuffer)
611   {
612     PixelData styleData = ConvertToPixelData(info.styleBuffer, info.width, info.height, info.offsetPosition, Pixel::RGBA8888);
613     AddTexture(textureSet, styleData, sampler, textureSetIndex);
614     ++textureSetIndex;
615   }
616
617   if(styleEnabled && isOverlayStyle && info.styleBuffer)
618   {
619     PixelData overlayStyleData = ConvertToPixelData(info.styleBuffer, info.width, info.height, info.offsetPosition, Pixel::RGBA8888);
620     AddTexture(textureSet, overlayStyleData, sampler, textureSetIndex);
621     ++textureSetIndex;
622   }
623
624   if(containsColorGlyph && !hasMultipleTextColors && info.maskBuffer)
625   {
626     PixelData maskData = ConvertToPixelData(info.maskBuffer, info.width, info.height, info.offsetPosition, Pixel::L8);
627     AddTexture(textureSet, maskData, sampler, textureSetIndex);
628   }
629
630   renderer.SetTextures(textureSet);
631
632   //Register transform properties
633   mImpl->mTransform.RegisterUniforms(renderer, Direction::LEFT_TO_RIGHT);
634
635   // Enable the pre-multiplied alpha to improve the text quality
636   renderer.SetProperty(Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, true);
637   renderer.RegisterProperty(PREMULTIPLIED_ALPHA, 1.0f);
638
639   // Set size and offset for the tiling.
640   renderer.RegisterProperty(SIZE, Vector2(info.width, info.height));
641   renderer.RegisterProperty(OFFSET, Vector2(info.offSet.x, info.offSet.y));
642   renderer.RegisterProperty("uHasMultipleTextColors", static_cast<float>(hasMultipleTextColors));
643   renderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
644
645   mRendererList.push_back(renderer);
646 }
647
648 void TextVisual::AddRenderer(Actor& actor, const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled, bool isOverlayStyle)
649 {
650   Shader shader = GetTextShader(mFactoryCache, hasMultipleTextColors, containsColorGlyph, styleEnabled);
651   mImpl->mRenderer.SetShader(shader);
652
653   // Get the maximum size.
654   const int maxTextureSize = Dali::GetMaxTextureSize();
655
656   // No tiling required. Use the default renderer.
657   if(size.height < maxTextureSize)
658   {
659     TextureSet textureSet = GetTextTexture(size, hasMultipleTextColors, containsColorGlyph, styleEnabled, isOverlayStyle);
660
661     mImpl->mRenderer.SetTextures(textureSet);
662     //Register transform properties
663     mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
664     mImpl->mRenderer.RegisterProperty("uHasMultipleTextColors", static_cast<float>(hasMultipleTextColors));
665     mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
666
667     mRendererList.push_back(mImpl->mRenderer);
668   }
669   // If the pixel data exceeds the maximum size, tiling is required.
670   else
671   {
672     // Filter mode needs to be set to linear to produce better quality while scaling.
673     Sampler sampler = Sampler::New();
674     sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR);
675
676     // Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture
677     Pixel::Format textPixelFormat = (containsColorGlyph || hasMultipleTextColors) ? Pixel::RGBA8888 : Pixel::L8;
678
679     // Check the text direction
680     Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection();
681
682     // Create a texture for the text without any styles
683     PixelData data = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat);
684
685     int verifiedWidth  = data.GetWidth();
686     int verifiedHeight = data.GetHeight();
687
688     // Set information for creating textures.
689     TilingInfo info(verifiedWidth, maxTextureSize, textPixelFormat);
690
691     // Get the buffer of text.
692     Dali::DevelPixelData::PixelDataBuffer textPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(data);
693     info.textBuffer                                     = textPixelData.buffer;
694
695     if(styleEnabled)
696     {
697       // Create RGBA texture for all the text styles (without the text itself)
698       PixelData                             styleData      = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888);
699       Dali::DevelPixelData::PixelDataBuffer stylePixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(styleData);
700       info.styleBuffer                                     = stylePixelData.buffer;
701     }
702
703     if(containsColorGlyph && !hasMultipleTextColors)
704     {
705       // Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation
706       PixelData                             maskData      = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8);
707       Dali::DevelPixelData::PixelDataBuffer maskPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(maskData);
708       info.maskBuffer                                     = maskPixelData.buffer;
709     }
710
711     // Get the current offset for recalculate the offset when tiling.
712     Property::Map retMap;
713     mImpl->mTransform.GetPropertyMap(retMap);
714     Property::Value* offsetValue = retMap.Find(Dali::Toolkit::Visual::Transform::Property::OFFSET);
715     if(offsetValue)
716     {
717       offsetValue->Get(info.offSet);
718     }
719
720     // Create a textureset in the default renderer.
721     CreateTextureSet(info, mImpl->mRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled, isOverlayStyle);
722
723     verifiedHeight -= maxTextureSize;
724
725     Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
726
727     int offsetPosition = verifiedWidth * maxTextureSize;
728     // Create a renderer by cutting maxTextureSize.
729     while(verifiedHeight > 0)
730     {
731       Renderer tilingRenderer = Renderer::New(geometry, shader);
732       tilingRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT);
733       // New offset position of buffer for tiling.
734       info.offsetPosition += offsetPosition;
735       // New height for tiling.
736       info.height = (verifiedHeight - maxTextureSize) > 0 ? maxTextureSize : verifiedHeight;
737       // New offset for tiling.
738       info.offSet.y += maxTextureSize;
739       // Create a textureset int the new tiling renderer.
740       CreateTextureSet(info, tilingRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled, isOverlayStyle);
741
742       verifiedHeight -= maxTextureSize;
743     }
744   }
745
746   mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
747
748   for(RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
749   {
750     Renderer renderer = (*iter);
751     if(renderer)
752     {
753       actor.AddRenderer(renderer);
754     }
755   }
756 }
757
758 TextureSet TextVisual::GetTextTexture(const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled, bool isOverlayStyle)
759 {
760   // Filter mode needs to be set to linear to produce better quality while scaling.
761   Sampler sampler = Sampler::New();
762   sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR);
763
764   TextureSet textureSet = TextureSet::New();
765
766   // Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture
767   Pixel::Format textPixelFormat = (containsColorGlyph || hasMultipleTextColors) ? Pixel::RGBA8888 : Pixel::L8;
768
769   // Check the text direction
770   Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection();
771
772   // Create a texture for the text without any styles
773   PixelData data = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat);
774
775   // It may happen the image atlas can't handle a pixel data it exceeds the maximum size.
776   // In that case, create a texture. TODO: should tile the text.
777   unsigned int textureSetIndex = 0u;
778   AddTexture(textureSet, data, sampler, textureSetIndex);
779   ++textureSetIndex;
780
781   if(styleEnabled)
782   {
783     // Create RGBA texture for all the text styles that render in the background (without the text itself)
784     PixelData styleData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888);
785     AddTexture(textureSet, styleData, sampler, textureSetIndex);
786     ++textureSetIndex;
787     // Create RGBA texture for overlay styles such as underline and strikethrough (without the text itself)
788     PixelData overlayStyleData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_OVERLAY_STYLE, false, Pixel::RGBA8888);
789     AddTexture(textureSet, overlayStyleData, sampler, textureSetIndex);
790     ++textureSetIndex;
791   }
792
793   if(containsColorGlyph && !hasMultipleTextColors)
794   {
795     // Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation
796     PixelData maskData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8);
797
798     AddTexture(textureSet, maskData, sampler, textureSetIndex);
799   }
800
801   return textureSet;
802 }
803
804 Shader TextVisual::GetTextShader(VisualFactoryCache& factoryCache, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled)
805 {
806   Shader shader;
807
808   if(hasMultipleTextColors && !styleEnabled)
809   {
810     // We don't animate text color if the text contains multiple colors
811     shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT);
812     if(!shader)
813     {
814       shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_SHADER_FRAG);
815       shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
816       factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT, shader);
817     }
818   }
819   else if(hasMultipleTextColors && styleEnabled)
820   {
821     // We don't animate text color if the text contains multiple colors
822     shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE);
823     if(!shader)
824     {
825       shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_WITH_STYLE_SHADER_FRAG);
826       shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
827       factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE, shader);
828     }
829   }
830   else if(!hasMultipleTextColors && !containsColorGlyph && !styleEnabled)
831   {
832     shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT);
833     if(!shader)
834     {
835       shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_SHADER_FRAG);
836       shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
837       factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT, shader);
838     }
839   }
840   else if(!hasMultipleTextColors && !containsColorGlyph && styleEnabled)
841   {
842     shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE);
843     if(!shader)
844     {
845       shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_SHADER_FRAG);
846       shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
847       factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE, shader);
848     }
849   }
850   else if(!hasMultipleTextColors && containsColorGlyph && !styleEnabled)
851   {
852     shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI);
853     if(!shader)
854     {
855       shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_EMOJI_SHADER_FRAG);
856       shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
857       factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI, shader);
858     }
859   }
860   else // if( !hasMultipleTextColors && containsColorGlyph && styleEnabled )
861   {
862     shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI);
863     if(!shader)
864     {
865       shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI_SHADER_FRAG);
866       shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
867       factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI, shader);
868     }
869   }
870
871   return shader;
872 }
873
874 } // namespace Internal
875
876 } // namespace Toolkit
877
878 } // namespace Dali