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