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