28cbfff293eff3b39b370fae5db61a02f5a3c705
[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 Vector3 ImageView::GetNaturalSize()
241 {
242   if( mVisual )
243   {
244     Vector2 rendererNaturalSize;
245     mVisual.GetNaturalSize( rendererNaturalSize );
246
247     Extents padding;
248     padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
249
250     rendererNaturalSize.width += ( padding.start + padding.end );
251     rendererNaturalSize.height += ( padding.top + padding.bottom );
252     return Vector3( rendererNaturalSize );
253   }
254
255   // if no visual then use Control's natural size
256   return Control::GetNaturalSize();
257 }
258
259 float ImageView::GetHeightForWidth( float width )
260 {
261   Extents padding;
262   padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
263
264   if( mVisual )
265   {
266     return mVisual.GetHeightForWidth( width ) + padding.top + padding.bottom;
267   }
268   else
269   {
270     return Control::GetHeightForWidth( width ) + padding.top + padding.bottom;
271   }
272 }
273
274 float ImageView::GetWidthForHeight( float height )
275 {
276   Extents padding;
277   padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
278
279   if( mVisual )
280   {
281     return mVisual.GetWidthForHeight( height ) + padding.start + padding.end;
282   }
283   else
284   {
285     return Control::GetWidthForHeight( height ) + padding.start + padding.end;
286   }
287 }
288
289 void ImageView::OnRelayout( const Vector2& size, RelayoutContainer& container )
290 {
291   Control::OnRelayout( size, container );
292   if( mVisual )
293   {
294     Property::Map transformMap = Property::Map();
295
296     Extents padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
297
298     bool zeroPadding = ( padding == Extents() );
299
300     Vector2 naturalSize;
301     mVisual.GetNaturalSize( naturalSize );
302
303     Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(
304           Self().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
305     if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
306     {
307       std::swap( padding.start, padding.end );
308     }
309
310     // remove padding from the size to know how much is left for the visual
311     Vector2 finalSize = size - Vector2( padding.start + padding.end, padding.top + padding.bottom );
312     Vector2 finalOffset = Vector2( padding.start, padding.top );
313
314     ApplyFittingMode( finalSize, naturalSize, finalOffset, zeroPadding , transformMap );
315
316     mVisual.SetTransformAndSize( transformMap, size );
317
318     // mVisual is not updated util the resource is ready in the case of visual replacement.
319     // So apply the transform and size to the new visual.
320     Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::ImageView::Property::IMAGE );
321     if( visual && visual != mVisual )
322     {
323       visual.SetTransformAndSize( transformMap, size );
324     }
325   }
326 }
327
328 void ImageView::OnResourceReady( Toolkit::Control control )
329 {
330   // Visual ready so update visual attached to this ImageView, following call to RelayoutRequest will use this visual.
331   mVisual = DevelControl::GetVisual( *this, Toolkit::ImageView::Property::IMAGE );
332   // Signal that a Relayout may be needed
333 }
334
335 void ImageView::SetTransformMapForFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, Visual::FittingMode fittingMode, Property::Map& transformMap )
336 {
337   switch(fittingMode)
338   {
339     case Visual::FittingMode::FIT_KEEP_ASPECT_RATIO:
340     {
341       auto availableVisualSize = finalSize;
342
343       // scale to fit the padded area
344       finalSize = naturalSize * std::min( ( naturalSize.width  ? ( availableVisualSize.width  / naturalSize.width  ) : 0 ),
345                                             ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
346
347       // calculate final offset within the padded area
348       finalOffset += ( availableVisualSize - finalSize ) * .5f;
349
350       // populate the transform map
351       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
352                   .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
353       break;
354     }
355     case Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO:
356     {
357       mImageViewPixelAreaSetByFittingMode = true;
358       auto availableVisualSize = finalSize;
359       finalSize = naturalSize * std::max( ( naturalSize.width  ? ( availableVisualSize.width  / naturalSize.width  ) : 0 ),
360                                           ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
361
362       auto originalOffset = finalOffset;
363       finalOffset += ( availableVisualSize - finalSize ) * .5f;
364
365       float x = abs( (availableVisualSize.width - finalSize.width ) / finalSize.width )* .5f;
366       float y = abs( (availableVisualSize.height - finalSize.height ) / finalSize.height ) * .5f;
367       float widthRatio = 1.f - abs( (availableVisualSize.width - finalSize.width ) / finalSize.width );
368       float heightRatio = 1.f - abs( (availableVisualSize.height - finalSize.height ) / finalSize.height );
369       Vector4 pixelArea = Vector4( x, y, widthRatio, heightRatio);
370       Self().SetProperty( Toolkit::ImageView::Property::PIXEL_AREA, pixelArea );
371
372       // populate the transform map
373       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, originalOffset )
374                   .Add( Toolkit::Visual::Transform::Property::SIZE, availableVisualSize );
375       break;
376     }
377     case Visual::FittingMode::CENTER:
378     {
379       auto availableVisualSize = finalSize;
380       if( availableVisualSize.width > naturalSize.width && availableVisualSize.height > naturalSize.height )
381       {
382         finalSize = naturalSize;
383       }
384       else
385       {
386         finalSize = naturalSize * std::min( ( naturalSize.width  ? ( availableVisualSize.width  / naturalSize.width  ) : 0 ),
387                                           ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
388       }
389
390       finalOffset += ( availableVisualSize - finalSize ) * .5f;
391
392       // populate the transform map
393       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
394                   .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
395       break;
396     }
397     case Visual::FittingMode::FILL:
398     {
399       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
400                   .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
401       break;
402     }
403     case Visual::FittingMode::FIT_WIDTH:
404     case Visual::FittingMode::FIT_HEIGHT:
405     {
406       // This FittingMode already converted
407       break;
408     }
409   }
410 }
411
412 void ImageView::ApplyFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, bool zeroPadding , Property::Map& transformMap )
413 {
414     Visual::FittingMode fittingMode = Toolkit::GetImplementation(mVisual).GetFittingMode();
415
416     // Reset PIXEL_AREA after using OVER_FIT_KEEP_ASPECT_RATIO
417     if( mImageViewPixelAreaSetByFittingMode )
418     {
419       Self().SetProperty( Toolkit::ImageView::Property::PIXEL_AREA, FULL_TEXTURE_RECT );
420       mImageViewPixelAreaSetByFittingMode = false;
421     }
422
423     if( ( !zeroPadding ) || // If padding is not zero
424         ( fittingMode != Visual::FittingMode::FILL ) )
425     {
426       mImageVisualPaddingSetByTransform = true;
427
428       // If FittingMode use FIT_WIDTH or FIT_HEIGTH, it need to change proper fittingMode
429       if( fittingMode == Visual::FittingMode::FIT_WIDTH )
430       {
431         fittingMode = ( finalSize.height  / naturalSize.height ) < ( finalSize.width / naturalSize.width ) ? Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::FIT_KEEP_ASPECT_RATIO;
432       }
433       else if( fittingMode == Visual::FittingMode::FIT_HEIGHT )
434       {
435         fittingMode = ( finalSize.height  / naturalSize.height ) < ( finalSize.width / naturalSize.width ) ? Visual::FittingMode::FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO;
436       }
437
438       SetTransformMapForFittingMode( finalSize, naturalSize, finalOffset, fittingMode, transformMap );
439
440       // Set extra value for applying transformMap
441       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY,
442                         Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
443                   .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN )
444                   .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN )
445                   .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY,
446                         Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) );
447     }
448     else if ( mImageVisualPaddingSetByTransform && zeroPadding )  // Reset offset to zero only if padding applied previously
449     {
450       mImageVisualPaddingSetByTransform = false;
451       // Reset the transform map
452       transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, Vector2::ZERO )
453                   .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY,
454                         Vector2( Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE ) )
455                   .Add( Toolkit::Visual::Transform::Property::SIZE, Vector2::ONE )
456                   .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY,
457                         Vector2( Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE ) );
458     }
459 }
460
461 ///////////////////////////////////////////////////////////
462 //
463 // Properties
464 //
465
466 void ImageView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
467 {
468   Toolkit::ImageView imageView = Toolkit::ImageView::DownCast( Dali::BaseHandle( object ) );
469
470   if ( imageView )
471   {
472     ImageView& impl = GetImpl( imageView );
473     switch ( index )
474     {
475       case Toolkit::ImageView::Property::IMAGE:
476       {
477         std::string imageUrl;
478         Property::Map* map;
479         if( value.Get( imageUrl ) )
480         {
481           impl.SetImage( imageUrl, ImageDimensions() );
482         }
483         // if its not a string then get a Property::Map from the property if possible.
484         else
485         {
486           map = value.GetMap();
487           if( map )
488           {
489             Property::Value* shaderValue = map->Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER );
490             // set image only if property map contains image information other than custom shader
491             if( map->Count() > 1u ||  !shaderValue )
492             {
493               impl.SetImage( *map );
494             }
495             // the property map contains only the custom shader
496             else if( ( map->Count() == 1u )&&( shaderValue ) )
497             {
498               Property::Map* shaderMap = shaderValue->GetMap();
499               if( shaderMap )
500               {
501                 impl.mShaderMap = *shaderMap;
502
503                 if( !impl.mUrl.empty() )
504                 {
505                   impl.SetImage( impl.mUrl, impl.mImageSize );
506                 }
507                 else if( impl.mImage )
508                 {
509                   impl.SetImage( impl.mImage );
510                 }
511                 else if( !impl.mPropertyMap.Empty() )
512                 {
513                   impl.SetImage( impl.mPropertyMap );
514                 }
515               }
516             }
517           }
518         }
519         break;
520       }
521
522       case Toolkit::ImageView::Property::PRE_MULTIPLIED_ALPHA:
523       {
524         bool isPre;
525         if( value.Get( isPre ) )
526         {
527           impl.EnablePreMultipliedAlpha( isPre );
528         }
529         break;
530       }
531     }
532   }
533 }
534
535 Property::Value ImageView::GetProperty( BaseObject* object, Property::Index propertyIndex )
536 {
537   Property::Value value;
538
539   Toolkit::ImageView imageview = Toolkit::ImageView::DownCast( Dali::BaseHandle( object ) );
540
541   if ( imageview )
542   {
543     ImageView& impl = GetImpl( imageview );
544     switch ( propertyIndex )
545     {
546       case Toolkit::ImageView::Property::IMAGE:
547       {
548         if ( !impl.mUrl.empty() )
549         {
550           value = impl.mUrl;
551         }
552         else if( impl.mImage )
553         {
554           Property::Map map;
555           Scripting::CreatePropertyMap( impl.mImage, map );
556           value = map;
557         }
558         else
559         {
560           Property::Map map;
561           Toolkit::Visual::Base visual = DevelControl::GetVisual( impl, Toolkit::ImageView::Property::IMAGE );
562           if( visual )
563           {
564             visual.CreatePropertyMap( map );
565           }
566           value = map;
567         }
568         break;
569       }
570
571       case Toolkit::ImageView::Property::PRE_MULTIPLIED_ALPHA:
572       {
573         value = impl.IsPreMultipliedAlphaEnabled();
574         break;
575       }
576     }
577   }
578
579   return value;
580 }
581
582 } // namespace Internal
583 } // namespace Toolkit
584 } // namespace Dali