45c494953acc2550d134996fae902b595afa5712
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / image-view / image-view-impl.cpp
1 /*
2  * Copyright (c) 2020 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 "image-view-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/images/resource-image.h>
23 #include <dali/public-api/object/type-registry.h>
24 #include <dali/public-api/object/type-registry-helper.h>
25 #include <dali/devel-api/scripting/scripting.h>
26
27 // INTERNAL INCLUDES
28 #include <dali-toolkit/public-api/controls/image-view/image-view.h>
29 #include <dali-toolkit/devel-api/controls/control-devel.h>
30 #include <dali-toolkit/public-api/visuals/visual-properties.h>
31 #include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
32 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
33 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
34 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
35
36 namespace Dali
37 {
38
39 namespace Toolkit
40 {
41
42 namespace Internal
43 {
44
45 namespace
46 {
47
48 const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
49
50 BaseHandle Create()
51 {
52   return Toolkit::ImageView::New();
53 }
54
55 // Setup properties, signals and actions using the type-registry.
56 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ImageView, Toolkit::Control, Create );
57 DALI_PROPERTY_REGISTRATION( Toolkit, ImageView, "reservedProperty01", STRING, RESERVED_PROPERTY_01 )
58 DALI_PROPERTY_REGISTRATION( Toolkit, ImageView, "image", MAP, IMAGE )
59 DALI_PROPERTY_REGISTRATION( Toolkit, ImageView, "preMultipliedAlpha", BOOLEAN, PRE_MULTIPLIED_ALPHA )
60
61 DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT( Toolkit, ImageView, "pixelArea", Vector4(0.f, 0.f, 1.f, 1.f), PIXEL_AREA )
62 DALI_TYPE_REGISTRATION_END()
63
64 } // anonymous namespace
65
66 using namespace Dali;
67
68 ImageView::ImageView()
69 : Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
70   mImageSize(),
71   mImageVisualPaddingSetByTransform( false ),
72   mImageViewPixelAreaSetByFittingMode( false )
73 {
74 }
75
76 ImageView::~ImageView()
77 {
78 }
79
80 Toolkit::ImageView ImageView::New()
81 {
82   ImageView* impl = new ImageView();
83
84   Toolkit::ImageView handle = Toolkit::ImageView( *impl );
85
86   // Second-phase init of the implementation
87   // This can only be done after the CustomActor connection has been made...
88   impl->Initialize();
89
90   return handle;
91 }
92
93 /////////////////////////////////////////////////////////////
94
95 void ImageView::OnInitialize()
96 {
97   // ImageView can relayout in the OnImageReady, alternative to a signal would be to have a upcall from the Control to ImageView
98   Dali::Toolkit::Control handle( GetOwner() );
99   handle.ResourceReadySignal().Connect( this, &ImageView::OnResourceReady );
100 }
101
102 void ImageView::SetImage( Image image )
103 {
104   // Don't bother comparing if we had a visual previously, just drop old visual and create new one
105   mImage = image;
106   mUrl.clear();
107   mPropertyMap.Clear();
108
109   Toolkit::Visual::Base visual =  Toolkit::VisualFactory::Get().CreateVisual( image );
110   if( visual )
111   {
112     if( !mVisual )
113     {
114       mVisual = visual;
115     }
116
117     if( !mShaderMap.Empty() )
118     {
119       Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
120       visualImpl.SetCustomShader( mShaderMap );
121     }
122
123     DevelControl::RegisterVisual( *this, Toolkit::ImageView::Property::IMAGE, visual );
124   }
125   else
126   {
127     // Unregister the existing visual
128     DevelControl::UnregisterVisual( *this, Toolkit::ImageView::Property::IMAGE );
129
130     // Trigger a size negotiation request that may be needed when unregistering a visual.
131     RelayoutRequest();
132   }
133
134   // Signal that a Relayout may be needed
135 }
136
137 void ImageView::SetImage( const Property::Map& map )
138 {
139   // Comparing a property map is too expensive so just creating a new visual
140   mPropertyMap = map;
141   mUrl.clear();
142   mImage.Reset();
143
144   Toolkit::Visual::Base visual =  Toolkit::VisualFactory::Get().CreateVisual( mPropertyMap );
145   if( visual )
146   {
147     // Don't set mVisual until it is ready and shown. Getters will still use current visual.
148     if( !mVisual )
149     {
150       mVisual = visual;
151     }
152
153     if( !mShaderMap.Empty() )
154     {
155       Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
156       visualImpl.SetCustomShader( mShaderMap );
157     }
158
159     DevelControl::RegisterVisual( *this, Toolkit::ImageView::Property::IMAGE, visual  );
160   }
161   else
162   {
163     // Unregister the exsiting visual
164     DevelControl::UnregisterVisual( *this, Toolkit::ImageView::Property::IMAGE );
165
166     // Trigger a size negotiation request that may be needed when unregistering a visual.
167     RelayoutRequest();
168   }
169
170   // Signal that a Relayout may be needed
171 }
172
173 void ImageView::SetImage( const std::string& url, ImageDimensions size )
174 {
175   // Don't bother comparing if we had a visual previously, just drop old visual and create new one
176   mUrl = url;
177   mImageSize = size;
178   mImage.Reset();
179   mPropertyMap.Clear();
180
181   // Don't set mVisual until it is ready and shown. Getters will still use current visual.
182   Toolkit::Visual::Base visual =  Toolkit::VisualFactory::Get().CreateVisual( url, size );
183   if( visual )
184   {
185     if( !mVisual )
186     {
187       mVisual = visual;
188     }
189
190     if( !mShaderMap.Empty() )
191     {
192       Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
193       visualImpl.SetCustomShader( mShaderMap );
194     }
195
196     DevelControl::RegisterVisual( *this, Toolkit::ImageView::Property::IMAGE, visual );
197   }
198   else
199   {
200     // Unregister the exsiting visual
201     DevelControl::UnregisterVisual( *this, Toolkit::ImageView::Property::IMAGE );
202
203     // Trigger a size negotiation request that may be needed when unregistering a visual.
204     RelayoutRequest();
205   }
206
207   // Signal that a Relayout may be needed
208 }
209
210 Image ImageView::GetImage() const
211 {
212   return mImage;
213 }
214
215 void ImageView::EnablePreMultipliedAlpha( bool preMultipled )
216 {
217   if( mVisual )
218   {
219     Toolkit::GetImplementation( mVisual ).EnablePreMultipliedAlpha( preMultipled );
220   }
221 }
222
223 bool ImageView::IsPreMultipliedAlphaEnabled() const
224 {
225   if( mVisual )
226   {
227     return Toolkit::GetImplementation( mVisual ).IsPreMultipliedAlphaEnabled();
228   }
229   return false;
230 }
231
232 void ImageView::SetDepthIndex( int depthIndex )
233 {
234   if( mVisual )
235   {
236     mVisual.SetDepthIndex( depthIndex );
237   }
238 }
239
240 void ImageView::OnStageConnection( int depth )
241 {
242   if( mImage )
243   {
244     mImage.UploadedSignal().Emit( mImage );
245   }
246
247   Dali::ResourceImage resourceImage = Dali::ResourceImage::DownCast( mImage );
248   if( resourceImage )
249   {
250     resourceImage.LoadingFinishedSignal().Emit( resourceImage );
251   }
252
253   Control::OnStageConnection( depth ); // Enabled visuals will be put on stage
254 }
255
256 Vector3 ImageView::GetNaturalSize()
257 {
258   if( mVisual )
259   {
260     Vector2 rendererNaturalSize;
261     mVisual.GetNaturalSize( rendererNaturalSize );
262
263     Extents padding;
264     padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
265
266     rendererNaturalSize.width += ( padding.start + padding.end );
267     rendererNaturalSize.height += ( padding.top + padding.bottom );
268     return Vector3( rendererNaturalSize );
269   }
270
271   // if no visual then use Control's natural size
272   return Control::GetNaturalSize();
273 }
274
275 float ImageView::GetHeightForWidth( float width )
276 {
277   Extents padding;
278   padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
279
280   if( mVisual )
281   {
282     return mVisual.GetHeightForWidth( width ) + padding.top + padding.bottom;
283   }
284   else
285   {
286     return Control::GetHeightForWidth( width ) + padding.top + padding.bottom;
287   }
288 }
289
290 float ImageView::GetWidthForHeight( float height )
291 {
292   Extents padding;
293   padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
294
295   if( mVisual )
296   {
297     return mVisual.GetWidthForHeight( height ) + padding.start + padding.end;
298   }
299   else
300   {
301     return Control::GetWidthForHeight( height ) + padding.start + padding.end;
302   }
303 }
304
305 void ImageView::OnRelayout( const Vector2& size, RelayoutContainer& container )
306 {
307   Control::OnRelayout( size, container );
308   if( mVisual )
309   {
310     Property::Map transformMap = Property::Map();
311
312     Extents padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
313
314     bool zeroPadding = ( padding == Extents() );
315
316     Vector2 naturalSize;
317     mVisual.GetNaturalSize( naturalSize );
318
319     Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(
320           Self().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
321     if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
322     {
323       std::swap( padding.start, padding.end );
324     }
325
326     // remove padding from the size to know how much is left for the visual
327     Vector2 finalSize = size - Vector2( padding.start + padding.end, padding.top + padding.bottom );
328     Vector2 finalOffset = Vector2( padding.start, padding.top );
329
330     ApplyFittingMode( finalSize, naturalSize, finalOffset, zeroPadding , transformMap );
331
332     mVisual.SetTransformAndSize( transformMap, size );
333
334     // mVisual is not updated util the resource is ready in the case of visual replacement.
335     // So apply the transform and size to the new visual.
336     Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::ImageView::Property::IMAGE );
337     if( visual && visual != mVisual )
338     {
339       visual.SetTransformAndSize( transformMap, size );
340     }
341   }
342 }
343
344 void ImageView::OnResourceReady( Toolkit::Control control )
345 {
346   // Visual ready so update visual attached to this ImageView, following call to RelayoutRequest will use this visual.
347   mVisual = DevelControl::GetVisual( *this, Toolkit::ImageView::Property::IMAGE );
348   // Signal that a Relayout may be needed
349 }
350
351 void ImageView::SetTransformMapForFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, Visual::FittingMode fittingMode, Property::Map& transformMap )
352 {
353   switch(fittingMode)
354   {
355     case Visual::FittingMode::FIT_KEEP_ASPECT_RATIO:
356     {
357       auto availableVisualSize = finalSize;
358
359       // scale to fit the padded area
360       finalSize = naturalSize * std::min( ( naturalSize.width  ? ( availableVisualSize.width  / naturalSize.width  ) : 0 ),
361                                             ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
362
363       // calculate final offset within the padded area
364       finalOffset += ( availableVisualSize - finalSize ) * .5f;
365
366       // populate the transform map
367       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
368                   .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
369       break;
370     }
371     case Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO:
372     {
373       mImageViewPixelAreaSetByFittingMode = true;
374       auto availableVisualSize = finalSize;
375       finalSize = naturalSize * std::max( ( naturalSize.width  ? ( availableVisualSize.width  / naturalSize.width  ) : 0 ),
376                                           ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
377
378       auto originalOffset = finalOffset;
379       finalOffset += ( availableVisualSize - finalSize ) * .5f;
380
381       float x = abs( (availableVisualSize.width - finalSize.width ) / finalSize.width )* .5f;
382       float y = abs( (availableVisualSize.height - finalSize.height ) / finalSize.height ) * .5f;
383       float widthRatio = 1.f - abs( (availableVisualSize.width - finalSize.width ) / finalSize.width );
384       float heightRatio = 1.f - abs( (availableVisualSize.height - finalSize.height ) / finalSize.height );
385       Vector4 pixelArea = Vector4( x, y, widthRatio, heightRatio);
386       Self().SetProperty( Toolkit::ImageView::Property::PIXEL_AREA, pixelArea );
387
388       // populate the transform map
389       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, originalOffset )
390                   .Add( Toolkit::Visual::Transform::Property::SIZE, availableVisualSize );
391       break;
392     }
393     case Visual::FittingMode::CENTER:
394     {
395       auto availableVisualSize = finalSize;
396       if( availableVisualSize.width > naturalSize.width && availableVisualSize.height > naturalSize.height )
397       {
398         finalSize = naturalSize;
399       }
400       else
401       {
402         finalSize = naturalSize * std::min( ( naturalSize.width  ? ( availableVisualSize.width  / naturalSize.width  ) : 0 ),
403                                           ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
404       }
405
406       finalOffset += ( availableVisualSize - finalSize ) * .5f;
407
408       // populate the transform map
409       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
410                   .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
411       break;
412     }
413     case Visual::FittingMode::FILL:
414     {
415       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
416                   .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
417       break;
418     }
419     case Visual::FittingMode::FIT_WIDTH:
420     case Visual::FittingMode::FIT_HEIGHT:
421     {
422       // This FittingMode already converted
423       break;
424     }
425   }
426 }
427
428 void ImageView::ApplyFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, bool zeroPadding , Property::Map& transformMap )
429 {
430     Visual::FittingMode fittingMode = Toolkit::GetImplementation(mVisual).GetFittingMode();
431
432     // Reset PIXEL_AREA after using OVER_FIT_KEEP_ASPECT_RATIO
433     if( mImageViewPixelAreaSetByFittingMode )
434     {
435       Self().SetProperty( Toolkit::ImageView::Property::PIXEL_AREA, FULL_TEXTURE_RECT );
436       mImageViewPixelAreaSetByFittingMode = false;
437     }
438
439     if( ( !zeroPadding ) || // If padding is not zero
440         ( fittingMode != Visual::FittingMode::FILL ) )
441     {
442       mImageVisualPaddingSetByTransform = true;
443
444       // If FittingMode use FIT_WIDTH or FIT_HEIGTH, it need to change proper fittingMode
445       if( fittingMode == Visual::FittingMode::FIT_WIDTH )
446       {
447         fittingMode = ( finalSize.height  / naturalSize.height ) < ( finalSize.width / naturalSize.width ) ? Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::FIT_KEEP_ASPECT_RATIO;
448       }
449       else if( fittingMode == Visual::FittingMode::FIT_HEIGHT )
450       {
451         fittingMode = ( finalSize.height  / naturalSize.height ) < ( finalSize.width / naturalSize.width ) ? Visual::FittingMode::FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO;
452       }
453
454       SetTransformMapForFittingMode( finalSize, naturalSize, finalOffset, fittingMode, transformMap );
455
456       // Set extra value for applying transformMap
457       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY,
458                         Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
459                   .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN )
460                   .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN )
461                   .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY,
462                         Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) );
463     }
464     else if ( mImageVisualPaddingSetByTransform && zeroPadding )  // Reset offset to zero only if padding applied previously
465     {
466       mImageVisualPaddingSetByTransform = false;
467       // Reset the transform map
468       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, Vector2::ZERO )
469                   .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY,
470                         Vector2( Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE ) )
471                   .Add( Toolkit::Visual::Transform::Property::SIZE, Vector2::ONE )
472                   .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY,
473                         Vector2( Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE ) );
474     }
475 }
476
477 ///////////////////////////////////////////////////////////
478 //
479 // Properties
480 //
481
482 void ImageView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
483 {
484   Toolkit::ImageView imageView = Toolkit::ImageView::DownCast( Dali::BaseHandle( object ) );
485
486   if ( imageView )
487   {
488     ImageView& impl = GetImpl( imageView );
489     switch ( index )
490     {
491       case Toolkit::ImageView::Property::IMAGE:
492       {
493         std::string imageUrl;
494         Property::Map* map;
495         if( value.Get( imageUrl ) )
496         {
497           impl.SetImage( imageUrl, ImageDimensions() );
498         }
499         // if its not a string then get a Property::Map from the property if possible.
500         else
501         {
502           map = value.GetMap();
503           if( map )
504           {
505             Property::Value* shaderValue = map->Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER );
506             // set image only if property map contains image information other than custom shader
507             if( map->Count() > 1u ||  !shaderValue )
508             {
509               impl.SetImage( *map );
510             }
511             // the property map contains only the custom shader
512             else if( ( map->Count() == 1u )&&( shaderValue ) )
513             {
514               Property::Map* shaderMap = shaderValue->GetMap();
515               if( shaderMap )
516               {
517                 impl.mShaderMap = *shaderMap;
518
519                 if( !impl.mUrl.empty() )
520                 {
521                   impl.SetImage( impl.mUrl, impl.mImageSize );
522                 }
523                 else if( impl.mImage )
524                 {
525                   impl.SetImage( impl.mImage );
526                 }
527                 else if( !impl.mPropertyMap.Empty() )
528                 {
529                   impl.SetImage( impl.mPropertyMap );
530                 }
531               }
532             }
533           }
534         }
535         break;
536       }
537
538       case Toolkit::ImageView::Property::PRE_MULTIPLIED_ALPHA:
539       {
540         bool isPre;
541         if( value.Get( isPre ) )
542         {
543           impl.EnablePreMultipliedAlpha( isPre );
544         }
545         break;
546       }
547     }
548   }
549 }
550
551 Property::Value ImageView::GetProperty( BaseObject* object, Property::Index propertyIndex )
552 {
553   Property::Value value;
554
555   Toolkit::ImageView imageview = Toolkit::ImageView::DownCast( Dali::BaseHandle( object ) );
556
557   if ( imageview )
558   {
559     ImageView& impl = GetImpl( imageview );
560     switch ( propertyIndex )
561     {
562       case Toolkit::ImageView::Property::IMAGE:
563       {
564         if ( !impl.mUrl.empty() )
565         {
566           value = impl.mUrl;
567         }
568         else if( impl.mImage )
569         {
570           Property::Map map;
571           Scripting::CreatePropertyMap( impl.mImage, map );
572           value = map;
573         }
574         else
575         {
576           Property::Map map;
577           Toolkit::Visual::Base visual = DevelControl::GetVisual( impl, Toolkit::ImageView::Property::IMAGE );
578           if( visual )
579           {
580             visual.CreatePropertyMap( map );
581           }
582           value = map;
583         }
584         break;
585       }
586
587       case Toolkit::ImageView::Property::PRE_MULTIPLIED_ALPHA:
588       {
589         value = impl.IsPreMultipliedAlphaEnabled();
590         break;
591       }
592     }
593   }
594
595   return value;
596 }
597
598 } // namespace Internal
599 } // namespace Toolkit
600 } // namespace Dali