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