6b31322d4221e1d0f02a66c2e152707175659d9c
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / texture-manager-impl.cpp
1  /*
2  * Copyright (c) 2017 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 #endif
83
84 const uint32_t      DEFAULT_ATLAS_SIZE( 1024u );                     ///< This size can fit 8 by 8 images of average size 128 * 128
85 const Vector4       FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f );       ///< UV Rectangle that covers the full Texture
86 const char * const  BROKEN_IMAGE_URL( DALI_IMAGE_DIR "broken.png" ); ///< URL For the broken image placeholder
87 const int           INVALID_INDEX( -1 );                             ///< Invalid index used to represent a non-existant TextureInfo struct
88 const int           INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
89
90 } // Anonymous namespace
91
92 TextureManager::MaskingData::MaskingData()
93 : mAlphaMaskUrl(),
94   mAlphaMaskId( INVALID_TEXTURE_ID ),
95   mContentScaleFactor( 1.0f ),
96   mCropToMask( true )
97 {
98 }
99
100 TextureManager::TextureManager()
101 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
102   mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
103   mCurrentTextureId( 0 )
104 {
105 }
106
107 TextureSet TextureManager::LoadTexture(
108     const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
109     Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
110     bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
111     bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
112     Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
113     AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
114     TextureManager::ReloadPolicy reloadPolicy )
115 {
116   TextureSet textureSet;
117
118   loadingStatus = false;
119   textureRect = FULL_ATLAS_RECT;
120
121   if( VisualUrl::TEXTURE == url.GetProtocolType())
122   {
123     std::string location = url.GetLocation();
124     if( location.size() > 0u )
125     {
126       TextureId id = std::stoi( location );
127       for( auto&& elem : mExternalTextures )
128       {
129         if( elem.textureId == id )
130         {
131           textureId = elem.textureId;
132           return elem.textureSet;
133         }
134       }
135     }
136   }
137   else if( synchronousLoading )
138   {
139     PixelData data;
140     if( url.IsValid() )
141     {
142       Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
143                                        orientationCorrection  );
144       if( pixelBuffer )
145       {
146         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
147       }
148     }
149     if( !data )
150     {
151       // use broken image
152       textureSet = TextureSet::New();
153       Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
154       if( pixelBuffer )
155       {
156         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
157       }
158       Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
159                                       data.GetWidth(), data.GetHeight() );
160       texture.Upload( data );
161       textureSet = TextureSet::New();
162       textureSet.SetTexture( 0u, texture );
163     }
164     else
165     {
166       if( atlasingStatus ) // attempt atlasing
167       {
168         textureSet = imageAtlasManager->Add( textureRect, data );
169       }
170       if( !textureSet ) // big image, no atlasing or atlasing failed
171       {
172         atlasingStatus = false;
173         Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
174                                         data.GetWidth(), data.GetHeight() );
175         texture.Upload( data );
176         textureSet = TextureSet::New();
177         textureSet.SetTexture( 0u, texture );
178       }
179     }
180   }
181   else
182   {
183     loadingStatus = true;
184     if( atlasingStatus )
185     {
186       textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
187     }
188     if( !textureSet ) // big image, no atlasing or atlasing failed
189     {
190       atlasingStatus = false;
191       if( !maskInfo )
192       {
193         textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
194                                  textureObserver, orientationCorrection, reloadPolicy );
195       }
196       else
197       {
198         textureId = RequestLoad( url,
199                                  maskInfo->mAlphaMaskId,
200                                  maskInfo->mContentScaleFactor,
201                                  desiredSize,
202                                  fittingMode, samplingMode,
203                                  TextureManager::NO_ATLAS,
204                                  maskInfo->mCropToMask,
205                                  textureObserver,
206                                  orientationCorrection,
207                                  reloadPolicy );
208       }
209
210       TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
211       loadingStatus = ( loadState == TextureManager::LOADING );
212
213       if( loadState == TextureManager::UPLOADED )
214       {
215         // UploadComplete has already been called - keep the same texture set
216         textureSet = GetTextureSet( textureId );
217       }
218     }
219   }
220
221   if( ! atlasingStatus && textureSet )
222   {
223     Sampler sampler = Sampler::New();
224     sampler.SetWrapMode(  wrapModeU, wrapModeV  );
225     textureSet.SetSampler( 0u, sampler );
226   }
227
228   return textureSet;
229 }
230
231 TextureManager::TextureId TextureManager::RequestLoad(
232   const VisualUrl&            url,
233   const ImageDimensions       desiredSize,
234   FittingMode::Type           fittingMode,
235   Dali::SamplingMode::Type    samplingMode,
236   const UseAtlas              useAtlas,
237   TextureUploadObserver*      observer,
238   bool                        orientationCorrection,
239   TextureManager::ReloadPolicy reloadPolicy )
240 {
241   return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
242                               false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy );
243 }
244
245 TextureManager::TextureId TextureManager::RequestLoad(
246   const VisualUrl&             url,
247   TextureId                    maskTextureId,
248   float                        contentScale,
249   const ImageDimensions        desiredSize,
250   FittingMode::Type            fittingMode,
251   Dali::SamplingMode::Type     samplingMode,
252   const UseAtlas               useAtlas,
253   bool                         cropToMask,
254   TextureUploadObserver*       observer,
255   bool                         orientationCorrection,
256   TextureManager::ReloadPolicy reloadPolicy )
257 {
258   return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
259                               cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy );
260 }
261
262 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
263 {
264   // Use the normal load procedure to get the alpha mask.
265   return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
266                               SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
267                               TextureManager::ReloadPolicy::CACHED );
268 }
269
270 TextureManager::TextureId TextureManager::RequestLoadInternal(
271   const VisualUrl&               url,
272   TextureId                       maskTextureId,
273   float                           contentScale,
274   const ImageDimensions           desiredSize,
275   FittingMode::Type               fittingMode,
276   Dali::SamplingMode::Type        samplingMode,
277   UseAtlas                        useAtlas,
278   bool                            cropToMask,
279   StorageType                     storageType,
280   TextureUploadObserver*          observer,
281   bool                            orientationCorrection,
282   TextureManager::ReloadPolicy    reloadPolicy )
283 {
284   // First check if the requested Texture is cached.
285   const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
286                                                 maskTextureId );
287
288   TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
289
290   // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
291   int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
292                                       maskTextureId );
293
294   // Check if the requested Texture exists in the cache.
295   if( cacheIndex != INVALID_CACHE_INDEX )
296   {
297     if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
298     {
299       // Mark this texture being used by another client resource. Forced reload would replace the current texture
300       // without the need for incrementing the reference count.
301       ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
302     }
303     textureId = mTextureInfoContainer[ cacheIndex ].textureId;
304     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
305                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
306   }
307
308   if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
309   {
310     // We need a new Texture.
311     textureId = GenerateUniqueTextureId();
312     mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
313                                                   desiredSize, contentScale, fittingMode, samplingMode,
314                                                   false, cropToMask, useAtlas, textureHash, orientationCorrection ) );
315     cacheIndex = mTextureInfoContainer.size() - 1u;
316
317     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
318                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
319   }
320
321   // The below code path is common whether we are using the cache or not.
322   // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
323   // or a new TextureInfo just created.
324   TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
325   textureInfo.maskTextureId = maskTextureId;
326   textureInfo.storageType = storageType;
327   textureInfo.orientationCorrection = orientationCorrection;
328
329   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
330                  textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
331                  textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
332                  textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
333                  textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
334
335   // Force reloading of texture by setting loadState unless already loading or cancelled.
336   if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
337        TextureManager::CANCELLED != textureInfo.loadState )
338   {
339     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
340                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
341     textureInfo.loadState = TextureManager::NOT_STARTED;
342   }
343
344   // Check if we should add the observer.
345   // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
346   switch( textureInfo.loadState )
347   {
348     case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
349     case TextureManager::NOT_STARTED:
350     {
351       LoadTexture( textureInfo );
352       ObserveTexture( textureInfo, observer );
353       break;
354     }
355     case TextureManager::LOADING:
356     {
357       ObserveTexture( textureInfo, observer );
358       break;
359     }
360     case TextureManager::UPLOADED:
361     {
362       if( observer )
363       {
364         // The Texture has already loaded. The other observers have already been notified.
365         // We need to send a "late" loaded notification for this observer.
366         observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
367                                   textureInfo.useAtlas, textureInfo.atlasRect );
368       }
369       break;
370     }
371     case TextureManager::CANCELLED:
372     {
373       // A cancelled texture hasn't finished loading yet. Treat as a loading texture
374       // (it's ref count has already been incremented, above)
375       textureInfo.loadState = TextureManager::LOADING;
376       ObserveTexture( textureInfo, observer );
377       break;
378     }
379     case TextureManager::LOAD_FINISHED:
380     case TextureManager::WAITING_FOR_MASK:
381       // Loading has already completed. Do nothing.
382       break;
383   }
384
385   // Return the TextureId for which this Texture can now be referenced by externally.
386   return textureId;
387 }
388
389 void TextureManager::Remove( const TextureManager::TextureId textureId )
390 {
391   int textureInfoIndex = GetCacheIndexFromId( textureId );
392   if( textureInfoIndex != INVALID_INDEX )
393   {
394     TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
395
396     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
397                    textureId, textureInfoIndex,
398                    textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
399                    textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
400                    textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
401                    textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
402
403     // Decrement the reference count and check if this is the last user of this Texture.
404     if( --textureInfo.referenceCount <= 0 )
405     {
406       // This is the last remove for this Texture.
407       textureInfo.referenceCount = 0;
408       bool removeTextureInfo = false;
409
410       // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
411       if( textureInfo.loadState == UPLOADED )
412       {
413         if( textureInfo.atlas )
414         {
415           textureInfo.atlas.Remove( textureInfo.atlasRect );
416         }
417         removeTextureInfo = true;
418       }
419       else if( textureInfo.loadState == LOADING )
420       {
421         // We mark the textureInfo for removal.
422         // Once the load has completed, this method will be called again.
423         textureInfo.loadState = CANCELLED;
424       }
425       else
426       {
427         // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
428         removeTextureInfo = true;
429       }
430
431       // If the state allows us to remove the TextureInfo data, we do so.
432       if( removeTextureInfo )
433       {
434         // Permanently remove the textureInfo struct.
435         mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
436       }
437     }
438   }
439 }
440
441 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
442 {
443   int cacheIndex = GetCacheIndexFromId( textureId );
444   DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
445
446   TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
447   return cachedTextureInfo.url;
448 }
449
450 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
451 {
452   LoadState loadState = TextureManager::NOT_STARTED;
453
454   int cacheIndex = GetCacheIndexFromId( textureId );
455   if( cacheIndex != INVALID_CACHE_INDEX )
456   {
457     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
458     loadState = cachedTextureInfo.loadState;
459   }
460   else
461   {
462     for( auto&& elem : mExternalTextures )
463     {
464       if( elem.textureId == textureId )
465       {
466         loadState = LoadState::UPLOADED;
467         break;
468       }
469     }
470   }
471   return loadState;
472 }
473
474 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
475 {
476   LoadState loadState = TextureManager::NOT_STARTED;
477
478   int cacheIndex = GetCacheIndexFromId( textureId );
479   if( cacheIndex != INVALID_CACHE_INDEX )
480   {
481     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
482     loadState = cachedTextureInfo.loadState;
483   }
484
485   return loadState;
486 }
487
488 TextureSet TextureManager::GetTextureSet( TextureId textureId )
489 {
490   TextureSet textureSet;// empty handle
491
492   int cacheIndex = GetCacheIndexFromId( textureId );
493   if( cacheIndex != INVALID_CACHE_INDEX )
494   {
495     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
496     textureSet = cachedTextureInfo.textureSet;
497   }
498   else
499   {
500     for( auto&& elem : mExternalTextures )
501     {
502       if( elem.textureId == textureId )
503       {
504         textureSet = elem.textureSet;
505         break;
506       }
507     }
508   }
509   return textureSet;
510 }
511
512 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
513 {
514   TextureManager::ExternalTextureInfo info;
515   info.textureId = GenerateUniqueTextureId();
516   info.textureSet = textureSet;
517   mExternalTextures.emplace_back( info );
518   return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
519 }
520
521 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
522 {
523   if( url.size() > 0u )
524   {
525     // get the location from the Url
526     VisualUrl parseUrl( url );
527     if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
528     {
529       std::string location = parseUrl.GetLocation();
530       if( location.size() > 0u )
531       {
532         TextureId id = std::stoi( location );
533         const auto end = mExternalTextures.end();
534         for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
535         {
536           if( iter->textureId == id )
537           {
538             auto textureSet = iter->textureSet;
539             mExternalTextures.erase( iter );
540             return textureSet;
541           }
542         }
543       }
544     }
545   }
546   return TextureSet();
547 }
548
549 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
550 {
551   bool success = true;
552
553   if( textureInfo.loadState == NOT_STARTED )
554   {
555     textureInfo.loadState = LOADING;
556
557     if( !textureInfo.loadSynchronously )
558     {
559       auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
560       auto loadingHelperIt = loadersContainer.GetNext();
561       DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
562       loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
563                             textureInfo.desiredSize, textureInfo.fittingMode,
564                             textureInfo.samplingMode, textureInfo.orientationCorrection );
565     }
566   }
567
568   return success;
569 }
570
571 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
572                                      TextureUploadObserver* observer )
573 {
574   if( observer )
575   {
576     textureInfo.observerList.PushBack( observer );
577     observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
578   }
579 }
580
581 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
582                                         Devel::PixelBuffer pixelBuffer )
583 {
584   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
585
586   if( loadingContainer.size() >= 1u )
587   {
588     AsyncLoadingInfo loadingInfo = loadingContainer.front();
589
590     if( loadingInfo.loadId == id )
591     {
592       int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
593       if( cacheIndex != INVALID_CACHE_INDEX )
594       {
595         TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
596
597         DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "  CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
598
599         if( textureInfo.loadState != CANCELLED )
600         {
601           // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
602           PostLoad( textureInfo, pixelBuffer );
603         }
604         else
605         {
606           Remove( textureInfo.textureId );
607         }
608       }
609     }
610
611     loadingContainer.pop_front();
612   }
613 }
614
615 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
616 {
617   // Was the load successful?
618   if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
619   {
620     // No atlas support for now
621     textureInfo.useAtlas = NO_ATLAS;
622
623     if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
624     {
625       // If there is a mask texture ID associated with this texture, then apply the mask
626       // if it's already loaded. If it hasn't, and the mask is still loading,
627       // wait for the mask to finish loading.
628       if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
629       {
630         LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
631         if( maskLoadState == LOADING )
632         {
633           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
634           textureInfo.loadState = WAITING_FOR_MASK;
635         }
636         else if( maskLoadState == LOAD_FINISHED )
637         {
638           ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
639           UploadTexture( pixelBuffer, textureInfo );
640           NotifyObservers( textureInfo, true );
641         }
642       }
643       else
644       {
645         UploadTexture( pixelBuffer, textureInfo );
646         NotifyObservers( textureInfo, true );
647       }
648     }
649     else
650     {
651       textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
652       textureInfo.loadState = LOAD_FINISHED;
653
654       // Check if there was another texture waiting for this load to complete
655       // (e.g. if this was an image mask, and its load is on a different thread)
656       CheckForWaitingTexture( textureInfo );
657     }
658   }
659   else
660   {
661     DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
662     // @todo If the load was unsuccessful, upload the broken image.
663     textureInfo.loadState = LOAD_FAILED;
664     CheckForWaitingTexture( textureInfo );
665     NotifyObservers( textureInfo, false );
666   }
667 }
668
669 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
670 {
671   // Search the cache, checking if any texture has this texture id as a
672   // maskTextureId:
673   const unsigned int size = mTextureInfoContainer.size();
674
675   for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
676   {
677     if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
678         mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
679     {
680       TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
681       Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
682       textureInfo.pixelBuffer.Reset();
683
684       if( maskTextureInfo.loadState == LOAD_FINISHED )
685       {
686         ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
687         UploadTexture( pixelBuffer, textureInfo );
688         NotifyObservers( textureInfo, true );
689       }
690       else
691       {
692         DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
693         textureInfo.loadState = LOAD_FAILED;
694         NotifyObservers( textureInfo, false );
695       }
696     }
697   }
698 }
699
700 void TextureManager::ApplyMask(
701   Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
702   float contentScale, bool cropToMask )
703 {
704   int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
705   Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
706   pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
707 }
708
709 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
710 {
711   if( textureInfo.useAtlas != USE_ATLAS )
712   {
713     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "  TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
714
715     Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
716                                     pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
717     PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
718     texture.Upload( pixelData );
719     if ( ! textureInfo.textureSet )
720     {
721       textureInfo.textureSet = TextureSet::New();
722     }
723     textureInfo.textureSet.SetTexture( 0u, texture );
724   }
725
726   // Update the load state.
727   // Note: This is regardless of success as we care about whether a
728   // load attempt is in progress or not.  If unsuccessful, a broken
729   // image is still loaded.
730   textureInfo.loadState = UPLOADED;
731 }
732
733 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
734 {
735   TextureId textureId = textureInfo.textureId;
736
737   // If there is an observer: Notify the load is complete, whether successful or not,
738   // and erase it from the list
739   unsigned int observerCount = textureInfo.observerList.Count();
740   TextureInfo* info = &textureInfo;
741
742   while( observerCount )
743   {
744     TextureUploadObserver* observer = info->observerList[0];
745
746     // During UploadComplete() a Control ResourceReady() signal is emitted.
747     // During that signal the app may add remove /add Textures (e.g. via
748     // ImageViews).  At this point no more observers can be added to the
749     // observerList, because textureInfo.loadState = UPLOADED. However it is
750     // possible for observers to be removed, hence we check the observer list
751     // count every iteration.
752
753     // The reference to the textureInfo struct can also become invalidated,
754     // because new load requests can modify the mTextureInfoContainer list
755     // (e.g. if more requests are pushed back it can cause the list to be
756     // resized invalidating the reference to the TextureInfo ).
757     observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect );
758     observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
759
760     // Get the textureInfo from the container again as it may have been
761     // invalidated,
762
763     int textureInfoIndex = GetCacheIndexFromId( textureId );
764     if( textureInfoIndex == INVALID_CACHE_INDEX)
765     {
766       return; // texture has been removed - can stop.
767     }
768
769     info = &mTextureInfoContainer[ textureInfoIndex ];
770     observerCount = info->observerList.Count();
771     if ( observerCount > 0 )
772     {
773       // remove the observer that was just triggered if it's still in the list
774       for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
775       {
776         if( *j == observer )
777         {
778           info->observerList.Erase( j );
779           observerCount--;
780           break;
781         }
782       }
783     }
784   }
785 }
786
787 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
788 {
789   return mCurrentTextureId++;
790 }
791
792 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
793 {
794   const unsigned int size = mTextureInfoContainer.size();
795
796   for( unsigned int i = 0; i < size; ++i )
797   {
798     if( mTextureInfoContainer[i].textureId == textureId )
799     {
800       return i;
801     }
802   }
803
804   return INVALID_CACHE_INDEX;
805 }
806
807 TextureManager::TextureHash TextureManager::GenerateHash(
808   const std::string&             url,
809   const ImageDimensions          size,
810   const FittingMode::Type        fittingMode,
811   const Dali::SamplingMode::Type samplingMode,
812   const UseAtlas                 useAtlas,
813   TextureId                      maskTextureId )
814 {
815   std::string hashTarget( url );
816   const size_t urlLength = hashTarget.length();
817   const uint16_t width = size.GetWidth();
818   const uint16_t height = size.GetWidth();
819
820   // If either the width or height has been specified, include the resizing options in the hash
821   if( width != 0 || height != 0 )
822   {
823     // We are appending 5 bytes to the URL to form the hash input.
824     hashTarget.resize( urlLength + 5u );
825     char* hashTargetPtr = &( hashTarget[ urlLength ] );
826
827     // Pack the width and height (4 bytes total).
828     *hashTargetPtr++ = size.GetWidth() & 0xff;
829     *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
830     *hashTargetPtr++ = size.GetHeight() & 0xff;
831     *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
832
833     // Bit-pack the FittingMode, SamplingMode and atlasing.
834     // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
835     *hashTargetPtr   = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
836   }
837   else
838   {
839     // We are not including sizing information, but we still need an extra byte for atlasing.
840     hashTarget.resize( urlLength + 1u );
841     // Add the atlasing to the hash input.
842     hashTarget[ urlLength ] = useAtlas;
843   }
844
845   if( maskTextureId != INVALID_TEXTURE_ID )
846   {
847     hashTarget.resize( urlLength + sizeof( TextureId ) );
848     TextureId* hashTargetPtr = reinterpret_cast<TextureId*>(&( hashTarget[ urlLength ] ));
849
850     // Append the hash target to the end of the URL byte by byte:
851     // (to avoid SIGBUS / alignment issues)
852     for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
853     {
854       *hashTargetPtr++ = maskTextureId & 0xff;
855       maskTextureId >>= 8u;
856     }
857   }
858
859   return Dali::CalculateHash( hashTarget );
860 }
861
862 int TextureManager::FindCachedTexture(
863   const TextureManager::TextureHash hash,
864   const std::string&                url,
865   const ImageDimensions             size,
866   const FittingMode::Type           fittingMode,
867   const Dali::SamplingMode::Type    samplingMode,
868   const bool                        useAtlas,
869   TextureId                         maskTextureId)
870 {
871   // Default to an invalid ID, in case we do not find a match.
872   int cacheIndex = INVALID_CACHE_INDEX;
873
874   // Iterate through our hashes to find a match.
875   const unsigned int count = mTextureInfoContainer.size();
876   for( unsigned int i = 0u; i < count; ++i )
877   {
878     if( mTextureInfoContainer[i].hash == hash )
879     {
880       // We have a match, now we check all the original parameters in case of a hash collision.
881       TextureInfo& textureInfo( mTextureInfoContainer[i] );
882
883       if( ( url == textureInfo.url.GetUrl() ) &&
884           ( useAtlas == textureInfo.useAtlas ) &&
885           ( maskTextureId == textureInfo.maskTextureId ) &&
886           ( size == textureInfo.desiredSize ) &&
887           ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
888             ( fittingMode == textureInfo.fittingMode &&
889               samplingMode == textureInfo.samplingMode ) ) )
890       {
891         // The found Texture is a match.
892         cacheIndex = i;
893         break;
894       }
895     }
896   }
897
898   return cacheIndex;
899 }
900
901 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
902 {
903   const unsigned int count = mTextureInfoContainer.size();
904   for( unsigned int i = 0; i < count; ++i )
905   {
906     TextureInfo& textureInfo( mTextureInfoContainer[i] );
907     for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
908          j != textureInfo.observerList.End(); )
909     {
910       if( *j == observer )
911       {
912         j = textureInfo.observerList.Erase( j );
913       }
914       else
915       {
916         ++j;
917       }
918     }
919   }
920 }
921
922 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
923 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
924                      AsyncLoadingInfoContainerType())
925 {
926 }
927
928 void TextureManager::AsyncLoadingHelper::Load(TextureId          textureId,
929                                               const VisualUrl&   url,
930                                               ImageDimensions    desiredSize,
931                                               FittingMode::Type  fittingMode,
932                                               SamplingMode::Type samplingMode,
933                                               bool               orientationCorrection)
934 {
935   mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
936   auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
937   mLoadingInfoContainer.back().loadId = id;
938 }
939
940 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
941 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
942 {
943 }
944
945 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
946     Toolkit::AsyncImageLoader loader,
947     TextureManager& textureManager,
948     AsyncLoadingInfoContainerType&& loadingInfoContainer)
949 : mLoader(loader),
950   mTextureManager(textureManager),
951   mLoadingInfoContainer(std::move(loadingInfoContainer))
952 {
953   DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
954       this, &AsyncLoadingHelper::AsyncLoadComplete);
955 }
956
957 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t           id,
958                                                            Devel::PixelBuffer pixelBuffer)
959 {
960   mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
961 }
962
963 } // namespace Internal
964
965 } // namespace Toolkit
966
967 } // namespace Dali