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