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