Merge "Add Flexbox demo to the DALI demo launcher" into devel/master
[platform/core/uifw/dali-demo.git] / examples / homescreen-benchmark / homescreen-benchmark.cpp
1 /*
2  * Copyright (c) 2016 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 // EXTERNAL INCLUDES
19 #include <dali-toolkit/dali-toolkit.h>
20 #include <sstream>
21 #include <iostream>
22
23 using namespace Dali;
24 using Dali::Toolkit::TextLabel;
25
26 namespace
27 {
28 enum IconType
29 {
30   IMAGEVIEW,
31   CHECKBOX
32 };
33
34 const char* IMAGE_PATH_PREFIX               ( DEMO_IMAGE_DIR "application-icon-" );
35 const char* IMAGE_PATH_POSTFIX              ( ".png" );
36 const int   TOTAL_ICON_DEFINITIONS          ( 147 );
37
38 const char* BACKGROUND_IMAGE                ( DEMO_IMAGE_DIR "background-3.jpg" );
39 const float PAGE_SCALE_FACTOR_X             ( 0.95f );
40 const float PAGE_SCALE_FACTOR_Y             ( 0.95f );
41 const float PAGE_DURATION_SCALE_FACTOR      ( 10.0f ); ///< Time-scale factor, larger = animation is slower
42
43 const float DEFAULT_OPT_ROW_COUNT           ( 5 );
44 const float DEFAULT_OPT_COL_COUNT           ( 4 );
45 const float DEFAULT_OPT_PAGE_COUNT          ( 10 );
46 const bool  DEFAULT_OPT_USE_TABLEVIEW       ( true );
47 const bool  DEFAULT_OPT_BATCHING_ENABLED    ( true );
48 const bool  DEFAULT_OPT_ICON_LABELS         ( true );
49 const IconType  DEFAULT_OPT_ICON_TYPE       ( IMAGEVIEW );
50
51 // The image/label area tries to make sure the positioning will be relative to previous sibling
52 const float IMAGE_AREA                      ( 0.60f );
53 const float LABEL_AREA                      ( 0.50f );
54
55
56
57 /**
58  * Random words used as unique application names.
59  * The number matches the value of TOTAL_ICON_DEFINITIONS.
60  */
61 const char* DEMO_APPS_NAMES[] =
62 {
63   "Achdyer",   "Aughm",       "Cerl",       "Daril",      "Emgha",     "Ghatan",     "Issum",     "Lertan",    "Mosorrad",
64   "Achtortor", "Aughtheryer", "Certin",     "Darpban",    "Emiton",    "Gibanis",    "Itenthbel", "Liadem",    "Mosraye",
65   "Ackirlor",  "Awitad",      "Checerper",  "Dasrad",     "Emworeng",  "Hatdyn",     "K'ackves",  "Liathar",   "Mosth",
66   "Ackptin",   "Banengon",    "Chegit",     "Deeqskel",   "Endnys",    "Heesban",    "Kagdra",    "Liephden",  "Neabar",
67   "Aighte",    "Banhinat",    "Cheirat",    "Delurnther", "Enessray",  "Hesub",      "Kalbankim", "Likellor",  "Neerdem",
68   "Akala",     "Belrisash",   "Che'rak",    "Denalda",    "Engyer",    "Hinkelenth", "Kal'enda",  "Loightmos", "Nichqua",
69   "Alealdny",  "Bilorm",      "Cheves",     "Derynkel",   "En'rady",   "Hirryer",    "Kimest",    "Loromum",   "Nudraough",
70   "Angash",    "Bleustcer",   "Chiperath",  "Deurnos",    "Enthount",  "Ideinta",    "Kimundeng", "Lorr",      "Nuyim",
71   "Anglor",    "Bliagelor",   "Chralerack", "Doyaryke",   "Enundem",   "Im'eld",     "Koachlor",  "Lortas",    "Nycha",
72   "Anveraugh", "Blorynton",   "Chram",      "Draithon",   "Essina",    "Ina'ir",     "Kuren",     "Lyerr",     "Nyia",
73   "Ardangas",  "Booten",      "Clyimen",    "Drantess",   "Faughald",  "Ing'moro",   "Kygver",    "Maustbur",  "Nyjac",
74   "Ardug",     "Bripolqua",   "Coqueang",   "Druardny",   "Fiummos",   "Ingormess",  "Kyning",    "Menvor",    "Nystondar",
75   "Ardworu",   "Bryray",      "Craennther", "Dynsaytor",  "Garash",    "Ingshy",     "Laiyach",   "Meusten",   "Okine",
76   "Ascerald",  "Burust",      "Cykage",     "Dytinris",   "Garight",   "Issath",     "Lasuzu",    "Mirodskel", "Oldit",
77   "Ash'ach",   "Cataikel",    "Dalek",      "Eeni",       "Garrynath", "Issendris",  "Lekew",     "Morhatrod", "Om'mose",
78   "Athiund",   "Cerilwar",    "Darhkel",    "Elmryn",     "Ghalora",   "Issey",      "Lerengom",  "Moserbel",  "Onye",
79   "Ososrak",   "Pecertin",    "Perrd"
80 };
81
82 // This code comes from command-line-options.cpp. the reason it's here is to
83 // keep consistent the extra-help formatting when '--help' used.
84 void PrintHelp( const char * const opt, const char * const optDescription)
85 {
86   const std::ios_base::fmtflags flags = std::cout.flags();
87   std::cout << std::left << "  -";
88   std::cout.width( 18 );
89   std::cout << opt;
90   std::cout << optDescription;
91   std::cout << std::endl;
92   std::cout.flags( flags );
93 }
94
95 }
96
97 /**
98  * @brief This example is a benchmark that mimics the paged applications list of the homescreen application.
99  */
100 class HomescreenBenchmark : public ConnectionTracker
101 {
102 public:
103
104   // Config structure passed to the constructor. It makes easier to increase number
105   // of setup parameters if needed.
106   struct Config
107   {
108     Config() :
109       mRows( DEFAULT_OPT_ROW_COUNT ),
110       mCols( DEFAULT_OPT_COL_COUNT ),
111       mPageCount( DEFAULT_OPT_PAGE_COUNT ),
112       mTableViewEnabled( DEFAULT_OPT_USE_TABLEVIEW ),
113       mBatchingEnabled( DEFAULT_OPT_BATCHING_ENABLED ),
114       mIconLabelsEnabled( DEFAULT_OPT_ICON_LABELS ),
115       mIconType( DEFAULT_OPT_ICON_TYPE )
116     {
117     }
118
119     int  mRows;
120     int  mCols;
121     int  mPageCount;
122     bool mTableViewEnabled;
123     bool mBatchingEnabled;
124     bool mIconLabelsEnabled;
125     IconType mIconType;
126   };
127
128   // animation script data
129   struct ScriptData
130   {
131     ScriptData( int pages, float duration, bool flick )
132     : mPages( pages ),
133       mDuration( duration ),
134       mFlick( flick )
135     {
136     }
137
138     int   mPages;    ///< Number of pages to scroll
139     float mDuration; ///< Duration
140     bool  mFlick;    ///< Use flick or 'one-by-one' scroll
141   };
142
143   HomescreenBenchmark( Application& application, const Config& config )
144   : mApplication( application ),
145     mConfig( config ),
146     mScriptFrame( 0 ),
147     mCurrentPage( 0 )
148   {
149     // Connect to the Application's Init signal.
150     mApplication.InitSignal().Connect( this, &HomescreenBenchmark::Create );
151   }
152
153   ~HomescreenBenchmark()
154   {
155   }
156
157   // The Init signal is received once (only) during the Application lifetime.
158   void Create( Application& application )
159   {
160     // Create benchmark script
161     CreateScript();
162
163     // Get a handle to the stage
164     Stage stage = Stage::GetCurrent();
165
166     mScrollParent = Actor::New();
167     mScrollParent.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
168     mScrollParent.SetAnchorPoint( AnchorPoint::CENTER );
169     mScrollParent.SetParentOrigin( ParentOrigin::CENTER );
170
171     // create background
172     Toolkit::ImageView background = Toolkit::ImageView::New( BACKGROUND_IMAGE );
173     Stage::GetCurrent().Add( background );
174     background.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
175     background.SetAnchorPoint( AnchorPoint::CENTER );
176     background.SetParentOrigin( ParentOrigin::CENTER );
177
178     PopulatePages();
179
180     stage.Add( mScrollParent );
181
182     // Respond to a click anywhere on the stage.
183     stage.GetRootLayer().TouchSignal().Connect( this, &HomescreenBenchmark::OnTouch );
184   }
185
186   bool OnTouch( Actor actor, const TouchData& touch )
187   {
188     // Quit the application.
189     mApplication.Quit();
190     return true;
191   }
192
193   Actor AddPage()
194   {
195     // Create root page actor.
196     Actor pageActor;
197
198     if( mConfig.mTableViewEnabled )
199     {
200       Toolkit::TableView tableView = Toolkit::TableView::New( mConfig.mRows, mConfig.mCols );
201
202       // Create geometry batcher for table view.
203       tableView.SetBackgroundColor( Vector4( 0.0f, 0.0f, 0.0f, 0.5f ) );
204       pageActor = tableView;
205     }
206     else
207     {
208       pageActor = Toolkit::Control::New();
209       pageActor.SetProperty( Toolkit::Control::Property::BACKGROUND_COLOR, Vector4( 0.0f, 0.0f, 0.0f, 0.5f ) );
210     }
211
212     pageActor.SetParentOrigin( ParentOrigin::CENTER );
213     pageActor.SetAnchorPoint( AnchorPoint::CENTER );
214     pageActor.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
215     pageActor.SetSizeModeFactor( Vector3( PAGE_SCALE_FACTOR_X, PAGE_SCALE_FACTOR_Y, 1.0f ) );
216     return pageActor;
217   }
218
219   Toolkit::ImageView CreateImageView( const unsigned int currentIconIndex )
220   {
221     // Create empty image to avoid early renderer creation
222     Toolkit::ImageView imageView = Toolkit::ImageView::New();
223
224     // Auto-generate the Icons image URL.
225     Property::Map map;
226     std::stringstream imagePath;
227     imagePath << IMAGE_PATH_PREFIX << currentIconIndex << IMAGE_PATH_POSTFIX;
228     map[ Dali::Toolkit::ImageVisual::Property::URL ] = imagePath.str();
229
230     // Enable/disable batching
231     map[ Toolkit::ImageVisual::Property::BATCHING_ENABLED ] = mConfig.mBatchingEnabled;
232
233     imageView.SetProperty( Toolkit::ImageView::Property::IMAGE, map );
234     imageView.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
235     imageView.SetSizeScalePolicy( SizeScalePolicy::FIT_WITH_ASPECT_RATIO );
236     imageView.SetAnchorPoint( AnchorPoint::CENTER );
237     imageView.SetParentOrigin( ParentOrigin::CENTER );
238     imageView.SetSizeModeFactor( Vector3( IMAGE_AREA, IMAGE_AREA, 1.0f ) );
239
240     return imageView;
241   }
242
243   Toolkit::Button CreateButton( const unsigned int currentIconIndex )
244   {
245     Toolkit::CheckBoxButton button = Toolkit::CheckBoxButton::New();
246     button.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
247     button.SetSizeScalePolicy( SizeScalePolicy::FIT_WITH_ASPECT_RATIO );
248     button.SetAnchorPoint( AnchorPoint::CENTER );
249     button.SetParentOrigin( ParentOrigin::CENTER );
250     button.SetProperty( Toolkit::Button::Property::SELECTED, ( currentIconIndex % 2 == 0 ) ); // Select half the button
251
252     return button;
253   }
254
255   void AddIconsToPage( Actor page )
256   {
257     Size stageSize( Stage::GetCurrent().GetSize() );
258     const float scaledHeight = stageSize.y * PAGE_SCALE_FACTOR_Y;
259     const float scaledWidth = stageSize.x * PAGE_SCALE_FACTOR_X;
260     const float PADDING = stageSize.y / 64.0f;
261     const float ROW_HEIGHT = ( scaledHeight - (PADDING*2.0f) ) / static_cast<float>( mConfig.mRows );
262     const float COL_WIDTH = ( scaledWidth - (PADDING*2.0f) ) / static_cast<float>( mConfig.mCols );
263
264     Vector2 dpi = Stage::GetCurrent().GetDpi();
265
266     static int currentIconIndex = 0;
267
268     for( int y = 0; y < mConfig.mRows; ++y )
269     {
270       for( int x = 0; x < mConfig.mCols; ++x )
271       {
272         // Create parent icon view
273         Toolkit::Control iconView = Toolkit::Control::New();
274         iconView.SetAnchorPoint( AnchorPoint::TOP_LEFT );
275         iconView.SetParentOrigin( ParentOrigin::TOP_LEFT );
276
277         if( !mConfig.mTableViewEnabled )
278         {
279           float rowX = x * COL_WIDTH + PADDING;
280           float rowY = y * ROW_HEIGHT + PADDING;
281           iconView.SetSize( Vector3( COL_WIDTH, ROW_HEIGHT, 1.0f ) );
282           iconView.SetPosition( Vector3( rowX, rowY, 0.0f ) );
283         }
284         else
285         {
286           iconView.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
287           iconView.SetSizeScalePolicy( SizeScalePolicy::FIT_WITH_ASPECT_RATIO );
288         }
289
290         Actor icon;
291
292         switch( mConfig.mIconType )
293         {
294           case CHECKBOX:
295           {
296             icon = CreateButton( currentIconIndex );
297             break;
298           }
299           case IMAGEVIEW:
300           {
301             icon = CreateImageView( currentIconIndex );
302             break;
303           }
304         }
305
306         if( mConfig.mIconLabelsEnabled )
307         {
308           // create label
309           Toolkit::TextLabel textLabel = Toolkit::TextLabel::New( DEMO_APPS_NAMES[currentIconIndex] );
310           textLabel.SetAnchorPoint( AnchorPoint::TOP_CENTER );
311           textLabel.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );
312           textLabel.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
313           textLabel.SetProperty( Toolkit::TextLabel::Property::TEXT_COLOR, Vector4( 1.0f, 1.0f, 1.0f, 1.0f ) ); // White.
314           textLabel.SetProperty( Toolkit::TextLabel::Property::POINT_SIZE, ( ( static_cast<float>( ROW_HEIGHT * LABEL_AREA ) * 72.0f )  / dpi.y ) * 0.25f );
315           textLabel.SetProperty( Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" );
316           textLabel.SetProperty( Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "TOP" );
317           icon.Add( textLabel );
318         }
319
320         iconView.Add( icon );
321         page.Add( iconView );
322
323         // We only have images and names for a certain number of icons.
324         // Wrap around if we have used them all.
325         if( ++currentIconIndex == TOTAL_ICON_DEFINITIONS )
326         {
327           currentIconIndex = 0;
328         }
329       }
330     }
331   }
332
333   void CreateScript()
334   {
335     const int lastPage = mConfig.mPageCount - 1;
336     const int halfA = lastPage / 2;
337     const int halfB = lastPage / 2 + lastPage % 2;
338     mScriptFrameData.push_back( ScriptData( lastPage,  1.5f, true  ) );
339     mScriptFrameData.push_back( ScriptData( -lastPage, 1.5f, true  ) );
340     mScriptFrameData.push_back( ScriptData( halfA,     1.0f, true  ) );
341     mScriptFrameData.push_back( ScriptData( halfB,     1.0f, true  ) );
342     mScriptFrameData.push_back( ScriptData( -lastPage, 0.5f, false ) );
343     mScriptFrameData.push_back( ScriptData( halfA,     0.5f, false ) );
344     mScriptFrameData.push_back( ScriptData( halfB,     1.0f, true  ) );
345     mScriptFrameData.push_back( ScriptData( -halfA,    1.0f, true  ) );
346     mScriptFrameData.push_back( ScriptData( 1,         0.1f, true  ) );
347     mScriptFrameData.push_back( ScriptData( -1,        0.1f, true  ) );
348     mScriptFrameData.push_back( ScriptData( 1,         0.1f, true  ) );
349     mScriptFrameData.push_back( ScriptData( -1,        0.1f, true  ) );
350     mScriptFrameData.push_back( ScriptData( 1,         0.1f, true  ) );
351     mScriptFrameData.push_back( ScriptData( -1,        0.1f, true  ) );
352     mScriptFrameData.push_back( ScriptData( halfA,     1.0f, true  ) );
353   }
354
355   void PopulatePages()
356   {
357     Vector3 stageSize( Stage::GetCurrent().GetSize() );
358
359     for( int i = 0; i < mConfig.mPageCount; ++i )
360     {
361       // Create page.
362       Actor page = AddPage();
363
364       // Populate icons.
365       AddIconsToPage( page );
366
367       // Move page 'a little bit up'.
368       page.SetParentOrigin( ParentOrigin::CENTER );
369       page.SetAnchorPoint( AnchorPoint::CENTER );
370       page.SetPosition( Vector3( stageSize.x * i, 0.0f, 0.0f ) );
371       mScrollParent.Add( page );
372
373       if( mConfig.mTableViewEnabled && mConfig.mBatchingEnabled )
374       {
375         page.SetProperty( Actor::Property::BATCH_PARENT, true );
376       }
377     }
378
379     mScrollParent.SetOpacity( 1.0f );
380     mScrollParent.SetScale( Vector3::ONE );
381
382     // Fade in.
383     ShowAnimation();
384   }
385
386   void ShowAnimation()
387   {
388     mShowAnimation = Animation::New( 1.0f );
389     mShowAnimation.AnimateTo( Property( mScrollParent, Actor::Property::COLOR_ALPHA ), 1.0f, AlphaFunction::EASE_IN_OUT );
390     mShowAnimation.AnimateTo( Property( mScrollParent, Actor::Property::SCALE ), Vector3::ONE, AlphaFunction::EASE_IN_OUT );
391     mShowAnimation.FinishedSignal().Connect( this, &HomescreenBenchmark::OnAnimationEnd );
392     mShowAnimation.Play();
393   }
394
395   void ScrollPages(int pages, float duration, bool flick)
396   {
397     duration *= PAGE_DURATION_SCALE_FACTOR;
398     Vector3 stageSize( Stage::GetCurrent().GetSize() );
399     mScrollAnimation = Animation::New( duration );
400     if( flick )
401     {
402       mScrollAnimation.AnimateBy( Property( mScrollParent, Actor::Property::POSITION ), Vector3( -stageSize.x * pages, 0.0f, 0.0f ), AlphaFunction::EASE_IN_OUT );
403     }
404     else
405     {
406       int totalPages = abs( pages );
407       for( int i = 0; i < totalPages; ++i )
408       {
409         mScrollAnimation.AnimateBy( Property( mScrollParent, Actor::Property::POSITION ), Vector3( pages < 0 ? stageSize.x : -stageSize.x, 0.0f, 0.0f ), AlphaFunction::EASE_IN_OUT, TimePeriod( duration * i, duration ) );
410       }
411     }
412     mScrollAnimation.FinishedSignal().Connect( this, &HomescreenBenchmark::OnAnimationEnd );
413     mScrollAnimation.Play();
414     mCurrentPage += pages;
415   }
416
417   void OnAnimationEnd( Animation& source )
418   {
419     if( mScriptFrame < mScriptFrameData.size() )
420     {
421       ScriptData& frame = mScriptFrameData[mScriptFrame];
422       ScrollPages( frame.mPages, frame.mDuration, frame.mFlick );
423       ++mScriptFrame;
424     }
425     else
426     {
427       mApplication.Quit();
428     }
429   }
430
431 private:
432
433   Application&                mApplication;
434   Actor                       mScrollParent;
435   Animation                   mShowAnimation;
436   Animation                   mScrollAnimation;
437   Config                      mConfig;
438   std::vector<ScriptData>     mScriptFrameData;
439   size_t                      mScriptFrame;
440   int                         mCurrentPage;
441 };
442
443 void RunTest( Application& application, const HomescreenBenchmark::Config& config, bool printHelpAndExit )
444 {
445   HomescreenBenchmark test( application, config );
446
447   if( printHelpAndExit )
448   {
449     PrintHelp( "c<num>",               " Number of columns" );
450     PrintHelp( "r<num>",               " Number of rows" );
451     PrintHelp( "p<num>",               " Number of pages ( must be greater than 1 )" );
452     PrintHelp( "-disable-tableview",   " Disables the use of TableView for layouting (must be enabled for batching)" );
453     PrintHelp( "-disable-batching",    " Disables geometry batching" );
454     PrintHelp( "-disable-icon-labels", " Disables labels for each icon" );
455     PrintHelp( "-use-checkbox",        " Uses checkboxes for icons" );
456     return;
457   }
458
459   application.MainLoop();
460 }
461
462 // Entry point for Linux & Tizen applications.
463 int DALI_EXPORT_API main( int argc, char **argv )
464 {
465   // Default settings.
466   HomescreenBenchmark::Config config;
467
468   bool printHelpAndExit = false;
469
470   for( int i = 1 ; i < argc; ++i )
471   {
472     std::string arg( argv[i] );
473     if( arg.compare( 0, 2, "-r" ) == 0 )
474     {
475       config.mRows = atoi( arg.substr( 2 ).c_str() );
476     }
477     else if( arg.compare( 0, 2, "-c" ) == 0 )
478     {
479       config.mCols = atoi( arg.substr( 2 ).c_str() );
480     }
481     else if( arg.compare( 0, 2, "-p" ) == 0 )
482     {
483       config.mPageCount = atoi( arg.substr( 2 ).c_str() );
484     }
485     else if( arg.compare( "--disable-tableview" ) == 0 )
486     {
487       config.mTableViewEnabled = false;
488     }
489     else if( arg.compare( "--disable-batching" ) == 0 )
490     {
491       config.mBatchingEnabled = false;
492     }
493     else if( arg.compare( "--disable-icon-labels" ) == 0 )
494     {
495       config.mIconLabelsEnabled = false;
496     }
497     else if( arg.compare( "--use-checkbox" ) == 0 )
498     {
499       config.mIconType = CHECKBOX;
500     }
501     else if ( arg.compare( "--help" ) == 0 )
502     {
503       printHelpAndExit = true;
504     }
505   }
506
507   Application application = Application::New( &argc, &argv );
508
509   RunTest( application, config, printHelpAndExit );
510
511   return 0;
512 }