DALi Version 1.2.52
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / text-scroller.cpp
1 /*
2  * Copyright (c) 2017 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/text/text-scroller.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/common/stage.h>
23 #include <dali/public-api/images/frame-buffer-image.h>
24 #include <dali/public-api/render-tasks/render-task-list.h>
25 #include <dali/public-api/rendering/geometry.h>
26 #include <dali/public-api/rendering/renderer.h>
27 #include <dali/public-api/rendering/sampler.h>
28 #include <dali/public-api/rendering/shader.h>
29 #include <dali/devel-api/images/texture-set-image.h>
30 #include <dali/integration-api/debug.h>
31
32 // INTERNAL INCLUDES
33 #include <dali-toolkit/internal/text/text-scroller-interface.h>
34
35 namespace Dali
36 {
37
38 namespace Toolkit
39 {
40
41 namespace
42 {
43
44 #if defined ( DEBUG_ENABLED )
45   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_SCROLLING");
46 #endif
47
48 const int MINIMUM_SCROLL_SPEED = 1; // Speed should be set by Property system.
49
50 const char* VERTEX_SHADER_SCROLL = DALI_COMPOSE_SHADER(
51   attribute mediump vec2 aPosition;\n
52   varying highp vec2 vTexCoord;\n
53   varying highp float vRatio;\n
54   uniform mediump mat4 uModelMatrix;\n
55   uniform mediump mat4 uViewMatrix;\n
56   uniform mediump mat4 uProjection;\n
57   uniform mediump vec3 uSize;\n
58   uniform mediump float uDelta;\n
59   uniform mediump vec2 uTextureSize;
60   uniform mediump float uGap;\n
61   uniform mediump float uAlign;\n
62   \n
63   void main()\n
64   {\n
65     {\n
66       highp vec4 vertexPosition = vec4(aPosition*uSize.xy, 0.0, 1.0);\n
67       vertexPosition = uViewMatrix *  uModelMatrix  * vertexPosition ;\n
68       vertexPosition.x = floor( vertexPosition.x ) + 0.5;
69       vertexPosition.y = floor( vertexPosition.y ) + 0.5;
70       float smallTextPadding = max(uSize.x - uTextureSize.x, 0. );\n
71       float gap = max( uGap, smallTextPadding );\n
72       float delta = floor ( uDelta ) + 0.5;
73       vTexCoord.x = ( delta  + ( uAlign * ( uTextureSize.x - uSize.x ) ) + (  aPosition.x * uSize.x ) )/ ( uTextureSize.x + gap );\n
74       vTexCoord.y = ( 0.5 + floor(  aPosition.y * uSize.y ) )/ ( uTextureSize.y ) ;\n
75       vRatio = uTextureSize.x / ( uTextureSize.x + gap );\n
76       gl_Position = uProjection * vertexPosition;
77     }\n
78   }\n
79 );
80
81 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
82   varying highp vec2 vTexCoord;\n
83   varying highp float vRatio;\n
84   uniform sampler2D sTexture;\n
85   \n
86   void main()\n
87   {\n
88     highp vec2 texCoord;\n
89     texCoord.y = vTexCoord.y;\n
90     texCoord.x = fract( vTexCoord.x ) / vRatio;\n
91     if ( texCoord.x > 1.0 )\n
92       discard;\n
93     \n
94     gl_FragColor = texture2D( sTexture, texCoord );\n
95   }\n
96 );
97
98 /**
99  * @brief How the text should be aligned when scrolling the text.
100  *
101  * 0.0f aligns the text to the left, 1.0f aligns the text to the right.
102  * The final alignment depends on three factors:
103  *   1) The alignment value of the text label (Use Text::Layout::HorizontalAlignment enumerations).
104  *   2) The text direction, i.e. whether it's LTR or RTL (0 = LTR, 1 = RTL).
105  *   3) Whether the text is greater than the size of the control ( 0 = Text width <= Control width, 1 = Text width > Control width ).
106  */
107 const float ALIGNMENT_TABLE[ Text::Layout::HORIZONTAL_ALIGN_COUNT ][ 2 ][ 2 ] =
108 {
109   // HORIZONTAL_ALIGN_BEGIN
110   {
111     { // LTR
112       0.0f, // Text width <= Control width
113       0.0f  // Text width >  Control width
114     },
115     { // RTL
116       1.0f, // Text width <= Control width
117       1.0f  // Text width >  Control width
118     }
119   },
120
121   // HORIZONTAL_ALIGN_CENTER
122   {
123     { // LTR
124       0.5f, // Text width <= Control width
125       0.0f  // Text width >  Control width
126     },
127     { // RTL
128       0.5f, // Text width <= Control width
129       1.0f  // Text width >  Control width
130     }
131   },
132
133   // HORIZONTAL_ALIGN_END
134   {
135     { // LTR
136       1.0f, // Text width <= Control width
137       0.0f  // Text width >  Control width
138     },
139     { // RTL
140       0.0f, // Text width <= Control width
141       1.0f  // Text width >  Control width
142     }
143   }
144 };
145
146 /**
147  * @brief Create and set up a camera for the render task to use
148  *
149  * @param[in] sizeOfTarget size of the source camera to look at
150  * @param[out] offscreenCamera custom camera
151  */
152 void CreateCameraActor( const Size& sizeOfTarget, CameraActor& offscreenCamera )
153 {
154   offscreenCamera = CameraActor::New();
155   offscreenCamera.SetOrthographicProjection( sizeOfTarget );
156   offscreenCamera.SetInvertYAxis( true );
157 }
158
159 /**
160  * @brief Create a render task
161  *
162  * @param[in] sourceActor actor to be used as source
163  * @param[in] cameraActor camera looking at source
164  * @param[in] offscreenTarget resulting image from render task
165  * @param[out] renderTask render task that has been setup
166  */
167 void CreateRenderTask( Actor sourceActor, CameraActor cameraActor , FrameBufferImage offscreenTarget, RenderTask& renderTask )
168 {
169   Stage stage = Stage::GetCurrent();
170   RenderTaskList taskList = stage.GetRenderTaskList();
171   renderTask = taskList.CreateTask();
172   renderTask.SetSourceActor( sourceActor );
173   renderTask.SetExclusive( true );
174   renderTask.SetInputEnabled( false );
175   renderTask.SetClearEnabled( true );
176   renderTask.SetCameraActor( cameraActor );
177   renderTask.SetTargetFrameBuffer( offscreenTarget );
178   renderTask.SetClearColor( Color::TRANSPARENT );
179   renderTask.SetCullMode( false );
180 }
181
182 /**
183  * @brief Create quad geometry for the mesh
184  *
185  * @param[out] geometry quad geometry that can be used for a mesh
186  */
187 void CreateGeometry( Geometry& geometry )
188 {
189   struct QuadVertex { Vector2 position;  };
190
191   QuadVertex quadVertexData[4] =
192   {
193       { Vector2( 0.0f, 0.0f) },
194       { Vector2( 1.0f, 0.0f) },
195       { Vector2( 0.0f, 1.0f) },
196       { Vector2( 1.0f, 1.0f) },
197   };
198
199   const unsigned short indices[6] =
200   {
201      3,1,0,0,2,3
202   };
203
204   Property::Map quadVertexFormat;
205   quadVertexFormat["aPosition"] = Property::VECTOR2;
206   PropertyBuffer quadVertices = PropertyBuffer::New( quadVertexFormat );
207   quadVertices.SetData(quadVertexData, 4 );
208
209   geometry = Geometry::New();
210   geometry.AddVertexBuffer( quadVertices );
211   geometry.SetIndexBuffer( indices, sizeof(indices)/sizeof(indices[0]) );
212 }
213
214
215 /**
216  * @brief Create a renderer
217  *
218  * @param[in] frameBufferImage texture to be used
219  * @param[out] renderer mesh renderer using the supplied texture
220  */
221 void CreateRenderer( FrameBufferImage frameBufferImage, Dali::Renderer& renderer )
222 {
223   Shader shader = Shader::New( VERTEX_SHADER_SCROLL , FRAGMENT_SHADER, Shader::Hint::NONE );
224
225   Sampler sampler = Sampler::New();
226   sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR );
227
228   TextureSet textureSet = TextureSet::New();
229   TextureSetImage( textureSet, 0u, frameBufferImage );
230   textureSet.SetSampler( 0u, sampler );
231
232   Geometry meshGeometry;
233   CreateGeometry( meshGeometry );
234
235   renderer = Renderer::New( meshGeometry, shader );
236   renderer.SetProperty( Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, true );
237   renderer.SetTextures( textureSet );
238 }
239
240 } // namespace
241
242 namespace Text
243 {
244
245 TextScrollerPtr TextScroller::New( ScrollerInterface& scrollerInterface )
246 {
247   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::New\n" );
248
249   TextScrollerPtr textScroller( new TextScroller( scrollerInterface) );
250   return textScroller;
251 }
252
253 void TextScroller::SetGap( int gap )
254 {
255   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetGap gap[%d]\n", gap );
256   mWrapGap = static_cast<float>(gap);
257 }
258
259 int TextScroller::GetGap() const
260 {
261   return static_cast<int>(mWrapGap);
262 }
263
264 void TextScroller::SetSpeed( int scrollSpeed )
265 {
266   mScrollSpeed = std::max( MINIMUM_SCROLL_SPEED, scrollSpeed );
267 }
268
269 int TextScroller::GetSpeed() const
270 {
271   return mScrollSpeed;
272 }
273
274 void TextScroller::SetLoopCount( int loopCount )
275 {
276   if ( loopCount >= 0 )
277   {
278     mLoopCount = loopCount;
279   }
280
281   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetLoopCount [%d] Status[%s]\n", mLoopCount, (loopCount)?"looping":"stop" );
282 }
283
284 int TextScroller::GetLoopCount() const
285 {
286   return mLoopCount;
287 }
288
289 void TextScroller::SetLoopDelay( float delay )
290 {
291   mLoopDelay = delay;
292 }
293
294 float TextScroller::GetLoopDelay() const
295 {
296   return mLoopDelay;
297 }
298
299 void TextScroller::SetStopMode( DevelTextLabel::AutoScrollStopMode::Type stopMode )
300 {
301   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetAutoScrollStopMode [%s]\n",(stopMode == DevelTextLabel::AutoScrollStopMode::IMMEDIATE)?"IMMEDIATE":"FINISH_LOOP" );
302   mStopMode = stopMode;
303 }
304
305 void TextScroller::StopScrolling()
306 {
307   if ( mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING )
308   {
309     switch( mStopMode )
310     {
311       case DevelTextLabel::AutoScrollStopMode::IMMEDIATE:
312       {
313         mScrollAnimation.Stop();
314         CleanUp();
315         mScrollerInterface.ScrollingFinished();
316         break;
317       }
318       case DevelTextLabel::AutoScrollStopMode::FINISH_LOOP:
319       {
320         mScrollAnimation.SetLoopCount( 1 ); // As animation already playing this allows the current animation to finish instead of trying to stop mid-way
321         break;
322       }
323       default:
324       {
325         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Undifined AutoScrollStopMode\n" );
326       }
327     }
328   }
329 }
330
331 DevelTextLabel::AutoScrollStopMode::Type TextScroller::GetStopMode() const
332 {
333   return mStopMode;
334 }
335
336 Actor TextScroller::GetSourceCamera() const
337 {
338   return mOffscreenCameraActor;
339 }
340
341 Actor TextScroller::GetScrollingText() const
342 {
343   return mScrollingTextActor;
344 }
345
346 TextScroller::TextScroller( ScrollerInterface& scrollerInterface ) : mScrollerInterface( scrollerInterface ),
347                             mScrollDeltaIndex( Property::INVALID_INDEX ),
348                             mScrollSpeed( MINIMUM_SCROLL_SPEED ),
349                             mLoopCount( 1 ),
350                             mLoopDelay( 0.0f ),
351                             mWrapGap( 0.0f ),
352                             mStopMode( DevelTextLabel::AutoScrollStopMode::FINISH_LOOP )
353 {
354   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller Default Constructor\n" );
355 }
356
357 TextScroller::~TextScroller()
358 {
359   CleanUp();
360 }
361
362 void TextScroller::SetParameters( Actor sourceActor, const Size& controlSize, const Size& offScreenSize, CharacterDirection direction, float alignmentOffset, Layout::HorizontalAlignment horizontalAlignment )
363 {
364   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters controlSize[%f,%f] offscreenSize[%f,%f] direction[%d] alignmentOffset[%f]\n",
365                  controlSize.x, controlSize.y, offScreenSize.x, offScreenSize.y, direction, alignmentOffset );
366
367   CleanUp(); //  If already scrolling then restart with new parameters
368
369   float animationProgress = 0.0f;
370   int   remainedLoop = mLoopCount;
371   if ( mScrollAnimation )
372   {
373     if( mScrollAnimation.GetState() == Animation::PLAYING )
374     {
375       animationProgress = mScrollAnimation.GetCurrentProgress();
376
377       if( mLoopCount > 0 ) // If not a ininity loop, then calculate remained loop
378       {
379         remainedLoop = mLoopCount - ( mScrollAnimation.GetCurrentLoop() );
380         remainedLoop = ( remainedLoop <= 0 ? 1 : remainedLoop );
381       }
382     }
383     mScrollAnimation.Clear();
384   }
385
386   FrameBufferImage offscreenRenderTargetForText = FrameBufferImage::New( offScreenSize.width, offScreenSize.height, Pixel::RGBA8888 );
387   Renderer renderer;
388
389   CreateCameraActor( offScreenSize, mOffscreenCameraActor );
390   CreateRenderer( offscreenRenderTargetForText, renderer );
391   CreateRenderTask( sourceActor, mOffscreenCameraActor, offscreenRenderTargetForText, mRenderTask );
392
393   float xPosition = 0.0f;
394   switch( horizontalAlignment )
395   {
396     case Layout::HORIZONTAL_ALIGN_BEGIN:
397     {
398       // Reposition camera to match alignment of target, RTL text has direction=true
399       if ( direction )
400       {
401         xPosition = alignmentOffset + offScreenSize.width * 0.5f;
402       }
403       else
404       {
405         xPosition = offScreenSize.width * 0.5f;
406       }
407       break;
408     }
409
410     case Layout::HORIZONTAL_ALIGN_CENTER:
411     {
412       xPosition = controlSize.width * 0.5f;
413       break;
414     }
415
416     case Layout::HORIZONTAL_ALIGN_END:
417     {
418       // Reposition camera to match alignment of target, RTL text has direction=true
419       if ( direction )
420       {
421         xPosition = offScreenSize.width * 0.5f;
422       }
423       else
424       {
425         xPosition = alignmentOffset + offScreenSize.width * 0.5f;
426       }
427       break;
428     }
429   }
430
431   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters xPosition[%f]\n", xPosition );
432
433   mOffscreenCameraActor.SetX( xPosition );
434   mOffscreenCameraActor.SetY( offScreenSize.height * 0.5f );
435
436   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters mWrapGap[%f]\n", mWrapGap );
437
438   const float align = ALIGNMENT_TABLE[ horizontalAlignment ][ direction ][ offScreenSize.width > controlSize.width ];
439   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters align[%f]\n", align );
440
441   mScrollingTextActor = Actor::New();
442   mScrollingTextActor.AddRenderer( renderer );
443   mScrollingTextActor.RegisterProperty( "uTextureSize", offScreenSize );
444   mScrollingTextActor.RegisterProperty( "uAlign", align );
445   mScrollingTextActor.RegisterProperty( "uGap", mWrapGap );
446   mScrollingTextActor.SetSize( controlSize.width, std::min( offScreenSize.height, controlSize.height ) );
447   mScrollDeltaIndex = mScrollingTextActor.RegisterProperty( "uDelta", 0.0f );
448
449   float scrollAmount = std::max( offScreenSize.width + mWrapGap, controlSize.width );
450   float scrollDuration =  scrollAmount / mScrollSpeed;
451
452   if ( direction  )
453   {
454      scrollAmount = -scrollAmount; // reverse direction of scrollung
455   }
456
457   StartScrolling( scrollAmount, scrollDuration, remainedLoop );
458   mScrollAnimation.SetCurrentProgress(animationProgress);
459 }
460
461 void TextScroller::AutoScrollAnimationFinished( Dali::Animation& animation )
462 {
463   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::AutoScrollAnimationFinished\n" );
464   CleanUp();
465   mScrollerInterface.ScrollingFinished();
466 }
467
468 void TextScroller::StartScrolling( float scrollAmount, float scrollDuration, int loopCount )
469 {
470   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::StartScrolling scrollAmount[%f] scrollDuration[%f], loop[%d] speed[%d]\n", scrollAmount, scrollDuration, loopCount, mScrollSpeed );
471
472   mScrollAnimation = Animation::New( scrollDuration );
473   mScrollAnimation.AnimateTo( Property( mScrollingTextActor, mScrollDeltaIndex ), scrollAmount, TimePeriod( mLoopDelay, scrollDuration ) );
474   mScrollAnimation.SetEndAction( Animation::Discard );
475   mScrollAnimation.SetLoopCount( loopCount );
476   mScrollAnimation.FinishedSignal().Connect( this, &TextScroller::AutoScrollAnimationFinished );
477   mScrollAnimation.Play();
478 }
479
480 void TextScroller::CleanUp()
481 {
482   if ( Stage::IsInstalled() )
483   {
484     Stage stage = Stage::GetCurrent();
485     RenderTaskList taskList = stage.GetRenderTaskList();
486     UnparentAndReset( mScrollingTextActor );
487     UnparentAndReset( mOffscreenCameraActor );
488     taskList.RemoveTask( mRenderTask );
489   }
490 }
491
492 } // namespace Text
493
494 } // namespace Toolkit
495
496 } // namespace Dali