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