Merge "Fixed the ItemView already scrolled to end logic" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / text / text-visual.cpp
1 /*
2  * Copyright (c) 2016 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 // INTERNAL HEADER
22 #include <dali-toolkit/devel-api/visuals/text-visual-properties.h>
23 #include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
24 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
25 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
26 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
27 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
28 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
29 #include <dali-toolkit/internal/text/text-font-style.h>
30
31 namespace Dali
32 {
33
34 namespace Toolkit
35 {
36
37 namespace Internal
38 {
39
40 namespace
41 {
42
43 // Property names - common properties defined in visual-string-constants.h/cpp
44 const char * const FONT_FAMILY_PROPERTY( "fontFamily" );
45 const char * const FONT_STYLE_PROPERTY( "fontStyle" );
46 const char * const POINT_SIZE_PROPERTY( "pointSize" );
47 const char * const MULTI_LINE_PROPERTY( "multiLine" );
48 const char * const HORIZONTAL_ALIGNMENT_PROPERTY( "horizontalAlignment" );
49 const char * const VERTICAL_ALIGNMENT_PROPERTY( "verticalAlignment" );
50 const char * const TEXT_COLOR_PROPERTY( "textColor" );
51 const char * const ENABLE_MARKUP_PROPERTY( "enableMarkup" );
52
53 const Scripting::StringEnum HORIZONTAL_ALIGNMENT_STRING_TABLE[] =
54 {
55   { "BEGIN",  Toolkit::Text::Layout::HORIZONTAL_ALIGN_BEGIN  },
56   { "CENTER", Toolkit::Text::Layout::HORIZONTAL_ALIGN_CENTER },
57   { "END",    Toolkit::Text::Layout::HORIZONTAL_ALIGN_END    },
58 };
59 const unsigned int HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof( HORIZONTAL_ALIGNMENT_STRING_TABLE ) / sizeof( HORIZONTAL_ALIGNMENT_STRING_TABLE[0] );
60
61 const Scripting::StringEnum VERTICAL_ALIGNMENT_STRING_TABLE[] =
62 {
63   { "TOP",    Toolkit::Text::Layout::VERTICAL_ALIGN_TOP    },
64   { "CENTER", Toolkit::Text::Layout::VERTICAL_ALIGN_CENTER },
65   { "BOTTOM", Toolkit::Text::Layout::VERTICAL_ALIGN_BOTTOM },
66 };
67 const unsigned int VERTICAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof( VERTICAL_ALIGNMENT_STRING_TABLE ) / sizeof( VERTICAL_ALIGNMENT_STRING_TABLE[0] );
68
69 const Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f );
70
71 std::string GetHorizontalAlignment( Toolkit::Text::Layout::HorizontalAlignment alignment )
72 {
73   const char* name = Scripting::GetEnumerationName<Toolkit::Text::Layout::HorizontalAlignment>( alignment,
74                                                                                                 HORIZONTAL_ALIGNMENT_STRING_TABLE,
75                                                                                                 HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT );
76
77   return std::string( name );
78 }
79
80 std::string GetVerticalAlignment( Toolkit::Text::Layout::VerticalAlignment alignment )
81 {
82   const char* name = Scripting::GetEnumerationName< Toolkit::Text::Layout::VerticalAlignment >( alignment,
83                                                                                                 VERTICAL_ALIGNMENT_STRING_TABLE,
84                                                                                                 VERTICAL_ALIGNMENT_STRING_TABLE_COUNT );
85
86   return std::string( name );
87 }
88
89 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
90   attribute mediump vec2 aPosition;\n
91   uniform mediump mat4 uMvpMatrix;\n
92   uniform mediump vec3 uSize;\n
93   uniform mediump vec4 pixelArea;
94
95   uniform mediump mat4 uModelMatrix;\n
96   uniform mediump mat4 uViewMatrix;\n
97   uniform mediump mat4 uProjection;\n
98
99   varying mediump vec2 vTexCoord;\n
100   \n
101   //Visual size and offset
102   uniform mediump vec2 offset;\n
103   uniform mediump vec2 size;\n
104   uniform mediump vec4 offsetSizeMode;\n
105   uniform mediump vec2 origin;\n
106   uniform mediump vec2 anchorPoint;\n
107
108   vec4 ComputeVertexPosition()\n
109   {\n
110     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
111     vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
112     return vec4( (aPosition + anchorPoint)*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
113   }\n
114
115   void main()\n
116   {\n
117     mediump vec4 nonAlignedVertex = uViewMatrix*uModelMatrix*ComputeVertexPosition();\n
118     mediump vec4 pixelAlignedVertex = vec4 ( floor(nonAlignedVertex.xyz), 1.0 );\n
119     mediump vec4 vertexPosition = uProjection*pixelAlignedVertex;\n
120
121     vTexCoord = pixelArea.xy+pixelArea.zw*(aPosition + vec2(0.5) );\n
122     gl_Position = vertexPosition;\n
123   }\n
124 );
125
126 const char* FRAGMENT_SHADER_ATLAS_CLAMP = DALI_COMPOSE_SHADER(
127     varying mediump vec2 vTexCoord;\n
128     uniform sampler2D sTexture;\n
129     uniform mediump vec4 uAtlasRect;\n
130     uniform lowp vec4 uColor;\n
131     uniform lowp vec3 mixColor;\n
132     uniform lowp float opacity;\n
133     \n
134     void main()\n
135     {\n
136       mediump vec2 texCoord = clamp( mix( uAtlasRect.xy, uAtlasRect.zw, vTexCoord ), uAtlasRect.xy, uAtlasRect.zw );\n
137       gl_FragColor = texture2D( sTexture, texCoord ) * uColor * vec4( mixColor, opacity );\n
138     }\n
139 );
140
141 /**
142  * Return Property index for the given string key
143  * param[in] stringKey the string index key
144  * return the key as an index
145  */
146
147 Dali::Property::Index StringKeyToIndexKey( const std::string& stringKey )
148 {
149   Dali::Property::Index result = Property::INVALID_KEY;
150
151   if( stringKey == VISUAL_TYPE )
152   {
153     result = Toolkit::Visual::Property::TYPE;
154   }
155   else if( stringKey == TEXT_PROPERTY )
156   {
157     result = Toolkit::TextVisual::Property::TEXT;
158   }
159   else if( stringKey == FONT_FAMILY_PROPERTY )
160   {
161     result = Toolkit::TextVisual::Property::FONT_FAMILY;
162   }
163   else if( stringKey == FONT_STYLE_PROPERTY )
164   {
165     result = Toolkit::TextVisual::Property::FONT_STYLE;
166   }
167   else if( stringKey == POINT_SIZE_PROPERTY )
168   {
169     result = Toolkit::TextVisual::Property::POINT_SIZE;
170   }
171   else if( stringKey == MULTI_LINE_PROPERTY )
172   {
173     result = Toolkit::TextVisual::Property::MULTI_LINE;
174   }
175   else if( stringKey == HORIZONTAL_ALIGNMENT_PROPERTY )
176   {
177     result = Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT;
178   }
179   else if( stringKey == VERTICAL_ALIGNMENT_PROPERTY )
180   {
181     result = Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT;
182   }
183   else if( stringKey == TEXT_COLOR_PROPERTY )
184   {
185     result = Toolkit::TextVisual::Property::TEXT_COLOR;
186   }
187   else if( stringKey == ENABLE_MARKUP_PROPERTY )
188   {
189     result = Toolkit::TextVisual::Property::ENABLE_MARKUP;
190   }
191
192   return result;
193 }
194
195 } // unnamed namespace
196
197 TextVisualPtr TextVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
198 {
199   TextVisualPtr TextVisualPtr( new TextVisual( factoryCache ) );
200   TextVisualPtr->SetProperties( properties );
201   return TextVisualPtr;
202 }
203
204 void TextVisual::ConvertStringKeysToIndexKeys( Property::Map& propertyMap )
205 {
206   Property::Map outMap;
207
208   for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
209   {
210     const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
211
212     Property::Index indexKey = keyValue.first.indexKey;
213
214     if ( keyValue.first.type == Property::Key::STRING )
215     {
216       indexKey = StringKeyToIndexKey( keyValue.first.stringKey );
217     }
218
219     outMap.Insert( indexKey, keyValue.second );
220   }
221
222   propertyMap = outMap;
223 }
224
225 float TextVisual::GetHeightForWidth( float width )
226 {
227   return mController->GetHeightForWidth( width );
228 }
229
230 void TextVisual::GetNaturalSize( Vector2& naturalSize )
231 {
232   naturalSize = mController->GetNaturalSize().GetVectorXY();
233 }
234
235 void TextVisual::DoCreatePropertyMap( Property::Map& map ) const
236 {
237   Property::Value value;
238
239   map.Clear();
240   map.Insert( Toolkit::DevelVisual::Property::TYPE, Toolkit::DevelVisual::TEXT );
241
242   std::string text;
243   mController->GetText( text );
244   map.Insert( Toolkit::TextVisual::Property::TEXT, text );
245
246   map.Insert( Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily() );
247
248   GetFontStyleProperty( mController, value, Text::FontStyle::DEFAULT );
249   map.Insert( Toolkit::TextVisual::Property::FONT_STYLE, value );
250
251   map.Insert( Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultPointSize() );
252
253   map.Insert( Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled() );
254
255   map.Insert( Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, GetHorizontalAlignment( mController->GetHorizontalAlignment() ) );
256
257   map.Insert( Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, GetVerticalAlignment( mController->GetVerticalAlignment() ) );
258
259   map.Insert( Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor() );
260
261   map.Insert( Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled() );
262 }
263
264 TextVisual::TextVisual( VisualFactoryCache& factoryCache )
265 : Visual::Base( factoryCache ),
266   mController( Text::Controller::New() ),
267   mTypesetter( Text::Typesetter::New( mController->GetTextModel() ) )
268 {
269 }
270
271 TextVisual::~TextVisual()
272 {
273 }
274
275 void TextVisual::DoSetProperties( const Property::Map& propertyMap )
276 {
277   for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
278   {
279     const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
280
281     Property::Index indexKey = keyValue.first.indexKey;
282
283     if( keyValue.first.type == Property::Key::STRING )
284     {
285       indexKey = StringKeyToIndexKey( keyValue.first.stringKey );
286     }
287
288     DoSetProperty( indexKey, keyValue.second );
289   }
290
291   // Elide the text if it exceeds the boundaries.
292   mController->SetTextElideEnabled( true );
293
294   // Retrieve the layout engine to set the cursor's width.
295   Text::Layout::Engine& engine = mController->GetLayoutEngine();
296
297   // Sets 0 as cursor's width.
298   engine.SetCursorWidth( 0u ); // Do not layout space for the cursor.
299 }
300
301 void TextVisual::DoSetOnStage( Actor& actor )
302 {
303   mControl = actor;
304
305   Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
306
307   Shader shader = mFactoryCache.GetShader( VisualFactoryCache::TEXT_SHADER );
308   if( ! shader )
309   {
310     shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_ATLAS_CLAMP );
311     shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
312
313     mFactoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER, shader );
314   }
315
316   mImpl->mRenderer = Renderer::New( geometry, shader );
317   mImpl->mRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT );
318
319   UpdateRenderer( true ); // Renderer needs textures and to be added to control
320 }
321
322 void TextVisual::DoSetOffStage( Actor& actor )
323 {
324   if( mImpl->mRenderer )
325   {
326     // Removes the renderer from the actor.
327     actor.RemoveRenderer( mImpl->mRenderer );
328
329     RemoveTextureSet();
330
331     // Resets the renderer.
332     mImpl->mRenderer.Reset();
333   }
334
335   // Resets the control handle.
336   mControl.Reset();
337 }
338
339 void TextVisual::OnSetTransform()
340 {
341   UpdateRenderer( false );
342 }
343
344 void TextVisual::DoSetProperty( Dali::Property::Index index, const Dali::Property::Value& propertyValue )
345 {
346   switch( index )
347   {
348     case Toolkit::TextVisual::Property::ENABLE_MARKUP:
349     {
350       const bool enableMarkup = propertyValue.Get<bool>();
351       mController->SetMarkupProcessorEnabled( enableMarkup );
352       break;
353     }
354     case Toolkit::TextVisual::Property::TEXT:
355     {
356       mController->SetText( propertyValue.Get<std::string>() );
357       break;
358     }
359     case Toolkit::TextVisual::Property::FONT_FAMILY:
360     {
361       SetFontFamilyProperty( mController, propertyValue );
362       break;
363     }
364     case Toolkit::TextVisual::Property::FONT_STYLE:
365     {
366       SetFontStyleProperty( mController, propertyValue, Text::FontStyle::DEFAULT );
367       break;
368     }
369     case Toolkit::TextVisual::Property::POINT_SIZE:
370     {
371       const float pointSize = propertyValue.Get<float>();
372       if( !Equals( mController->GetDefaultPointSize(), pointSize ) )
373       {
374         mController->SetDefaultPointSize( pointSize );
375       }
376       break;
377     }
378     case Toolkit::TextVisual::Property::MULTI_LINE:
379     {
380       mController->SetMultiLineEnabled( propertyValue.Get<bool>() );
381       break;
382     }
383     case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
384     {
385       Toolkit::Text::Layout::HorizontalAlignment alignment( Toolkit::Text::Layout::HORIZONTAL_ALIGN_BEGIN );
386       if( Scripting::GetEnumeration< Toolkit::Text::Layout::HorizontalAlignment >( propertyValue.Get< std::string >().c_str(),
387                                                                                    HORIZONTAL_ALIGNMENT_STRING_TABLE,
388                                                                                    HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT,
389                                                                                    alignment ) )
390       {
391         mController->SetHorizontalAlignment( alignment );
392       }
393       break;
394     }
395     case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
396     {
397       Toolkit::Text::Layout::VerticalAlignment alignment( Toolkit::Text::Layout::VERTICAL_ALIGN_BOTTOM );
398       if( Scripting::GetEnumeration< Toolkit::Text::Layout::VerticalAlignment >( propertyValue.Get< std::string >().c_str(),
399                                                                                  VERTICAL_ALIGNMENT_STRING_TABLE,
400                                                                                  VERTICAL_ALIGNMENT_STRING_TABLE_COUNT,
401                                                                                  alignment ) )
402       {
403         mController->SetVerticalAlignment( alignment );
404       }
405       break;
406     }
407     case Toolkit::TextVisual::Property::TEXT_COLOR:
408     {
409       const Vector4& textColor = propertyValue.Get< Vector4 >();
410       if( mController->GetDefaultColor() != textColor )
411       {
412         mController->SetDefaultColor( textColor );
413       }
414       break;
415     }
416   }
417 }
418
419 void TextVisual::UpdateRenderer( bool initializeRendererAndTexture )
420 {
421   Actor control = mControl.GetHandle();
422   if( !control )
423   {
424     // Nothing to do.
425     return;
426   }
427
428   // Calculates the size to be used to relayout.
429   Vector2 relayoutSize;
430
431   const bool isWidthRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.z ) < Math::MACHINE_EPSILON_1000;
432   const bool isHeightRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.w ) < Math::MACHINE_EPSILON_1000;
433
434   // Round the size and offset to avoid pixel alignement issues.
435   relayoutSize.width = floorf( 0.5f + ( isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width ) );
436   relayoutSize.height = floorf( 0.5f + ( isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height ) );
437
438   if( ( fabsf( relayoutSize.width ) < Math::MACHINE_EPSILON_1000 ) || ( fabsf( relayoutSize.height ) < Math::MACHINE_EPSILON_1000 ) )
439   {
440     // Removes the texture set.
441     RemoveTextureSet();
442
443     // Remove any renderer previously set.
444     if( mImpl->mRenderer )
445     {
446       control.RemoveRenderer( mImpl->mRenderer );
447     }
448
449     // Nothing else to do if the relayout size is zero.
450     return;
451   }
452
453   const Text::Controller::UpdateTextType updateTextType = mController->Relayout( relayoutSize );
454
455   if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) || initializeRendererAndTexture )
456   {
457     // Removes the texture set.
458     RemoveTextureSet();
459
460     // Remove any renderer previously set.
461     if( mImpl->mRenderer )
462     {
463       control.RemoveRenderer( mImpl->mRenderer );
464     }
465
466     if( ( relayoutSize.width > Math::MACHINE_EPSILON_1000 ) &&
467         ( relayoutSize.height > Math::MACHINE_EPSILON_1000 ) )
468     {
469       PixelData data = mTypesetter->Render( relayoutSize );
470
471       Vector4 atlasRect = FULL_TEXTURE_RECT;
472
473       // Texture set not retrieved from Atlas Manager whilst pixel offset visible.
474
475       // It may happen the image atlas can't handle a pixel data it exceeds the maximum size.
476       // In that case, create a texture. TODO: should tile the text.
477
478       Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D,
479                                       data.GetPixelFormat(),
480                                       data.GetWidth(),
481                                       data.GetHeight() );
482
483       texture.Upload( data );
484
485       TextureSet textureSet = TextureSet::New();
486       textureSet.SetTexture( 0u, texture );
487
488       mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
489
490       mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect );
491
492       //Register transform properties
493       mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
494
495       // Filter mode needs to be set to nearest to avoid blurry text.
496       Sampler sampler = Sampler::New();
497       sampler.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
498       textureSet.SetSampler( 0u, sampler );
499
500       mImpl->mRenderer.SetTextures( textureSet );
501
502       control.AddRenderer( mImpl->mRenderer );
503     }
504   }
505 }
506
507 void TextVisual::RemoveTextureSet()
508 {
509   if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
510   {
511     // Removes the text's image from the texture atlas.
512     Vector4 atlasRect;
513
514     const Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
515     if( index != Property::INVALID_INDEX )
516     {
517       const Property::Value& atlasRectValue = mImpl->mRenderer.GetProperty( index );
518       atlasRectValue.Get( atlasRect );
519
520       const TextureSet& textureSet = mImpl->mRenderer.GetTextures();
521       mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
522     }
523   }
524 }
525
526 } // namespace Internal
527
528 } // namespace Toolkit
529
530 } // namespace Dali