Merge remote-tracking branch 'origin/tizen' into new_text
[platform/core/uifw/dali-demo.git] / demo / dali-table-view.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include "dali-table-view.h"
20 #include "examples/shared/view.h"
21
22 // EXTERNAL INCLUDES
23 #include <algorithm>
24 #include <sstream>
25 #include<unistd.h>
26
27 using namespace Dali;
28 using namespace Dali::Toolkit;
29
30 ///////////////////////////////////////////////////////////////////////////////
31
32 namespace
33 {
34
35 const std::string BUTTON_BACKWARD( "Backward" );
36 const std::string BUTTON_FORWARD( "Forward" );
37 const std::string BUTTON_QUIT( "Quit" );
38 const std::string BUTTON_OK( "Ok" );
39 const std::string BUTTON_CANCEL( "Cancel" );
40
41 const std::string DEFAULT_BACKGROUND_IMAGE_PATH( DALI_IMAGE_DIR "background-gradient.jpg" );
42 const std::string LOGO_PATH( DALI_IMAGE_DIR "dali-logo.png" );
43 const std::string DEFAULT_TOOLBAR_IMAGE_PATH( DALI_IMAGE_DIR "top-bar.png" );
44 const std::string BUTTON_BACKGROUND(DALI_IMAGE_DIR "button-background.png");
45 const std::string TILE_BACKGROUND(DALI_IMAGE_DIR "item-background.png");
46 const std::string TILE_BACKGROUND_ALPHA(DALI_IMAGE_DIR "item-background-alpha.png");
47
48 const char * const DEFAULT_TOOLBAR_TEXT( "TOUCH TO LAUNCH EXAMPLE" );
49
50 const float BUTTON_PRESS_ANIMATION_TIME = 0.25f;                ///< Time to perform button scale effect.
51 const float ROTATE_ANIMATION_TIME = 0.5f;                       ///< Time to perform rotate effect.
52 const int MAX_PAGES = 256;                                      ///< Maximum pages (arbitrary safety limit)
53 const int EXAMPLES_PER_ROW = 3;
54 const int ROWS_PER_PAGE = 3;
55 const int EXAMPLES_PER_PAGE = EXAMPLES_PER_ROW * ROWS_PER_PAGE;
56 const float 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   mRootActor.SetFixedHeight( 1, mLogo.GetImage().GetHeight() + LOGO_BOTTOM_PADDING_HEIGHT );
264
265   Alignment alignment = Alignment::New();
266   alignment.Add(mLogo);
267   mRootActor.AddChild( alignment, TableView::CellPosition( 1, 0 ) );
268
269   // scrollview occupying the majority of the screen
270   mScrollView = ScrollView::New();
271
272   mScrollView.SetAnchorPoint( AnchorPoint::CENTER );
273   mScrollView.SetParentOrigin( ParentOrigin::CENTER );
274   mScrollView.ApplyConstraint( Dali::Constraint::New<Dali::Vector3>( Dali::Actor::SIZE, Dali::ParentSource( Dali::Actor::SIZE ), Dali::RelativeToConstraint( TABLE_RELATIVE_SIZE ) ) );
275   mScrollView.SetAxisAutoLock( true );
276   mScrollView.ScrollCompletedSignal().Connect( this, &DaliTableView::OnScrollComplete );
277   mScrollView.ScrollStartedSignal().Connect( this, &DaliTableView::OnScrollStart );
278   mScrollView.TouchedSignal().Connect( this, &DaliTableView::OnScrollTouched );
279
280   mScrollViewLayer = Layer::New();
281   mScrollViewLayer.SetAnchorPoint( AnchorPoint::CENTER );
282   mScrollViewLayer.SetParentOrigin( ParentOrigin::CENTER );
283   mScrollViewLayer.SetSize( stageSize );
284   mScrollViewLayer.Add( mScrollView );
285   mRootActor.AddChild( mScrollViewLayer, TableView::CellPosition( 2, 0 ) );
286
287   // Setup the scenegraph
288   // 1) Add scroll view effect and setup constraints on pages
289   ApplyScrollViewEffect();
290
291   // 2) Add pages and tiles
292   Populate();
293
294   // 3) Populate scrollview with background so constraints on background layers can work with scrollview
295   SetupBackground( mScrollView, stageSize );
296
297   // 4) Remove constraints for inner cube effect
298   for( TableViewListIter pageIter = mTableViewList.begin(); pageIter != mTableViewList.end(); ++pageIter )
299   {
300     TableView page = *pageIter;
301
302     unsigned int numChildren = page.GetChildCount();
303     Actor pageActor = page;
304     for( unsigned int i=0; i<numChildren; ++i)
305     {
306       // Remove old effect's manual constraints.
307       Actor child = pageActor.GetChildAt(i);
308       if( child )
309       {
310         child.RemoveConstraints();
311       }
312     }
313   }
314
315   // Set initial orientation
316   unsigned int degrees = application.GetOrientation().GetDegrees();
317   Rotate( degrees );
318
319   Dali::Window winHandle = application.GetWindow();
320   winHandle.AddAvailableOrientation( Dali::Window::PORTRAIT );
321   winHandle.RemoveAvailableOrientation( Dali::Window::LANDSCAPE );
322   winHandle.AddAvailableOrientation( Dali::Window::PORTRAIT_INVERSE );
323   winHandle.RemoveAvailableOrientation( Dali::Window::LANDSCAPE_INVERSE );
324
325   Dali::Orientation orientation = winHandle.GetOrientation();
326   orientation.ChangedSignal().Connect( this, &DaliTableView::OrientationChanged );
327
328   winHandle.ShowIndicator( Dali::Window::INVISIBLE );
329
330   //
331   mAnimationTimer = Timer::New( BACKGROUND_ANIMATION_DURATION );
332   mAnimationTimer.TickSignal().Connect( this, &DaliTableView::PauseBackgroundAnimation );
333   mAnimationTimer.Start();
334   mBackgroundAnimsPlaying = true;
335
336   KeyboardFocusManager::Get().PreFocusChangeSignal().Connect( this, &DaliTableView::OnKeyboardPreFocusChange );
337   KeyboardFocusManager::Get().FocusedActorActivatedSignal().Connect( this, &DaliTableView::OnFocusedActorActivated );
338 }
339
340 void DaliTableView::Populate()
341 {
342   const Vector2 stageSize = Stage::GetCurrent().GetSize();
343
344   const Size demoTileSize( 0.25f * stageSize.width, 0.25f * stageSize.height );
345
346   mTotalPages = ( mExampleList.size() + EXAMPLES_PER_PAGE - 1 ) / EXAMPLES_PER_PAGE;
347
348   // Populate ScrollView.
349   if( mExampleList.size() > 0 )
350   {
351     if( mSortAlphabetically )
352     {
353       sort( mExampleList.begin(), mExampleList.end(), CompareByTitle );
354     }
355
356     unsigned int exampleCount = 0;
357     ExampleListConstIter iter = mExampleList.begin();
358     for( int t = 0; t < mTotalPages; t++ )
359     {
360       // Create Table. (contains up to 9 Examples)
361       TableView tableView = TableView::New( 4, 3 );
362       // Add tableView to container.
363       mScrollView.Add( tableView );
364       ApplyEffectToPage( tableView, TABLE_RELATIVE_SIZE );
365
366       tableView.SetAnchorPoint( AnchorPoint::CENTER );
367       tableView.SetParentOrigin( ParentOrigin::CENTER );
368       // 2 pixels of padding
369       tableView.SetCellPadding( Size( 2.0f, 2.0f ) );
370
371       Constraint constraint = Constraint::New<Vector3>( Actor::SCALE,
372                                                         LocalSource( Actor::SIZE ),
373                                                         ParentSource( Actor::SIZE ),
374                                                         ScaleToFitConstraint() );
375       tableView.ApplyConstraint(constraint);
376
377       // Apply visibility constraint to table view
378       Constraint visibleConstraint = Constraint::New< bool >( Actor::VISIBLE,
379                                                               LocalSource( Actor::POSITION ),
380                                                               ParentSource( Actor::SIZE ),
381                                                               TableViewVisibilityConstraint() );
382       visibleConstraint.SetRemoveAction( Constraint::Discard );
383       tableView.ApplyConstraint( visibleConstraint );
384
385       // add cells to table
386       for( int y = 0; y < ROWS_PER_PAGE; y++ )
387       {
388         for( int x = 0; x < EXAMPLES_PER_ROW; x++ )
389         {
390           const Example& example = ( *iter );
391
392           Actor tile = CreateTile( example.name, example.title, demoTileSize, true );
393           FocusManager focusManager = FocusManager::Get();
394           focusManager.SetFocusOrder( tile, ++exampleCount );
395           focusManager.SetAccessibilityAttribute( tile, Dali::Toolkit::FocusManager::ACCESSIBILITY_LABEL,
396                                                   example.title );
397           focusManager.SetAccessibilityAttribute( tile, Dali::Toolkit::FocusManager::ACCESSIBILITY_TRAIT, "Tile" );
398           focusManager.SetAccessibilityAttribute( tile, Dali::Toolkit::FocusManager::ACCESSIBILITY_HINT,
399                                                   "You can run this example" );
400
401           tableView.AddChild( tile, TableView::CellPosition( y, x ) );
402           iter++;
403
404           if( iter == mExampleList.end() )
405           {
406             break;
407           }
408         }
409         if( iter == mExampleList.end() )
410         {
411           break;
412         }
413       }
414
415       // last row is thin.
416       tableView.SetFixedHeight( 3, BOTTOM_ROW_HEIGHT );
417
418       std::stringstream out;
419       out << ( t + 1 ) << " of " << mTotalPages;
420       Actor pageNumberText = CreateTile( "", out.str(), Size( 0.8f * stageSize.width, BOTTOM_ROW_HEIGHT ), false );
421
422       pageNumberText.ApplyConstraint( Constraint::New< Vector3 >( Actor::POSITION, Source( tableView, Actor::WORLD_POSITION),
423                                                                    TranslateLocalConstraint( Vector3( 0.0f, stageSize.y * 0.4f, 0.0f ) ) ) );
424       pageNumberText.ApplyConstraint( Constraint::New< Quaternion >( Actor::ROTATION, Source( tableView, Actor::WORLD_ROTATION ), EqualToConstraint() ) );
425       pageNumberText.ApplyConstraint( Constraint::New< Vector4 >( Actor::COLOR, Source( tableView, Actor::COLOR ), EqualToConstraint() ) );
426
427       //Stage::GetCurrent().Add( pageNumberText );
428
429       // Set tableview position
430       Vector3 tableViewPos( stageSize.x * TABLE_RELATIVE_SIZE.x * t, 0.0f, 0.0f );
431       tableView.SetPosition( tableViewPos );
432
433       mTableViewList.push_back( tableView );
434
435       if( iter == mExampleList.end() )
436       {
437         break;
438       }
439     }
440   }
441
442   // Update Ruler info.
443   mScrollRulerX = new FixedRuler( stageSize.width * TABLE_RELATIVE_SIZE.x );
444   mScrollRulerY = new DefaultRuler();
445   mScrollRulerX->SetDomain( RulerDomain( 0.0f, mTotalPages * stageSize.width * TABLE_RELATIVE_SIZE.x, true ) );
446   mScrollRulerY->Disable();
447   mScrollView.SetRulerX( mScrollRulerX );
448   mScrollView.SetRulerY( mScrollRulerY );
449 }
450
451 void DaliTableView::OrientationChanged( Orientation orientation )
452 {
453   // TODO: Implement if orientation change required
454 }
455
456 void DaliTableView::Rotate( unsigned int degrees )
457 {
458   // Resize the root actor
459   Vector2 stageSize = Stage::GetCurrent().GetSize();
460   Vector3 targetSize( stageSize.x, stageSize.y, 1.0f );
461
462   if( degrees == 90 || degrees == 270 )
463   {
464     targetSize = Vector3( stageSize.y, stageSize.x, 1.0f );
465   }
466
467   if( mRotateAnimation )
468   {
469     mRotateAnimation.Stop();
470     mRotateAnimation.Clear();
471   }
472
473   mRotateAnimation = Animation::New( ROTATE_ANIMATION_TIME );
474   mRotateAnimation.RotateTo( mRootActor, Degree( 360 - degrees ), Vector3::ZAXIS, AlphaFunctions::EaseOut );
475   mRotateAnimation.Resize( mRootActor, targetSize, AlphaFunctions::EaseOut );
476   mRotateAnimation.Play();
477 }
478
479 Actor DaliTableView::CreateTile( const std::string& name, const std::string& title, const Size& parentSize, bool addBackground )
480 {
481   Actor tile = Actor::New();
482   tile.SetName( name );
483   tile.SetAnchorPoint( AnchorPoint::CENTER );
484   tile.SetParentOrigin( ParentOrigin::CENTER );
485
486   // make the tile 100% of parent
487   tile.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
488
489   Actor content = Actor::New();
490   content.SetAnchorPoint( AnchorPoint::CENTER );
491   content.SetParentOrigin( ParentOrigin::CENTER );
492   content.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
493   tile.Add(content);
494
495   // create background image
496   if( addBackground )
497   {
498     Image bg = Image::New( TILE_BACKGROUND );
499     ImageActor image = ImageActor::New( bg );
500     image.SetAnchorPoint( AnchorPoint::CENTER );
501     image.SetParentOrigin( ParentOrigin::CENTER );
502     // make the image 100% of tile
503     image.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
504     // move image back to get text appear in front
505     image.SetZ( -1 );
506     image.SetStyle( ImageActor::STYLE_NINE_PATCH );
507     image.SetNinePatchBorder( Vector4( IMAGE_BORDER_LEFT, IMAGE_BORDER_TOP, IMAGE_BORDER_RIGHT, IMAGE_BORDER_BOTTOM ) );
508
509     content.Add( image );
510
511     // Add stencil
512     ImageActor stencil = NewStencilImage();
513     stencil.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
514     image.Add( stencil );
515   }
516
517   // Set the tile to be keyboard focusable
518   tile.SetKeyboardFocusable(true);
519
520   // connect to the touch events
521   tile.TouchedSignal().Connect( this, &DaliTableView::OnTilePressed );
522   tile.HoveredSignal().Connect( this, &DaliTableView::OnTileHovered );
523
524   return tile;
525 }
526
527 ImageActor DaliTableView::NewStencilImage()
528 {
529   Image alpha = Image::New( TILE_BACKGROUND_ALPHA );
530
531   ImageActor stencilActor = ImageActor::New( alpha );
532   stencilActor.SetStyle( ImageActor::STYLE_NINE_PATCH );
533   stencilActor.SetNinePatchBorder( Vector4( IMAGE_BORDER_LEFT, IMAGE_BORDER_TOP, IMAGE_BORDER_RIGHT, IMAGE_BORDER_BOTTOM ) );
534
535   stencilActor.SetParentOrigin( ParentOrigin::CENTER );
536   stencilActor.SetAnchorPoint( AnchorPoint::CENTER );
537   stencilActor.SetDrawMode( DrawMode::STENCIL );
538
539   Dali::ShaderEffect shaderEffect = AlphaDiscardEffect::New();
540   stencilActor.SetShaderEffect( shaderEffect );
541
542   return stencilActor;
543 }
544
545 bool DaliTableView::OnTilePressed( Actor actor, const TouchEvent& event )
546 {
547   bool consumed = false;
548
549   const TouchPoint& point = event.GetPoint( 0 );
550   if( TouchPoint::Down == point.state )
551   {
552     mPressedActor = actor;
553     consumed = true;
554   }
555
556   // A button press is only valid if the Down & Up events
557   // both occurred within the button.
558   if( ( TouchPoint::Up == point.state ) &&
559       ( mPressedActor == actor ) )
560   {
561     std::string name = actor.GetName();
562     ExampleMapConstIter iter = mExampleMap.find( name );
563
564     FocusManager focusManager = FocusManager::Get();
565
566     if( iter != mExampleMap.end() )
567     {
568       // ignore Example button presses when scrolling or button animating.
569       if( ( !mScrolling ) && ( !mPressedAnimation ) )
570       {
571         // do nothing, until pressed animation finished.
572         consumed = true;
573       }
574     }
575
576     if( consumed )
577     {
578       mPressedAnimation = Animation::New( BUTTON_PRESS_ANIMATION_TIME );
579       mPressedAnimation.SetEndAction( Animation::Discard );
580
581       // scale the content actor within the Tile, as to not affect the placement within the Table.
582       Actor content = actor.GetChildAt(0);
583       mPressedAnimation.ScaleTo( content, Vector3( 0.9f, 0.9f, 1.0f ), AlphaFunctions::EaseInOut, 0.0f,
584                                  BUTTON_PRESS_ANIMATION_TIME * 0.5f );
585       mPressedAnimation.ScaleTo( content, Vector3::ONE, AlphaFunctions::EaseInOut, BUTTON_PRESS_ANIMATION_TIME * 0.5f,
586                                  BUTTON_PRESS_ANIMATION_TIME * 0.5f );
587       mPressedAnimation.Play();
588       mPressedAnimation.FinishedSignal().Connect( this, &DaliTableView::OnPressedAnimationFinished );
589     }
590   }
591   return consumed;
592 }
593
594 void DaliTableView::OnPressedAnimationFinished( Dali::Animation& source )
595 {
596   mPressedAnimation.Reset();
597   if( mPressedActor )
598   {
599     std::string name = mPressedActor.GetName();
600     ExampleMapConstIter iter = mExampleMap.find( name );
601
602     if( iter == mExampleMap.end() )
603     {
604       if( name == BUTTON_QUIT )
605       {
606         // Move focus to the OK button
607         FocusManager focusManager = FocusManager::Get();
608
609         // Enable the group mode and wrap mode
610         focusManager.SetGroupMode( true );
611         focusManager.SetWrapMode( true );
612       }
613     }
614     else
615     {
616       const Example& example( iter->second );
617
618       std::stringstream stream;
619       stream << DALI_EXAMPLE_BIN << example.name.c_str();
620       pid_t pid = fork();
621       if( pid == 0)
622       {
623         execlp( stream.str().c_str(), example.name.c_str(), NULL );
624         DALI_ASSERT_ALWAYS(false && "exec failed!");
625       }
626     }
627     mPressedActor.Reset();
628   }
629 }
630
631 void DaliTableView::OnScrollStart( const Dali::Vector3& position )
632 {
633   mScrolling = true;
634
635   PlayAnimation();
636 }
637
638 void DaliTableView::OnScrollComplete( const Dali::Vector3& position )
639 {
640   mScrolling = false;
641
642   // move focus to 1st item of new page
643   FocusManager focusManager = FocusManager::Get();
644   focusManager.SetCurrentFocusActor(mTableViewList[mScrollView.GetCurrentPage()].GetChildAt(TableView::CellPosition(1, 0)) );
645
646 }
647
648 bool DaliTableView::OnScrollTouched( Actor actor, const TouchEvent& event )
649 {
650   const TouchPoint& point = event.GetPoint( 0 );
651   if( TouchPoint::Down == point.state )
652   {
653     mPressedActor = actor;
654   }
655
656   return false;
657 }
658
659 void DaliTableView::ApplyScrollViewEffect()
660 {
661   // Remove old effect if exists.
662
663   if( mScrollViewEffect )
664   {
665     mScrollView.RemoveEffect( mScrollViewEffect );
666   }
667
668   // Just one effect for now
669   SetupInnerPageCubeEffect();
670
671   mScrollView.ApplyEffect( mScrollViewEffect );
672 }
673
674 void DaliTableView::SetupInnerPageCubeEffect()
675 {
676   ScrollViewCustomEffect customEffect;
677   mScrollViewEffect = customEffect = ScrollViewCustomEffect::New();
678   mScrollView.SetScrollSnapDuration( EFFECT_SNAP_DURATION );
679   mScrollView.SetScrollFlickDuration( EFFECT_FLICK_DURATION );
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   ImageActor logo = ImageActor::New( image );
892
893   logo.SetAnchorPoint( AnchorPoint::CENTER );
894   logo.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
895
896   return logo;
897 }
898
899 bool DaliTableView::PauseBackgroundAnimation()
900 {
901   PauseAnimation();
902
903   return false;
904 }
905
906 void DaliTableView::PauseAnimation()
907 {
908   if( mBackgroundAnimsPlaying )
909   {
910     for( AnimationListIter animIter = mBackgroundAnimations.begin(); animIter != mBackgroundAnimations.end(); ++animIter )
911     {
912       Animation anim = *animIter;
913
914       anim.Pause();
915     }
916
917     mBackgroundAnimsPlaying = false;
918   }
919 }
920
921 void DaliTableView::PlayAnimation()
922 {
923   if ( !mBackgroundAnimsPlaying )
924   {
925     for( AnimationListIter animIter = mBackgroundAnimations.begin(); animIter != mBackgroundAnimations.end(); ++animIter )
926     {
927       Animation anim = *animIter;
928
929       anim.Play();
930     }
931
932     mBackgroundAnimsPlaying = true;
933   }
934
935   mAnimationTimer.SetInterval( BACKGROUND_ANIMATION_DURATION );
936 }
937
938 Dali::Actor DaliTableView::OnKeyboardPreFocusChange( Dali::Actor current, Dali::Actor proposed, Dali::Toolkit::Control::KeyboardFocusNavigationDirection direction )
939 {
940   Actor nextFocusActor = proposed;
941
942   if ( !current && !proposed  )
943   {
944     // Set the initial focus to the first tile in the current page should be focused.
945     nextFocusActor = mTableViewList[mScrollView.GetCurrentPage()].GetChildAt(TableView::CellPosition(0, 0));
946   }
947   else if( !proposed || (proposed && proposed == mScrollViewLayer) )
948   {
949     // ScrollView is being focused but nothing in the current page can be focused further
950     // in the given direction. We should work out which page to scroll to next.
951     int currentPage = mScrollView.GetCurrentPage();
952     int newPage = currentPage;
953     if( direction == Dali::Toolkit::Control::Left )
954     {
955       newPage--;
956     }
957     else if( direction == Dali::Toolkit::Control::Right )
958     {
959       newPage++;
960     }
961
962     newPage = std::max(0, std::min(static_cast<int>(mScrollRulerX->GetTotalPages() - 1), newPage));
963     if( newPage == currentPage )
964     {
965       if( direction == Dali::Toolkit::Control::Left )
966       {
967         newPage = mScrollRulerX->GetTotalPages() - 1;
968       } else if( direction == Dali::Toolkit::Control::Right )
969       {
970         newPage = 0;
971       }
972     }
973
974     // Scroll to the page in the given direction
975     mScrollView.ScrollTo(newPage);
976
977     if( direction == Dali::Toolkit::Control::Left )
978     {
979       // Work out the cell position for the last tile
980       int remainingExamples = mExampleList.size() - newPage * EXAMPLES_PER_PAGE;
981       int rowPos = (remainingExamples >= EXAMPLES_PER_PAGE) ? ROWS_PER_PAGE - 1 : ( (remainingExamples % EXAMPLES_PER_PAGE + EXAMPLES_PER_ROW) / EXAMPLES_PER_ROW - 1 );
982       int colPos = remainingExamples >= EXAMPLES_PER_PAGE ? EXAMPLES_PER_ROW - 1 : ( remainingExamples % EXAMPLES_PER_PAGE - rowPos * EXAMPLES_PER_ROW - 1 );
983
984       // Move the focus to the last tile in the new page.
985       nextFocusActor = mTableViewList[newPage].GetChildAt(TableView::CellPosition(rowPos, colPos));
986     }
987     else
988     {
989       // Move the focus to the first tile in the new page.
990       nextFocusActor = mTableViewList[newPage].GetChildAt(TableView::CellPosition(0, 0));
991     }
992   }
993
994   return nextFocusActor;
995 }
996
997 void DaliTableView::OnFocusedActorActivated( Dali::Actor activatedActor )
998 {
999   if(activatedActor)
1000   {
1001     mPressedActor = activatedActor;
1002
1003     // Activate the current focused actor;
1004     TouchEvent touchEventUp;
1005     touchEventUp.points.push_back( TouchPoint ( 0, TouchPoint::Up, 0.0f, 0.0f ) );
1006     OnTilePressed(mPressedActor, touchEventUp);
1007   }
1008 }
1009
1010 bool DaliTableView::OnTileHovered( Actor actor, const HoverEvent& event )
1011 {
1012   KeyboardFocusManager::Get().SetCurrentFocusActor( actor );
1013   return true;
1014 }
1015
1016