Removed some constraints from dali-table-view
[platform/core/uifw/dali-demo.git] / demo / dali-table-view.cpp
1 /*
2  * Copyright (c) 2014 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-table-view.h"
20 #include "examples/shared/view.h"
21
22 // EXTERNAL INCLUDES
23 #include <algorithm>
24 #include <sstream>
25 #include<unistd.h>
26
27 using namespace Dali;
28 using namespace Dali::Toolkit;
29
30 ///////////////////////////////////////////////////////////////////////////////
31
32 namespace
33 {
34
35 const std::string BUTTON_BACKWARD( "Backward" );
36 const std::string BUTTON_FORWARD( "Forward" );
37 const std::string BUTTON_QUIT( "Quit" );
38 const std::string BUTTON_OK( "Ok" );
39 const std::string BUTTON_CANCEL( "Cancel" );
40
41 const std::string DEFAULT_BACKGROUND_IMAGE_PATH( DALI_IMAGE_DIR "background-gradient.jpg" );
42 const std::string LOGO_PATH( DALI_IMAGE_DIR "dali-logo.png" );
43 const std::string DEFAULT_TOOLBAR_IMAGE_PATH( DALI_IMAGE_DIR "top-bar.png" );
44 const std::string BUTTON_BACKGROUND(DALI_IMAGE_DIR "button-background.png");
45 const std::string TILE_BACKGROUND(DALI_IMAGE_DIR "item-background.png");
46 const std::string TILE_BACKGROUND_ALPHA(DALI_IMAGE_DIR "item-background-alpha.png");
47
48 const char * const DEFAULT_TOOLBAR_TEXT( "TOUCH TO LAUNCH EXAMPLE" );
49
50 const float BUTTON_PRESS_ANIMATION_TIME = 0.25f;                ///< Time to perform button scale effect.
51 const float ROTATE_ANIMATION_TIME = 0.5f;                       ///< Time to perform rotate effect.
52 const int MAX_PAGES = 256;                                      ///< Maximum pages (arbitrary safety limit)
53 const int EXAMPLES_PER_ROW = 3;
54 const int ROWS_PER_PAGE = 3;
55 const int EXAMPLES_PER_PAGE = EXAMPLES_PER_ROW * ROWS_PER_PAGE;
56 const float LOGO_MARGIN_RATIO = 0.5f / 0.9f;
57 const float BOTTOM_PADDING_RATIO = 0.4f / 0.9f;
58 const Vector3 SCROLLVIEW_RELATIVE_SIZE(0.9f, 1.0f, 0.8f );     ///< ScrollView's relative size to its parent
59 const Vector3 TABLE_RELATIVE_SIZE(0.9f, 0.9f, 0.8f );          ///< TableView's relative size to the entire stage. The Y value means sum of the logo and table relative heights.
60 const float STENCIL_RELATIVE_SIZE = 1.0f;
61
62 const float EFFECT_SNAP_DURATION = 0.66f;                       ///< Scroll Snap Duration for Effects
63 const float EFFECT_FLICK_DURATION = 0.5f;                       ///< Scroll Flick Duration for Effects
64 const Vector3 ANGLE_CUBE_PAGE_ROTATE(Math::PI * 0.5f, Math::PI * 0.5f, 0.0f);
65
66 const int NUM_BACKGROUND_IMAGES = 18;
67 const float BACKGROUND_SWIPE_SCALE = 0.025f;
68 const float BACKGROUND_SPREAD_SCALE = 1.5f;
69 const float SCALE_MOD = 1000.0f * Math::PI * 2.0f;
70 const float SCALE_SPEED = 10.0f;
71 const float SCALE_SPEED_SIN = 0.1f;
72
73 const unsigned int BACKGROUND_ANIMATION_DURATION = 15000; // 15 secs
74
75 const float BACKGROUND_Z = -1.0f;
76 const float BACKGROUND_SIZE_SCALE = 1.0f;
77 const Vector4 BACKGROUND_COLOR( 1.0f, 1.0f, 1.0f, 1.0f );
78
79 const float BUBBLE_MIN_Z = -1.0;
80 const float BUBBLE_MAX_Z = 0.0f;
81
82 // 3D Effect constants
83 const Vector2 ANGLE_SWING_3DEFFECT( Math::PI_2 * 0.75, Math::PI_2 * 0.75f ); ///< Angle Swing in radians
84 const Vector2 POSITION_SWING_3DEFFECT( 0.55f, 0.4f );             ///< Position Swing relative to stage size.
85 const Vector3 ANCHOR_3DEFFECT_STYLE0( -105.0f, 30.0f, -240.0f ); ///< Rotation Anchor position for 3D Effect (Style 0)
86 const Vector3 ANCHOR_3DEFFECT_STYLE1( 65.0f, -70.0f, -500.0f );  ///< Rotation Anchor position for 3D Effect (Style 1)
87
88 const std::string             DEFAULT_TEXT_STYLE_FONT_FAMILY("HelveticaNeue");
89 const std::string             DEFAULT_TEXT_STYLE_FONT_STYLE("Regular");
90 const Dali::PointSize         DEFAULT_TEXT_STYLE_POINT_SIZE( 8.0f );
91 const Dali::TextStyle::Weight DEFAULT_TEXT_STYLE_WEIGHT(Dali::TextStyle::REGULAR);
92 const Dali::Vector4           DEFAULT_TEXT_STYLE_COLOR(0.7f, 0.7f, 0.7f, 1.0f);
93
94 const std::string             TABLE_TEXT_STYLE_FONT_FAMILY("HelveticaNeue");
95 const std::string             TABLE_TEXT_STYLE_FONT_STYLE("Regular");
96 const Dali::PointSize         TABLE_TEXT_STYLE_POINT_SIZE( 8.0f );
97 const Dali::TextStyle::Weight TABLE_TEXT_STYLE_WEIGHT(Dali::TextStyle::LIGHT);
98 const Dali::Vector4           TABLE_TEXT_STYLE_COLOR(0.0f, 0.0f, 0.0f, 1.0f);
99
100 Vector3 ScalePointSize(const Vector3& vec)
101 {
102   return Vector3( DemoHelper::ScalePointSize( vec.x ), DemoHelper::ScalePointSize( vec.y ), DemoHelper::ScalePointSize( vec.z ) );
103 }
104
105 #define DP(x) DemoHelper::ScalePointSize(x)
106
107 TextStyle GetTableTextStyle()
108 {
109   TextStyle textStyle;
110   textStyle.SetFontName(TABLE_TEXT_STYLE_FONT_FAMILY);
111   textStyle.SetFontStyle(TABLE_TEXT_STYLE_FONT_STYLE);
112   textStyle.SetFontPointSize( Dali::PointSize(DemoHelper::ScalePointSize(TABLE_TEXT_STYLE_POINT_SIZE)));
113   textStyle.SetWeight(TABLE_TEXT_STYLE_WEIGHT);
114   textStyle.SetTextColor(TABLE_TEXT_STYLE_COLOR);
115   return textStyle;
116 }
117
118 /**
119  * Creates the background image
120  */
121 ImageActor CreateBackground( std::string imagePath )
122 {
123   Image image = ResourceImage::New( imagePath );
124   ImageActor background = ImageActor::New( image );
125
126   background.SetAnchorPoint( AnchorPoint::CENTER );
127   background.SetParentOrigin( ParentOrigin::CENTER );
128   background.SetZ( -1.0f );
129
130   return background;
131 }
132
133 // These values depend on the tile image
134 const float IMAGE_BORDER_LEFT = 11.0f;
135 const float IMAGE_BORDER_RIGHT = IMAGE_BORDER_LEFT;
136 const float IMAGE_BORDER_TOP = IMAGE_BORDER_LEFT;
137 const float IMAGE_BORDER_BOTTOM = IMAGE_BORDER_LEFT;
138
139 /**
140  * Constraint to return a position for a bubble based on the scroll value and vertical wrapping.
141  */
142 struct AnimateBubbleConstraint
143 {
144 public:
145   AnimateBubbleConstraint( const Vector3& initialPos, float scale, float size )
146       : mInitialX( initialPos.x ),
147         mScale( scale ),
148         mShapeSize( size )
149   {
150   }
151
152   Vector3 operator()( const Vector3& current, const PropertyInput& scrollProperty, const PropertyInput& parentSize )
153   {
154     Vector3 pos( current );
155
156     // Wrap bubbles verically.
157     if( pos.y + mShapeSize * 0.5f < -parentSize.GetVector3().y * 0.5f )
158     {
159       pos.y += parentSize.GetVector3().y + mShapeSize;
160     }
161
162     // Bubbles X position moves parallax to horizontal
163     // panning by a scale factor unique to each bubble.
164     pos.x = mInitialX + ( scrollProperty.GetVector3().x * mScale );
165     return pos;
166   }
167
168 private:
169   float mInitialX;
170   float mScale;
171   float mShapeSize;
172 };
173
174 bool CompareByTitle( const Example& lhs, const Example& rhs )
175 {
176   return lhs.title < rhs.title;
177 }
178
179 } // namespace
180
181 DaliTableView::DaliTableView( Application& application )
182     : mApplication( application ),
183         mScrolling( false ),
184         mBackgroundImagePath( DEFAULT_BACKGROUND_IMAGE_PATH ),
185         mSortAlphabetically( false ),
186         mBackgroundAnimsPlaying( false )
187 {
188   application.InitSignal().Connect( this, &DaliTableView::Initialize );
189 }
190
191 DaliTableView::~DaliTableView()
192 {
193 }
194
195 void DaliTableView::AddExample( Example example )
196 {
197   mExampleList.push_back( example );
198   mExampleMap[ example.name ] = example;
199 }
200
201 void DaliTableView::SetBackgroundPath( std::string imagePath )
202 {
203   mBackgroundImagePath = imagePath;
204 }
205
206 void DaliTableView::SortAlphabetically( bool sortAlphabetically )
207 {
208   mSortAlphabetically = sortAlphabetically;
209 }
210
211 void DaliTableView::Initialize( Application& application )
212 {
213   Stage::GetCurrent().KeyEventSignal().Connect( this, &DaliTableView::OnKeyEvent );
214
215   const Vector2 stageSize = Stage::GetCurrent().GetSize();
216
217   // Background
218   mBackground = CreateBackground( mBackgroundImagePath );
219   // set same size as parent actor
220   mBackground.SetSize( stageSize );
221   Stage::GetCurrent().Add( mBackground );
222
223   // Render entire content as overlays, as is all on same 2D plane.
224   mRootActor = TableView::New( 4, 1 );
225   mRootActor.SetAnchorPoint( AnchorPoint::CENTER );
226   mRootActor.SetParentOrigin( ParentOrigin::CENTER );
227   Stage::GetCurrent().Add( mRootActor );
228
229   // Toolbar at top
230   Dali::Toolkit::ToolBar toolbar;
231   Dali::Layer toolBarLayer = DemoHelper::CreateToolbar(toolbar,
232                                                        DEFAULT_TOOLBAR_IMAGE_PATH,
233                                                        DEFAULT_TOOLBAR_TEXT,
234                                                        DemoHelper::DEFAULT_VIEW_STYLE,
235                                                        DemoHelper::GetDefaultTextStyle());
236
237   mRootActor.AddChild( toolBarLayer, TableView::CellPosition( 0, 0 ) );
238   const float toolbarHeight = DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
239   mRootActor.SetFixedHeight( 0, toolbarHeight );
240
241   // Add logo
242   mLogo = CreateLogo( LOGO_PATH );
243   const float paddingHeight = ( ( 1.f-TABLE_RELATIVE_SIZE.y ) * stageSize.y );
244   const float logoMargin = paddingHeight * LOGO_MARGIN_RATIO;
245   const float logoHeight = mLogo.GetImage().GetHeight() + logoMargin;
246   mRootActor.SetFixedHeight( 1, logoHeight );
247
248   const float bottomMargin = paddingHeight * BOTTOM_PADDING_RATIO;
249   mButtonsPageRelativeSize = Vector3( TABLE_RELATIVE_SIZE.x, 1.f - ( toolbarHeight + logoHeight + bottomMargin) / stageSize.height, TABLE_RELATIVE_SIZE.z );
250   mRootActor.SetFixedHeight( 2, mButtonsPageRelativeSize.y * stageSize.height );
251
252   Alignment alignment = Alignment::New();
253   alignment.Add(mLogo);
254   mRootActor.AddChild( alignment, TableView::CellPosition( 1, 0 ) );
255
256   // scrollview occupying the majority of the screen
257   mScrollView = ScrollView::New();
258
259   mScrollView.SetAnchorPoint( AnchorPoint::CENTER );
260   mScrollView.SetParentOrigin( ParentOrigin::CENTER );
261   mScrollView.ApplyConstraint( Dali::Constraint::New<Dali::Vector3>( Dali::Actor::SIZE, Dali::ParentSource( Dali::Actor::SIZE ),
262                                                                      Dali::RelativeToConstraint( SCROLLVIEW_RELATIVE_SIZE ) ) );
263   mScrollView.SetAxisAutoLock( true );
264   mScrollView.ScrollCompletedSignal().Connect( this, &DaliTableView::OnScrollComplete );
265   mScrollView.ScrollStartedSignal().Connect( this, &DaliTableView::OnScrollStart );
266   mScrollView.TouchedSignal().Connect( this, &DaliTableView::OnScrollTouched );
267
268   mScrollViewLayer = Layer::New();
269   mScrollViewLayer.SetAnchorPoint( AnchorPoint::CENTER );
270   mScrollViewLayer.SetParentOrigin( ParentOrigin::CENTER );
271   mScrollViewLayer.SetDrawMode( DrawMode::OVERLAY );
272
273   // Populate background and bubbles - needs to be scrollViewLayer so scroll ends show
274   SetupBackground( mScrollView, mScrollViewLayer, stageSize );
275
276   mScrollViewLayer.Add( mScrollView );
277   mRootActor.AddChild( mScrollViewLayer, TableView::CellPosition( 2, 0 ) );
278
279   // Add scroll view effect and setup constraints on pages
280   ApplyScrollViewEffect();
281
282   // Add pages and tiles
283   Populate();
284
285   // Remove constraints for inner cube effect
286   ApplyCubeEffectToActors();
287
288   // Set initial orientation
289   unsigned int degrees = application.GetOrientation().GetDegrees();
290   Rotate( degrees );
291
292   Dali::Window winHandle = application.GetWindow();
293   winHandle.AddAvailableOrientation( Dali::Window::PORTRAIT );
294   winHandle.RemoveAvailableOrientation( Dali::Window::LANDSCAPE );
295   winHandle.AddAvailableOrientation( Dali::Window::PORTRAIT_INVERSE );
296   winHandle.RemoveAvailableOrientation( Dali::Window::LANDSCAPE_INVERSE );
297
298   Dali::Orientation orientation = winHandle.GetOrientation();
299   orientation.ChangedSignal().Connect( this, &DaliTableView::OrientationChanged );
300
301   winHandle.ShowIndicator( Dali::Window::INVISIBLE );
302
303   //
304   mAnimationTimer = Timer::New( BACKGROUND_ANIMATION_DURATION );
305   mAnimationTimer.TickSignal().Connect( this, &DaliTableView::PauseBackgroundAnimation );
306   mAnimationTimer.Start();
307   mBackgroundAnimsPlaying = true;
308
309   KeyboardFocusManager::Get().PreFocusChangeSignal().Connect( this, &DaliTableView::OnKeyboardPreFocusChange );
310   KeyboardFocusManager::Get().FocusedActorActivatedSignal().Connect( this, &DaliTableView::OnFocusedActorActivated );
311 }
312
313 void DaliTableView::ApplyCubeEffectToActors()
314 {
315   for( ActorIter pageIter = mPages.begin(); pageIter != mPages.end(); ++pageIter )
316   {
317     Actor page = *pageIter;
318
319     unsigned int numChildren = page.GetChildCount();
320     Actor pageActor = page;
321     for( unsigned int i=0; i<numChildren; ++i)
322     {
323       // Remove old effect's manual constraints.
324       Actor child = pageActor.GetChildAt(i);
325       if( child )
326       {
327         ApplyCubeEffectToActor( child );
328       }
329     }
330   }
331 }
332 void DaliTableView::Populate()
333 {
334   const Vector2 stageSize = Stage::GetCurrent().GetSize();
335
336   mTotalPages = ( mExampleList.size() + EXAMPLES_PER_PAGE - 1 ) / EXAMPLES_PER_PAGE;
337
338   // Populate ScrollView.
339   if( mExampleList.size() > 0 )
340   {
341     if( mSortAlphabetically )
342     {
343       sort( mExampleList.begin(), mExampleList.end(), CompareByTitle );
344     }
345
346     unsigned int exampleCount = 0;
347     ExampleListConstIter iter = mExampleList.begin();
348
349     for( int t = 0; t < mTotalPages; t++ )
350     {
351       // Create Table. (contains up to 9 Examples)
352       Actor page = Actor::New();
353
354       // Add tableView to container.
355       mScrollView.Add( page );
356
357       page.SetAnchorPoint( AnchorPoint::CENTER );
358       page.SetParentOrigin( ParentOrigin::CENTER );
359       page.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
360
361       // add cells to table
362       const float margin = 4.0f;
363
364       // Calculate the number of images going across (columns) within a page, according to the screen resolution and dpi.
365       const Size tileSize((stageSize.x * mButtonsPageRelativeSize.x / EXAMPLES_PER_ROW) - margin, (stageSize.y * mButtonsPageRelativeSize.y / ROWS_PER_PAGE) - margin );
366
367       for(int row = 0; row < ROWS_PER_PAGE; row++)
368       {
369         for(int column = 0; column < EXAMPLES_PER_ROW; column++)
370         {
371           const Example& example = ( *iter );
372
373           Actor tile = CreateTile( example.name, example.title, tileSize, true );
374           FocusManager focusManager = FocusManager::Get();
375           focusManager.SetFocusOrder( tile, ++exampleCount );
376           focusManager.SetAccessibilityAttribute( tile, Dali::Toolkit::FocusManager::ACCESSIBILITY_LABEL,
377                                                   example.title );
378           focusManager.SetAccessibilityAttribute( tile, Dali::Toolkit::FocusManager::ACCESSIBILITY_TRAIT, "Tile" );
379           focusManager.SetAccessibilityAttribute( tile, Dali::Toolkit::FocusManager::ACCESSIBILITY_HINT,
380                                                   "You can run this example" );
381
382           Vector3 position( margin * 0.5f + (tileSize.x + margin) * column - stageSize.width * mButtonsPageRelativeSize.x * 0.5f,
383                            margin * 0.5f + (tileSize.y + margin) * row - stageSize.height * mButtonsPageRelativeSize.y * 0.5f,
384                             0.0f);
385           tile.SetPosition( position + Vector3( tileSize.x, tileSize.y, 0.0f ) * 0.5f );
386           tile.SetSize( tileSize );
387           page.Add( tile );
388
389           iter++;
390
391           if( iter == mExampleList.end() )
392           {
393             break;
394           }
395         }
396
397         if( iter == mExampleList.end() )
398         {
399           break;
400         }
401       }
402
403       // Set tableview position
404       Vector3 pagePos( stageSize.x * mButtonsPageRelativeSize.x * t, 0.0f, 0.0f );
405       page.SetPosition( pagePos );
406
407       mPages.push_back( page );
408
409       if( iter == mExampleList.end() )
410       {
411         break;
412       }
413     }
414   }
415
416   // Update Ruler info.
417   mScrollRulerX = new FixedRuler( stageSize.width * mButtonsPageRelativeSize.x );
418   mScrollRulerY = new DefaultRuler();
419   mScrollRulerX->SetDomain( RulerDomain( 0.0f, mTotalPages * stageSize.width * mButtonsPageRelativeSize.x, true ) );
420   mScrollRulerY->Disable();
421   mScrollView.SetRulerX( mScrollRulerX );
422   mScrollView.SetRulerY( mScrollRulerY );
423 }
424
425 void DaliTableView::OrientationChanged( Orientation orientation )
426 {
427   // TODO: Implement if orientation change required
428 }
429
430 void DaliTableView::Rotate( unsigned int degrees )
431 {
432   // Resize the root actor
433   Vector2 stageSize = Stage::GetCurrent().GetSize();
434   Vector3 targetSize( stageSize.x, stageSize.y, 1.0f );
435
436   if( degrees == 90 || degrees == 270 )
437   {
438     targetSize = Vector3( stageSize.y, stageSize.x, 1.0f );
439   }
440
441   if( mRotateAnimation )
442   {
443     mRotateAnimation.Stop();
444     mRotateAnimation.Clear();
445   }
446
447   mRotateAnimation = Animation::New( ROTATE_ANIMATION_TIME );
448   mRotateAnimation.RotateTo( mRootActor, Degree( 360 - degrees ), Vector3::ZAXIS, AlphaFunctions::EaseOut );
449   mRotateAnimation.Resize( mRootActor, targetSize, AlphaFunctions::EaseOut );
450   mRotateAnimation.Play();
451 }
452
453 Actor DaliTableView::CreateTile( const std::string& name, const std::string& title, const Size& parentSize, bool addBackground )
454 {
455   Actor tile = Actor::New();
456   tile.SetName( name );
457   tile.SetAnchorPoint( AnchorPoint::CENTER );
458   tile.SetParentOrigin( ParentOrigin::CENTER );
459
460   // create background image
461   if( addBackground )
462   {
463     Image bg = ResourceImage::New( TILE_BACKGROUND );
464     ImageActor image = ImageActor::New( bg );
465     image.SetAnchorPoint( AnchorPoint::CENTER );
466     image.SetParentOrigin( ParentOrigin::CENTER );
467     // make the image 100% of tile
468     image.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
469     // move image back to get text appear in front
470     image.SetZ( -1 );
471     image.SetStyle( ImageActor::STYLE_NINE_PATCH );
472     image.SetNinePatchBorder( Vector4( IMAGE_BORDER_LEFT, IMAGE_BORDER_TOP, IMAGE_BORDER_RIGHT, IMAGE_BORDER_BOTTOM ) );
473     tile.Add( image );
474
475     // Add stencil
476     ImageActor stencil = NewStencilImage();
477     stencil.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
478     image.Add( stencil );
479   }
480
481   TextView text = TextView::New( title );
482   text.SetAnchorPoint( AnchorPoint::CENTER );
483   text.SetParentOrigin( ParentOrigin::CENTER );
484   text.SetWidthExceedPolicy( Toolkit::TextView::ShrinkToFit );
485   text.SetMultilinePolicy( Toolkit::TextView::SplitByWord );
486   text.SetLineJustification( Toolkit::TextView::Center );
487   text.SetTextAlignment( Toolkit::Alignment::Type( Alignment::HorizontalCenter | Alignment::VerticalCenter ) );
488   text.SetColor( Color::WHITE );
489   text.SetZ( 1 );
490   // make the text 90% of tile
491   text.SetSize( 0.9f * parentSize.width, 0.9f * parentSize.height );
492   text.SetStyleToCurrentText( GetTableTextStyle() );
493   text.SetSnapshotModeEnabled( false );
494   tile.Add( text );
495
496   // Set the tile to be keyboard focusable
497   tile.SetKeyboardFocusable(true);
498
499   // connect to the touch events
500   tile.TouchedSignal().Connect( this, &DaliTableView::OnTilePressed );
501   tile.HoveredSignal().Connect( this, &DaliTableView::OnTileHovered );
502
503   return tile;
504 }
505
506 ImageActor DaliTableView::NewStencilImage()
507 {
508   Image alpha = ResourceImage::New( TILE_BACKGROUND_ALPHA );
509
510   ImageActor stencilActor = ImageActor::New( alpha );
511   stencilActor.SetStyle( ImageActor::STYLE_NINE_PATCH );
512   stencilActor.SetNinePatchBorder( Vector4( IMAGE_BORDER_LEFT, IMAGE_BORDER_TOP, IMAGE_BORDER_RIGHT, IMAGE_BORDER_BOTTOM ) );
513
514   stencilActor.SetParentOrigin( ParentOrigin::CENTER );
515   stencilActor.SetAnchorPoint( AnchorPoint::CENTER );
516   stencilActor.SetDrawMode( DrawMode::STENCIL );
517
518   Dali::ShaderEffect shaderEffect = AlphaDiscardEffect::New();
519   stencilActor.SetShaderEffect( shaderEffect );
520
521   return stencilActor;
522 }
523
524 bool DaliTableView::OnTilePressed( Actor actor, const TouchEvent& event )
525 {
526   bool consumed = false;
527
528   const TouchPoint& point = event.GetPoint( 0 );
529   if( TouchPoint::Down == point.state )
530   {
531     mPressedActor = actor;
532     consumed = true;
533   }
534
535   // A button press is only valid if the Down & Up events
536   // both occurred within the button.
537   if( ( TouchPoint::Up == point.state ) &&
538       ( mPressedActor == actor ) )
539   {
540     std::string name = actor.GetName();
541     ExampleMapConstIter iter = mExampleMap.find( name );
542
543     FocusManager focusManager = FocusManager::Get();
544
545     if( iter != mExampleMap.end() )
546     {
547       // ignore Example button presses when scrolling or button animating.
548       if( ( !mScrolling ) && ( !mPressedAnimation ) )
549       {
550         // do nothing, until pressed animation finished.
551         consumed = true;
552       }
553     }
554
555     if( consumed )
556     {
557       mPressedAnimation = Animation::New( BUTTON_PRESS_ANIMATION_TIME );
558       mPressedAnimation.SetEndAction( Animation::Discard );
559
560       // scale the content actor within the Tile, as to not affect the placement within the Table.
561       Actor content = actor.GetChildAt(0);
562       mPressedAnimation.ScaleTo( content, Vector3( 0.9f, 0.9f, 1.0f ), AlphaFunctions::EaseInOut, 0.0f,
563                                  BUTTON_PRESS_ANIMATION_TIME * 0.5f );
564       mPressedAnimation.ScaleTo( content, Vector3::ONE, AlphaFunctions::EaseInOut, BUTTON_PRESS_ANIMATION_TIME * 0.5f,
565                                  BUTTON_PRESS_ANIMATION_TIME * 0.5f );
566       mPressedAnimation.Play();
567       mPressedAnimation.FinishedSignal().Connect( this, &DaliTableView::OnPressedAnimationFinished );
568     }
569   }
570   return consumed;
571 }
572
573 void DaliTableView::OnPressedAnimationFinished( Dali::Animation& source )
574 {
575   mPressedAnimation.Reset();
576   if( mPressedActor )
577   {
578     std::string name = mPressedActor.GetName();
579     ExampleMapConstIter iter = mExampleMap.find( name );
580
581     if( iter == mExampleMap.end() )
582     {
583       if( name == BUTTON_QUIT )
584       {
585         // Move focus to the OK button
586         FocusManager focusManager = FocusManager::Get();
587
588         // Enable the group mode and wrap mode
589         focusManager.SetGroupMode( true );
590         focusManager.SetWrapMode( true );
591       }
592     }
593     else
594     {
595       const Example& example( iter->second );
596
597       std::stringstream stream;
598       stream << DALI_EXAMPLE_BIN << example.name.c_str();
599       pid_t pid = fork();
600       if( pid == 0)
601       {
602         execlp( stream.str().c_str(), example.name.c_str(), NULL );
603         DALI_ASSERT_ALWAYS(false && "exec failed!");
604       }
605     }
606     mPressedActor.Reset();
607   }
608 }
609
610 void DaliTableView::OnScrollStart( const Dali::Vector3& position )
611 {
612   mScrolling = true;
613
614   PlayAnimation();
615 }
616
617 void DaliTableView::OnScrollComplete( const Dali::Vector3& position )
618 {
619   mScrolling = false;
620
621   // move focus to 1st item of new page
622   FocusManager focusManager = FocusManager::Get();
623   focusManager.SetCurrentFocusActor(mPages[mScrollView.GetCurrentPage()].GetChildAt(0) );
624
625   ApplyCubeEffectToActors();
626 }
627
628 bool DaliTableView::OnScrollTouched( Actor actor, const TouchEvent& event )
629 {
630   const TouchPoint& point = event.GetPoint( 0 );
631   if( TouchPoint::Down == point.state )
632   {
633     mPressedActor = actor;
634   }
635
636   return false;
637 }
638
639 void DaliTableView::ApplyScrollViewEffect()
640 {
641   // Remove old effect if exists.
642
643   if( mScrollViewEffect )
644   {
645     mScrollView.RemoveEffect( mScrollViewEffect );
646   }
647
648   // Just one effect for now
649   SetupInnerPageCubeEffect();
650
651   mScrollView.ApplyEffect( mScrollViewEffect );
652 }
653
654 void DaliTableView::SetupInnerPageCubeEffect()
655 {
656   mScrollViewEffect = ScrollViewCubeEffect::New();
657   mScrollView.SetScrollSnapDuration( EFFECT_SNAP_DURATION );
658   mScrollView.SetScrollFlickDuration( EFFECT_FLICK_DURATION );
659   mScrollView.RemoveConstraintsFromChildren();
660 }
661
662 void DaliTableView::ApplyCubeEffectToActor( Actor actor )
663 {
664   actor.RemoveConstraints();
665
666   ScrollViewCubeEffect cubeEffect = ScrollViewCubeEffect::DownCast(mScrollViewEffect);
667   cubeEffect.ApplyToActor( actor,
668                            ScalePointSize( ( rand() & 1 ) ? ANCHOR_3DEFFECT_STYLE0 : ANCHOR_3DEFFECT_STYLE1 ),
669                            ANGLE_SWING_3DEFFECT,
670                            POSITION_SWING_3DEFFECT * Vector2(Stage::GetCurrent().GetSize()));
671 }
672
673 void DaliTableView::OnKeyEvent( const KeyEvent& event )
674 {
675   if( event.state == KeyEvent::Down )
676   {
677     if ( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
678     {
679       mApplication.Quit();
680     }
681   }
682 }
683
684 void DaliTableView::SetupBackground( Actor bubbleContainer, Actor backgroundLayer, const Vector2& size )
685 {
686   // Create distance field shape.
687   BitmapImage distanceField;
688   Size imageSize( 512, 512 );
689   CreateShapeImage( CIRCLE, imageSize, distanceField );
690
691   // Create solid background colour.
692   ImageActor backgroundColourActor = Dali::Toolkit::CreateSolidColorActor( BACKGROUND_COLOR );
693   backgroundColourActor.SetAnchorPoint( AnchorPoint::CENTER );
694   backgroundColourActor.SetParentOrigin( ParentOrigin::CENTER );
695   backgroundColourActor.SetSize( size * BACKGROUND_SIZE_SCALE );
696   backgroundColourActor.SetZ( BACKGROUND_Z );
697   backgroundColourActor.SetPositionInheritanceMode( DONT_INHERIT_POSITION );
698   backgroundLayer.Add( backgroundColourActor );
699
700   // Add bubbles to the bubbleContainer.
701   // Note: The bubbleContainer is parented externally to this function.
702   AddBackgroundActors( bubbleContainer, NUM_BACKGROUND_IMAGES, distanceField, size );
703 }
704
705 void DaliTableView::AddBackgroundActors( Actor layer, int count, BitmapImage distanceField, const Dali::Vector2& size )
706 {
707   for( int i = 0; i < count; ++i )
708   {
709     float randSize = Random::Range( 10.0f, 400.0f );
710     float hue = Random::Range( 0.3f, 1.0f );
711     Vector4 randColour( hue, hue*0.5, 0.0f, Random::Range( 0.3f, 0.6f ));
712
713     ImageActor dfActor = ImageActor::New( distanceField );
714     mBackgroundActors.push_back( dfActor );
715     dfActor.SetSize( Vector2( randSize, randSize ) );
716     dfActor.SetParentOrigin( ParentOrigin::CENTER );
717
718     Toolkit::DistanceFieldEffect effect = Toolkit::DistanceFieldEffect::New();
719     dfActor.SetShaderEffect( effect );
720     dfActor.SetColor( randColour );
721     effect.SetOutlineParams( Vector2( 0.55f, 0.00f ) );
722     effect.SetSmoothingEdge( 0.5f );
723     layer.Add( dfActor );
724
725     // Setup animation
726     Vector3 actorPos(
727         Random::Range( -size.x * 0.5f * BACKGROUND_SPREAD_SCALE, size.x * 0.5f * BACKGROUND_SPREAD_SCALE ),
728         Random::Range( -size.y * 0.5f - randSize, size.y * 0.5f + randSize ),
729         Random::Range( BUBBLE_MIN_Z, BUBBLE_MAX_Z ) );
730     dfActor.SetPosition( actorPos );
731
732     // Define bubble horizontal parallax and vertical wrapping
733     Constraint animConstraint = Constraint::New < Vector3 > ( Actor::POSITION,
734       Source( mScrollView, mScrollView.GetPropertyIndex( ScrollView::SCROLL_POSITION_PROPERTY_NAME ) ),
735       Dali::ParentSource( Dali::Actor::SIZE ),
736       AnimateBubbleConstraint( actorPos, Random::Range( -0.85f, 0.35f ), randSize ) );
737     dfActor.ApplyConstraint( animConstraint );
738
739     // Kickoff animation
740     Animation animation = Animation::New( Random::Range( 40.0f, 200.0f ) );
741     KeyFrames keyframes = KeyFrames::New();
742     keyframes.Add( 0.0f, actorPos );
743     Vector3 toPos( actorPos );
744     toPos.y -= ( size.y + randSize );
745     keyframes.Add( 1.0f, toPos );
746     animation.AnimateBetween( Property( dfActor, Actor::POSITION ), keyframes );
747     animation.SetLooping( true );
748     animation.Play();
749     mBackgroundAnimations.push_back( animation );
750   }
751 }
752
753 void DaliTableView::CreateShapeImage( ShapeType shapeType, const Size& size, BitmapImage& distanceFieldOut )
754 {
755   // this bitmap will hold the alpha map for the distance field shader
756   distanceFieldOut = BitmapImage::New( size.width, size.height, Pixel::A8 );
757
758   // Generate bit pattern
759   std::vector< unsigned char > imageDataA8;
760   imageDataA8.reserve( size.width * size.height ); // A8
761
762   switch( shapeType )
763   {
764     case CIRCLE:
765       GenerateCircle( size, imageDataA8 );
766       break;
767     case SQUARE:
768       GenerateSquare( size, imageDataA8 );
769       break;
770     default:
771       break;
772   }
773
774   PixelBuffer* buffer = distanceFieldOut.GetBuffer();
775   if( buffer )
776   {
777     GenerateDistanceFieldMap( &imageDataA8[ 0 ], size, buffer, size, 8.0f, size );
778     distanceFieldOut.Update();
779   }
780 }
781
782 void DaliTableView::GenerateSquare( const Size& size, std::vector< unsigned char >& distanceFieldOut )
783 {
784   for( int h = 0; h < size.height; ++h )
785   {
786     for( int w = 0; w < size.width; ++w )
787     {
788       distanceFieldOut.push_back( 0xFF );
789     }
790   }
791 }
792
793 void DaliTableView::GenerateCircle( const Size& size, std::vector< unsigned char >& distanceFieldOut )
794 {
795   const float radius = size.width * 0.5f * size.width * 0.5f;
796   Vector2 center( size.width / 2, size.height / 2 );
797
798   for( int h = 0; h < size.height; ++h )
799   {
800     for( int w = 0; w < size.width; ++w )
801     {
802       Vector2 pos( w, h );
803       Vector2 dist = pos - center;
804
805       if( dist.x * dist.x + dist.y * dist.y > radius )
806       {
807         distanceFieldOut.push_back( 0x00 );
808       }
809       else
810       {
811         distanceFieldOut.push_back( 0xFF );
812       }
813     }
814   }
815 }
816
817 ImageActor DaliTableView::CreateLogo( std::string imagePath )
818 {
819   Image image = ResourceImage::New( imagePath );
820   ImageActor logo = ImageActor::New( image );
821
822   logo.SetAnchorPoint( AnchorPoint::CENTER );
823   logo.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
824
825   return logo;
826 }
827
828 bool DaliTableView::PauseBackgroundAnimation()
829 {
830   PauseAnimation();
831
832   return false;
833 }
834
835 void DaliTableView::PauseAnimation()
836 {
837   if( mBackgroundAnimsPlaying )
838   {
839     for( AnimationListIter animIter = mBackgroundAnimations.begin(); animIter != mBackgroundAnimations.end(); ++animIter )
840     {
841       Animation anim = *animIter;
842
843       anim.Pause();
844     }
845
846     mBackgroundAnimsPlaying = false;
847   }
848 }
849
850 void DaliTableView::PlayAnimation()
851 {
852   if ( !mBackgroundAnimsPlaying )
853   {
854     for( AnimationListIter animIter = mBackgroundAnimations.begin(); animIter != mBackgroundAnimations.end(); ++animIter )
855     {
856       Animation anim = *animIter;
857
858       anim.Play();
859     }
860
861     mBackgroundAnimsPlaying = true;
862   }
863
864   mAnimationTimer.SetInterval( BACKGROUND_ANIMATION_DURATION );
865 }
866
867 Dali::Actor DaliTableView::OnKeyboardPreFocusChange( Dali::Actor current, Dali::Actor proposed, Dali::Toolkit::Control::KeyboardFocusNavigationDirection direction )
868 {
869   Actor nextFocusActor = proposed;
870
871   if ( !current && !proposed  )
872   {
873     // Set the initial focus to the first tile in the current page should be focused.
874     nextFocusActor = mPages[mScrollView.GetCurrentPage()].GetChildAt(0);
875   }
876   else if( !proposed || (proposed && proposed == mScrollViewLayer) )
877   {
878     // ScrollView is being focused but nothing in the current page can be focused further
879     // in the given direction. We should work out which page to scroll to next.
880     int currentPage = mScrollView.GetCurrentPage();
881     int newPage = currentPage;
882     if( direction == Dali::Toolkit::Control::Left )
883     {
884       newPage--;
885     }
886     else if( direction == Dali::Toolkit::Control::Right )
887     {
888       newPage++;
889     }
890
891     newPage = std::max(0, std::min(static_cast<int>(mScrollRulerX->GetTotalPages() - 1), newPage));
892     if( newPage == currentPage )
893     {
894       if( direction == Dali::Toolkit::Control::Left )
895       {
896         newPage = mScrollRulerX->GetTotalPages() - 1;
897       } else if( direction == Dali::Toolkit::Control::Right )
898       {
899         newPage = 0;
900       }
901     }
902
903     // Scroll to the page in the given direction
904     mScrollView.ScrollTo(newPage);
905
906     if( direction == Dali::Toolkit::Control::Left )
907     {
908       // Work out the cell position for the last tile
909       int remainingExamples = mExampleList.size() - newPage * EXAMPLES_PER_PAGE;
910       int rowPos = (remainingExamples >= EXAMPLES_PER_PAGE) ? ROWS_PER_PAGE - 1 : ( (remainingExamples % EXAMPLES_PER_PAGE + EXAMPLES_PER_ROW) / EXAMPLES_PER_ROW - 1 );
911       int colPos = remainingExamples >= EXAMPLES_PER_PAGE ? EXAMPLES_PER_ROW - 1 : ( remainingExamples % EXAMPLES_PER_PAGE - rowPos * EXAMPLES_PER_ROW - 1 );
912
913       // Move the focus to the last tile in the new page.
914       nextFocusActor = mPages[newPage].GetChildAt(colPos * EXAMPLES_PER_ROW + rowPos);
915     }
916     else
917     {
918       // Move the focus to the first tile in the new page.
919       nextFocusActor = mPages[newPage].GetChildAt(0);
920     }
921   }
922
923   return nextFocusActor;
924 }
925
926 void DaliTableView::OnFocusedActorActivated( Dali::Actor activatedActor )
927 {
928   if(activatedActor)
929   {
930     mPressedActor = activatedActor;
931
932     // Activate the current focused actor;
933     TouchEvent touchEventUp;
934     touchEventUp.points.push_back( TouchPoint ( 0, TouchPoint::Up, 0.0f, 0.0f ) );
935     OnTilePressed(mPressedActor, touchEventUp);
936   }
937 }
938
939 bool DaliTableView::OnTileHovered( Actor actor, const HoverEvent& event )
940 {
941   KeyboardFocusManager::Get().SetCurrentFocusActor( actor );
942   return true;
943 }
944
945