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