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