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