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