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