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