[dali_1.2.22] Merge branch 'devel/master'
[platform/core/uifw/dali-demo.git] / examples / image-scaling-irregular-grid / image-scaling-irregular-grid-example.cpp
1 /*
2  * Copyright (c) 2017 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 /**
19  * @file image-scaling-irregular-grid-example.cpp
20  * @brief Demonstrates how to use image scaling modes when loading images.
21  *
22  * If an image is going to be drawn on-screen at a lower resolution than it is
23  * stored at on-disk, the scaling feature of the image loader can be used to
24  * reduce the image to save memory, improve performance, and potentially display
25  * a better small version of the image than if the default size were loaded.
26  *
27  * The functions CreateImage and CreateImageView below show how to build an
28  * image using a scaling mode to have %Dali resize it during loading.
29  *
30  * This demo defaults to the SCALE_TO_FILL mode of ImageAttributes which makes
31  * sure that every pixel in the loaded image is filled with a source colour
32  * from the image's central region while losing the minimum number of pixels
33  * from its periphery.
34  * It is the best option for producing thumbnails of input images that have
35  * diverse aspect ratios.
36  *
37  * The other four scaling modes of dali can be cycled-through for the whole
38  * grid  using the button in the top-right of the toolbar.
39  * A single image can be cycled by clicking the image directly.
40  *
41  * @see CreateImage CreateImageView
42  */
43
44 // EXTERNAL INCLUDES
45 #include <algorithm>
46 #include <map>
47 #include <dali-toolkit/dali-toolkit.h>
48 #include <dali-toolkit/devel-api/controls/buttons/button-devel.h>
49 #include <iostream>
50
51 // INTERNAL INCLUDES
52 #include "grid-flags.h"
53 #include "shared/view.h"
54
55 using namespace Dali;
56 using namespace Dali::Toolkit;
57 using namespace Dali::Demo;
58
59 namespace
60 {
61
62 /** Controls the output of application logging. */
63 //#define DEBUG_PRINT_DIAGNOSTICS;
64
65 const char* BACKGROUND_IMAGE( DEMO_IMAGE_DIR "background-gradient.jpg" );
66 const char* TOOLBAR_IMAGE( DEMO_IMAGE_DIR "top-bar.png" );
67 const char* APPLICATION_TITLE( "Image Scaling Modes" );
68 const char* TOGGLE_SCALING_IMAGE( DEMO_IMAGE_DIR "icon-change.png" );
69 const char* TOGGLE_SCALING_IMAGE_SELECTED( DEMO_IMAGE_DIR "icon-change-selected.png" );
70
71 /** The width of the grid in whole grid cells. */
72 const unsigned GRID_WIDTH = 9;
73 /** Limit the grid to be no higher than this in units of a cell. */
74 const unsigned GRID_MAX_HEIGHT = 600;
75
76 /** The space between the edge of a grid cell and the image embedded within it. */
77 const unsigned GRID_CELL_PADDING = 4;
78
79 /** The aspect ratio of cells in the image grid. */
80 const float CELL_ASPECT_RATIO = 1.33333333333333333333f;
81
82 const Dali::FittingMode::Type DEFAULT_SCALING_MODE = Dali::FittingMode::SCALE_TO_FILL;
83
84 /** The number of times to spin an image on touching, each spin taking a second.*/
85 const float SPIN_DURATION = 1.0f;
86
87 /** The target image sizes in grid cells. */
88 const Vector2 IMAGE_SIZES[] = {
89  Vector2( 1, 1 ),
90  Vector2( 2, 1 ),
91  Vector2( 3, 1 ),
92  Vector2( 1, 2 ),
93  Vector2( 1, 3 ),
94  Vector2( 2, 3 ),
95  Vector2( 3, 2 ),
96  // Large, tall configuration:
97  Vector2( GRID_WIDTH / 2, GRID_WIDTH + GRID_WIDTH / 2 ),
98  // Large, square-ish images to show shrink-to-fit well with wide and tall images:
99  Vector2( GRID_WIDTH / 2, GRID_WIDTH / 2.0f * CELL_ASPECT_RATIO + 0.5f ),
100  Vector2( GRID_WIDTH - 2, (GRID_WIDTH - 2) * CELL_ASPECT_RATIO + 0.5f ),
101 };
102 const unsigned NUM_IMAGE_SIZES = sizeof(IMAGE_SIZES) / sizeof(IMAGE_SIZES[0]);
103
104 /** Images to load into the grid. These are mostly large and non-square to
105  *  show the scaling. */
106 const char* IMAGE_PATHS[] = {
107
108   DEMO_IMAGE_DIR "dali-logo.png",
109   DEMO_IMAGE_DIR "com.samsung.dali-demo.ico",
110   DEMO_IMAGE_DIR "square_primitive_shapes.bmp",
111   DEMO_IMAGE_DIR "gallery-large-14.wbmp",
112
113   // Images that show aspect ratio changes clearly in primitive shapes:
114
115   DEMO_IMAGE_DIR "portrait_screen_primitive_shapes.gif",
116   DEMO_IMAGE_DIR "landscape_screen_primitive_shapes.gif",
117
118   // Images from other demos that are tall, wide or just large:
119
120   DEMO_IMAGE_DIR "gallery-large-1.jpg",
121   DEMO_IMAGE_DIR "gallery-large-2.jpg",
122   DEMO_IMAGE_DIR "gallery-large-3.jpg",
123   DEMO_IMAGE_DIR "gallery-large-4.jpg",
124   DEMO_IMAGE_DIR "gallery-large-5.jpg",
125   DEMO_IMAGE_DIR "gallery-large-6.jpg",
126   DEMO_IMAGE_DIR "gallery-large-7.jpg",
127   DEMO_IMAGE_DIR "gallery-large-8.jpg",
128   DEMO_IMAGE_DIR "gallery-large-9.jpg",
129   DEMO_IMAGE_DIR "gallery-large-10.jpg",
130   DEMO_IMAGE_DIR "gallery-large-11.jpg",
131   DEMO_IMAGE_DIR "gallery-large-12.jpg",
132   DEMO_IMAGE_DIR "gallery-large-13.jpg",
133   DEMO_IMAGE_DIR "gallery-large-14.jpg",
134   DEMO_IMAGE_DIR "gallery-large-15.jpg",
135   DEMO_IMAGE_DIR "gallery-large-16.jpg",
136   DEMO_IMAGE_DIR "gallery-large-17.jpg",
137   DEMO_IMAGE_DIR "gallery-large-18.jpg",
138   DEMO_IMAGE_DIR "gallery-large-19.jpg",
139   DEMO_IMAGE_DIR "gallery-large-20.jpg",
140   DEMO_IMAGE_DIR "gallery-large-21.jpg",
141
142   DEMO_IMAGE_DIR "background-1.jpg",
143   DEMO_IMAGE_DIR "background-2.jpg",
144   DEMO_IMAGE_DIR "background-3.jpg",
145   DEMO_IMAGE_DIR "background-4.jpg",
146   DEMO_IMAGE_DIR "background-5.jpg",
147   DEMO_IMAGE_DIR "background-blocks.jpg",
148   DEMO_IMAGE_DIR "background-magnifier.jpg",
149
150   DEMO_IMAGE_DIR "background-1.jpg",
151   DEMO_IMAGE_DIR "background-2.jpg",
152   DEMO_IMAGE_DIR "background-3.jpg",
153   DEMO_IMAGE_DIR "background-4.jpg",
154   DEMO_IMAGE_DIR "background-5.jpg",
155   DEMO_IMAGE_DIR "background-blocks.jpg",
156   DEMO_IMAGE_DIR "background-magnifier.jpg",
157
158   DEMO_IMAGE_DIR "book-landscape-cover-back.jpg",
159   DEMO_IMAGE_DIR "book-landscape-cover.jpg",
160   DEMO_IMAGE_DIR "book-landscape-p1.jpg",
161   DEMO_IMAGE_DIR "book-landscape-p2.jpg",
162
163   DEMO_IMAGE_DIR "book-portrait-cover.jpg",
164   DEMO_IMAGE_DIR "book-portrait-p1.jpg",
165   DEMO_IMAGE_DIR "book-portrait-p2.jpg",
166   NULL
167 };
168 const unsigned NUM_IMAGE_PATHS = sizeof(IMAGE_PATHS) / sizeof(IMAGE_PATHS[0]) - 1u;
169
170
171 /**
172  * Creates an Image
173  *
174  * @param[in] filename The path of the image.
175  * @param[in] width The width of the image in pixels.
176  * @param[in] height The height of the image in pixels.
177  * @param[in] fittingMode The mode to use when scaling the image to fit the desired dimensions.
178  */
179 Image CreateImage(const std::string& filename, unsigned int width, unsigned int height, Dali::FittingMode::Type fittingMode )
180 {
181 #ifdef DEBUG_PRINT_DIAGNOSTICS
182     fprintf( stderr, "CreateImage(%s, %u, %u, fittingMode=%u)\n", filename.c_str(), width, height, unsigned( fittingMode ) );
183 #endif
184   Image image = ResourceImage::New( filename, ImageDimensions( width, height ), fittingMode, Dali::SamplingMode::BOX_THEN_LINEAR );
185
186   return image;
187 }
188
189 /**
190  * Creates an ImageView
191  *
192  * @param[in] filename The path of the image.
193  * @param[in] width The width of the image in pixels.
194  * @param[in] height The height of the image in pixels.
195  * @param[in] fittingMode The mode to use when scaling the image to fit the desired dimensions.
196  */
197 ImageView CreateImageView(const std::string& filename, unsigned int width, unsigned int height, Dali::FittingMode::Type fittingMode )
198 {
199   Image img = CreateImage( filename, width, height, fittingMode );
200   ImageView actor = ImageView::New( img );
201   actor.SetName( filename );
202   actor.SetParentOrigin(ParentOrigin::CENTER);
203   actor.SetAnchorPoint(AnchorPoint::CENTER);
204
205   return actor;
206 }
207
208 /** Cycle the scaling mode options. */
209 Dali::FittingMode::Type NextMode( const Dali::FittingMode::Type oldMode )
210 {
211   Dali::FittingMode::Type newMode = FittingMode::SHRINK_TO_FIT;
212   switch ( oldMode )
213   {
214     case FittingMode::SHRINK_TO_FIT:
215       newMode = FittingMode::SCALE_TO_FILL;
216       break;
217     case FittingMode::SCALE_TO_FILL:
218       newMode = FittingMode::FIT_WIDTH;
219       break;
220     case FittingMode::FIT_WIDTH:
221       newMode = FittingMode::FIT_HEIGHT;
222       break;
223     case FittingMode::FIT_HEIGHT:
224       newMode = FittingMode::SHRINK_TO_FIT;
225       break;
226   }
227   return newMode;
228 }
229
230 /**
231  * Bundle an image path with the rectangle to pack it into.
232  * */
233 struct ImageConfiguration
234 {
235   ImageConfiguration( const char * const path, const Vector2 dimensions ) :
236     path( path ),
237     dimensions( dimensions )
238   {}
239   const char * path;
240   Vector2 dimensions;
241 };
242
243 /**
244  * Post-layout image data.
245  */
246 struct PositionedImage
247 {
248   PositionedImage(ImageConfiguration& configuration, unsigned cellX, unsigned cellY, Vector2 imageGridDims) :
249     configuration( configuration ),
250     cellX( cellX ),
251     cellY( cellY ),
252     imageGridDims( imageGridDims )
253   {}
254
255   ImageConfiguration configuration;
256   unsigned cellX;
257   unsigned cellY;
258   Vector2 imageGridDims;
259 };
260
261 }
262
263 /**
264  * @brief The main class of the demo.
265  */
266 class ImageScalingIrregularGridController : public ConnectionTracker
267 {
268 public:
269
270   ImageScalingIrregularGridController( Application& application )
271   : mApplication( application ),
272     mScrolling( false )
273   {
274     std::cout << "ImageScalingIrregularGridController::ImageScalingIrregularGridController" << std::endl;
275
276     // Connect to the Application's Init signal
277     mApplication.InitSignal().Connect( this, &ImageScalingIrregularGridController::Create );
278   }
279
280   ~ImageScalingIrregularGridController()
281   {
282     // Nothing to do here.
283   }
284
285   /**
286    * One-time setup in response to Application InitSignal.
287    */
288   void Create( Application& application )
289   {
290     std::cout << "ImageScalingIrregularGridController::Create" << std::endl;
291
292     // Get a handle to the stage:
293     Stage stage = Stage::GetCurrent();
294
295     // Connect to input event signals:
296     stage.KeyEventSignal().Connect(this, &ImageScalingIrregularGridController::OnKeyEvent);
297
298     // Hide the indicator bar
299     mApplication.GetWindow().ShowIndicator(Dali::Window::INVISIBLE);
300
301     // Create a default view with a default tool bar:
302     mContentLayer = DemoHelper::CreateView( mApplication,
303                                             mView,
304                                             mToolBar,
305                                             BACKGROUND_IMAGE,
306                                             TOOLBAR_IMAGE,
307                                             "" );
308
309     // Create an image scaling toggle button. (right of toolbar)
310     Toolkit::PushButton toggleScalingButton = Toolkit::PushButton::New();
311     toggleScalingButton.SetProperty( Toolkit::DevelButton::Property::UNSELECTED_BACKGROUND_VISUAL, TOGGLE_SCALING_IMAGE );
312     toggleScalingButton.SetProperty( Toolkit::DevelButton::Property::SELECTED_BACKGROUND_VISUAL, TOGGLE_SCALING_IMAGE_SELECTED );
313     toggleScalingButton.ClickedSignal().Connect( this, &ImageScalingIrregularGridController::OnToggleScalingTouched );
314     mToolBar.AddControl( toggleScalingButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalRight, DemoHelper::DEFAULT_MODE_SWITCH_PADDING  );
315
316     SetTitle( APPLICATION_TITLE );
317
318     // Build the main content of the widow:
319     PopulateContentLayer( DEFAULT_SCALING_MODE );
320   }
321
322   /**
323    * Build the main part of the application's view.
324    */
325   void PopulateContentLayer( const Dali::FittingMode::Type fittingMode )
326   {
327     Stage stage = Stage::GetCurrent();
328     Vector2 stageSize = stage.GetSize();
329
330     float fieldHeight;
331     Actor imageField = BuildImageField( stageSize.x, GRID_WIDTH, GRID_MAX_HEIGHT, fittingMode, fieldHeight );
332
333     mScrollView = ScrollView::New();
334
335     mScrollView.ScrollStartedSignal().Connect( this, &ImageScalingIrregularGridController::OnScrollStarted );
336     mScrollView.ScrollCompletedSignal().Connect( this, &ImageScalingIrregularGridController::OnScrollCompleted );
337
338     mScrollView.SetAnchorPoint(AnchorPoint::CENTER);
339     mScrollView.SetParentOrigin(ParentOrigin::CENTER);
340
341     mScrollView.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
342
343     mScrollView.SetAxisAutoLock( true );
344     mScrollView.SetAxisAutoLockGradient( 1.0f );
345
346     // Restrict scrolling to mostly vertical only, but with some horizontal wiggle-room:
347
348     RulerPtr rulerX = new FixedRuler( stageSize.width ); //< Pull the view back to the grid's centre-line when touch is release using a snapping ruler.
349     rulerX->SetDomain( RulerDomain( stageSize.width * -0.125f, stageSize.width * 1.125f ) ); //< Scroll slightly left/right of image field.
350     mScrollView.SetRulerX ( rulerX );
351
352     RulerPtr rulerY = new DefaultRuler(); //< Snap in multiples of a screen / stage height
353     rulerY->SetDomain( RulerDomain( - fieldHeight * 0.5f + stageSize.height * 0.5f - GRID_CELL_PADDING, fieldHeight * 0.5f + stageSize.height * 0.5f + GRID_CELL_PADDING ) );
354     mScrollView.SetRulerY ( rulerY );
355
356     mContentLayer.Add( mScrollView );
357     mScrollView.Add( imageField );
358     mGridActor = imageField;
359
360     // Create the scroll bar
361     mScrollBarVertical = ScrollBar::New(Toolkit::ScrollBar::Vertical);
362     mScrollBarVertical.SetParentOrigin(ParentOrigin::TOP_RIGHT);
363     mScrollBarVertical.SetAnchorPoint(AnchorPoint::TOP_RIGHT);
364     mScrollBarVertical.SetResizePolicy(Dali::ResizePolicy::FILL_TO_PARENT, Dali::Dimension::HEIGHT);
365     mScrollBarVertical.SetResizePolicy(Dali::ResizePolicy::FIT_TO_CHILDREN, Dali::Dimension::WIDTH);
366     mScrollView.Add(mScrollBarVertical);
367
368     mScrollBarHorizontal = ScrollBar::New(Toolkit::ScrollBar::Horizontal);
369     mScrollBarHorizontal.SetParentOrigin(ParentOrigin::BOTTOM_LEFT);
370     mScrollBarHorizontal.SetAnchorPoint(AnchorPoint::TOP_LEFT);
371     mScrollBarHorizontal.SetResizePolicy(Dali::ResizePolicy::FIT_TO_CHILDREN, Dali::Dimension::WIDTH);
372     mScrollBarHorizontal.SetOrientation(Quaternion(Radian( 1.5f * Math::PI ), Vector3::ZAXIS));
373     mScrollView.Add(mScrollBarHorizontal);
374
375     mScrollView.OnRelayoutSignal().Connect( this, &ImageScalingIrregularGridController::OnScrollViewRelayout );
376
377     // Scroll to top of grid so first images loaded are on-screen:
378     mScrollView.ScrollTo( Vector2( 0, -1000000 ) );
379   }
380
381   void OnScrollViewRelayout(Actor actor)
382   {
383     // Make the height of the horizontal scroll bar to be the same as the width of scroll view.
384     mScrollBarHorizontal.SetSize(Vector2(0.0f, mScrollView.GetRelayoutSize( Dimension::WIDTH) ));
385   }
386
387   /**
388    * Build a field of images scaled into a variety of shapes from very wide,
389    * through square, to very tall. The images are direct children of the Dali::Actor
390    * returned.
391    **/
392   Actor BuildImageField( const float fieldWidth,
393                            const unsigned gridWidth,
394                            const unsigned maxGridHeight,
395                            Dali::FittingMode::Type fittingMode,
396                            float & outFieldHeight )
397   {
398     // Generate the list of image configurations to be fitted into the field:
399
400     std::vector<ImageConfiguration> configurations;
401     configurations.reserve( NUM_IMAGE_PATHS * NUM_IMAGE_SIZES );
402     for( unsigned imageIndex = 0; imageIndex < NUM_IMAGE_PATHS; ++imageIndex )
403     {
404       for( unsigned dimensionsIndex = 0; dimensionsIndex < NUM_IMAGE_SIZES; ++ dimensionsIndex )
405       {
406         configurations.push_back( ImageConfiguration( IMAGE_PATHS[imageIndex], IMAGE_SIZES[dimensionsIndex] ) );
407       }
408     }
409     // Stir-up the list to get some nice irregularity in the generated field:
410     std::random_shuffle( configurations.begin(), configurations.end() );
411     std::random_shuffle( configurations.begin(), configurations.end() );
412
413     // Place the images in the grid:
414
415     std::vector<ImageConfiguration>::iterator config, end;
416     GridFlags grid( gridWidth, maxGridHeight );
417     std::vector<PositionedImage> placedImages;
418
419     for( config = configurations.begin(), end = configurations.end(); config != end; ++config )
420     {
421       unsigned cellX, cellY;
422       Vector2 imageGridDims;
423
424       // Allocate a region of the grid for the image:
425       bool allocated = grid.AllocateRegion( config->dimensions, cellX, cellY, imageGridDims );
426       if( !allocated )
427       {
428 #ifdef DEBUG_PRINT_DIAGNOSTICS
429           fprintf( stderr, "Failed to allocate image in grid with dims (%f, %f) and path: %s.\n", config->dimensions.x, config->dimensions.y, config->path );
430 #endif
431         continue;
432       }
433
434       placedImages.push_back( PositionedImage( *config, cellX, cellY, imageGridDims ) );
435     }
436     DALI_ASSERT_DEBUG( grid.DebugCheckGridValid() && "Cells were set more than once, indicating erroneous overlap in placing images on the grid." );
437     const unsigned actualGridHeight = grid.GetHighestUsedRow() + 1;
438
439     // Take the images images in the grid and turn their logical locations into
440     // coordinates in a frame defined by a parent actor:
441
442     Actor gridActor = Actor::New();
443     gridActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
444     gridActor.SetParentOrigin( ParentOrigin::CENTER );
445     gridActor.SetAnchorPoint( AnchorPoint::CENTER );
446
447     // Work out the constants of the grid and cell dimensions and positions:
448     const float cellWidth = fieldWidth / gridWidth;
449     const float cellHeight = cellWidth / CELL_ASPECT_RATIO;
450     const Vector2 cellSize = Vector2( cellWidth, cellHeight );
451     outFieldHeight = actualGridHeight * cellHeight;
452     const Vector2 gridOrigin = Vector2( -fieldWidth * 0.5f, -outFieldHeight * 0.5 );
453
454     // Build the image actors in their right locations in their parent's frame:
455     for( std::vector<PositionedImage>::const_iterator i = placedImages.begin(), end = placedImages.end(); i != end; ++i )
456     {
457       const PositionedImage& imageSource = *i;
458       const Vector2 imageSize = imageSource.imageGridDims * cellSize - Vector2( GRID_CELL_PADDING * 2, GRID_CELL_PADDING * 2 );
459       const Vector2 imageRegionCorner = gridOrigin + cellSize * Vector2( imageSource.cellX, imageSource.cellY );
460       const Vector2 imagePosition = imageRegionCorner + Vector2( GRID_CELL_PADDING , GRID_CELL_PADDING ) + imageSize * 0.5f;
461
462       ImageView image = CreateImageView( imageSource.configuration.path, imageSize.x, imageSize.y, fittingMode );
463       image.SetPosition( Vector3( imagePosition.x, imagePosition.y, 0 ) );
464       image.SetSize( imageSize );
465       image.TouchSignal().Connect( this, &ImageScalingIrregularGridController::OnTouchImage );
466       mFittingModes[image.GetId()] = fittingMode;
467       mResourceUrls[image.GetId()] = imageSource.configuration.path;
468       mSizes[image.GetId()] = imageSize;
469
470       gridActor.Add( image );
471     }
472
473     return gridActor;
474   }
475
476  /**
477   * Upon Touching an image (Release), change its scaling mode and make it spin, provided we're not scrolling.
478   * @param[in] actor The actor touched
479   * @param[in] event The Touch information.
480   */
481   bool OnTouchImage( Actor actor, const TouchData& event )
482   {
483     if( ( event.GetPointCount() > 0 ) && ( !mScrolling ) )
484     {
485       if( event.GetState( 0 ) == PointState::UP )
486       {
487         // Spin the image a few times:
488         Animation animation = Animation::New(SPIN_DURATION);
489         animation.AnimateBy( Property( actor, Actor::Property::ORIENTATION ), Quaternion( Radian( Degree(360.0f * SPIN_DURATION) ), Vector3::XAXIS ), AlphaFunction::EASE_OUT );
490         animation.Play();
491
492         // Change the scaling mode:
493         const unsigned id = actor.GetId();
494         Dali::FittingMode::Type newMode = NextMode( mFittingModes[id] );
495         const Vector2 imageSize = mSizes[actor.GetId()];
496
497         const std::string& url = mResourceUrls[id];
498         Image newImage = CreateImage( url, imageSize.width + 0.5f, imageSize.height + 0.5f, newMode );
499         ImageView imageView = ImageView::DownCast( actor );
500         if(imageView)
501         {
502           imageView.SetImage( newImage );
503         }
504         mFittingModes[id] = newMode;
505       }
506     }
507     return false;
508   }
509
510  /**
511   * Main key event handler.
512   * Quit on escape key.
513   */
514   void OnKeyEvent(const KeyEvent& event)
515   {
516     if( event.state == KeyEvent::Down )
517     {
518       if( IsKey( event, Dali::DALI_KEY_ESCAPE )
519           || IsKey( event, Dali::DALI_KEY_BACK ) )
520       {
521         mApplication.Quit();
522       }
523     }
524   }
525
526  /**
527   * Signal handler, called when the 'Scaling' button has been touched.
528   *
529   * @param[in] button The button that was pressed.
530   */
531   bool OnToggleScalingTouched( Button button )
532   {
533     const unsigned numChildren = mGridActor.GetChildCount();
534
535     for( unsigned i = 0; i < numChildren; ++i )
536     {
537       ImageView gridImageView = ImageView::DownCast( mGridActor.GetChildAt( i ) );
538       if( gridImageView )
539       {
540         // Cycle the scaling mode options:
541         unsigned int id = gridImageView.GetId();
542
543         const Vector2 imageSize = mSizes[ id ];
544         Dali::FittingMode::Type newMode = NextMode( mFittingModes[ id ] );
545         Image newImage = CreateImage( mResourceUrls[ id ], imageSize.width, imageSize.height, newMode );
546         gridImageView.SetImage( newImage );
547
548         mFittingModes[ id ] = newMode;
549
550         SetTitle( std::string( newMode == FittingMode::SHRINK_TO_FIT ? "SHRINK_TO_FIT" : newMode == FittingMode::SCALE_TO_FILL ?  "SCALE_TO_FILL" : newMode == FittingMode::FIT_WIDTH ? "FIT_WIDTH" : "FIT_HEIGHT" ) );
551       }
552     }
553     return true;
554   }
555
556   /**
557    * Sets/Updates the title of the View
558    * @param[in] title The new title for the view.
559    */
560   void SetTitle(const std::string& title)
561   {
562     if(!mTitleActor)
563     {
564       mTitleActor = DemoHelper::CreateToolBarLabel( "" );
565       // Add title to the tool bar.
566       mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
567     }
568
569     mTitleActor.SetProperty( TextLabel::Property::TEXT, title );
570   }
571
572   /**
573    * When scroll starts (i.e. user starts to drag scrollview),
574    * note this state (mScrolling = true)
575    * @param[in] position Current Scroll Position
576    */
577   void OnScrollStarted( const Vector2& position )
578   {
579     mScrolling = true;
580   }
581
582   /**
583    * When scroll starts (i.e. user stops dragging scrollview, and scrollview has snapped to destination),
584    * note this state (mScrolling = false).
585    * @param[in] position Current Scroll Position
586    */
587   void OnScrollCompleted( const Vector2& position )
588   {
589     mScrolling = false;
590   }
591
592 private:
593   Application&  mApplication;
594
595   Layer mContentLayer;                ///< The content layer (contains non gui chrome actors)
596   Toolkit::Control mView;             ///< The View instance.
597   Toolkit::ToolBar mToolBar;          ///< The View's Toolbar.
598   TextLabel mTitleActor;               ///< The Toolbar's Title.
599   Actor mGridActor;                   ///< The container for the grid of images
600   ScrollView mScrollView;             ///< ScrollView UI Component
601   ScrollBar mScrollBarVertical;
602   ScrollBar mScrollBarHorizontal;
603   bool mScrolling;                    ///< ScrollView scrolling state (true = scrolling, false = stationary)
604   std::map<unsigned, Dali::FittingMode::Type> mFittingModes; ///< Stores the current scaling mode of each image, keyed by image actor id.
605   std::map<unsigned, std::string> mResourceUrls; ///< Stores the url of each image, keyed by image actor id.
606   std::map<unsigned, Vector2> mSizes; ///< Stores the current size of each image, keyed by image actor id.
607 };
608
609 void RunTest( Application& application )
610 {
611   ImageScalingIrregularGridController test( application );
612
613   application.MainLoop();
614 }
615
616 /** Entry point for Linux & Tizen applications */
617 int DALI_EXPORT_API main( int argc, char **argv )
618 {
619   Application application = Application::New( &argc, &argv, DEMO_THEME_PATH );
620
621   RunTest( application );
622
623   return 0;
624 }