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