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