Add GetVisualProperty to Control
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / texture-manager-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 <dali-toolkit/internal/visuals/texture-manager-impl.h>
20
21 // EXTERNAL HEADERS
22 #include <cstdlib>
23 #include <string>
24 #include <dali/public-api/math/vector4.h>
25 #include <dali/devel-api/adaptor-framework/environment-variable.h>
26 #include <dali/devel-api/adaptor-framework/image-loading.h>
27 #include <dali/devel-api/common/hash.h>
28 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
29 #include <dali/integration-api/debug.h>
30 #include <dali/public-api/rendering/geometry.h>
31
32 // INTERNAL HEADERS
33 #include <dali-toolkit/internal/image-loader/image-atlas-impl.h>
34 #include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
35 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
36 #include <dali-toolkit/internal/visuals/rendering-addon.h>
37
38 namespace
39 {
40
41 constexpr auto INITIAL_CACHE_NUMBER = size_t{0u};
42 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
43 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
44
45 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
46 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
47
48 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
49 {
50   using Dali::EnvironmentVariable::GetEnvironmentVariable;
51   auto numberString = GetEnvironmentVariable(environmentVariable);
52   auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
53   constexpr auto MAX_NUMBER_OF_THREADS = 100u;
54   DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS );
55   return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue;
56 }
57
58 size_t GetNumberOfLocalLoaderThreads()
59 {
60   return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
61 }
62
63 size_t GetNumberOfRemoteLoaderThreads()
64 {
65   return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
66 }
67
68 } // namespace
69
70 namespace Dali
71 {
72
73 namespace Toolkit
74 {
75
76 namespace Internal
77 {
78
79 namespace
80 {
81
82 #ifdef DEBUG_ENABLED
83 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TEXTURE_MANAGER" );
84
85 #define GET_LOAD_STATE_STRING( loadState ) \
86   loadState == TextureManager::LoadState::NOT_STARTED ? "NOT_STARTED" :             \
87     loadState == TextureManager::LoadState::LOADING ? "LOADING" :                   \
88     loadState == TextureManager::LoadState::LOAD_FINISHED ? "LOAD_FINISHED" :       \
89     loadState == TextureManager::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" : \
90     loadState == TextureManager::LoadState::MASK_APPLYING ? "MASK_APPLYING" :         \
91     loadState == TextureManager::LoadState::MASK_APPLIED ? "MASK_APPLIED" :         \
92     loadState == TextureManager::LoadState::UPLOADED ? "UPLOADED" :                 \
93     loadState == TextureManager::LoadState::CANCELLED ? "CANCELLED" :               \
94     loadState == TextureManager::LoadState::LOAD_FAILED ? "LOAD_FAILED" : "Unknown"
95
96 #endif
97
98 const uint32_t      DEFAULT_ATLAS_SIZE( 1024u );                     ///< This size can fit 8 by 8 images of average size 128 * 128
99 const Vector4       FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f );       ///< UV Rectangle that covers the full Texture
100 const int           INVALID_INDEX( -1 );                             ///< Invalid index used to represent a non-existant TextureInfo struct
101 const int           INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
102
103
104 void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
105 {
106   if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
107   {
108     if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
109     {
110       pixelBuffer.MultiplyColorByAlpha();
111     }
112   }
113   else
114   {
115     preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
116   }
117 }
118
119 } // Anonymous namespace
120
121 TextureManager::MaskingData::MaskingData()
122 : mAlphaMaskUrl(),
123   mAlphaMaskId( INVALID_TEXTURE_ID ),
124   mContentScaleFactor( 1.0f ),
125   mCropToMask( true )
126 {
127 }
128
129 TextureManager::TextureManager()
130 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
131   mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
132   mExternalTextures(),
133   mLifecycleObservers(),
134   mLoadQueue(),
135   mBrokenImageUrl(""),
136   mCurrentTextureId( 0 ),
137   mQueueLoadFlag(false)
138 {
139   // Initialize the AddOn
140   RenderingAddOn::Get();
141 }
142
143 TextureManager::~TextureManager()
144 {
145   for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
146   {
147     (*iter)->TextureManagerDestroyed();
148   }
149 }
150
151 TextureSet TextureManager::LoadAnimatedImageTexture(
152   Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex, Dali::SamplingMode::Type samplingMode,
153   bool synchronousLoading, TextureManager::TextureId& textureId, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver )
154 {
155   TextureSet textureSet;
156
157   if( synchronousLoading )
158   {
159     Devel::PixelBuffer pixelBuffer;
160     if( animatedImageLoading )
161     {
162       pixelBuffer = animatedImageLoading.LoadFrame( frameIndex );
163     }
164     if( !pixelBuffer )
165     {
166       // use broken image
167       pixelBuffer = LoadImageFromFile( mBrokenImageUrl );
168       PixelData pixelData;
169       if( pixelBuffer )
170       {
171         pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
172       }
173       Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(),
174                                       pixelData.GetWidth(), pixelData.GetHeight() );
175       texture.Upload( pixelData );
176       textureSet = TextureSet::New();
177       textureSet.SetTexture( 0u, texture );
178     }
179     else
180     {
181       PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
182       if( !textureSet )
183       {
184         Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(),
185                                         pixelData.GetWidth(), pixelData.GetHeight() );
186         texture.Upload( pixelData );
187         textureSet = TextureSet::New();
188         textureSet.SetTexture( 0u, texture );
189       }
190     }
191   }
192   else
193   {
194     auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
195     textureId = RequestLoadInternal( animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
196                                      SamplingMode::BOX_THEN_LINEAR, TextureManager::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver,
197                                      true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex );
198     TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
199     if( loadState == TextureManager::LoadState::UPLOADED )
200     {
201       // UploadComplete has already been called - keep the same texture set
202       textureSet = GetTextureSet( textureId );
203     }
204   }
205
206   if( textureSet )
207   {
208     Sampler sampler = Sampler::New();
209     sampler.SetWrapMode(  wrapModeU, wrapModeV  );
210     textureSet.SetSampler( 0u, sampler );
211   }
212
213   return textureSet;
214 }
215
216 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
217   const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureUploadObserver* textureObserver, bool orientationCorrection, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
218 {
219   Devel::PixelBuffer pixelBuffer;
220   if( synchronousLoading )
221   {
222     if( url.IsValid() )
223     {
224       pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
225                                        orientationCorrection  );
226       if( pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
227       {
228         PreMultiply( pixelBuffer, preMultiplyOnLoad );
229       }
230     }
231   }
232   else
233   {
234     RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
235                          false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED,
236                          preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u );
237   }
238
239   return pixelBuffer;
240 }
241
242 TextureSet TextureManager::LoadTexture(
243   const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
244   Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo,
245   bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
246   Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus,
247   Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
248   AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
249   TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
250 {
251   TextureSet textureSet;
252
253   loadingStatus = false;
254   textureRect = FULL_ATLAS_RECT;
255
256   if( VisualUrl::TEXTURE == url.GetProtocolType())
257   {
258     std::string location = url.GetLocation();
259     if( location.size() > 0u )
260     {
261       TextureId id = std::stoi( location );
262       for( auto&& elem : mExternalTextures )
263       {
264         if( elem.textureId == id )
265         {
266           preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
267           textureId = elem.textureId;
268           return elem.textureSet;
269         }
270       }
271     }
272   }
273   else if( synchronousLoading )
274   {
275     PixelData data;
276     if( url.IsValid() )
277     {
278       Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
279                                        orientationCorrection  );
280       if( maskInfo && maskInfo->mAlphaMaskUrl.IsValid() )
281       {
282         Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile( maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(),
283                                              FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true  );
284         if( maskPixelBuffer )
285         {
286           pixelBuffer.ApplyMask( maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask );
287         }
288       }
289       if( pixelBuffer )
290       {
291         PreMultiply( pixelBuffer, preMultiplyOnLoad );
292         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
293       }
294     }
295     if( !data )
296     {
297       // use broken image
298       Devel::PixelBuffer pixelBuffer = LoadImageFromFile( mBrokenImageUrl );
299       if( pixelBuffer )
300       {
301         PreMultiply( pixelBuffer, preMultiplyOnLoad );
302         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
303       }
304       Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
305                                       data.GetWidth(), data.GetHeight() );
306       texture.Upload( data );
307       textureSet = TextureSet::New();
308       textureSet.SetTexture( 0u, texture );
309     }
310     else
311     {
312       if( atlasingStatus ) // attempt atlasing
313       {
314         textureSet = imageAtlasManager->Add( textureRect, data );
315       }
316       if( !textureSet ) // big image, no atlasing or atlasing failed
317       {
318         atlasingStatus = false;
319         Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
320                                         data.GetWidth(), data.GetHeight() );
321         texture.Upload( data );
322         textureSet = TextureSet::New();
323         textureSet.SetTexture( 0u, texture );
324       }
325       else
326       {
327         textureRectSize.SetWidth(data.GetWidth());
328         textureRectSize.SetHeight(data.GetHeight());
329       }
330     }
331   }
332   else
333   {
334     loadingStatus = true;
335     if( atlasingStatus )
336     {
337       textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
338     }
339     if( !textureSet ) // big image, no atlasing or atlasing failed
340     {
341       atlasingStatus = false;
342       if( !maskInfo || !maskInfo->mAlphaMaskUrl.IsValid() )
343       {
344         textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
345                                  textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
346       }
347       else
348       {
349         maskInfo->mAlphaMaskId = RequestMaskLoad( maskInfo->mAlphaMaskUrl );
350         textureId = RequestLoad( url,
351                                  maskInfo->mAlphaMaskId,
352                                  maskInfo->mContentScaleFactor,
353                                  desiredSize,
354                                  fittingMode, samplingMode,
355                                  TextureManager::NO_ATLAS,
356                                  maskInfo->mCropToMask,
357                                  textureObserver,
358                                  orientationCorrection,
359                                  reloadPolicy, preMultiplyOnLoad );
360       }
361
362       TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
363       if( loadState == TextureManager::LoadState::UPLOADED )
364       {
365         // UploadComplete has already been called - keep the same texture set
366         textureSet = GetTextureSet( textureId );
367       }
368
369       // If we are loading the texture, or waiting for the ready signal handler to complete, inform
370       // caller that they need to wait.
371       loadingStatus = ( loadState == TextureManager::LoadState::LOADING ||
372                         loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
373                         loadState == TextureManager::LoadState::MASK_APPLYING ||
374                         loadState == TextureManager::LoadState::MASK_APPLIED ||
375                         loadState == TextureManager::LoadState::NOT_STARTED ||
376                         mQueueLoadFlag );
377
378     }
379     else
380     {
381       textureRectSize = desiredSize;
382     }
383   }
384
385   if( ! atlasingStatus && textureSet )
386   {
387     Sampler sampler = Sampler::New();
388     sampler.SetWrapMode(  wrapModeU, wrapModeV  );
389     textureSet.SetSampler( 0u, sampler );
390   }
391
392   return textureSet;
393 }
394
395 TextureManager::TextureId TextureManager::RequestLoad(
396   const VisualUrl&                url,
397   const ImageDimensions           desiredSize,
398   FittingMode::Type               fittingMode,
399   Dali::SamplingMode::Type        samplingMode,
400   const UseAtlas                  useAtlas,
401   TextureUploadObserver*          observer,
402   bool                            orientationCorrection,
403   TextureManager::ReloadPolicy    reloadPolicy,
404   TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
405 {
406   return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
407                               false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
408                               preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u );
409 }
410
411 TextureManager::TextureId TextureManager::RequestLoad(
412   const VisualUrl&                url,
413   TextureId                       maskTextureId,
414   float                           contentScale,
415   const ImageDimensions           desiredSize,
416   FittingMode::Type               fittingMode,
417   Dali::SamplingMode::Type        samplingMode,
418   const UseAtlas                  useAtlas,
419   bool                            cropToMask,
420   TextureUploadObserver*          observer,
421   bool                            orientationCorrection,
422   TextureManager::ReloadPolicy    reloadPolicy,
423   TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
424 {
425   return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
426                               cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
427                               preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u );
428 }
429
430 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
431 {
432   // Use the normal load procedure to get the alpha mask.
433   auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
434   return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
435                               SamplingMode::NO_FILTER, NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true,
436                               TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u );
437 }
438
439 TextureManager::TextureId TextureManager::RequestLoadInternal(
440   const VisualUrl&                url,
441   TextureId                       maskTextureId,
442   float                           contentScale,
443   const ImageDimensions           desiredSize,
444   FittingMode::Type               fittingMode,
445   Dali::SamplingMode::Type        samplingMode,
446   UseAtlas                        useAtlas,
447   bool                            cropToMask,
448   StorageType                     storageType,
449   TextureUploadObserver*          observer,
450   bool                            orientationCorrection,
451   TextureManager::ReloadPolicy    reloadPolicy,
452   TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
453   Dali::AnimatedImageLoading      animatedImageLoading,
454   uint32_t                        frameIndex )
455 {
456   // First check if the requested Texture is cached.
457   bool isAnimatedImage = ( animatedImageLoading ) ? true : false;
458
459   TextureHash textureHash = INITIAL_CACHE_NUMBER;
460   int cacheIndex = INVALID_CACHE_INDEX;
461   if(storageType != StorageType::RETURN_PIXEL_BUFFER)
462   {
463     textureHash = GenerateHash(url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, isAnimatedImage, frameIndex);
464
465     // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
466     cacheIndex = FindCachedTexture(textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, preMultiplyOnLoad, isAnimatedImage, frameIndex);
467   }
468
469   TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
470
471   // Check if the requested Texture exists in the cache.
472   if( cacheIndex != INVALID_CACHE_INDEX )
473   {
474     if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
475     {
476       // Mark this texture being used by another client resource. Forced reload would replace the current texture
477       // without the need for incrementing the reference count.
478       ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
479     }
480     textureId = mTextureInfoContainer[ cacheIndex ].textureId;
481
482     // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
483     preMultiplyOnLoad = mTextureInfoContainer[ cacheIndex ].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
484
485     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
486                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
487   }
488
489   if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
490   {
491     // We need a new Texture.
492     textureId = GenerateUniqueTextureId();
493     bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
494     mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
495                                                   desiredSize, contentScale, fittingMode, samplingMode,
496                                                   false, cropToMask, useAtlas, textureHash, orientationCorrection,
497                                                   preMultiply, animatedImageLoading, frameIndex ) );
498     cacheIndex = mTextureInfoContainer.size() - 1u;
499
500     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
501                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
502   }
503
504   // The below code path is common whether we are using the cache or not.
505   // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
506   // or a new TextureInfo just created.
507   TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
508   textureInfo.maskTextureId = maskTextureId;
509   textureInfo.storageType = storageType;
510   textureInfo.orientationCorrection = orientationCorrection;
511
512   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n",
513                  GET_LOAD_STATE_STRING(textureInfo.loadState ) );
514
515   // Force reloading of texture by setting loadState unless already loading or cancelled.
516   if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
517        TextureManager::LoadState::LOADING != textureInfo.loadState &&
518        TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
519        TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
520        TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
521        TextureManager::LoadState::CANCELLED != textureInfo.loadState )
522   {
523     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
524                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
525
526     textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
527   }
528
529   // Check if we should add the observer.
530   // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
531   switch( textureInfo.loadState )
532   {
533     case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
534     case TextureManager::LoadState::NOT_STARTED:
535     {
536       LoadOrQueueTexture( textureInfo, observer ); // If called inside NotifyObservers, queues until afterwards
537       break;
538     }
539     case TextureManager::LoadState::LOADING:
540     case TextureManager::LoadState::WAITING_FOR_MASK:
541     case TextureManager::LoadState::MASK_APPLYING:
542     case TextureManager::LoadState::MASK_APPLIED:
543     {
544       ObserveTexture( textureInfo, observer );
545       break;
546     }
547     case TextureManager::LoadState::UPLOADED:
548     {
549       if( observer )
550       {
551         LoadOrQueueTexture( textureInfo, observer );
552       }
553       break;
554     }
555     case TextureManager::LoadState::CANCELLED:
556     {
557       // A cancelled texture hasn't finished loading yet. Treat as a loading texture
558       // (it's ref count has already been incremented, above)
559       textureInfo.loadState = TextureManager::LoadState::LOADING;
560       ObserveTexture( textureInfo, observer );
561       break;
562     }
563     case TextureManager::LoadState::LOAD_FINISHED:
564     {
565       // Loading has already completed.
566       if( observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
567       {
568         LoadOrQueueTexture( textureInfo, observer );
569       }
570       break;
571     }
572   }
573
574   // Return the TextureId for which this Texture can now be referenced by externally.
575   return textureId;
576 }
577
578 void TextureManager::Remove( const TextureManager::TextureId textureId, TextureUploadObserver* observer )
579 {
580   int textureInfoIndex = GetCacheIndexFromId( textureId );
581   if( textureInfoIndex != INVALID_INDEX )
582   {
583     TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
584
585     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
586                    "TextureManager::Remove(%d) url:%s\n  cacheIdx:%d loadState:%s reference count = %d\n",
587                    textureId, textureInfo.url.GetUrl().c_str(),
588                    textureInfoIndex, GET_LOAD_STATE_STRING( textureInfo.loadState ), textureInfo.referenceCount );
589
590     // Decrement the reference count and check if this is the last user of this Texture.
591     if( --textureInfo.referenceCount <= 0 )
592     {
593       // This is the last remove for this Texture.
594       textureInfo.referenceCount = 0;
595       bool removeTextureInfo = false;
596
597       // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
598       if( textureInfo.loadState == LoadState::UPLOADED )
599       {
600         if( textureInfo.atlas )
601         {
602           textureInfo.atlas.Remove( textureInfo.atlasRect );
603         }
604         removeTextureInfo = true;
605       }
606       else if( textureInfo.loadState == LoadState::LOADING )
607       {
608         // We mark the textureInfo for removal.
609         // Once the load has completed, this method will be called again.
610         textureInfo.loadState = LoadState::CANCELLED;
611       }
612       else
613       {
614         // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
615         removeTextureInfo = true;
616       }
617
618       // If the state allows us to remove the TextureInfo data, we do so.
619       if( removeTextureInfo )
620       {
621         // Permanently remove the textureInfo struct.
622         mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
623       }
624     }
625
626     if( observer )
627     {
628       // Remove element from the LoadQueue
629       for( auto&& element : mLoadQueue )
630       {
631         if( element.mObserver == observer )
632         {
633           mLoadQueue.Erase( &element );
634           break;
635         }
636       }
637     }
638   }
639 }
640
641 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
642 {
643   VisualUrl visualUrl("");
644   int cacheIndex = GetCacheIndexFromId( textureId );
645
646   if( cacheIndex != INVALID_CACHE_INDEX )
647   {
648     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
649                    cacheIndex, textureId );
650
651     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
652     visualUrl = cachedTextureInfo.url;
653   }
654   return visualUrl;
655 }
656
657 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
658 {
659   LoadState loadState = TextureManager::LoadState::NOT_STARTED;
660
661   int cacheIndex = GetCacheIndexFromId( textureId );
662   if( cacheIndex != INVALID_CACHE_INDEX )
663   {
664     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
665     loadState = cachedTextureInfo.loadState;
666   }
667   else
668   {
669     for( auto&& elem : mExternalTextures )
670     {
671       if( elem.textureId == textureId )
672       {
673         loadState = LoadState::UPLOADED;
674         break;
675       }
676     }
677   }
678   return loadState;
679 }
680
681 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
682 {
683   LoadState loadState = TextureManager::LoadState::NOT_STARTED;
684
685   int cacheIndex = GetCacheIndexFromId( textureId );
686   if( cacheIndex != INVALID_CACHE_INDEX )
687   {
688     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
689     loadState = cachedTextureInfo.loadState;
690   }
691
692   return loadState;
693 }
694
695 TextureSet TextureManager::GetTextureSet( TextureId textureId )
696 {
697   TextureSet textureSet;// empty handle
698
699   int cacheIndex = GetCacheIndexFromId( textureId );
700   if( cacheIndex != INVALID_CACHE_INDEX )
701   {
702     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
703     textureSet = cachedTextureInfo.textureSet;
704   }
705   else
706   {
707     for( auto&& elem : mExternalTextures )
708     {
709       if( elem.textureId == textureId )
710       {
711         textureSet = elem.textureSet;
712         break;
713       }
714     }
715   }
716   return textureSet;
717 }
718
719 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
720 {
721   TextureManager::ExternalTextureInfo info;
722   info.textureId = GenerateUniqueTextureId();
723   info.textureSet = textureSet;
724   mExternalTextures.emplace_back( info );
725   return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
726 }
727
728 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
729 {
730   if( url.size() > 0u )
731   {
732     // get the location from the Url
733     VisualUrl parseUrl( url );
734     if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
735     {
736       std::string location = parseUrl.GetLocation();
737       if( location.size() > 0u )
738       {
739         TextureId id = std::stoi( location );
740         const auto end = mExternalTextures.end();
741         for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
742         {
743           if( iter->textureId == id )
744           {
745             auto textureSet = iter->textureSet;
746             mExternalTextures.erase( iter );
747             return textureSet;
748           }
749         }
750       }
751     }
752   }
753   return TextureSet();
754 }
755
756 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
757 {
758   // make sure an observer doesn't observe the same object twice
759   // otherwise it will get multiple calls to ObjectDestroyed()
760   DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
761   mLifecycleObservers.PushBack( &observer );
762 }
763
764 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
765 {
766   // Find the observer...
767   auto endIter =  mLifecycleObservers.End();
768   for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
769   {
770     if( (*iter) == &observer)
771     {
772       mLifecycleObservers.Erase( iter );
773       break;
774     }
775   }
776   DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
777 }
778
779 void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
780 {
781   switch( textureInfo.loadState )
782   {
783     case LoadState::NOT_STARTED:
784     case LoadState::LOAD_FAILED:
785     {
786       if( mQueueLoadFlag )
787       {
788         QueueLoadTexture( textureInfo, observer );
789       }
790       else
791       {
792         LoadTexture( textureInfo, observer );
793       }
794       break;
795     }
796     case LoadState::UPLOADED:
797     {
798       if( mQueueLoadFlag )
799       {
800         QueueLoadTexture( textureInfo, observer );
801       }
802       else
803       {
804         // The Texture has already loaded. The other observers have already been notified.
805         // We need to send a "late" loaded notification for this observer.
806         observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
807                                   textureInfo.useAtlas, textureInfo.atlasRect,
808                                   textureInfo.preMultiplied );
809       }
810       break;
811     }
812     case LoadState::LOADING:
813     case LoadState::CANCELLED:
814     case LoadState::LOAD_FINISHED:
815     case LoadState::WAITING_FOR_MASK:
816     case LoadState::MASK_APPLYING:
817     case LoadState::MASK_APPLIED:
818     {
819       break;
820     }
821   }
822 }
823
824 void TextureManager::QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
825 {
826   auto textureId = textureInfo.textureId;
827   mLoadQueue.PushBack( LoadQueueElement( textureId, observer) );
828
829   observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
830 }
831
832 void TextureManager::LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
833 {
834   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n",
835                  textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
836
837   textureInfo.loadState = LoadState::LOADING;
838   if( !textureInfo.loadSynchronously )
839   {
840     auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
841     auto loadingHelperIt = loadersContainer.GetNext();
842     auto premultiplyOnLoad = ( textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID ) ?
843                                DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
844     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
845     if( textureInfo.animatedImageLoading )
846     {
847       loadingHelperIt->LoadAnimatedImage( textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex );
848     }
849     else
850     {
851       loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
852                             textureInfo.desiredSize, textureInfo.fittingMode,
853                             textureInfo.samplingMode, textureInfo.orientationCorrection,
854                             premultiplyOnLoad );
855     }
856   }
857   ObserveTexture( textureInfo, observer );
858 }
859
860 void TextureManager::ProcessQueuedTextures()
861 {
862   for( auto&& element : mLoadQueue )
863   {
864     if( !element.mObserver )
865     {
866       continue;
867     }
868
869     int cacheIndex = GetCacheIndexFromId( element.mTextureId );
870     if( cacheIndex != INVALID_CACHE_INDEX )
871     {
872       TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
873       if( textureInfo.loadState == LoadState::UPLOADED )
874       {
875         element.mObserver->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
876                                            textureInfo.useAtlas, textureInfo.atlasRect,
877                                            textureInfo.preMultiplied );
878       }
879       else if ( textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
880       {
881         element.mObserver->LoadComplete( true, textureInfo.pixelBuffer, textureInfo.url, textureInfo.preMultiplied );
882       }
883       else
884       {
885         LoadTexture( textureInfo, element.mObserver );
886       }
887     }
888   }
889   mLoadQueue.Clear();
890 }
891
892 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
893                                      TextureUploadObserver* observer )
894 {
895   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n",
896                  textureInfo.url.GetUrl().c_str(), observer );
897
898   if( observer )
899   {
900     textureInfo.observerList.PushBack( observer );
901     observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
902   }
903 }
904
905 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
906                                         Devel::PixelBuffer pixelBuffer )
907 {
908   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
909
910   if( loadingContainer.size() >= 1u )
911   {
912     AsyncLoadingInfo loadingInfo = loadingContainer.front();
913
914     if( loadingInfo.loadId == id )
915     {
916       int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
917       if( cacheIndex != INVALID_CACHE_INDEX )
918       {
919         TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
920
921         DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
922                        "  textureId:%d Url:%s CacheIndex:%d LoadState: %d\n",
923                        textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState );
924
925         if( textureInfo.loadState != LoadState::CANCELLED )
926         {
927           // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
928           PostLoad( textureInfo, pixelBuffer );
929         }
930         else
931         {
932           Remove( textureInfo.textureId, nullptr );
933         }
934       }
935     }
936
937     loadingContainer.pop_front();
938   }
939 }
940
941 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
942 {
943   // Was the load successful?
944   if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
945   {
946     // No atlas support for now
947     textureInfo.useAtlas = NO_ATLAS;
948     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
949
950     if( textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE )
951     {
952       // If there is a mask texture ID associated with this texture, then apply the mask
953       // if it's already loaded. If it hasn't, and the mask is still loading,
954       // wait for the mask to finish loading.
955       if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
956       {
957         if( textureInfo.loadState == LoadState::MASK_APPLYING )
958         {
959           textureInfo.loadState = LoadState::MASK_APPLIED;
960           UploadTexture( pixelBuffer, textureInfo );
961           NotifyObservers( textureInfo, true );
962         }
963         else
964         {
965           LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
966           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
967           if( maskLoadState == LoadState::LOADING )
968           {
969             textureInfo.loadState = LoadState::WAITING_FOR_MASK;
970           }
971           else if( maskLoadState == LoadState::LOAD_FINISHED )
972           {
973             // Send New Task to Thread
974             ApplyMask( textureInfo, textureInfo.maskTextureId );
975           }
976         }
977       }
978       else
979       {
980         UploadTexture( pixelBuffer, textureInfo );
981         NotifyObservers( textureInfo, true );
982       }
983     }
984     else
985     {
986       textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
987       textureInfo.loadState = LoadState::LOAD_FINISHED;
988
989       if( textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
990       {
991         NotifyObservers( textureInfo, true );
992       }
993       else
994       {
995         // Check if there was another texture waiting for this load to complete
996         // (e.g. if this was an image mask, and its load is on a different thread)
997         CheckForWaitingTexture( textureInfo );
998       }
999     }
1000   }
1001   else
1002   {
1003     // @todo If the load was unsuccessful, upload the broken image.
1004     textureInfo.loadState = LoadState::LOAD_FAILED;
1005     CheckForWaitingTexture( textureInfo );
1006     NotifyObservers( textureInfo, false );
1007   }
1008 }
1009
1010 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
1011 {
1012   // Search the cache, checking if any texture has this texture id as a
1013   // maskTextureId:
1014   const unsigned int size = mTextureInfoContainer.size();
1015
1016   for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
1017   {
1018     if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
1019         mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK )
1020     {
1021       TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
1022
1023       if( maskTextureInfo.loadState == LoadState::LOAD_FINISHED )
1024       {
1025         // Send New Task to Thread
1026         ApplyMask( textureInfo, maskTextureInfo.textureId );
1027       }
1028       else
1029       {
1030         textureInfo.pixelBuffer.Reset();
1031         textureInfo.loadState = LoadState::LOAD_FAILED;
1032         NotifyObservers( textureInfo, false );
1033       }
1034     }
1035   }
1036 }
1037
1038 void TextureManager::ApplyMask( TextureInfo& textureInfo, TextureId maskTextureId )
1039 {
1040   int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
1041   if( maskCacheIndex != INVALID_CACHE_INDEX )
1042   {
1043     Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
1044     Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
1045     textureInfo.pixelBuffer.Reset();
1046
1047     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n",
1048                    textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
1049
1050     textureInfo.loadState = LoadState::MASK_APPLYING;
1051     auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1052     auto loadingHelperIt = loadersContainer.GetNext();
1053     auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1054     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1055     loadingHelperIt->ApplyMask( textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad );
1056   }
1057 }
1058
1059 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
1060 {
1061   if( textureInfo.useAtlas != USE_ATLAS )
1062   {
1063     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "  TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
1064
1065     // Check if this pixelBuffer is premultiplied
1066     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1067
1068     auto& renderingAddOn = RenderingAddOn::Get();
1069     if( renderingAddOn.IsValid() )
1070     {
1071       renderingAddOn.CreateGeometry( textureInfo.textureId, pixelBuffer );
1072     }
1073
1074     Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
1075                                     pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
1076
1077     PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
1078     texture.Upload( pixelData );
1079     if ( ! textureInfo.textureSet )
1080     {
1081       textureInfo.textureSet = TextureSet::New();
1082     }
1083     textureInfo.textureSet.SetTexture( 0u, texture );
1084   }
1085
1086   // Update the load state.
1087   // Note: This is regardless of success as we care about whether a
1088   // load attempt is in progress or not.  If unsuccessful, a broken
1089   // image is still loaded.
1090   textureInfo.loadState = LoadState::UPLOADED;
1091 }
1092
1093 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
1094 {
1095   TextureId textureId = textureInfo.textureId;
1096
1097   // If there is an observer: Notify the load is complete, whether successful or not,
1098   // and erase it from the list
1099   TextureInfo* info = &textureInfo;
1100
1101   mQueueLoadFlag = true;
1102
1103   while( info->observerList.Count() )
1104   {
1105     TextureUploadObserver* observer = info->observerList[0];
1106
1107     // During UploadComplete() a Control ResourceReady() signal is emitted.
1108     // During that signal the app may add remove /add Textures (e.g. via
1109     // ImageViews).
1110     // It is possible for observers to be removed from the observer list,
1111     // and it is also possible for the mTextureInfoContainer to be modified,
1112     // invalidating the reference to the textureInfo struct.
1113     // Texture load requests for the same URL are deferred until the end of this
1114     // method.
1115     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n",
1116                    textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState ) );
1117
1118     // It is possible for the observer to be deleted.
1119     // Disconnect and remove the observer first.
1120     observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
1121
1122     info->observerList.Erase( info->observerList.begin() );
1123
1124     if( info->storageType == StorageType::RETURN_PIXEL_BUFFER )
1125     {
1126       observer->LoadComplete( success, info->pixelBuffer, info->url, info->preMultiplied );
1127     }
1128     else
1129     {
1130       observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
1131                                 info->preMultiplied );
1132     }
1133
1134     // Get the textureInfo from the container again as it may have been invalidated.
1135     int textureInfoIndex = GetCacheIndexFromId( textureId );
1136     if( textureInfoIndex == INVALID_CACHE_INDEX)
1137     {
1138       break; // texture has been removed - can stop.
1139     }
1140     info = &mTextureInfoContainer[ textureInfoIndex ];
1141   }
1142
1143   mQueueLoadFlag = false;
1144   ProcessQueuedTextures();
1145
1146   if( info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0 )
1147   {
1148     Remove( info->textureId, nullptr );
1149   }
1150 }
1151
1152 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
1153 {
1154   return mCurrentTextureId++;
1155 }
1156
1157 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
1158 {
1159   const unsigned int size = mTextureInfoContainer.size();
1160
1161   for( unsigned int i = 0; i < size; ++i )
1162   {
1163     if( mTextureInfoContainer[i].textureId == textureId )
1164     {
1165       return i;
1166     }
1167   }
1168
1169   return INVALID_CACHE_INDEX;
1170 }
1171
1172 TextureManager::TextureHash TextureManager::GenerateHash(
1173   const std::string&             url,
1174   const ImageDimensions          size,
1175   const FittingMode::Type        fittingMode,
1176   const Dali::SamplingMode::Type samplingMode,
1177   const UseAtlas                 useAtlas,
1178   TextureId                      maskTextureId,
1179   bool                           isAnimationImage,
1180   uint32_t                       frameIndex )
1181 {
1182   std::string hashTarget( url );
1183   const size_t urlLength = hashTarget.length();
1184   const uint16_t width = size.GetWidth();
1185   const uint16_t height = size.GetWidth();
1186
1187   // If either the width or height has been specified, include the resizing options in the hash
1188   if( width != 0 || height != 0 )
1189   {
1190     // We are appending 5 bytes to the URL to form the hash input.
1191     hashTarget.resize( urlLength + 5u );
1192     char* hashTargetPtr = &( hashTarget[ urlLength ] );
1193
1194     // Pack the width and height (4 bytes total).
1195     *hashTargetPtr++ = size.GetWidth() & 0xff;
1196     *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
1197     *hashTargetPtr++ = size.GetHeight() & 0xff;
1198     *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
1199
1200     // Bit-pack the FittingMode, SamplingMode and atlasing.
1201     // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
1202     *hashTargetPtr   = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
1203   }
1204   else
1205   {
1206     // We are not including sizing information, but we still need an extra byte for atlasing.
1207     hashTarget.resize( urlLength + 1u );
1208
1209     // Add the atlasing to the hash input.
1210     switch( useAtlas )
1211     {
1212       case UseAtlas::NO_ATLAS:
1213       {
1214         hashTarget[ urlLength ] = 'f';
1215         break;
1216       }
1217       case UseAtlas::USE_ATLAS:
1218       {
1219         hashTarget[ urlLength ] = 't';
1220         break;
1221       }
1222     }
1223   }
1224
1225   if( isAnimationImage )
1226   {
1227     auto textureIdIndex = hashTarget.length();
1228     hashTarget.resize( hashTarget.length() + sizeof( uint32_t ) );
1229     char* hashTargetPtr = &( hashTarget[ textureIdIndex ] );
1230
1231     for( size_t byteIter = 0; byteIter < sizeof( uint32_t ); ++byteIter )
1232     {
1233       *hashTargetPtr++ = frameIndex & 0xff;
1234       frameIndex >>= 8u;
1235     }
1236   }
1237
1238   if( maskTextureId != INVALID_TEXTURE_ID )
1239   {
1240     auto textureIdIndex = hashTarget.length();
1241     hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
1242     unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
1243
1244     // Append the texture id to the end of the URL byte by byte:
1245     // (to avoid SIGBUS / alignment issues)
1246     for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
1247     {
1248       *hashTargetPtr++ = maskTextureId & 0xff;
1249       maskTextureId >>= 8u;
1250     }
1251   }
1252
1253   return Dali::CalculateHash( hashTarget );
1254 }
1255
1256 int TextureManager::FindCachedTexture(
1257   const TextureManager::TextureHash hash,
1258   const std::string&                url,
1259   const ImageDimensions             size,
1260   const FittingMode::Type           fittingMode,
1261   const Dali::SamplingMode::Type    samplingMode,
1262   const bool                        useAtlas,
1263   TextureId                         maskTextureId,
1264   TextureManager::MultiplyOnLoad    preMultiplyOnLoad,
1265   bool                              isAnimatedImage,
1266   uint32_t                          frameIndex )
1267 {
1268   // Default to an invalid ID, in case we do not find a match.
1269   int cacheIndex = INVALID_CACHE_INDEX;
1270
1271   // Iterate through our hashes to find a match.
1272   const unsigned int count = mTextureInfoContainer.size();
1273   for( unsigned int i = 0u; i < count; ++i )
1274   {
1275     if( mTextureInfoContainer[i].hash == hash )
1276     {
1277       // We have a match, now we check all the original parameters in case of a hash collision.
1278       TextureInfo& textureInfo( mTextureInfoContainer[i] );
1279
1280       if( ( url == textureInfo.url.GetUrl() ) &&
1281           ( useAtlas == textureInfo.useAtlas ) &&
1282           ( maskTextureId == textureInfo.maskTextureId ) &&
1283           ( size == textureInfo.desiredSize ) &&
1284           ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
1285             ( fittingMode == textureInfo.fittingMode &&
1286               samplingMode == textureInfo.samplingMode ) ) &&
1287           ( isAnimatedImage == ( ( textureInfo.animatedImageLoading ) ? true : false ) ) &&
1288           ( frameIndex == textureInfo.frameIndex ) )
1289       {
1290         // 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different.
1291         // 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false.
1292         if( ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad )
1293             || ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied ) )
1294         {
1295           // The found Texture is a match.
1296           cacheIndex = i;
1297           break;
1298         }
1299       }
1300     }
1301   }
1302
1303   return cacheIndex;
1304 }
1305
1306 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1307 {
1308   const unsigned int count = mTextureInfoContainer.size();
1309   for( unsigned int i = 0; i < count; ++i )
1310   {
1311     TextureInfo& textureInfo( mTextureInfoContainer[i] );
1312     for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1313          j != textureInfo.observerList.End(); )
1314     {
1315       if( *j == observer )
1316       {
1317         j = textureInfo.observerList.Erase( j );
1318       }
1319       else
1320       {
1321         ++j;
1322       }
1323     }
1324   }
1325
1326   // Remove element from the LoadQueue
1327   for( auto&& element : mLoadQueue )
1328   {
1329     if( element.mObserver == observer )
1330     {
1331       element.mObserver = nullptr;
1332     }
1333   }
1334 }
1335
1336
1337 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1338 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1339                      AsyncLoadingInfoContainerType())
1340 {
1341 }
1342
1343 void TextureManager::AsyncLoadingHelper::LoadAnimatedImage( TextureId                   textureId,
1344                                                             Dali::AnimatedImageLoading  animatedImageLoading,
1345                                                             uint32_t                    frameIndex )
1346 {
1347   mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
1348   auto id = DevelAsyncImageLoader::LoadAnimatedImage( mLoader, animatedImageLoading, frameIndex );
1349   mLoadingInfoContainer.back().loadId = id;
1350 }
1351
1352 void TextureManager::AsyncLoadingHelper::Load( TextureId                                textureId,
1353                                                const VisualUrl&                         url,
1354                                                ImageDimensions                          desiredSize,
1355                                                FittingMode::Type                        fittingMode,
1356                                                SamplingMode::Type                       samplingMode,
1357                                                bool                                     orientationCorrection,
1358                                                DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
1359 {
1360   mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
1361   auto id = DevelAsyncImageLoader::Load( mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad );
1362   mLoadingInfoContainer.back().loadId = id;
1363 }
1364
1365 void TextureManager::AsyncLoadingHelper::ApplyMask( TextureId                                textureId,
1366                                                     Devel::PixelBuffer                       pixelBuffer,
1367                                                     Devel::PixelBuffer                       maskPixelBuffer,
1368                                                     float                                    contentScale,
1369                                                     bool                                     cropToMask,
1370                                                     DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
1371 {
1372   mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
1373   auto id = DevelAsyncImageLoader::ApplyMask( mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad );
1374   mLoadingInfoContainer.back().loadId = id;
1375 }
1376
1377 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1378 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1379 {
1380 }
1381
1382 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1383     Toolkit::AsyncImageLoader loader,
1384     TextureManager& textureManager,
1385     AsyncLoadingInfoContainerType&& loadingInfoContainer)
1386 : mLoader(loader),
1387   mTextureManager(textureManager),
1388   mLoadingInfoContainer(std::move(loadingInfoContainer))
1389 {
1390   DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1391       this, &AsyncLoadingHelper::AsyncLoadComplete);
1392 }
1393
1394 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t           id,
1395                                                            Devel::PixelBuffer pixelBuffer )
1396 {
1397   mTextureManager.AsyncLoadComplete( mLoadingInfoContainer, id, pixelBuffer );
1398 }
1399
1400 void TextureManager::SetBrokenImageUrl(const std::string& brokenImageUrl)
1401 {
1402   mBrokenImageUrl = brokenImageUrl;
1403 }
1404
1405 const std::string TextureManager::GetBrokenImageUrl()
1406 {
1407   return mBrokenImageUrl;
1408 }
1409
1410 Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements )
1411 {
1412   return RenderingAddOn::Get().IsValid() ?
1413          RenderingAddOn::Get().GetGeometry( textureId, frontElements, backElements) :
1414          Geometry();
1415 }
1416
1417 } // namespace Internal
1418
1419 } // namespace Toolkit
1420
1421 } // namespace Dali