TextVisual pixel aligned and uses new shader
[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   if( !geometry )
273   {
274     geometry =  VisualFactoryCache::CreateQuadGeometry();
275     mFactoryCache.SaveGeometry( VisualFactoryCache::QUAD_GEOMETRY , geometry );
276   }
277
278   Shader shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_ATLAS_CLAMP );
279   mFactoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP, shader );
280
281   shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
282
283   mImpl->mRenderer = Renderer::New( geometry, shader );
284   mImpl->mRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::TEXT );
285
286   UpdateRenderer();
287 }
288
289 void TextVisual::DoSetOffStage( Actor& actor )
290 {
291   if( mImpl->mRenderer )
292   {
293     // Removes the renderer from the actor.
294     actor.RemoveRenderer( mImpl->mRenderer );
295
296     RemoveTextureSet();
297
298     // Resets the renderer.
299     mImpl->mRenderer.Reset();
300   }
301
302   // Resets the control handle.
303   mControl.Reset();
304 }
305
306 void TextVisual::OnSetTransform()
307 {
308   UpdateRenderer();
309 }
310
311 void TextVisual::DoSetProperty( Dali::Property::Index index, const Dali::Property::Value& propertyValue )
312 {
313   switch( index )
314   {
315     case Toolkit::TextVisual::Property::ENABLE_MARKUP:
316     {
317       const bool enableMarkup = propertyValue.Get<bool>();
318       mController->SetMarkupProcessorEnabled( enableMarkup );
319       break;
320     }
321     case Toolkit::TextVisual::Property::TEXT:
322     {
323       mController->SetText( propertyValue.Get<std::string>() );
324       break;
325     }
326     case Toolkit::TextVisual::Property::FONT_FAMILY:
327     {
328       SetFontFamilyProperty( mController, propertyValue );
329       break;
330     }
331     case Toolkit::TextVisual::Property::FONT_STYLE:
332     {
333       SetFontStyleProperty( mController, propertyValue, Text::FontStyle::DEFAULT );
334       break;
335     }
336     case Toolkit::TextVisual::Property::POINT_SIZE:
337     {
338       const float pointSize = propertyValue.Get<float>();
339       if( !Equals( mController->GetDefaultPointSize(), pointSize ) )
340       {
341         mController->SetDefaultPointSize( pointSize );
342       }
343       break;
344     }
345     case Toolkit::TextVisual::Property::MULTI_LINE:
346     {
347       mController->SetMultiLineEnabled( propertyValue.Get<bool>() );
348       break;
349     }
350     case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
351     {
352       Toolkit::Text::Layout::HorizontalAlignment alignment( Toolkit::Text::Layout::HORIZONTAL_ALIGN_BEGIN );
353       if( Scripting::GetEnumeration< Toolkit::Text::Layout::HorizontalAlignment >( propertyValue.Get< std::string >().c_str(),
354                                                                                    HORIZONTAL_ALIGNMENT_STRING_TABLE,
355                                                                                    HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT,
356                                                                                    alignment ) )
357       {
358         mController->SetHorizontalAlignment( alignment );
359       }
360       break;
361     }
362     case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
363     {
364       Toolkit::Text::Layout::VerticalAlignment alignment( Toolkit::Text::Layout::VERTICAL_ALIGN_BOTTOM );
365       if( Scripting::GetEnumeration< Toolkit::Text::Layout::VerticalAlignment >( propertyValue.Get< std::string >().c_str(),
366                                                                                  VERTICAL_ALIGNMENT_STRING_TABLE,
367                                                                                  VERTICAL_ALIGNMENT_STRING_TABLE_COUNT,
368                                                                                  alignment ) )
369       {
370         mController->SetVerticalAlignment( alignment );
371       }
372       break;
373     }
374     case Toolkit::TextVisual::Property::TEXT_COLOR:
375     {
376       const Vector4& textColor = propertyValue.Get< Vector4 >();
377       if( mController->GetDefaultColor() != textColor )
378       {
379         mController->SetDefaultColor( textColor );
380       }
381       break;
382     }
383   }
384 }
385
386 void TextVisual::UpdateRenderer()
387 {
388   Actor control = mControl.GetHandle();
389   if( !control )
390   {
391     // Nothing to do.
392     return;
393   }
394
395   // Calculates the size to be used to relayout.
396   Vector2 relayoutSize;
397
398   const bool isWidthRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.z ) < Math::MACHINE_EPSILON_1000;
399   const bool isHeightRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.w ) < Math::MACHINE_EPSILON_1000;
400
401   // Round the size and offset to avoid pixel alignement issues.
402   relayoutSize.width = floorf( 0.5f + ( isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width ) );
403   relayoutSize.height = floorf( 0.5f + ( isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height ) );
404
405   if( ( fabsf( relayoutSize.width ) < Math::MACHINE_EPSILON_1000 ) || ( fabsf( relayoutSize.height ) < Math::MACHINE_EPSILON_1000 ) )
406   {
407     // Removes the texture set.
408     RemoveTextureSet();
409
410     // Remove any renderer previously set.
411     if( mImpl->mRenderer )
412     {
413       control.RemoveRenderer( mImpl->mRenderer );
414     }
415
416     // Nothing else to do if the relayout size is zero.
417     return;
418   }
419
420   const Text::Controller::UpdateTextType updateTextType = mController->Relayout( relayoutSize );
421
422   if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) )
423   {
424     // Removes the texture set.
425     RemoveTextureSet();
426
427     // Remove any renderer previously set.
428     if( mImpl->mRenderer )
429     {
430       control.RemoveRenderer( mImpl->mRenderer );
431     }
432
433     if( ( relayoutSize.width > Math::MACHINE_EPSILON_1000 ) &&
434         ( relayoutSize.height > Math::MACHINE_EPSILON_1000 ) )
435     {
436       PixelData data = mTypesetter->Render( relayoutSize );
437
438       Vector4 atlasRect = FULL_TEXTURE_RECT;
439       TextureSet textureSet = mFactoryCache.GetAtlasManager()->Add( atlasRect, data );
440
441       if( textureSet )
442       {
443         mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
444       }
445       else
446       {
447         // It may happen the image atlas can't handle a pixel data it exceeds the maximum size.
448         // In that case, create a texture. TODO: should tile the text.
449
450         Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D,
451                                         data.GetPixelFormat(),
452                                         data.GetWidth(),
453                                         data.GetHeight() );
454
455         texture.Upload( data );
456
457         textureSet = TextureSet::New();
458         textureSet.SetTexture( 0u, texture );
459
460         mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
461       }
462
463       mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect );
464
465       //Register transform properties
466       mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
467
468       // Filter mode needs to be set to nearest to avoid blurry text.
469       Sampler sampler = Sampler::New();
470       sampler.SetFilterMode( FilterMode::NEAREST, FilterMode::NEAREST );
471       textureSet.SetSampler( 0u, sampler );
472
473       mImpl->mRenderer.SetTextures( textureSet );
474
475       control.AddRenderer( mImpl->mRenderer );
476     }
477   }
478 }
479
480 void TextVisual::RemoveTextureSet()
481 {
482   if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
483   {
484     // Removes the text's image from the texture atlas.
485     Vector4 atlasRect;
486
487     const Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
488     if( index != Property::INVALID_INDEX )
489     {
490       const Property::Value& atlasRectValue = mImpl->mRenderer.GetProperty( index );
491       atlasRectValue.Get( atlasRect );
492
493       const TextureSet& textureSet = mImpl->mRenderer.GetTextures();
494       mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
495     }
496   }
497 }
498
499 } // namespace Internal
500
501 } // namespace Toolkit
502
503 } // namespace Dali