[Tizen](ATSPI) squashed implementation
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / page-turn-view / page-turn-view-impl.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/controls/page-turn-view/page-turn-view-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <cstring> // for strcmp
23 #include <dali/public-api/animation/animation.h>
24 #include <dali/public-api/animation/constraint.h>
25 #include <dali/public-api/object/type-registry.h>
26 #include <dali/public-api/object/type-registry-helper.h>
27 #include <dali/integration-api/debug.h>
28
29 // INTERNAL INCLUDES
30 #include <dali-toolkit/public-api/visuals/visual-properties.h>
31 #include <dali-toolkit/internal/controls/page-turn-view/page-turn-effect.h>
32 #include <dali-toolkit/internal/controls/page-turn-view/page-turn-book-spine-effect.h>
33 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
34 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
35 #include <dali-toolkit/internal/controls/control/control-data-impl.h>
36
37 using namespace Dali;
38
39 namespace //Unnamed namespace
40 {
41 // properties set on shader, these properties have the constant value in regardless of the page status
42 const char * const PROPERTY_SPINE_SHADOW ( "uSpineShadowParameter" ); // uniform for both spine and turn effect
43
44 // properties set on actor, the value of these properties varies depending on the page status
45 //    properties used in turn effect
46 const char * const PROPERTY_TURN_DIRECTION( "uIsTurningBack" ); // uniform
47 const char * const PROPERTY_COMMON_PARAMETERS( "uCommonParameters" ); //uniform
48
49 const char * const PROPERTY_PAN_DISPLACEMENT( "panDisplacement" );// property used to constrain the uniforms
50 const char * const PROPERTY_PAN_CENTER( "panCenter" );// property used to constrain the uniforms
51
52 // default grid density for page turn effect, 20 pixels by 20 pixels
53 const float DEFAULT_GRID_DENSITY(20.0f);
54
55 // to bent the page, the minimal horizontal pan start position is viewPageSize.x * MINIMUM_START_POSITION_RATIO
56 const float MINIMUM_START_POSITION_RATIO(0.6f);
57
58 // the maximum vertical displacement of pan gesture, if exceed, will reduce it: viewPageSize.y * MAXIMUM_VERTICAL_MOVEMENT_RATIO
59 const float MAXIMUM_VERTICAL_MOVEMENT_RATIO(0.15f);
60
61 // when the x component of pan position reaches viewPageSize.x * PAGE_TURN_OVER_THRESHOLD_RATIO, page starts to turn over
62 const float PAGE_TURN_OVER_THRESHOLD_RATIO(0.5f);
63
64 // duration of animation, shorter for faster speed
65 const float PAGE_SLIDE_BACK_ANIMATION_DURATION(1.0f);
66 const float PAGE_TURN_OVER_ANIMATION_DURATION(1.2f);
67
68 // the major&minor radius (in pixels) to form an ellipse shape
69 // the top-left quarter of this ellipse is used to calculate spine normal for simulating shadow
70 const Vector2 DEFAULT_SPINE_SHADOW_PARAMETER(50.0f, 20.0f);
71
72 // constants for shadow casting
73 const float POINT_LIGHT_HEIGHT_RATIO(2.f);
74 const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.5f);
75
76 // constraints ////////////////////////////////////////////////////////////////
77 /**
78  * Original Center Constraint
79  *
80  * This constraint adjusts the original center property of the page turn shader effect
81  * based on the X-direction displacement of the pan gesture
82  */
83 struct OriginalCenterConstraint
84 {
85   OriginalCenterConstraint(const Vector2& originalCenter, const Vector2& offset)
86   : mOldCenter( originalCenter )
87   {
88     mNewCenter = originalCenter + offset;
89     mDistance = offset.Length() * 0.5f;
90     mDirection = offset  / mDistance;
91   }
92
93   void operator()( Vector2& current, const PropertyInputContainer& inputs )
94   {
95     float displacement = inputs[0]->GetFloat();
96
97     if( displacement < mDistance )
98     {
99       current = mOldCenter + mDirection * displacement;
100     }
101     else
102     {
103       current = mNewCenter + Vector2(0.25f*(displacement-mDistance), 0.f);
104     }
105   }
106
107   Vector2 mOldCenter;
108   Vector2 mNewCenter;
109   float mDistance;
110   Vector2 mDirection;
111 };
112
113 /**
114  * Rotation Constraint
115  *
116  * This constraint adjusts the rotation property of the page actor
117  * based on the X-direction displacement of the pan gesture
118  */
119 struct RotationConstraint
120 {
121   RotationConstraint( float distance, float pageWidth, bool isTurnBack )
122   : mDistance( distance*0.5f )
123   {
124     mStep = 1.f / pageWidth;
125     mSign = isTurnBack ? -1.0f : 1.0f;
126     mConst = isTurnBack ? -1.0f : 0.f;
127     mRotation = isTurnBack ? Quaternion( Radian( -Math::PI ), Vector3::YAXIS ) : Quaternion( Radian(0.f), Vector3::YAXIS );
128   }
129
130   void operator()( Quaternion& current, const PropertyInputContainer& inputs )
131   {
132     float displacement = inputs[0]->GetFloat();
133     if( displacement < mDistance)
134     {
135       current = mRotation;
136     }
137     else
138     {
139       float coef = std::max(-1.0f, mStep*(mDistance-displacement));
140       float angle = Math::PI * ( mConst + mSign * coef );
141       current = Quaternion( Radian( angle ), Vector3::YAXIS );
142     }
143   }
144
145   float mDistance;
146   float mStep;
147   float mConst;
148   float mSign;
149   Quaternion mRotation;
150 };
151
152 /**
153  * Current Center Constraint
154  *
155  * This constraint adjusts the current center property of the page turn shader effect
156  * based on the pan position and the original center position
157  */
158 struct CurrentCenterConstraint
159 {
160   CurrentCenterConstraint( float pageWidth )
161   : mPageWidth( pageWidth )
162   {
163     mThres = pageWidth * PAGE_TURN_OVER_THRESHOLD_RATIO * 0.5f;
164   }
165
166   void operator()( Vector2& current, const PropertyInputContainer& inputs )
167   {
168     const Vector2& centerPosition = inputs[0]->GetVector2();
169     if( centerPosition.x > 0.f )
170     {
171       current.x = mThres+centerPosition.x * 0.5f;
172       current.y = centerPosition.y;
173     }
174     else
175     {
176       const Vector2& centerOrigin = inputs[1]->GetVector2();
177       Vector2 direction = centerOrigin - Vector2(mThres, centerPosition.y);
178       float coef = 1.f+(centerPosition.x*2.f / mPageWidth);
179       // when coef <= 0, the page is flat, slow down the last moment of the page stretch by 10 times to avoid a small bounce
180       if(coef < 0.025f)
181       {
182         coef = (coef+0.225f)/10.0f;
183       }
184       current = centerOrigin - direction * coef;
185     }
186   }
187
188   float mPageWidth;
189   float mThres;
190 };
191
192 struct ShadowBlurStrengthConstraint
193 {
194   ShadowBlurStrengthConstraint( float thres )
195   : mThres( thres )
196   {}
197
198   void operator()( float& blurStrength,  const PropertyInputContainer& inputs )
199   {
200     float displacement = inputs[2]->GetFloat();
201     if( EqualsZero(displacement))
202     {
203       const Vector2& cur = inputs[0]->GetVector2();
204       const Vector2& ori = inputs[1]->GetVector2();
205       blurStrength =  5.f*(ori-cur).Length() / mThres;
206     }
207     else
208     {
209       blurStrength =  1.f - (displacement-2.f*mThres)/mThres;
210     }
211
212     blurStrength = blurStrength > 1.f ? 1.f : ( blurStrength < 0.f ? 0.f : blurStrength );
213   }
214
215   float mThres;
216 };
217
218 } //unnamed namespace
219
220 namespace Dali
221 {
222
223 namespace Toolkit
224 {
225
226 namespace Internal
227 {
228
229 namespace
230 {
231
232 BaseHandle Create()
233 {
234   // empty handle as we cannot create PageTurnView(but type registered for page turn signal)
235   return BaseHandle();
236 }
237
238 // Setup properties, signals and actions using the type-registry.
239 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnView, Toolkit::Control, Create );
240
241 DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "viewPageSize",        VECTOR2, VIEW_PAGE_SIZE )
242 DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "currentPageId",   INTEGER, CURRENT_PAGE_ID )
243 DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "spineShadow",     VECTOR2, SPINE_SHADOW )
244
245 DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnStarted",    SIGNAL_PAGE_TURN_STARTED )
246 DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnFinished",   SIGNAL_PAGE_TURN_FINISHED )
247 DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanStarted",     SIGNAL_PAGE_PAN_STARTED )
248 DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanFinished",    SIGNAL_PAGE_PAN_FINISHED )
249
250 DALI_TYPE_REGISTRATION_END()
251
252 }
253
254 // these several constants are also used in the derived classes
255 const char * const PageTurnView::PROPERTY_TEXTURE_WIDTH( "uTextureWidth" ); // uniform name
256 const char * const PageTurnView::PROPERTY_ORIGINAL_CENTER( "originalCenter" ); // property used to constrain the uniform
257 const char * const PageTurnView::PROPERTY_CURRENT_CENTER( "currentCenter" );// property used to constrain the uniform
258 const int PageTurnView::MAXIMUM_TURNING_NUM = 4;
259 const int PageTurnView::NUMBER_OF_CACHED_PAGES_EACH_SIDE = MAXIMUM_TURNING_NUM + 1;
260 const int PageTurnView::NUMBER_OF_CACHED_PAGES = NUMBER_OF_CACHED_PAGES_EACH_SIDE*2;
261 const float PageTurnView::STATIC_PAGE_INTERVAL_DISTANCE = 1.0f;
262
263 PageTurnView::Page::Page()
264 : isTurnBack( false )
265 {
266   actor = Actor::New();
267   actor.SetAnchorPoint( AnchorPoint::CENTER_LEFT );
268   actor.SetParentOrigin( ParentOrigin::CENTER_LEFT );
269   actor.SetVisible( false );
270
271   propertyPanDisplacement = actor.RegisterProperty( PROPERTY_PAN_DISPLACEMENT, 0.f );
272   propertyPanCenter = actor.RegisterProperty(PROPERTY_PAN_CENTER, Vector2::ZERO);
273
274   propertyOriginalCenter = actor.RegisterProperty(PROPERTY_ORIGINAL_CENTER, Vector2::ZERO);
275   propertyCurrentCenter = actor.RegisterProperty(PROPERTY_CURRENT_CENTER, Vector2::ZERO);
276   Matrix zeroMatrix(true);
277   actor.RegisterProperty(PROPERTY_COMMON_PARAMETERS, zeroMatrix);
278   propertyTurnDirection = actor.RegisterProperty(PROPERTY_TURN_DIRECTION, -1.f);
279 }
280
281 void PageTurnView::Page::SetTexture( Texture texture )
282 {
283   if( !textureSet )
284   {
285     textureSet = TextureSet::New();
286   }
287   textureSet.SetTexture( 0u, texture );
288 }
289
290 void PageTurnView::Page::UseEffect(Shader newShader)
291 {
292   shader = newShader;
293   if( renderer )
294   {
295     renderer.SetShader( shader );
296   }
297 }
298
299 void PageTurnView::Page::UseEffect(Shader newShader, Geometry geometry)
300 {
301   UseEffect( newShader );
302
303   if( !renderer )
304   {
305     renderer = Renderer::New( geometry, shader );
306
307     if( !textureSet )
308     {
309       textureSet = TextureSet::New();
310     }
311
312     renderer.SetTextures( textureSet );
313     renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
314     actor.AddRenderer( renderer );
315   }
316 }
317
318 void PageTurnView::Page::ChangeTurnDirection()
319 {
320   isTurnBack = !isTurnBack;
321   actor.SetProperty( propertyTurnDirection, isTurnBack ? 1.f : -1.f );
322 }
323
324 void PageTurnView::Page::SetPanDisplacement(float value)
325 {
326  actor.SetProperty( propertyPanDisplacement, value );
327 }
328
329 void PageTurnView::Page::SetPanCenter( const Vector2& value )
330 {
331   actor.SetProperty( propertyPanCenter, value );
332 }
333
334 void PageTurnView::Page::SetOriginalCenter( const Vector2& value )
335 {
336   actor.SetProperty( propertyOriginalCenter, value );
337 }
338
339 void PageTurnView::Page::SetCurrentCenter( const Vector2& value )
340 {
341   actor.SetProperty( propertyCurrentCenter, value );
342 }
343
344 PageTurnView::PageTurnView( PageFactory& pageFactory, const Vector2& viewPageSize )
345 : Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
346   mPageFactory( &pageFactory ),
347   mPageSize( viewPageSize ),
348   mSpineShadowParameter( DEFAULT_SPINE_SHADOW_PARAMETER ),
349   mDistanceUpCorner( 0.f ),
350   mDistanceBottomCorner( 0.f ),
351   mPanDisplacement( 0.f ),
352   mTotalPageCount( 0 ),
353   mCurrentPageIndex( 0 ),
354   mTurningPageIndex( 0 ),
355   mIndex( 0 ),
356   mSlidingCount( 0 ),
357   mAnimatingCount( 0 ),
358   mConstraints( false ),
359   mPress( false ),
360   mPageUpdated( true ),
361   mPageTurnStartedSignal(),
362   mPageTurnFinishedSignal(),
363   mPagePanStartedSignal(),
364   mPagePanFinishedSignal()
365 {
366   DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
367     return std::unique_ptr< Dali::Accessibility::Accessible >(
368       new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::PAGE_TAB_LIST ) );
369   } );
370 }
371
372 PageTurnView::~PageTurnView()
373 {
374 }
375
376 void PageTurnView::OnInitialize()
377 {
378    // create the book spine effect for static pages
379   Property::Map spineEffectMap = CreatePageTurnBookSpineEffect();
380   mSpineEffectShader = CreateShader( spineEffectMap );
381   mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
382   // create the turn effect for turning pages
383   Property::Map turnEffectMap = CreatePageTurnEffect();
384   mTurnEffectShader = CreateShader( turnEffectMap );
385   mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
386
387   // create the grid geometry for pages
388   uint16_t width = static_cast<uint16_t>(mPageSize.width / DEFAULT_GRID_DENSITY + 0.5f);
389   uint16_t height = static_cast<uint16_t>(mPageSize.height / DEFAULT_GRID_DENSITY + 0.5f);
390   mGeometry = VisualFactoryCache::CreateGridGeometry( Uint16Pair( width, height ) );
391
392   mPages.reserve( NUMBER_OF_CACHED_PAGES );
393   for( int i = 0; i < NUMBER_OF_CACHED_PAGES; i++ )
394   {
395     mPages.push_back( Page() );
396     mPages[i].actor.SetSize( mPageSize );
397     Self().Add( mPages[i].actor );
398   }
399
400   // create the layer for turning pages
401   mTurningPageLayer = Layer::New();
402   mTurningPageLayer.SetAnchorPoint( AnchorPoint::CENTER_LEFT );
403   mTurningPageLayer.SetBehavior(Layer::LAYER_3D);
404   mTurningPageLayer.Raise();
405
406   // Set control size and the parent origin of page layers
407   OnPageTurnViewInitialize();
408
409   Self().Add(mTurningPageLayer);
410
411   mTotalPageCount = static_cast<int>( mPageFactory->GetNumberOfPages() );
412   // add pages to the scene, and set depth for the stacked pages
413   for( int i = 0; i < NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ )
414   {
415     AddPage( i );
416     mPages[i].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
417   }
418   mPages[0].actor.SetVisible(true);
419
420   // enable the pan gesture which is attached to the control
421   EnableGestureDetection(Gesture::Type(Gesture::Pan));
422 }
423
424 Shader PageTurnView::CreateShader( const Property::Map& shaderMap )
425 {
426   Shader shader;
427   Property::Value* shaderValue = shaderMap.Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER );
428   Property::Map shaderSource;
429   if( shaderValue && shaderValue->Get( shaderSource ) )
430   {
431     std::string vertexShader;
432     Property::Value* vertexShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER );
433     if( !vertexShaderValue || !vertexShaderValue->Get( vertexShader ) )
434     {
435       DALI_LOG_ERROR("PageTurnView::CreateShader failed: vertex shader source is not available.\n");
436     }
437     std::string fragmentShader;
438     Property::Value* fragmentShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER );
439     if( !fragmentShaderValue || !fragmentShaderValue->Get( fragmentShader ) )
440     {
441       DALI_LOG_ERROR("PageTurnView::CreateShader failed: fragment shader source is not available.\n");
442     }
443     shader = Shader::New( vertexShader, fragmentShader );
444   }
445   else
446   {
447     DALI_LOG_ERROR("PageTurnView::CreateShader failed: shader source is not available.\n");
448   }
449
450   return shader;
451 }
452
453 void PageTurnView::SetupShadowView()
454 {
455   mShadowView = Toolkit::ShadowView::New( 0.25f, 0.25f );
456   Vector3 origin = mTurningPageLayer.GetCurrentParentOrigin();
457   mShadowView.SetParentOrigin( origin );
458   mShadowView.SetAnchorPoint( origin );
459   mShadowView.SetPointLightFieldOfView( Math::PI / 2.0f);
460   mShadowView.SetShadowColor(DEFAULT_SHADOW_COLOR);
461
462   mShadowPlaneBackground = Actor::New();
463   mShadowPlaneBackground.SetParentOrigin( ParentOrigin::CENTER );
464   mShadowPlaneBackground.SetSize( mControlSize );
465   Self().Add( mShadowPlaneBackground );
466   mShadowView.SetShadowPlaneBackground( mShadowPlaneBackground );
467
468   mPointLight = Actor::New();
469   mPointLight.SetAnchorPoint( origin );
470   mPointLight.SetParentOrigin( origin );
471   mPointLight.SetPosition( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO );
472   Self().Add( mPointLight );
473   mShadowView.SetPointLight( mPointLight );
474
475   mTurningPageLayer.Add( mShadowView );
476   mShadowView.Activate();
477 }
478
479 void PageTurnView::OnStageConnection( int depth )
480 {
481   SetupShadowView();
482
483   Control::OnStageConnection( depth );
484 }
485
486 void PageTurnView::OnStageDisconnection()
487 {
488   if(mShadowView)
489   {
490     mShadowView.RemoveConstraints();
491     mPointLight.Unparent();
492     mShadowPlaneBackground.Unparent();
493     mShadowView.Unparent();
494   }
495
496   // make sure the status of the control is updated correctly when the pan gesture is interrupted
497   StopTurning();
498
499   Control::OnStageDisconnection();
500 }
501
502 void PageTurnView::SetPageSize( const Vector2& viewPageSize )
503 {
504   mPageSize = viewPageSize;
505
506   if( mPointLight )
507   {
508     mPointLight.SetPosition( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO );
509   }
510
511   for( size_t i=0; i<mPages.size(); i++ )
512   {
513     mPages[i].actor.SetSize( mPageSize );
514   }
515
516   OnPageTurnViewInitialize();
517
518   if( mShadowPlaneBackground )
519   {
520     mShadowPlaneBackground.SetSize( mControlSize );
521   }
522 }
523
524 Vector2 PageTurnView::GetPageSize()
525 {
526   return mPageSize;
527 }
528
529 void PageTurnView::SetSpineShadowParameter( const Vector2& spineShadowParameter )
530 {
531   mSpineShadowParameter = spineShadowParameter;
532
533   // set spine shadow parameter to all the shader effects
534   mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
535   mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
536 }
537
538 Vector2 PageTurnView::GetSpineShadowParameter()
539 {
540   return mSpineShadowParameter;
541 }
542
543 void PageTurnView::GoToPage( unsigned int pageId )
544 {
545   int pageIdx = Clamp( static_cast<int>(pageId), 0, mTotalPageCount-1);
546
547   if( mCurrentPageIndex == pageIdx  )
548   {
549     return;
550   }
551
552   // if any animation ongoing, stop it.
553   StopTurning();
554
555   // record the new current page index
556   mCurrentPageIndex = pageIdx;
557
558
559   // add the current page and the pages right before and after it
560   for( int i = pageIdx - NUMBER_OF_CACHED_PAGES_EACH_SIDE; i < pageIdx + NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ )
561   {
562     AddPage( i );
563   }
564
565   mPages[pageId%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
566   if( pageId > 0 )
567   {
568     mPages[(pageId-1)%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
569   }
570   // set ordered depth to the stacked pages
571   OrganizePageDepth();
572 }
573
574 unsigned int PageTurnView::GetCurrentPage()
575 {
576   DALI_ASSERT_ALWAYS( mCurrentPageIndex >= 0 );
577   return static_cast< unsigned int >( mCurrentPageIndex );
578 }
579
580 void PageTurnView::AddPage( int pageIndex )
581 {
582   if(pageIndex > -1  && pageIndex < mTotalPageCount) // whether the page is available from the page factory
583   {
584     int index = pageIndex % NUMBER_OF_CACHED_PAGES;
585
586     Texture newPage;
587     newPage = mPageFactory->NewPage( pageIndex );
588     DALI_ASSERT_ALWAYS( newPage && "must pass in valid texture" );
589
590     bool isLeftSide = ( pageIndex < mCurrentPageIndex );
591     if( mPages[index].isTurnBack != isLeftSide )
592     {
593       mPages[index].ChangeTurnDirection();
594     }
595
596     float degree = isLeftSide ? 180.f :0.f;
597     mPages[index].actor.SetOrientation( Degree( degree ), Vector3::YAXIS );
598     mPages[index].actor.SetVisible( false );
599     mPages[index].UseEffect( mSpineEffectShader, mGeometry );
600     mPages[index].SetTexture( newPage );
601
602     // For Portrait, nothing to do
603     // For Landscape, set the parent origin to CENTER
604     OnAddPage( mPages[index].actor, isLeftSide );
605   }
606 }
607
608 void PageTurnView::RemovePage( int pageIndex )
609 {
610   if( pageIndex > -1 && pageIndex < mTotalPageCount)
611   {
612     int index = pageIndex % NUMBER_OF_CACHED_PAGES;
613     mPages[index].actor.SetVisible(false);
614   }
615 }
616
617 void PageTurnView::OnPan( const PanGesture& gesture )
618 {
619   // the pan gesture is attached to control itself instead of each page
620   switch( gesture.state )
621   {
622     case Gesture::Started:
623     {
624       // check whether the undergoing turning page number already reaches the maximum allowed
625       if( mPageUpdated && mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1 )
626       {
627         SetPanActor( gesture.position ); // determine which page actor is panned
628         if( mTurningPageIndex != -1 && mPages[mTurningPageIndex % NUMBER_OF_CACHED_PAGES].actor.GetParent() != Self()) // if the page is added to turning layer,it is undergoing an animation currently
629         {
630           mTurningPageIndex = -1;
631         }
632         PanStarted( SetPanPosition( gesture.position ) );  // pass in the pan position in the local page coordinate
633       }
634       else
635       {
636         mTurningPageIndex = -1;
637       }
638       break;
639     }
640     case Gesture::Continuing:
641     {
642       PanContinuing( SetPanPosition( gesture.position ) ); // pass in the pan position in the local page coordinate
643       break;
644     }
645     case Gesture::Finished:
646     case Gesture::Cancelled:
647     {
648       PanFinished( SetPanPosition( gesture.position ), gesture.GetSpeed() );
649       break;
650     }
651     case Gesture::Clear:
652     case Gesture::Possible:
653     default:
654     {
655       break;
656     }
657   }
658 }
659
660 void PageTurnView::PanStarted( const Vector2& gesturePosition )
661 {
662   mPressDownPosition = gesturePosition;
663
664   if( mTurningPageIndex == -1 )
665   {
666     return;
667   }
668
669   mIndex = mTurningPageIndex % NUMBER_OF_CACHED_PAGES;
670
671   mOriginalCenter = gesturePosition;
672   mPress = false;
673   mPageUpdated = false;
674
675   // Guard against destruction during signal emission
676   Toolkit::PageTurnView handle( GetOwner() );
677   mPagePanStartedSignal.Emit( handle );
678 }
679
680 void PageTurnView::PanContinuing( const Vector2& gesturePosition )
681 {
682   if( mTurningPageIndex == -1  )
683   {
684     return;
685   }
686
687   // Guard against destruction during signal emission
688   Toolkit::PageTurnView handle( GetOwner() );
689
690   if(!mPress)
691   {
692     // when the touch down position is near the spine
693     // or when the panning goes outwards or some other position which would tear the paper in real situation
694     // we change the start position into the current panning position and update the shader parameters
695     if( mOriginalCenter.x <  mPageSize.width*MINIMUM_START_POSITION_RATIO
696         || gesturePosition.x > mOriginalCenter.x-1.0f
697         || ( ( gesturePosition.x/mOriginalCenter.x > gesturePosition.y/mOriginalCenter.y ) &&
698              ( gesturePosition.x/mOriginalCenter.x > (gesturePosition.y-mPageSize.height )/(mOriginalCenter.y-mPageSize.height ) ) ) )
699     {
700       mOriginalCenter = gesturePosition;
701     }
702     else
703     {
704       mDistanceUpCorner = mOriginalCenter.Length();
705       mDistanceBottomCorner = ( mOriginalCenter - Vector2( 0.0f, mPageSize.height ) ).Length();
706       mShadowView.Add( mPages[mIndex].actor );
707       mPages[mIndex].UseEffect( mTurnEffectShader );
708       mPages[mIndex].SetOriginalCenter( mOriginalCenter );
709       mCurrentCenter = mOriginalCenter;
710       mPages[mIndex].SetCurrentCenter( mCurrentCenter );
711       mPanDisplacement = 0.f;
712       mConstraints = false;
713       mPress = true;
714       mAnimatingCount++;
715
716       mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), !mPages[mIndex].isTurnBack );
717       int id = mTurningPageIndex + (mPages[mIndex].isTurnBack ? -1 : 1);
718       if( id >=0 && id < mTotalPageCount )
719       {
720         mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
721       }
722
723       mShadowView.RemoveConstraints();
724       Actor self = Self();
725       mPages[mIndex].SetPanDisplacement( 0.f );
726
727       Constraint shadowBlurStrengthConstraint = Constraint::New<float>( mShadowView, mShadowView.GetBlurStrengthPropertyIndex(), ShadowBlurStrengthConstraint( mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO ) );
728       shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor,  mPages[mIndex].propertyCurrentCenter) );
729       shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor,  mPages[mIndex].propertyOriginalCenter) );
730       shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor,  mPages[mIndex].propertyPanDisplacement) );
731       shadowBlurStrengthConstraint.Apply();
732     }
733   }
734   else
735   {
736     Vector2 currentCenter = gesturePosition;
737
738     // Test whether the new current center would tear the paper from the top pine in real situation
739     // we do not forbid this totally, which would restrict the panning gesture too much
740     // instead, set it to the nearest allowable position
741     float distanceUpCorner = currentCenter.Length();
742     float distanceBottomCorner = ( currentCenter-Vector2( 0.0f, mPageSize.height ) ).Length();
743     if( distanceUpCorner > mDistanceUpCorner )
744     {
745       currentCenter = currentCenter*mDistanceUpCorner/distanceUpCorner;
746     }
747     // would tear the paper from the bottom spine in real situation
748     if( distanceBottomCorner > mDistanceBottomCorner )
749     {
750       currentCenter = ( ( currentCenter - Vector2( 0.0f, mPageSize.height ) )*mDistanceBottomCorner/distanceBottomCorner + Vector2(0.0f,mPageSize.height ) );
751     }
752     // If direction has a very high y component, reduce it.
753     Vector2 curveDirection = currentCenter - mOriginalCenter;
754     if( fabs( curveDirection.y ) > fabs( curveDirection.x ) )
755     {
756       currentCenter.y = mOriginalCenter.y + ( currentCenter.y - mOriginalCenter.y ) * fabs( curveDirection.x/curveDirection.y );
757     }
758     // If the vertical distance is high, reduce it
759     float yShift = currentCenter.y - mOriginalCenter.y;
760     if( fabs( yShift ) > mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO )
761     {
762       currentCenter.y = mOriginalCenter.y + yShift*mPageSize.height*MAXIMUM_VERTICAL_MOVEMENT_RATIO/fabs(yShift );
763     }
764
765     // use contraints to control the page shape and rotation when the pan position is near the spine
766     if( currentCenter.x <= mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO && mOriginalCenter.x > mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO )
767     {
768       // set the property values used by the constraints
769       mPanDisplacement = mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO - currentCenter.x;
770       mPages[mIndex].SetPanDisplacement( mPanDisplacement );
771       mPages[mIndex].SetPanCenter( currentCenter );
772
773       // set up the OriginalCenterConstraint and CurrentCebterConstraint to the PageTurnEdffect
774       // also set up the RotationConstraint to the page actor
775       if( !mConstraints )
776       {
777         Vector2 corner;
778         // the corner position need to be a little far away from the page edge to ensure the whole page is lift up
779         if( currentCenter.y >= mOriginalCenter.y )
780         {
781           corner = Vector2( 1.1f*mPageSize.width, 0.f );
782         }
783         else
784         {
785           corner = mPageSize*1.1f;
786         }
787
788         Vector2 offset( currentCenter-mOriginalCenter );
789         float k = - ( (mOriginalCenter.x-corner.x)*offset.x + (mOriginalCenter.y-corner.y)*offset.y )
790                    /( offset.x*offset.x + offset.y*offset.y );
791         offset *= k;
792         Actor self = Self();
793
794         Constraint originalCenterConstraint = Constraint::New<Vector2>( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter, OriginalCenterConstraint( mOriginalCenter, offset ));
795         originalCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) );
796         originalCenterConstraint.Apply();
797
798         Constraint currentCenterConstraint = Constraint::New<Vector2>( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter, CurrentCenterConstraint(mPageSize.width));
799         currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanCenter ) );
800         currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter ) );
801         currentCenterConstraint.Apply();
802
803         PageTurnApplyInternalConstraint( mPages[mIndex].actor, mPageSize.height );
804
805         float distance = offset.Length();
806         Constraint rotationConstraint = Constraint::New<Quaternion>( mPages[mIndex].actor, Actor::Property::ORIENTATION, RotationConstraint(distance, mPageSize.width, mPages[mIndex].isTurnBack));
807         rotationConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) );
808         rotationConstraint.Apply();
809
810         mConstraints = true;
811       }
812     }
813     else
814     {
815       if(mConstraints) // remove the constraint is the pan position move back to far away from the spine
816       {
817         mPages[mIndex].actor.RemoveConstraints();
818         mPages[mIndex].SetOriginalCenter(mOriginalCenter );
819         mConstraints = false;
820         mPanDisplacement = 0.f;
821       }
822
823       mPages[mIndex].SetCurrentCenter( currentCenter );
824       mCurrentCenter = currentCenter;
825       PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height );
826     }
827   }
828 }
829
830 void PageTurnView::PanFinished( const Vector2& gesturePosition, float gestureSpeed )
831 {
832   // Guard against destruction during signal emission
833   Toolkit::PageTurnView handle( GetOwner() );
834
835   if( mTurningPageIndex == -1  )
836   {
837     if( mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1)
838     {
839       OnPossibleOutwardsFlick( gesturePosition, gestureSpeed );
840     }
841
842     return;
843   }
844
845   mPagePanFinishedSignal.Emit( handle );
846
847   if(mPress)
848   {
849     if(mConstraints) // if with constraints, the pan finished position is near spine, set up an animation to turn the page over
850     {
851       // update the pages here instead of in the TurnedOver callback function
852       // as new page is allowed to respond to the pan gesture before other pages finishing animation
853       if(mPages[mIndex].isTurnBack)
854       {
855         mCurrentPageIndex--;
856         RemovePage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE );
857         AddPage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE );
858       }
859       else
860       {
861         mCurrentPageIndex++;
862         RemovePage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 );
863         AddPage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 );
864       }
865       OrganizePageDepth();
866
867       // set up an animation to turn the page over
868       float width = mPageSize.width*(1.f+PAGE_TURN_OVER_THRESHOLD_RATIO);
869       Animation animation = Animation::New( std::max(0.1f,PAGE_TURN_OVER_ANIMATION_DURATION * (1.0f - mPanDisplacement / width)) );
870       animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement),
871                            width,AlphaFunction::EASE_OUT_SINE);
872       animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter),
873                            Vector2(-mPageSize.width*1.1f, 0.5f*mPageSize.height), AlphaFunction::EASE_OUT_SINE);
874       mAnimationPageIdPair[animation] = mTurningPageIndex;
875       animation.Play();
876       animation.FinishedSignal().Connect( this, &PageTurnView::TurnedOver );
877     }
878     else // the pan finished position is far away from the spine, set up an animation to slide the page back instead of turning over
879     {
880       Animation animation= Animation::New( PAGE_SLIDE_BACK_ANIMATION_DURATION * (mOriginalCenter.x - mCurrentCenter.x) / mPageSize.width / PAGE_TURN_OVER_THRESHOLD_RATIO );
881       animation.AnimateTo( Property( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter ),
882                            mOriginalCenter, AlphaFunction::LINEAR );
883       mAnimationPageIdPair[animation] = mTurningPageIndex;
884       animation.Play();
885       mSlidingCount++;
886       animation.FinishedSignal().Connect( this, &PageTurnView::SliddenBack );
887
888       mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), mPages[mIndex].isTurnBack );
889     }
890   }
891   else
892   {
893     // In portrait view, an outwards flick should turn the previous page back
894     // In landscape view, nothing to do
895     OnPossibleOutwardsFlick( gesturePosition, gestureSpeed );
896   }
897   mPageUpdated = true;
898 }
899
900 void PageTurnView::TurnedOver( Animation& animation )
901 {
902   int pageId = mAnimationPageIdPair[animation];
903   int index = pageId%NUMBER_OF_CACHED_PAGES;
904
905   mPages[index].ChangeTurnDirection();
906   mPages[index].actor.RemoveConstraints();
907   Self().Add(mPages[index].actor);
908   mAnimatingCount--;
909   mAnimationPageIdPair.erase( animation );
910
911   float degree = mPages[index].isTurnBack ? 180.f : 0.f;
912   mPages[index].actor.SetOrientation( Degree(degree), Vector3::YAXIS );
913   mPages[index].UseEffect( mSpineEffectShader );
914
915   int id = pageId + (mPages[index].isTurnBack ? -1 : 1);
916   if( id >=0 && id < mTotalPageCount )
917   {
918     mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(false);
919   }
920
921   OnTurnedOver( mPages[index].actor, mPages[index].isTurnBack );
922
923   // Guard against destruction during signal emission
924   Toolkit::PageTurnView handle( GetOwner() );
925   mPageTurnFinishedSignal.Emit( handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack );
926 }
927
928 void PageTurnView::SliddenBack( Animation& animation )
929 {
930   int pageId = mAnimationPageIdPair[animation];
931   int index = pageId%NUMBER_OF_CACHED_PAGES;
932   Self().Add(mPages[index].actor);
933   mSlidingCount--;
934   mAnimatingCount--;
935   mAnimationPageIdPair.erase( animation );
936
937   mPages[index].UseEffect( mSpineEffectShader );
938
939   int id = pageId + (mPages[index].isTurnBack ? -1 : 1);
940   if( id >=0 && id < mTotalPageCount )
941   {
942     mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(false);
943   }
944
945   // Guard against destruction during signal emission
946   Toolkit::PageTurnView handle( GetOwner() );
947   mPageTurnFinishedSignal.Emit( handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack );
948 }
949
950 void PageTurnView::OrganizePageDepth()
951 {
952   for( int i=0; i<NUMBER_OF_CACHED_PAGES_EACH_SIDE;i++ )
953   {
954     if(mCurrentPageIndex+i < mTotalPageCount)
955     {
956       mPages[( mCurrentPageIndex+i )%NUMBER_OF_CACHED_PAGES].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
957     }
958     if( mCurrentPageIndex >= i + 1 )
959     {
960       mPages[( mCurrentPageIndex-i-1 )%NUMBER_OF_CACHED_PAGES].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
961     }
962   }
963 }
964
965 void PageTurnView::StopTurning()
966 {
967   mAnimatingCount = 0;
968   mSlidingCount = 0;
969
970   if( !mPageUpdated )
971   {
972     int index = mTurningPageIndex % NUMBER_OF_CACHED_PAGES;
973     Self().Add( mPages[ index ].actor );
974     mPages[ index ].actor.RemoveConstraints();
975     mPages[ index ].UseEffect( mSpineEffectShader );
976     float degree = mTurningPageIndex==mCurrentPageIndex ? 0.f :180.f;
977     mPages[index].actor.SetOrientation( Degree(degree), Vector3::YAXIS );
978     mPageUpdated = true;
979   }
980
981   if( !mAnimationPageIdPair.empty() )
982   {
983     for (std::map<Animation,int>::iterator it=mAnimationPageIdPair.begin(); it!=mAnimationPageIdPair.end(); ++it)
984     {
985       static_cast<Animation>(it->first).SetCurrentProgress( 1.f );
986     }
987   }
988 }
989
990 Toolkit::PageTurnView::PageTurnSignal& PageTurnView::PageTurnStartedSignal()
991 {
992   return mPageTurnStartedSignal;
993 }
994
995 Toolkit::PageTurnView::PageTurnSignal& PageTurnView::PageTurnFinishedSignal()
996 {
997   return mPageTurnFinishedSignal;
998 }
999
1000 Toolkit::PageTurnView::PagePanSignal& PageTurnView::PagePanStartedSignal()
1001 {
1002   return mPagePanStartedSignal;
1003 }
1004
1005 Toolkit::PageTurnView::PagePanSignal& PageTurnView::PagePanFinishedSignal()
1006 {
1007   return mPagePanFinishedSignal;
1008 }
1009
1010 bool PageTurnView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1011 {
1012   Dali::BaseHandle handle( object );
1013
1014   bool connected( true );
1015   Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( handle );
1016
1017   if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_STARTED ) )
1018   {
1019     pageTurnView.PageTurnStartedSignal().Connect( tracker, functor );
1020   }
1021   else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_FINISHED ) )
1022   {
1023     pageTurnView.PageTurnFinishedSignal().Connect( tracker, functor );
1024   }
1025   else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_STARTED ) )
1026   {
1027     pageTurnView.PagePanStartedSignal().Connect( tracker, functor );
1028   }
1029   else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_FINISHED ) )
1030   {
1031     pageTurnView.PagePanFinishedSignal().Connect( tracker, functor );
1032   }
1033   else
1034   {
1035     // signalName does not match any signal
1036     connected = false;
1037   }
1038
1039   return connected;
1040 }
1041
1042 void PageTurnView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1043 {
1044   Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) );
1045
1046   if( pageTurnView )
1047   {
1048     PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) );
1049
1050     switch( index )
1051     {
1052       case Toolkit::PageTurnView::Property::VIEW_PAGE_SIZE:
1053       {
1054         pageTurnViewImpl.SetPageSize( value.Get<Vector2>() );
1055         break;
1056       }
1057       case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID:
1058       {
1059         pageTurnViewImpl.GoToPage( value.Get<int>() );
1060         break;
1061       }
1062       case Toolkit::PageTurnView::Property::SPINE_SHADOW:
1063       {
1064         pageTurnViewImpl.SetSpineShadowParameter( value.Get<Vector2>() );
1065         break;
1066       }
1067     }
1068   }
1069 }
1070
1071 Property::Value PageTurnView::GetProperty( BaseObject* object, Property::Index index )
1072 {
1073   Property::Value value;
1074
1075   Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) );
1076
1077   if( pageTurnView )
1078   {
1079     PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) );
1080
1081     switch( index )
1082     {
1083       case Toolkit::PageTurnView::Property::VIEW_PAGE_SIZE:
1084       {
1085         value = pageTurnViewImpl.GetPageSize();
1086         break;
1087       }
1088       case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID:
1089       {
1090         value = static_cast<int>( pageTurnViewImpl.GetCurrentPage() );
1091         break;
1092       }
1093       case Toolkit::PageTurnView::Property::SPINE_SHADOW:
1094       {
1095         value = pageTurnViewImpl.GetSpineShadowParameter();
1096         break;
1097       }
1098     }
1099   }
1100   return value;
1101 }
1102
1103 } // namespace Internal
1104
1105 } // namespace Toolkit
1106
1107 } // namespace Dali