Merge "Make -DUSE_DEFAULT_RESOURCE_DIR=OFF compile again" into devel/master
[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 && !isAnimatedImage)
462   {
463     textureHash = GenerateHash(url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId);
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);
467   }
468
469   TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
470   // Check if the requested Texture exists in the cache.
471   if( cacheIndex != INVALID_CACHE_INDEX )
472   {
473     if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
474     {
475       // Mark this texture being used by another client resource. Forced reload would replace the current texture
476       // without the need for incrementing the reference count.
477       ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
478     }
479     textureId = mTextureInfoContainer[ cacheIndex ].textureId;
480
481     // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
482     preMultiplyOnLoad = mTextureInfoContainer[ cacheIndex ].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
483
484     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
485                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
486   }
487
488   if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
489   {
490     // We need a new Texture.
491     textureId = GenerateUniqueTextureId();
492     bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
493     mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
494                                                   desiredSize, contentScale, fittingMode, samplingMode,
495                                                   false, cropToMask, useAtlas, textureHash, orientationCorrection,
496                                                   preMultiply, animatedImageLoading, frameIndex ) );
497     cacheIndex = mTextureInfoContainer.size() - 1u;
498
499     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
500                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
501   }
502
503   // The below code path is common whether we are using the cache or not.
504   // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
505   // or a new TextureInfo just created.
506   TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
507   textureInfo.maskTextureId = maskTextureId;
508   textureInfo.storageType = storageType;
509   textureInfo.orientationCorrection = orientationCorrection;
510
511   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n",
512                  GET_LOAD_STATE_STRING(textureInfo.loadState ) );
513
514   // Force reloading of texture by setting loadState unless already loading or cancelled.
515   if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
516        TextureManager::LoadState::LOADING != textureInfo.loadState &&
517        TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
518        TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
519        TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
520        TextureManager::LoadState::CANCELLED != textureInfo.loadState )
521   {
522     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
523                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
524
525     textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
526   }
527
528   // Check if we should add the observer.
529   // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
530   switch( textureInfo.loadState )
531   {
532     case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
533     case TextureManager::LoadState::NOT_STARTED:
534     {
535       LoadOrQueueTexture( textureInfo, observer ); // If called inside NotifyObservers, queues until afterwards
536       break;
537     }
538     case TextureManager::LoadState::LOADING:
539     case TextureManager::LoadState::WAITING_FOR_MASK:
540     case TextureManager::LoadState::MASK_APPLYING:
541     case TextureManager::LoadState::MASK_APPLIED:
542     {
543       ObserveTexture( textureInfo, observer );
544       break;
545     }
546     case TextureManager::LoadState::UPLOADED:
547     {
548       if( observer )
549       {
550         LoadOrQueueTexture( textureInfo, observer );
551       }
552       break;
553     }
554     case TextureManager::LoadState::CANCELLED:
555     {
556       // A cancelled texture hasn't finished loading yet. Treat as a loading texture
557       // (it's ref count has already been incremented, above)
558       textureInfo.loadState = TextureManager::LoadState::LOADING;
559       ObserveTexture( textureInfo, observer );
560       break;
561     }
562     case TextureManager::LoadState::LOAD_FINISHED:
563     {
564       // Loading has already completed.
565       if( observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
566       {
567         LoadOrQueueTexture( textureInfo, observer );
568       }
569       break;
570     }
571   }
572
573   // Return the TextureId for which this Texture can now be referenced by externally.
574   return textureId;
575 }
576
577 void TextureManager::Remove( const TextureManager::TextureId textureId, TextureUploadObserver* observer )
578 {
579   int textureInfoIndex = GetCacheIndexFromId( textureId );
580   if( textureInfoIndex != INVALID_INDEX )
581   {
582     TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
583
584     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
585                    "TextureManager::Remove(%d) url:%s\n  cacheIdx:%d loadState:%s reference count = %d\n",
586                    textureId, textureInfo.url.GetUrl().c_str(),
587                    textureInfoIndex, GET_LOAD_STATE_STRING( textureInfo.loadState ), textureInfo.referenceCount );
588
589     // Decrement the reference count and check if this is the last user of this Texture.
590     if( --textureInfo.referenceCount <= 0 )
591     {
592       // This is the last remove for this Texture.
593       textureInfo.referenceCount = 0;
594       bool removeTextureInfo = false;
595
596       // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
597       if( textureInfo.loadState == LoadState::UPLOADED )
598       {
599         if( textureInfo.atlas )
600         {
601           textureInfo.atlas.Remove( textureInfo.atlasRect );
602         }
603         removeTextureInfo = true;
604       }
605       else if( textureInfo.loadState == LoadState::LOADING )
606       {
607         // We mark the textureInfo for removal.
608         // Once the load has completed, this method will be called again.
609         textureInfo.loadState = LoadState::CANCELLED;
610       }
611       else
612       {
613         // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
614         removeTextureInfo = true;
615       }
616
617       // If the state allows us to remove the TextureInfo data, we do so.
618       if( removeTextureInfo )
619       {
620         // Permanently remove the textureInfo struct.
621         mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
622       }
623     }
624
625     if( observer )
626     {
627       // Remove element from the LoadQueue
628       for( auto&& element : mLoadQueue )
629       {
630         if( element.mObserver == observer )
631         {
632           mLoadQueue.Erase( &element );
633           break;
634         }
635       }
636     }
637   }
638 }
639
640 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
641 {
642   VisualUrl visualUrl("");
643   int cacheIndex = GetCacheIndexFromId( textureId );
644
645   if( cacheIndex != INVALID_CACHE_INDEX )
646   {
647     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
648                    cacheIndex, textureId );
649
650     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
651     visualUrl = cachedTextureInfo.url;
652   }
653   return visualUrl;
654 }
655
656 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
657 {
658   LoadState loadState = TextureManager::LoadState::NOT_STARTED;
659
660   int cacheIndex = GetCacheIndexFromId( textureId );
661   if( cacheIndex != INVALID_CACHE_INDEX )
662   {
663     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
664     loadState = cachedTextureInfo.loadState;
665   }
666   else
667   {
668     for( auto&& elem : mExternalTextures )
669     {
670       if( elem.textureId == textureId )
671       {
672         loadState = LoadState::UPLOADED;
673         break;
674       }
675     }
676   }
677   return loadState;
678 }
679
680 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
681 {
682   LoadState loadState = TextureManager::LoadState::NOT_STARTED;
683
684   int cacheIndex = GetCacheIndexFromId( textureId );
685   if( cacheIndex != INVALID_CACHE_INDEX )
686   {
687     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
688     loadState = cachedTextureInfo.loadState;
689   }
690
691   return loadState;
692 }
693
694 TextureSet TextureManager::GetTextureSet( TextureId textureId )
695 {
696   TextureSet textureSet;// empty handle
697
698   int cacheIndex = GetCacheIndexFromId( textureId );
699   if( cacheIndex != INVALID_CACHE_INDEX )
700   {
701     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
702     textureSet = cachedTextureInfo.textureSet;
703   }
704   else
705   {
706     for( auto&& elem : mExternalTextures )
707     {
708       if( elem.textureId == textureId )
709       {
710         textureSet = elem.textureSet;
711         break;
712       }
713     }
714   }
715   return textureSet;
716 }
717
718 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
719 {
720   TextureManager::ExternalTextureInfo info;
721   info.textureId = GenerateUniqueTextureId();
722   info.textureSet = textureSet;
723   mExternalTextures.emplace_back( info );
724   return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
725 }
726
727 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
728 {
729   if( url.size() > 0u )
730   {
731     // get the location from the Url
732     VisualUrl parseUrl( url );
733     if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
734     {
735       std::string location = parseUrl.GetLocation();
736       if( location.size() > 0u )
737       {
738         TextureId id = std::stoi( location );
739         const auto end = mExternalTextures.end();
740         for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
741         {
742           if( iter->textureId == id )
743           {
744             auto textureSet = iter->textureSet;
745             mExternalTextures.erase( iter );
746             return textureSet;
747           }
748         }
749       }
750     }
751   }
752   return TextureSet();
753 }
754
755 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
756 {
757   // make sure an observer doesn't observe the same object twice
758   // otherwise it will get multiple calls to ObjectDestroyed()
759   DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
760   mLifecycleObservers.PushBack( &observer );
761 }
762
763 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
764 {
765   // Find the observer...
766   auto endIter =  mLifecycleObservers.End();
767   for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
768   {
769     if( (*iter) == &observer)
770     {
771       mLifecycleObservers.Erase( iter );
772       break;
773     }
774   }
775   DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
776 }
777
778 void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
779 {
780   switch( textureInfo.loadState )
781   {
782     case LoadState::NOT_STARTED:
783     case LoadState::LOAD_FAILED:
784     {
785       if( mQueueLoadFlag )
786       {
787         QueueLoadTexture( textureInfo, observer );
788       }
789       else
790       {
791         LoadTexture( textureInfo, observer );
792       }
793       break;
794     }
795     case LoadState::UPLOADED:
796     {
797       if( mQueueLoadFlag )
798       {
799         QueueLoadTexture( textureInfo, observer );
800       }
801       else
802       {
803         // The Texture has already loaded. The other observers have already been notified.
804         // We need to send a "late" loaded notification for this observer.
805         observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
806                                   textureInfo.useAtlas, textureInfo.atlasRect,
807                                   textureInfo.preMultiplied );
808       }
809       break;
810     }
811     case LoadState::LOADING:
812     case LoadState::CANCELLED:
813     case LoadState::LOAD_FINISHED:
814     case LoadState::WAITING_FOR_MASK:
815     case LoadState::MASK_APPLYING:
816     case LoadState::MASK_APPLIED:
817     {
818       break;
819     }
820   }
821 }
822
823 void TextureManager::QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
824 {
825   auto textureId = textureInfo.textureId;
826   mLoadQueue.PushBack( LoadQueueElement( textureId, observer) );
827
828   observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
829 }
830
831 void TextureManager::LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
832 {
833   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n",
834                  textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
835
836   textureInfo.loadState = LoadState::LOADING;
837   if( !textureInfo.loadSynchronously )
838   {
839     auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
840     auto loadingHelperIt = loadersContainer.GetNext();
841     auto premultiplyOnLoad = ( textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID ) ?
842                                DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
843     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
844     if( textureInfo.animatedImageLoading )
845     {
846       loadingHelperIt->LoadAnimatedImage( textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex );
847     }
848     else
849     {
850       loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
851                             textureInfo.desiredSize, textureInfo.fittingMode,
852                             textureInfo.samplingMode, textureInfo.orientationCorrection,
853                             premultiplyOnLoad );
854     }
855   }
856   ObserveTexture( textureInfo, observer );
857 }
858
859 void TextureManager::ProcessQueuedTextures()
860 {
861   for( auto&& element : mLoadQueue )
862   {
863     if( !element.mObserver )
864     {
865       continue;
866     }
867
868     int cacheIndex = GetCacheIndexFromId( element.mTextureId );
869     if( cacheIndex != INVALID_CACHE_INDEX )
870     {
871       TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
872       if( textureInfo.loadState == LoadState::UPLOADED )
873       {
874         element.mObserver->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
875                                            textureInfo.useAtlas, textureInfo.atlasRect,
876                                            textureInfo.preMultiplied );
877       }
878       else if ( textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
879       {
880         element.mObserver->LoadComplete( true, textureInfo.pixelBuffer, textureInfo.url, textureInfo.preMultiplied );
881       }
882       else
883       {
884         LoadTexture( textureInfo, element.mObserver );
885       }
886     }
887   }
888   mLoadQueue.Clear();
889 }
890
891 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
892                                      TextureUploadObserver* observer )
893 {
894   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n",
895                  textureInfo.url.GetUrl().c_str(), observer );
896
897   if( observer )
898   {
899     textureInfo.observerList.PushBack( observer );
900     observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
901   }
902 }
903
904 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
905                                         Devel::PixelBuffer pixelBuffer )
906 {
907   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
908
909   if( loadingContainer.size() >= 1u )
910   {
911     AsyncLoadingInfo loadingInfo = loadingContainer.front();
912
913     if( loadingInfo.loadId == id )
914     {
915       int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
916       if( cacheIndex != INVALID_CACHE_INDEX )
917       {
918         TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
919
920         DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
921                        "  textureId:%d Url:%s CacheIndex:%d LoadState: %d\n",
922                        textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState );
923
924         if( textureInfo.loadState != LoadState::CANCELLED )
925         {
926           // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
927           PostLoad( textureInfo, pixelBuffer );
928         }
929         else
930         {
931           Remove( textureInfo.textureId, nullptr );
932         }
933       }
934     }
935
936     loadingContainer.pop_front();
937   }
938 }
939
940 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
941 {
942   // Was the load successful?
943   if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
944   {
945     // No atlas support for now
946     textureInfo.useAtlas = NO_ATLAS;
947     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
948
949     if( textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE )
950     {
951       // If there is a mask texture ID associated with this texture, then apply the mask
952       // if it's already loaded. If it hasn't, and the mask is still loading,
953       // wait for the mask to finish loading.
954       if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
955       {
956         if( textureInfo.loadState == LoadState::MASK_APPLYING )
957         {
958           textureInfo.loadState = LoadState::MASK_APPLIED;
959           UploadTexture( pixelBuffer, textureInfo );
960           NotifyObservers( textureInfo, true );
961         }
962         else
963         {
964           LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
965           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
966           if( maskLoadState == LoadState::LOADING )
967           {
968             textureInfo.loadState = LoadState::WAITING_FOR_MASK;
969           }
970           else if( maskLoadState == LoadState::LOAD_FINISHED )
971           {
972             // Send New Task to Thread
973             ApplyMask( textureInfo, textureInfo.maskTextureId );
974           }
975         }
976       }
977       else
978       {
979         UploadTexture( pixelBuffer, textureInfo );
980         NotifyObservers( textureInfo, true );
981       }
982     }
983     else
984     {
985       textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
986       textureInfo.loadState = LoadState::LOAD_FINISHED;
987
988       if( textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
989       {
990         NotifyObservers( textureInfo, true );
991       }
992       else
993       {
994         // Check if there was another texture waiting for this load to complete
995         // (e.g. if this was an image mask, and its load is on a different thread)
996         CheckForWaitingTexture( textureInfo );
997       }
998     }
999   }
1000   else
1001   {
1002     textureInfo.loadState = LoadState::LOAD_FAILED;
1003     CheckForWaitingTexture( textureInfo );
1004     NotifyObservers( textureInfo, false );
1005   }
1006 }
1007
1008 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
1009 {
1010   // Search the cache, checking if any texture has this texture id as a
1011   // maskTextureId:
1012   const unsigned int size = mTextureInfoContainer.size();
1013
1014   for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
1015   {
1016     if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
1017         mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK )
1018     {
1019       TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
1020
1021       if( maskTextureInfo.loadState == LoadState::LOAD_FINISHED )
1022       {
1023         // Send New Task to Thread
1024         ApplyMask( textureInfo, maskTextureInfo.textureId );
1025       }
1026       else
1027       {
1028         textureInfo.pixelBuffer.Reset();
1029         textureInfo.loadState = LoadState::LOAD_FAILED;
1030         NotifyObservers( textureInfo, false );
1031       }
1032     }
1033   }
1034 }
1035
1036 void TextureManager::ApplyMask( TextureInfo& textureInfo, TextureId maskTextureId )
1037 {
1038   int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
1039   if( maskCacheIndex != INVALID_CACHE_INDEX )
1040   {
1041     Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
1042     Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
1043     textureInfo.pixelBuffer.Reset();
1044
1045     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n",
1046                    textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
1047
1048     textureInfo.loadState = LoadState::MASK_APPLYING;
1049     auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1050     auto loadingHelperIt = loadersContainer.GetNext();
1051     auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1052     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1053     loadingHelperIt->ApplyMask( textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad );
1054   }
1055 }
1056
1057 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
1058 {
1059   if( textureInfo.useAtlas != USE_ATLAS )
1060   {
1061     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "  TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
1062
1063     // Check if this pixelBuffer is premultiplied
1064     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1065
1066     auto& renderingAddOn = RenderingAddOn::Get();
1067     if( renderingAddOn.IsValid() )
1068     {
1069       renderingAddOn.CreateGeometry( textureInfo.textureId, pixelBuffer );
1070     }
1071
1072     Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
1073                                     pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
1074
1075     PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
1076     texture.Upload( pixelData );
1077     if ( ! textureInfo.textureSet )
1078     {
1079       textureInfo.textureSet = TextureSet::New();
1080     }
1081     textureInfo.textureSet.SetTexture( 0u, texture );
1082   }
1083
1084   // Update the load state.
1085   // Note: This is regardless of success as we care about whether a
1086   // load attempt is in progress or not.  If unsuccessful, a broken
1087   // image is still loaded.
1088   textureInfo.loadState = LoadState::UPLOADED;
1089 }
1090
1091 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
1092 {
1093   TextureId textureId = textureInfo.textureId;
1094
1095   // If there is an observer: Notify the load is complete, whether successful or not,
1096   // and erase it from the list
1097   TextureInfo* info = &textureInfo;
1098
1099   mQueueLoadFlag = true;
1100
1101   while( info->observerList.Count() )
1102   {
1103     TextureUploadObserver* observer = info->observerList[0];
1104
1105     // During UploadComplete() a Control ResourceReady() signal is emitted.
1106     // During that signal the app may add remove /add Textures (e.g. via
1107     // ImageViews).
1108     // It is possible for observers to be removed from the observer list,
1109     // and it is also possible for the mTextureInfoContainer to be modified,
1110     // invalidating the reference to the textureInfo struct.
1111     // Texture load requests for the same URL are deferred until the end of this
1112     // method.
1113     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n",
1114                    textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState ) );
1115
1116     // It is possible for the observer to be deleted.
1117     // Disconnect and remove the observer first.
1118     observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
1119
1120     info->observerList.Erase( info->observerList.begin() );
1121
1122     if( info->storageType == StorageType::RETURN_PIXEL_BUFFER )
1123     {
1124       observer->LoadComplete( success, info->pixelBuffer, info->url, info->preMultiplied );
1125     }
1126     else
1127     {
1128       observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
1129                                 info->preMultiplied );
1130     }
1131
1132     // Get the textureInfo from the container again as it may have been invalidated.
1133     int textureInfoIndex = GetCacheIndexFromId( textureId );
1134     if( textureInfoIndex == INVALID_CACHE_INDEX)
1135     {
1136       break; // texture has been removed - can stop.
1137     }
1138     info = &mTextureInfoContainer[ textureInfoIndex ];
1139   }
1140
1141   mQueueLoadFlag = false;
1142   ProcessQueuedTextures();
1143
1144   if( info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0 )
1145   {
1146     Remove( info->textureId, nullptr );
1147   }
1148 }
1149
1150 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
1151 {
1152   return mCurrentTextureId++;
1153 }
1154
1155 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
1156 {
1157   const unsigned int size = mTextureInfoContainer.size();
1158
1159   for( unsigned int i = 0; i < size; ++i )
1160   {
1161     if( mTextureInfoContainer[i].textureId == textureId )
1162     {
1163       return i;
1164     }
1165   }
1166
1167   return INVALID_CACHE_INDEX;
1168 }
1169
1170 TextureManager::TextureHash TextureManager::GenerateHash(
1171   const std::string&             url,
1172   const ImageDimensions          size,
1173   const FittingMode::Type        fittingMode,
1174   const Dali::SamplingMode::Type samplingMode,
1175   const UseAtlas                 useAtlas,
1176   TextureId                      maskTextureId)
1177 {
1178   std::string hashTarget( url );
1179   const size_t urlLength = hashTarget.length();
1180   const uint16_t width = size.GetWidth();
1181   const uint16_t height = size.GetWidth();
1182
1183   // If either the width or height has been specified, include the resizing options in the hash
1184   if( width != 0 || height != 0 )
1185   {
1186     // We are appending 5 bytes to the URL to form the hash input.
1187     hashTarget.resize( urlLength + 5u );
1188     char* hashTargetPtr = &( hashTarget[ urlLength ] );
1189
1190     // Pack the width and height (4 bytes total).
1191     *hashTargetPtr++ = size.GetWidth() & 0xff;
1192     *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
1193     *hashTargetPtr++ = size.GetHeight() & 0xff;
1194     *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
1195
1196     // Bit-pack the FittingMode, SamplingMode and atlasing.
1197     // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
1198     *hashTargetPtr   = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
1199   }
1200   else
1201   {
1202     // We are not including sizing information, but we still need an extra byte for atlasing.
1203     hashTarget.resize( urlLength + 1u );
1204
1205     // Add the atlasing to the hash input.
1206     switch( useAtlas )
1207     {
1208       case UseAtlas::NO_ATLAS:
1209       {
1210         hashTarget[ urlLength ] = 'f';
1211         break;
1212       }
1213       case UseAtlas::USE_ATLAS:
1214       {
1215         hashTarget[ urlLength ] = 't';
1216         break;
1217       }
1218     }
1219   }
1220
1221   if( maskTextureId != INVALID_TEXTURE_ID )
1222   {
1223     auto textureIdIndex = hashTarget.length();
1224     hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
1225     unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
1226
1227     // Append the texture id to the end of the URL byte by byte:
1228     // (to avoid SIGBUS / alignment issues)
1229     for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
1230     {
1231       *hashTargetPtr++ = maskTextureId & 0xff;
1232       maskTextureId >>= 8u;
1233     }
1234   }
1235
1236   return Dali::CalculateHash( hashTarget );
1237 }
1238
1239 int TextureManager::FindCachedTexture(
1240   const TextureManager::TextureHash hash,
1241   const std::string&                url,
1242   const ImageDimensions             size,
1243   const FittingMode::Type           fittingMode,
1244   const Dali::SamplingMode::Type    samplingMode,
1245   const bool                        useAtlas,
1246   TextureId                         maskTextureId,
1247   TextureManager::MultiplyOnLoad    preMultiplyOnLoad)
1248 {
1249   // Default to an invalid ID, in case we do not find a match.
1250   int cacheIndex = INVALID_CACHE_INDEX;
1251
1252   // Iterate through our hashes to find a match.
1253   const unsigned int count = mTextureInfoContainer.size();
1254   for( unsigned int i = 0u; i < count; ++i )
1255   {
1256     if( mTextureInfoContainer[i].hash == hash )
1257     {
1258       // We have a match, now we check all the original parameters in case of a hash collision.
1259       TextureInfo& textureInfo( mTextureInfoContainer[i] );
1260
1261       if( ( url == textureInfo.url.GetUrl() ) &&
1262           ( useAtlas == textureInfo.useAtlas ) &&
1263           ( maskTextureId == textureInfo.maskTextureId ) &&
1264           ( size == textureInfo.desiredSize ) &&
1265           ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
1266             ( fittingMode == textureInfo.fittingMode &&
1267               samplingMode == textureInfo.samplingMode ) ) )
1268       {
1269         // 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different.
1270         // 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false.
1271         if( ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad )
1272             || ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied ) )
1273         {
1274           // The found Texture is a match.
1275           cacheIndex = i;
1276           break;
1277         }
1278       }
1279     }
1280   }
1281
1282   return cacheIndex;
1283 }
1284
1285 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1286 {
1287   const unsigned int count = mTextureInfoContainer.size();
1288   for( unsigned int i = 0; i < count; ++i )
1289   {
1290     TextureInfo& textureInfo( mTextureInfoContainer[i] );
1291     for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1292          j != textureInfo.observerList.End(); )
1293     {
1294       if( *j == observer )
1295       {
1296         j = textureInfo.observerList.Erase( j );
1297       }
1298       else
1299       {
1300         ++j;
1301       }
1302     }
1303   }
1304
1305   // Remove element from the LoadQueue
1306   for( auto&& element : mLoadQueue )
1307   {
1308     if( element.mObserver == observer )
1309     {
1310       element.mObserver = nullptr;
1311     }
1312   }
1313 }
1314
1315
1316 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1317 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1318                      AsyncLoadingInfoContainerType())
1319 {
1320 }
1321
1322 void TextureManager::AsyncLoadingHelper::LoadAnimatedImage( TextureId                   textureId,
1323                                                             Dali::AnimatedImageLoading  animatedImageLoading,
1324                                                             uint32_t                    frameIndex )
1325 {
1326   mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
1327   auto id = DevelAsyncImageLoader::LoadAnimatedImage( mLoader, animatedImageLoading, frameIndex );
1328   mLoadingInfoContainer.back().loadId = id;
1329 }
1330
1331 void TextureManager::AsyncLoadingHelper::Load( TextureId                                textureId,
1332                                                const VisualUrl&                         url,
1333                                                ImageDimensions                          desiredSize,
1334                                                FittingMode::Type                        fittingMode,
1335                                                SamplingMode::Type                       samplingMode,
1336                                                bool                                     orientationCorrection,
1337                                                DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
1338 {
1339   mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
1340   auto id = DevelAsyncImageLoader::Load( mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad );
1341   mLoadingInfoContainer.back().loadId = id;
1342 }
1343
1344 void TextureManager::AsyncLoadingHelper::ApplyMask( TextureId                                textureId,
1345                                                     Devel::PixelBuffer                       pixelBuffer,
1346                                                     Devel::PixelBuffer                       maskPixelBuffer,
1347                                                     float                                    contentScale,
1348                                                     bool                                     cropToMask,
1349                                                     DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
1350 {
1351   mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
1352   auto id = DevelAsyncImageLoader::ApplyMask( mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad );
1353   mLoadingInfoContainer.back().loadId = id;
1354 }
1355
1356 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1357 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1358 {
1359 }
1360
1361 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1362     Toolkit::AsyncImageLoader loader,
1363     TextureManager& textureManager,
1364     AsyncLoadingInfoContainerType&& loadingInfoContainer)
1365 : mLoader(loader),
1366   mTextureManager(textureManager),
1367   mLoadingInfoContainer(std::move(loadingInfoContainer))
1368 {
1369   DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1370       this, &AsyncLoadingHelper::AsyncLoadComplete);
1371 }
1372
1373 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t           id,
1374                                                            Devel::PixelBuffer pixelBuffer )
1375 {
1376   mTextureManager.AsyncLoadComplete( mLoadingInfoContainer, id, pixelBuffer );
1377 }
1378
1379 void TextureManager::SetBrokenImageUrl(const std::string& brokenImageUrl)
1380 {
1381   mBrokenImageUrl = brokenImageUrl;
1382 }
1383
1384 Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements )
1385 {
1386   return RenderingAddOn::Get().IsValid() ?
1387          RenderingAddOn::Get().GetGeometry( textureId, frontElements, backElements) :
1388          Geometry();
1389 }
1390
1391 } // namespace Internal
1392
1393 } // namespace Toolkit
1394
1395 } // namespace Dali