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