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