[dali_2.3.20] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / animated-vector-image / animated-vector-image-visual.cpp
1 /*
2  * Copyright (c) 2024 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-toolkit/internal/visuals/animated-vector-image/animated-vector-image-visual.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/adaptor-framework/window-devel.h>
23 #include <dali/devel-api/common/stage.h>
24 #include <dali/devel-api/rendering/renderer-devel.h>
25 #include <dali/integration-api/adaptor-framework/adaptor.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/math/math-utils.h>
28 #include <dali/public-api/rendering/decorated-visual-renderer.h>
29
30 // INTERNAL INCLUDES
31 #include <dali-toolkit/devel-api/visuals/animated-vector-image-visual-signals-devel.h>
32 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
33 #include <dali-toolkit/devel-api/visuals/visual-actions-devel.h>
34 #include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
35 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
36 #include <dali-toolkit/internal/visuals/image-visual-shader-feature-builder.h>
37 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
38 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
39 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
40 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
41 #include <dali-toolkit/public-api/visuals/visual-properties.h>
42
43 namespace Dali
44 {
45 namespace Toolkit
46 {
47 namespace Internal
48 {
49 namespace
50 {
51 const int CUSTOM_PROPERTY_COUNT(1); // pixel area,
52
53 const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
54
55 // stop behavior
56 DALI_ENUM_TO_STRING_TABLE_BEGIN(STOP_BEHAVIOR)
57   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME)
58   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME)
59   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME)
60 DALI_ENUM_TO_STRING_TABLE_END(STOP_BEHAVIOR)
61
62 // looping mode
63 DALI_ENUM_TO_STRING_TABLE_BEGIN(LOOPING_MODE)
64   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::LoopingMode, RESTART)
65   DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::LoopingMode, AUTO_REVERSE)
66 DALI_ENUM_TO_STRING_TABLE_END(LOOPING_MODE)
67
68 #if defined(DEBUG_ENABLED)
69 Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
70 #endif
71
72 } // unnamed namespace
73
74 AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
75 {
76   AnimatedVectorImageVisualPtr visual(new AnimatedVectorImageVisual(factoryCache, shaderFactory, imageUrl, ImageDimensions{}));
77   visual->SetProperties(properties);
78   visual->Initialize();
79   return visual;
80 }
81
82 AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, ImageDimensions size)
83 {
84   AnimatedVectorImageVisualPtr visual(new AnimatedVectorImageVisual(factoryCache, shaderFactory, imageUrl, size));
85   visual->Initialize();
86   return visual;
87 }
88
89 AnimatedVectorImageVisual::AnimatedVectorImageVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, ImageDimensions size)
90 : Visual::Base(factoryCache, Visual::FittingMode::FILL, static_cast<Toolkit::Visual::Type>(Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE)),
91   mImageUrl(imageUrl),
92   mAnimationData(),
93   mVectorAnimationTask(new VectorAnimationTask(factoryCache)),
94   mImageVisualShaderFactory(shaderFactory),
95   mVisualSize(),
96   mVisualScale(Vector2::ONE),
97   mDesiredSize(size),
98   mPlacementActor(),
99   mPlayState(DevelImageVisual::PlayState::STOPPED),
100   mEventCallback(nullptr),
101   mLastSentPlayStateId(0u),
102   mLoadFailed(false),
103   mRendererAdded(false),
104   mCoreShutdown(false),
105   mRedrawInScalingDown(true),
106   mEnableFrameCache(false),
107   mUseNativeImage(false),
108   mNotifyAfterRasterization(false)
109 {
110   // the rasterized image is with pre-multiplied alpha format
111   mImpl->mFlags |= Visual::Base::Impl::IS_PREMULTIPLIED_ALPHA;
112
113   // By default, load a file synchronously
114   mImpl->mFlags |= Visual::Base::Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
115 }
116
117 AnimatedVectorImageVisual::~AnimatedVectorImageVisual()
118 {
119   if(!mCoreShutdown)
120   {
121     if(mImageUrl.IsBufferResource())
122     {
123       TextureManager& textureManager = mFactoryCache.GetTextureManager();
124       textureManager.RemoveEncodedImageBuffer(mImageUrl.GetUrl());
125     }
126
127     auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
128     vectorAnimationManager.RemoveObserver(*this);
129
130     if(mEventCallback)
131     {
132       mFactoryCache.GetVectorAnimationManager().UnregisterEventCallback(mEventCallback);
133       mEventCallback = nullptr;
134     }
135
136     // Finalize animation task and disconnect the signal in the main thread
137     mVectorAnimationTask->ResourceReadySignal().Disconnect(this, &AnimatedVectorImageVisual::OnResourceReady);
138     mVectorAnimationTask->Finalize();
139   }
140 }
141
142 void AnimatedVectorImageVisual::VectorAnimationManagerDestroyed()
143 {
144   // Core is shutting down. Don't talk to the plugin any more.
145   mCoreShutdown = true;
146 }
147
148 void AnimatedVectorImageVisual::GetNaturalSize(Vector2& naturalSize)
149 {
150   if(mDesiredSize.GetWidth() > 0 && mDesiredSize.GetHeight() > 0)
151   {
152     naturalSize.x = mDesiredSize.GetWidth();
153     naturalSize.y = mDesiredSize.GetHeight();
154   }
155   else if(mVisualSize != Vector2::ZERO)
156   {
157     naturalSize = mVisualSize;
158   }
159   else
160   {
161     if(mLoadFailed && mImpl->mRenderer)
162     {
163       // Load failed, use broken image size
164       auto textureSet = mImpl->mRenderer.GetTextures();
165       if(textureSet && textureSet.GetTextureCount())
166       {
167         auto texture = textureSet.GetTexture(0);
168         if(texture)
169         {
170           naturalSize.x = texture.GetWidth();
171           naturalSize.y = texture.GetHeight();
172           return;
173         }
174       }
175     }
176     else
177     {
178       uint32_t width, height;
179       mVectorAnimationTask->GetDefaultSize(width, height);
180       naturalSize.x = width;
181       naturalSize.y = height;
182     }
183   }
184
185   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::GetNaturalSize: w = %f, h = %f [%p]\n", naturalSize.width, naturalSize.height, this);
186 }
187
188 void AnimatedVectorImageVisual::DoCreatePropertyMap(Property::Map& map) const
189 {
190   map.Clear();
191   map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE);
192   if(mImageUrl.IsValid())
193   {
194     map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
195   }
196   map.Insert(Toolkit::DevelImageVisual::Property::LOOP_COUNT, mAnimationData.loopCount);
197
198   uint32_t startFrame, endFrame;
199   mVectorAnimationTask->GetPlayRange(startFrame, endFrame);
200
201   Property::Array playRange;
202   playRange.PushBack(static_cast<int32_t>(startFrame));
203   playRange.PushBack(static_cast<int32_t>(endFrame));
204   map.Insert(Toolkit::DevelImageVisual::Property::PLAY_RANGE, playRange);
205
206   map.Insert(Toolkit::DevelImageVisual::Property::PLAY_STATE, static_cast<int32_t>(mPlayState));
207   map.Insert(Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, static_cast<int32_t>(mVectorAnimationTask->GetCurrentFrameNumber()));
208   map.Insert(Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, static_cast<int32_t>(mVectorAnimationTask->GetTotalFrameNumber()));
209
210   map.Insert(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mAnimationData.stopBehavior);
211   map.Insert(Toolkit::DevelImageVisual::Property::LOOPING_MODE, mAnimationData.loopingMode);
212   map.Insert(Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, mRedrawInScalingDown);
213
214   Property::Map layerInfo;
215   mVectorAnimationTask->GetLayerInfo(layerInfo);
216   map.Insert(Toolkit::DevelImageVisual::Property::CONTENT_INFO, layerInfo);
217
218   Property::Map markerInfo;
219   mVectorAnimationTask->GetMarkerInfo(markerInfo);
220   map.Insert(Toolkit::DevelImageVisual::Property::MARKER_INFO, markerInfo);
221
222   map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired());
223   map.Insert(Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth());
224   map.Insert(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight());
225   map.Insert(Toolkit::DevelImageVisual::Property::ENABLE_FRAME_CACHE, mEnableFrameCache);
226   map.Insert(Toolkit::DevelImageVisual::Property::NOTIFY_AFTER_RASTERIZATION, mNotifyAfterRasterization);
227 }
228
229 void AnimatedVectorImageVisual::DoCreateInstancePropertyMap(Property::Map& map) const
230 {
231   // Do nothing
232 }
233
234 void AnimatedVectorImageVisual::EnablePreMultipliedAlpha(bool preMultiplied)
235 {
236   // Make always enable pre multiplied alpha whether preMultiplied value is false.
237   if(!preMultiplied)
238   {
239     DALI_LOG_WARNING("Note : AnimatedVectorVisual cannot disable PreMultipliedAlpha\n");
240   }
241 }
242
243 void AnimatedVectorImageVisual::DoSetProperties(const Property::Map& propertyMap)
244 {
245   // url already passed in from constructor
246   for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
247   {
248     KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
249     if(keyValue.first.type == Property::Key::INDEX)
250     {
251       DoSetProperty(keyValue.first.indexKey, keyValue.second);
252     }
253     else
254     {
255       if(keyValue.first == LOOP_COUNT_NAME)
256       {
257         DoSetProperty(Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second);
258       }
259       else if(keyValue.first == PLAY_RANGE_NAME)
260       {
261         DoSetProperty(Toolkit::DevelImageVisual::Property::PLAY_RANGE, keyValue.second);
262       }
263       else if(keyValue.first == STOP_BEHAVIOR_NAME)
264       {
265         DoSetProperty(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second);
266       }
267       else if(keyValue.first == LOOPING_MODE_NAME)
268       {
269         DoSetProperty(Toolkit::DevelImageVisual::Property::LOOPING_MODE, keyValue.second);
270       }
271       else if(keyValue.first == REDRAW_IN_SCALING_DOWN_NAME)
272       {
273         DoSetProperty(Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, keyValue.second);
274       }
275       else if(keyValue.first == SYNCHRONOUS_LOADING)
276       {
277         DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second);
278       }
279       else if(keyValue.first == IMAGE_DESIRED_WIDTH)
280       {
281         DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second);
282       }
283       else if(keyValue.first == IMAGE_DESIRED_HEIGHT)
284       {
285         DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second);
286       }
287       else if(keyValue.first == ENABLE_FRAME_CACHE)
288       {
289         DoSetProperty(Toolkit::DevelImageVisual::Property::ENABLE_FRAME_CACHE, keyValue.second);
290       }
291       else if(keyValue.first == NOTIFY_AFTER_RASTERIZATION)
292       {
293         DoSetProperty(Toolkit::DevelImageVisual::Property::NOTIFY_AFTER_RASTERIZATION, keyValue.second);
294       }
295     }
296   }
297
298   TriggerVectorRasterization();
299 }
300
301 void AnimatedVectorImageVisual::DoSetProperty(Property::Index index, const Property::Value& value)
302 {
303   switch(index)
304   {
305     case Toolkit::DevelImageVisual::Property::LOOP_COUNT:
306     {
307       int32_t loopCount;
308       if(value.Get(loopCount))
309       {
310         mAnimationData.loopCount = loopCount;
311         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_LOOP_COUNT;
312       }
313       break;
314     }
315     case Toolkit::DevelImageVisual::Property::PLAY_RANGE:
316     {
317       const Property::Array* array = value.GetArray();
318       if(array)
319       {
320         mAnimationData.playRange = *array;
321         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_RANGE;
322       }
323       else if(value.GetType() == Property::STRING)
324       {
325         std::string markerName;
326         if(value.Get(markerName))
327         {
328           Property::Array array;
329           array.Add(markerName);
330           mAnimationData.playRange = std::move(array);
331           mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_RANGE;
332         }
333       }
334       break;
335     }
336     case Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR:
337     {
338       int32_t stopBehavior = mAnimationData.stopBehavior;
339       if(Scripting::GetEnumerationProperty(value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior))
340       {
341         mAnimationData.stopBehavior = DevelImageVisual::StopBehavior::Type(stopBehavior);
342         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_STOP_BEHAVIOR;
343       }
344       break;
345     }
346     case Toolkit::DevelImageVisual::Property::LOOPING_MODE:
347     {
348       int32_t loopingMode = mAnimationData.loopingMode;
349       if(Scripting::GetEnumerationProperty(value, LOOPING_MODE_TABLE, LOOPING_MODE_TABLE_COUNT, loopingMode))
350       {
351         mAnimationData.loopingMode = DevelImageVisual::LoopingMode::Type(loopingMode);
352         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_LOOPING_MODE;
353       }
354       break;
355     }
356     case Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN:
357     {
358       bool redraw;
359       if(value.Get(redraw))
360       {
361         mRedrawInScalingDown = redraw;
362       }
363       break;
364     }
365     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
366     {
367       bool sync = false;
368       if(value.Get(sync))
369       {
370         if(sync)
371         {
372           mImpl->mFlags |= Visual::Base::Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
373         }
374         else
375         {
376           mImpl->mFlags &= ~Visual::Base::Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
377         }
378       }
379       break;
380     }
381     case Toolkit::ImageVisual::Property::DESIRED_WIDTH:
382     {
383       int32_t desiredWidth = 0;
384       if(value.Get(desiredWidth))
385       {
386         mDesiredSize.SetWidth(desiredWidth);
387       }
388       break;
389     }
390
391     case Toolkit::ImageVisual::Property::DESIRED_HEIGHT:
392     {
393       int32_t desiredHeight = 0;
394       if(value.Get(desiredHeight))
395       {
396         mDesiredSize.SetHeight(desiredHeight);
397       }
398       break;
399     }
400
401     case Toolkit::DevelImageVisual::Property::ENABLE_FRAME_CACHE:
402     {
403       bool enableFrameCache = false;
404       if(value.Get(enableFrameCache))
405       {
406         mEnableFrameCache = enableFrameCache;
407         if(mVectorAnimationTask)
408         {
409           mVectorAnimationTask->KeepRasterizedBuffer(mEnableFrameCache);
410         }
411       }
412       break;
413     }
414
415     case Toolkit::DevelImageVisual::Property::NOTIFY_AFTER_RASTERIZATION:
416     {
417       bool notifyAfterRasterization = false;
418       if(value.Get(notifyAfterRasterization))
419       {
420         if(mNotifyAfterRasterization != notifyAfterRasterization)
421         {
422           mNotifyAfterRasterization = notifyAfterRasterization;
423
424           mAnimationData.notifyAfterRasterization = mNotifyAfterRasterization;
425           mAnimationData.resendFlag |= VectorAnimationTask::RESEND_NOTIFY_AFTER_RASTERIZATION;
426         }
427       }
428       break;
429     }
430   }
431 }
432
433 void AnimatedVectorImageVisual::OnInitialize(void)
434 {
435   mVectorAnimationTask->ResourceReadySignal().Connect(this, &AnimatedVectorImageVisual::OnResourceReady);
436   mVectorAnimationTask->SetAnimationFinishedCallback(MakeCallback(this, &AnimatedVectorImageVisual::OnAnimationFinished));
437
438   EncodedImageBuffer encodedImageBuffer;
439
440   if(mImageUrl.IsBufferResource())
441   {
442     // Increase reference count of External Resources :
443     // EncodedImageBuffer.
444     // Reference count will be decreased at destructor of the visual.
445     TextureManager& textureManager = mFactoryCache.GetTextureManager();
446     textureManager.UseExternalResource(mImageUrl.GetUrl());
447
448     encodedImageBuffer = textureManager.GetEncodedImageBuffer(mImageUrl.GetUrl());
449   }
450
451   mVectorAnimationTask->KeepRasterizedBuffer(mEnableFrameCache);
452   mVectorAnimationTask->RequestLoad(mImageUrl, encodedImageBuffer, IsSynchronousLoadingRequired());
453
454   auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
455   vectorAnimationManager.AddObserver(*this);
456
457   Shader shader = GenerateShader();
458
459   Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
460
461   mImpl->mRenderer = DecoratedVisualRenderer::New(geometry, shader);
462   mImpl->mRenderer.ReserveCustomProperties(CUSTOM_PROPERTY_COUNT);
463
464   TextureSet textureSet = TextureSet::New();
465   mImpl->mRenderer.SetTextures(textureSet);
466
467   // Register transform properties
468   mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
469
470   mVectorAnimationTask->SetRenderer(mImpl->mRenderer);
471 }
472
473 void AnimatedVectorImageVisual::DoSetOnScene(Actor& actor)
474 {
475   // Defer the rasterisation task until we get given a size (by Size Negotiation algorithm)
476
477   // Hold the weak handle of the placement actor and delay the adding of renderer until the rasterization is finished.
478   mPlacementActor = actor;
479
480   if(mLoadFailed)
481   {
482     Vector2 imageSize = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
483     mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize, false);
484     actor.AddRenderer(mImpl->mRenderer);
485     mRendererAdded = true;
486     ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
487   }
488   else
489   {
490     // Add property notification for scaling & size
491     mScaleNotification = actor.AddPropertyNotification(Actor::Property::WORLD_SCALE, StepCondition(0.1f, 1.0f));
492     mScaleNotification.NotifySignal().Connect(this, &AnimatedVectorImageVisual::OnScaleNotification);
493
494     mSizeNotification = actor.AddPropertyNotification(Actor::Property::SIZE, StepCondition(3.0f));
495     mSizeNotification.NotifySignal().Connect(this, &AnimatedVectorImageVisual::OnSizeNotification);
496
497     DevelActor::VisibilityChangedSignal(actor).Connect(this, &AnimatedVectorImageVisual::OnControlVisibilityChanged);
498
499     Window window = DevelWindow::Get(actor);
500     if(window)
501     {
502       mPlacementWindow = window;
503       DevelWindow::VisibilityChangedSignal(window).Connect(this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged);
504     }
505
506     if(mImpl->mEventObserver)
507     {
508       // The visual needs it's size set before it can be rasterized hence request relayout once on stage
509       mImpl->mEventObserver->RelayoutRequest(*this);
510     }
511
512     mAnimationData.resendFlag |= VectorAnimationTask::RESEND_NEED_RESOURCE_READY;
513     TriggerVectorRasterization();
514   }
515
516   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOnScene [%p]\n", this);
517 }
518
519 void AnimatedVectorImageVisual::DoSetOffScene(Actor& actor)
520 {
521   StopAnimation();
522   TriggerVectorRasterization();
523
524   if(mImpl->mRenderer)
525   {
526     actor.RemoveRenderer(mImpl->mRenderer);
527     mRendererAdded = false;
528   }
529
530   // Remove property notification
531   actor.RemovePropertyNotification(mScaleNotification);
532   actor.RemovePropertyNotification(mSizeNotification);
533
534   DevelActor::VisibilityChangedSignal(actor).Disconnect(this, &AnimatedVectorImageVisual::OnControlVisibilityChanged);
535
536   Window window = mPlacementWindow.GetHandle();
537   if(window)
538   {
539     DevelWindow::VisibilityChangedSignal(window).Disconnect(this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged);
540     mPlacementWindow.Reset();
541   }
542
543   mPlacementActor.Reset();
544
545   // Reset the visual size to zero so that when adding the actor back to stage the rasterization is forced
546   mVisualSize           = Vector2::ZERO;
547   mVisualScale          = Vector2::ONE;
548   mAnimationData.width  = 0;
549   mAnimationData.height = 0;
550
551   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOffScene [%p]\n", this);
552 }
553
554 void AnimatedVectorImageVisual::OnSetTransform()
555 {
556   Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize);
557
558   if(IsOnScene() && visualSize != mVisualSize)
559   {
560     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSetTransform: width = %f, height = %f [%p]\n", visualSize.width, visualSize.height, this);
561
562     mVisualSize = visualSize;
563
564     SetVectorImageSize();
565
566     if(mPlayState == DevelImageVisual::PlayState::PLAYING && mAnimationData.playState != DevelImageVisual::PlayState::PLAYING)
567     {
568       mAnimationData.playState = DevelImageVisual::PlayState::PLAYING;
569       mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
570     }
571
572     TriggerVectorRasterization();
573   }
574 }
575
576 void AnimatedVectorImageVisual::UpdateShader()
577 {
578   if(mImpl->mRenderer)
579   {
580     Shader shader = GenerateShader();
581     mImpl->mRenderer.SetShader(shader);
582   }
583 }
584
585 void AnimatedVectorImageVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes)
586 {
587   // Check if action is valid for this visual type and perform action if possible
588   switch(actionId)
589   {
590     case DevelAnimatedVectorImageVisual::Action::PLAY:
591     {
592       if(IsOnScene() && mVisualSize != Vector2::ZERO)
593       {
594         // Always resend Playing state. If task is already playing, it will be ignored at Rasterize time.
595         mAnimationData.playState = DevelImageVisual::PlayState::PLAYING;
596         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
597       }
598       mPlayState = DevelImageVisual::PlayState::PLAYING;
599       break;
600     }
601     case DevelAnimatedVectorImageVisual::Action::PAUSE:
602     {
603       if(mAnimationData.playState == DevelImageVisual::PlayState::PLAYING)
604       {
605         mAnimationData.playState = DevelImageVisual::PlayState::PAUSED;
606         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
607       }
608       mPlayState = DevelImageVisual::PlayState::PAUSED;
609       break;
610     }
611     case DevelAnimatedVectorImageVisual::Action::STOP:
612     {
613       if(mAnimationData.playState != DevelImageVisual::PlayState::STOPPED)
614       {
615         mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
616         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
617       }
618       mPlayState = DevelImageVisual::PlayState::STOPPED;
619       break;
620     }
621     case DevelAnimatedVectorImageVisual::Action::JUMP_TO:
622     {
623       int32_t frameNumber;
624       if(attributes.Get(frameNumber))
625       {
626         mAnimationData.currentFrame = frameNumber;
627         mAnimationData.resendFlag |= VectorAnimationTask::RESEND_CURRENT_FRAME;
628       }
629       break;
630     }
631     case DevelAnimatedVectorImageVisual::Action::FLUSH:
632     {
633       if(DALI_LIKELY(!mCoreShutdown))
634       {
635         SendAnimationData();
636       }
637       break;
638     }
639   }
640
641   TriggerVectorRasterization();
642 }
643
644 void AnimatedVectorImageVisual::OnDoActionExtension(const Property::Index actionId, Dali::Any attributes)
645 {
646   switch(actionId)
647   {
648     case DevelAnimatedVectorImageVisual::Action::SET_DYNAMIC_PROPERTY:
649     {
650       DevelAnimatedVectorImageVisual::DynamicPropertyInfo info = AnyCast<DevelAnimatedVectorImageVisual::DynamicPropertyInfo>(attributes);
651       mAnimationData.dynamicProperties.push_back(info);
652       mAnimationData.resendFlag |= VectorAnimationTask::RESEND_DYNAMIC_PROPERTY;
653       break;
654     }
655   }
656
657   TriggerVectorRasterization();
658 }
659
660 void AnimatedVectorImageVisual::OnResourceReady(VectorAnimationTask::ResourceStatus status)
661 {
662   AnimatedVectorImageVisualPtr self = this; // Keep reference until this API finished
663
664   if(status == VectorAnimationTask::ResourceStatus::LOADED)
665   {
666     if(mImpl->mEventObserver)
667     {
668       mImpl->mEventObserver->RelayoutRequest(*this);
669     }
670   }
671   else
672   {
673     mLoadFailed = status == VectorAnimationTask::ResourceStatus::FAILED ? true : false;
674     if(status == VectorAnimationTask::ResourceStatus::READY)
675     {
676       // Texture was ready. Change the shader if we need.
677       bool useNativeImage = false;
678       if(mImpl->mRenderer)
679       {
680         auto textureSet = mImpl->mRenderer.GetTextures();
681         if(textureSet && textureSet.GetTextureCount() > 0)
682         {
683           auto texture = textureSet.GetTexture(0u);
684           if(texture)
685           {
686             useNativeImage = DevelTexture::IsNative(texture);
687
688             if(mUseNativeImage != useNativeImage)
689             {
690               mUseNativeImage = useNativeImage;
691               UpdateShader();
692             }
693           }
694         }
695       }
696     }
697
698     // If weak handle is holding a placement actor, it is the time to add the renderer to actor.
699     Actor actor = mPlacementActor.GetHandle();
700     if(actor && !mRendererAdded)
701     {
702       if(!mLoadFailed)
703       {
704         actor.AddRenderer(mImpl->mRenderer);
705         ResourceReady(Toolkit::Visual::ResourceStatus::READY);
706       }
707       else
708       {
709         Vector2 imageSize = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
710         mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize, false);
711         actor.AddRenderer(mImpl->mRenderer);
712         ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
713       }
714
715       mRendererAdded = true;
716     }
717   }
718
719   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "status = %d [%p]\n", status, this);
720 }
721
722 void AnimatedVectorImageVisual::OnAnimationFinished(uint32_t playStateId)
723 {
724   // Only send event when animation is finished by the last Play/Pause/Stop request.
725   if(mLastSentPlayStateId != playStateId)
726   {
727     return;
728   }
729
730   AnimatedVectorImageVisualPtr self = this; // Keep reference until this API finished
731
732   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnAnimationFinished: action state = %d [%p]\n", mPlayState, this);
733
734   if(mPlayState != DevelImageVisual::PlayState::STOPPED)
735   {
736     mPlayState = DevelImageVisual::PlayState::STOPPED;
737
738     mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
739
740     if(mImpl->mEventObserver)
741     {
742       mImpl->mEventObserver->NotifyVisualEvent(*this, DevelAnimatedVectorImageVisual::Signal::ANIMATION_FINISHED);
743     }
744   }
745
746   if(!mNotifyAfterRasterization && mImpl->mRenderer)
747   {
748     mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED);
749   }
750 }
751
752 void AnimatedVectorImageVisual::SendAnimationData()
753 {
754   if(mAnimationData.resendFlag)
755   {
756     if(mAnimationData.resendFlag & VectorAnimationTask::RESEND_PLAY_STATE)
757     {
758       // Keep last sent playId. It will be used when we try to emit AnimationFinished signal.
759       // The OnAnimationFinished signal what before Play/Pause/Stop action send could be come after action sent.
760       // To ensure the OnAnimationFinished signal comes belong to what we sent, we need to keep last sent playId.
761       mAnimationData.playStateId = ++mLastSentPlayStateId;
762     }
763     mVectorAnimationTask->SetAnimationData(mAnimationData);
764
765     if(mImpl->mRenderer &&
766        ((mAnimationData.resendFlag & VectorAnimationTask::RESEND_PLAY_STATE) ||
767         (mAnimationData.resendFlag & VectorAnimationTask::RESEND_NOTIFY_AFTER_RASTERIZATION)))
768     {
769       if(!mNotifyAfterRasterization && mPlayState == DevelImageVisual::PlayState::PLAYING)
770       {
771         // Make rendering behaviour if we don't notify after rasterization, but animation playing.
772         mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY);
773       }
774       else
775       {
776         // Otherwise, notify will be sended after rasterization. Make behaviour as required.
777         mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED);
778       }
779     }
780
781     mAnimationData.resendFlag = 0;
782   }
783 }
784
785 void AnimatedVectorImageVisual::SetVectorImageSize()
786 {
787   uint32_t width, height;
788   if(mDesiredSize.GetWidth() > 0 && mDesiredSize.GetHeight() > 0)
789   {
790     width  = mDesiredSize.GetWidth();
791     height = mDesiredSize.GetHeight();
792   }
793   else
794   {
795     width  = static_cast<uint32_t>(mVisualSize.width * mVisualScale.width);
796     height = static_cast<uint32_t>(mVisualSize.height * mVisualScale.height);
797   }
798
799   if(mAnimationData.width != width || mAnimationData.height != height)
800   {
801     mAnimationData.width  = width;
802     mAnimationData.height = height;
803     mAnimationData.resendFlag |= VectorAnimationTask::RESEND_SIZE;
804   }
805 }
806
807 void AnimatedVectorImageVisual::StopAnimation()
808 {
809   if(mAnimationData.playState != DevelImageVisual::PlayState::STOPPED)
810   {
811     mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
812     mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
813
814     mPlayState = DevelImageVisual::PlayState::STOPPED;
815   }
816 }
817
818 void AnimatedVectorImageVisual::TriggerVectorRasterization()
819 {
820   if(!mEventCallback && !mCoreShutdown)
821   {
822     mEventCallback               = MakeCallback(this, &AnimatedVectorImageVisual::OnProcessEvents);
823     auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
824     vectorAnimationManager.RegisterEventCallback(mEventCallback);
825     Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
826   }
827 }
828
829 void AnimatedVectorImageVisual::OnScaleNotification(PropertyNotification& source)
830 {
831   Actor actor = mPlacementActor.GetHandle();
832   if(actor)
833   {
834     Vector3 scale = actor.GetProperty<Vector3>(Actor::Property::WORLD_SCALE);
835
836     if((!Dali::Equals(mVisualScale.width, scale.width) || !Dali::Equals(mVisualScale.height, scale.height)) && (mRedrawInScalingDown || scale.width >= 1.0f || scale.height >= 1.0f))
837     {
838       mVisualScale.width  = scale.width;
839       mVisualScale.height = scale.height;
840
841       DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnScaleNotification: scale = %f, %f [%p]\n", mVisualScale.width, mVisualScale.height, this);
842
843       SetVectorImageSize();
844       SendAnimationData();
845
846       Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
847     }
848   }
849 }
850
851 void AnimatedVectorImageVisual::OnSizeNotification(PropertyNotification& source)
852 {
853   Actor actor = mPlacementActor.GetHandle();
854   if(actor)
855   {
856     Vector3 size = actor.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
857
858     if(!Dali::Equals(mVisualSize.width, size.width) || !Dali::Equals(mVisualSize.height, size.height))
859     {
860       mVisualSize.width  = size.width;
861       mVisualSize.height = size.height;
862
863       DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSizeNotification: size = %f, %f [%p]\n", mVisualSize.width, mVisualSize.height, this);
864
865       SetVectorImageSize();
866       SendAnimationData();
867
868       Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
869     }
870   }
871 }
872
873 void AnimatedVectorImageVisual::OnControlVisibilityChanged(Actor actor, bool visible, DevelActor::VisibilityChange::Type type)
874 {
875   if(!visible)
876   {
877     StopAnimation();
878     TriggerVectorRasterization();
879
880     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnControlVisibilityChanged: invisibile. Pause animation [%p]\n", this);
881   }
882 }
883
884 void AnimatedVectorImageVisual::OnWindowVisibilityChanged(Window window, bool visible)
885 {
886   if(!visible)
887   {
888     StopAnimation();
889     TriggerVectorRasterization();
890
891     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnWindowVisibilityChanged: invisibile. Pause animation [%p]\n", this);
892   }
893 }
894
895 void AnimatedVectorImageVisual::OnProcessEvents()
896 {
897   SendAnimationData();
898
899   mEventCallback = nullptr; // The callback will be deleted in the VectorAnimationManager
900 }
901
902 Shader AnimatedVectorImageVisual::GenerateShader() const
903 {
904   Shader shader;
905   if(mImpl->mCustomShader)
906   {
907     shader = Shader::New(mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader,
908                          mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader,
909                          mImpl->mCustomShader->mHints);
910
911     shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
912   }
913   else
914   {
915     shader = mImageVisualShaderFactory.GetShader(
916       mFactoryCache,
917       ImageVisualShaderFeatureBuilder()
918         .EnableRoundedCorner(IsRoundedCornerRequired())
919         .EnableBorderline(IsBorderlineRequired())
920         .SetTextureForFragmentShaderCheck(mUseNativeImage ? mImpl->mRenderer.GetTextures().GetTexture(0) : Dali::Texture()));
921   }
922   return shader;
923 }
924
925 } // namespace Internal
926
927 } // namespace Toolkit
928
929 } // namespace Dali