Fix ImageView issue
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / texture-manager-impl.h
1 #ifndef DALI_TOOLKIT_TEXTURE_MANAGER_IMPL_H
2 #define DALI_TOOLKIT_TEXTURE_MANAGER_IMPL_H
3
4 /*
5  * Copyright (c) 2017 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 // EXTERNAL INCLUDES
21 #include <deque>
22 #include <functional>
23 #include <string>
24 #include <memory>
25 #include <dali/public-api/common/dali-vector.h>
26 #include <dali/public-api/object/ref-object.h>
27 #include <dali/public-api/rendering/texture-set.h>
28 #include <dali/devel-api/common/owner-container.h>
29 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
30
31 // INTERNAL INCLUDES
32 #include <dali-toolkit/devel-api/image-loader/async-image-loader-devel.h>
33 #include <dali-toolkit/devel-api/image-loader/image-atlas.h>
34 #include <dali-toolkit/public-api/image-loader/async-image-loader.h>
35 #include <dali-toolkit/internal/visuals/texture-upload-observer.h>
36 #include <dali-toolkit/internal/visuals/visual-url.h>
37 #include <dali-toolkit/internal/helpers/round-robin-container-view.h>
38 #include <dali-toolkit/internal/image-loader/async-image-loader-impl.h>
39
40
41 namespace Dali
42 {
43
44 namespace Toolkit
45 {
46
47 namespace Internal
48 {
49 class ImageAtlasManager;
50 typedef IntrusivePtr<ImageAtlasManager> ImageAtlasManagerPtr;
51
52 /**
53  * The TextureManager provides a common Image loading API for Visuals.
54  *
55  * The TextureManager is responsible for providing sync, async, atlased and non-atlased loads.
56  * Texture caching is provided and performed when possible.
57  * Broken Images are automatically provided on load failure.
58  */
59 class TextureManager : public ConnectionTracker
60 {
61 public:
62
63   typedef int32_t TextureId;       ///< The TextureId type. This is used as a handle to refer to a particular Texture.
64   static const int INVALID_TEXTURE_ID = -1; ///< Used to represent a null TextureId or error
65
66   /**
67    * Whether the texture should be atlased or uploaded into it's own GPU texture
68    */
69   enum UseAtlas
70   {
71     NO_ATLAS,
72     USE_ATLAS
73   };
74
75   /**
76    * Whether the pixel data should be kept in TextureManager, or uploaded for rendering
77    */
78   enum StorageType
79   {
80     KEEP_PIXEL_BUFFER,
81     UPLOAD_TO_TEXTURE
82   };
83
84   /**
85    * Whether the texture should be loaded synchronously or asynchronously.
86    */
87   enum LoadType
88   {
89     LOAD_ASYNCHRONOUSLY,
90     LOAD_SYNCHRONOUSLY
91   };
92
93   /**
94    * @brief The LoadState Enumeration represents the current state of a particular Texture's life-cycle.
95    */
96   enum LoadState
97   {
98     NOT_STARTED,     ///< Default
99     LOADING,         ///< Loading has been started, but not finished.
100     LOAD_FINISHED,   ///< Loading has finished. (for CPU storage only)
101     WAITING_FOR_MASK,///< Loading has finished, but waiting for mask image
102     UPLOADED,        ///< Uploaded and ready. (For GPU upload only)
103     CANCELLED,       ///< Removed before loading completed
104     LOAD_FAILED      ///< Async loading failed, e.g. connection problem
105   };
106
107   /**
108    * @brief Types of reloading policies
109    */
110   enum class ReloadPolicy
111   {
112     CACHED = 0,             ///< Loads cached texture if it exists.
113     FORCED                  ///< Forces reloading of texture.
114   };
115
116   /**
117    * @brief Whether to multiply alpha into color channels on load
118    */
119   enum class MultiplyOnLoad
120   {
121     LOAD_WITHOUT_MULTIPLY = 0, ///< Don't modify the image
122     MULTIPLY_ON_LOAD           ///< Multiply alpha into color channels on load
123   };
124
125 public:
126
127   struct MaskingData
128   {
129     MaskingData();
130     ~MaskingData() = default;
131
132     VisualUrl mAlphaMaskUrl;
133     TextureManager::TextureId mAlphaMaskId;
134     float mContentScaleFactor;
135     bool mCropToMask;
136   };
137   using MaskingDataPointer = std::unique_ptr<MaskingData>;
138
139
140   /**
141    * Class to provide lifecycle event on destruction of texture manager.
142    */
143   struct LifecycleObserver
144   {
145     /**
146      * Called shortly before the texture manager is destroyed.
147      */
148     virtual void TextureManagerDestroyed() = 0;
149   };
150
151   /**
152    * Constructor.
153    */
154   TextureManager();
155
156   /**
157    * Destructor.
158    */
159   ~TextureManager();
160
161   // TextureManager Main API:
162
163   /**
164    * @brief Requests an image load of the given URL.
165    *
166    * The parameters are used to specify how the image is loaded.
167    * The observer has the UploadComplete method called when the load is ready.
168    *
169    * When the client has finished with the Texture, Remove() should be called.
170    *
171    * @param[in] url                   The URL of the image to load
172    * @param[in] desiredSize           The size the image is likely to appear at. This can be set to 0,0 for automatic
173    * @param[in] fittingMode           The FittingMode to use
174    * @param[in] samplingMode          The SamplingMode to use
175    * @param[in] maskInfo              Mask info structure
176    * @param[in] synchronousLoading    true if the URL should be loaded synchronously
177    * @param[out] textureId,           The textureId of the URL
178    * @param[out] textureRect          The rectangle within the texture atlas that this URL occupies,
179    *                                  this is the rectangle in normalized coordinates.
180    * @param[out] textureRectSize      The rectangle within the texture atlas that this URL occupies,
181    *                                  this is the same rectangle in pixels.
182    * @param[in,out] atlasingStatus    Set to USE_ATLAS to attempt atlasing. If atlasing fails, the image will still
183    *                                  be loaded, and marked successful, but this will be set to false.
184    *                                  If atlasing succeeds, this will be set to true.
185    * @param[out] loadingStatus        The loading status of the texture
186    * @param[in] wrapModeU             Horizontal Wrap mode
187    * @param[in] wrapModeV             Vertical Wrap mode
188    * @param[in] textureObserver       The client object should inherit from this and provide the "UploadCompleted" virtual.
189    *                                  This is called when an image load completes (or fails).
190    * @param[in] atlasObserver         This is used if the texture is atlased, and will be called instead of
191    *                                  textureObserver.UploadCompleted
192    * @param[in] imageAtlasManager     The atlas manager to use for atlasing textures
193    * @param[in] orientationCorrection Whether to rotate image to match embedded orientation data
194    * @param[in] reloadPolicy          Forces a reload of the texture even if already cached
195    * @param[in,out] preMultiplyOnLoad True if the image color should be multiplied by it's alpha. Set to false if the
196    *                                  image has no alpha channel
197    *
198    * @return                          The texture set containing the image, or empty if still loading.
199    */
200
201   TextureSet LoadTexture( const VisualUrl&             url,
202                           Dali::ImageDimensions        desiredSize,
203                           Dali::FittingMode::Type      fittingMode,
204                           Dali::SamplingMode::Type     samplingMode,
205                           const MaskingDataPointer&    maskInfo,
206                           bool                         synchronousLoading,
207                           TextureManager::TextureId&   textureId,
208                           Vector4&                     textureRect,
209                           Dali::ImageDimensions&       textureRectSize,
210                           bool&                        atlasingStatus,
211                           bool&                        loadingStatus,
212                           Dali::WrapMode::Type         wrapModeU,
213                           Dali::WrapMode::Type         wrapModeV,
214                           TextureUploadObserver*       textureObserver,
215                           AtlasUploadObserver*         atlasObserver,
216                           ImageAtlasManagerPtr         imageAtlasManager,
217                           bool                         orientationCorrection,
218                           TextureManager::ReloadPolicy reloadPolicy,
219                           MultiplyOnLoad&              preMultiplyOnLoad );
220
221   /**
222    * @brief Requests an image load of the given URL.
223    *
224    * The parameters are used to specify how the image is loaded.
225    * The observer has the UploadComplete method called when the load is ready.
226    *
227    * When the client has finished with the Texture, Remove() should be called.
228    *
229    * @param[in] url                   The URL of the image to load
230    * @param[in] desiredSize           The size the image is likely to appear at. This can be set to 0,0 for automatic
231    * @param[in] fittingMode           The FittingMode to use
232    * @param[in] samplingMode          The SamplingMode to use
233    * @param[in] useAtlasing           Set to USE_ATLAS to attempt atlasing. If atlasing fails, the image will still be loaded, and marked successful,
234    *                                  but "useAtlasing" will be set to false in the "UploadCompleted" callback from the TextureManagerUploadObserver.
235    * @param[in] observer              The client object should inherit from this and provide the "UploadCompleted" virtual.
236    *                                  This is called when an image load completes (or fails).
237    * @param[in] orientationCorrection Whether to rotate image to match embedded orientation data
238    * @param[in] reloadPolicy          Forces a reload of the texture even if already cached
239    * @param[in,out] preMultiplyOnLoad     True if the image color should be multiplied by it's alpha. Set to false if the image has no alpha channel
240    * @return                          A TextureId to use as a handle to reference this Texture
241    */
242   TextureId RequestLoad( const VisualUrl&                   url,
243                          const ImageDimensions              desiredSize,
244                          FittingMode::Type                  fittingMode,
245                          Dali::SamplingMode::Type           samplingMode,
246                          const UseAtlas                     useAtlasing,
247                          TextureUploadObserver*             observer,
248                          bool                               orientationCorrection,
249                          TextureManager::ReloadPolicy       reloadPolicy,
250                          MultiplyOnLoad&                    preMultiplyOnLoad );
251
252   /**
253    * @brief Requests an image load of the given URL, when the texture has
254    * have loaded, it will perform a blend with the image mask, and upload
255    * the blended texture.
256    *
257    * The parameters are used to specify how the image is loaded.
258    * The observer has the UploadComplete method called when the load is ready.
259    *
260    * When the client has finished with the Texture, Remove() should be called.
261    *
262    * @param[in] url                   The URL of the image to load
263    * @param[in] maskTextureId         The texture id of an image to mask this with
264    *                                  (can be INVALID if no masking required)
265    * @param[in] contentScale          The scale factor to apply to the image before masking
266    * @param[in] desiredSize           The size the image is likely to appear at. This can be set to 0,0 for automatic
267    * @param[in] fittingMode           The FittingMode to use
268    * @param[in] samplingMode          The SamplingMode to use
269    * @param[in] useAtlasing           Set to USE_ATLAS to attempt atlasing. If atlasing fails, the image will still
270    *                                  be loaded, and marked successful,
271    *                                  but "useAtlasing" will be set to false in the "UploadCompleted" callback from
272    *                                  the TextureManagerUploadObserver.
273    * @param[in] cropToMask            Only used with masking, this will crop the scaled image to the mask size.
274    *                                  If false, then the mask will be scaled to fit the image before being applied.
275    * @param[in] observer              The client object should inherit from this and provide the "UploadCompleted"
276    *                                  virtual.
277    *                                  This is called when an image load completes (or fails).
278    * @param[in] orientationCorrection Whether to rotate image to match embedded orientation data
279    * @param[in] reloadPolicy          Forces a reload of the texture even if already cached
280    * @param[in] preMultiplyOnLoad     True if the image color should be multiplied by it's alpha. Set to false if the
281    *                                  image has no alpha channel
282    * @return                          A TextureId to use as a handle to reference this Texture
283    */
284   TextureId RequestLoad( const VisualUrl&                   url,
285                          TextureId                          maskTextureId,
286                          float                              contentScale,
287                          const ImageDimensions              desiredSize,
288                          FittingMode::Type                  fittingMode,
289                          Dali::SamplingMode::Type           samplingMode,
290                          const UseAtlas                     useAtlasing,
291                          bool                               cropToMask,
292                          TextureUploadObserver*             observer,
293                          bool                               orientationCorrection,
294                          TextureManager::ReloadPolicy       reloadPolicy,
295                          MultiplyOnLoad&                    preMultiplyOnLoad );
296
297   /**
298    * Requests a masking image to be loaded. This mask is not uploaded to GL,
299    * instead, it is stored in CPU memory, and can be used for CPU blending.
300    */
301   TextureId RequestMaskLoad( const VisualUrl& maskUrl );
302
303   /**
304    * @brief Remove a Texture from the TextureManager.
305    *
306    * Textures are cached and therefore only the removal of the last
307    * occurrence of a Texture will cause its removal internally.
308    *
309    * @param[in] textureId The ID of the Texture to remove.
310    */
311   void Remove( const TextureManager::TextureId textureId );
312
313   /**
314    * @brief Get the visualUrl associated with the texture id.
315    * @param[in] textureId The texture Id to get
316    * @return The visual Url associated with the texture id.
317    */
318   VisualUrl GetVisualUrl( TextureId textureId );
319
320   /**
321    * @brief Get the current state of a texture
322    * @param[in] textureId The texture id to query
323    * @return The loading state if the texture is valid, or NOT_STARTED if the textureId
324    * is not valid.
325    */
326   LoadState GetTextureState( TextureId textureId );
327
328   /**
329    * @brief Get the associated texture set if the texture id is valid
330    * @param[in] textureId The texture Id to look up
331    * @return the associated texture set, or an empty handle if textureId is not valid
332    */
333   TextureSet GetTextureSet( TextureId textureId );
334
335   /**
336    * Adds an external texture to the texture manager
337    * @param[in] texture The texture to add
338    * @return string containing the URL for the texture
339    */
340   std::string AddExternalTexture( TextureSet& texture );
341
342   /**
343    * Removes an external texture from texture manager
344    * @param[in] url The string containing the texture to remove
345    * @return handle to the texture
346    */
347   TextureSet RemoveExternalTexture( const std::string& url );
348
349   /**
350    * Add an observer to the object.
351    * @param[in] observer The observer to add.
352    */
353   void AddObserver( TextureManager::LifecycleObserver& observer );
354
355   /**
356    * Remove an observer from the object
357    * @pre The observer has already been added.
358    * @param[in] observer The observer to remove.
359    */
360   void RemoveObserver( TextureManager::LifecycleObserver& observer );
361
362   /**
363    * @brief Set an image to be used when a visual has failed to correctly render
364    * @param[in] brokenImageUrl The broken image url.
365    */
366   void SetBrokenImageUrl(const std::string& brokenImageUrl);
367
368 private:
369
370   /**
371    * @brief Requests an image load of the given URL, when the texture has
372    * have loaded, if there is a valid maskTextureId, it will perform a
373    * CPU blend with the mask, and upload the blend texture.
374    *
375    * The parameters are used to specify how the image is loaded.
376    * The observer has the UploadComplete method called when the load is ready.
377    *
378    * When the client has finished with the Texture, Remove() should be called.
379    *
380    * @param[in] url                   The URL of the image to load
381    * @param[in] maskTextureId         The texture id of an image to use as a mask. If no mask is required, then set
382    *                                  to INVALID_TEXTURE_ID
383    * @param[in] contentScale          The scaling factor to apply to the content when masking
384    * @param[in] desiredSize           The size the image is likely to appear at. This can be set to 0,0 for automatic
385    * @param[in] fittingMode           The FittingMode to use
386    * @param[in] samplingMode          The SamplingMode to use
387    * @param[in] useAtlasing           Set to USE_ATLAS to attempt atlasing. If atlasing fails, the image will still be
388    *                                  loaded, and marked successful, but "useAtlasing" will be set to false in the
389    *                                  "UploadCompleted" callback from the TextureManagerUploadObserver.
390    * @param[in] cropToMask            Whether to crop the target after masking, or scale the mask to the image before
391    *                                  masking.
392    * @param[in] storageType,          Whether the pixel data is stored in the cache or uploaded to the GPU
393    * @param[in] observer              The client object should inherit from this and provide the "UploadCompleted"
394    *                                  virtual.
395    *                                  This is called when an image load completes (or fails).
396    * @param[in] orientationCorrection Whether to rotate image to match embedded orientation data
397    * @param[in] reloadPolicy          Forces a reload of the texture even if already cached
398    * @param[in] preMultiplyOnLoad     True if the image color should be multiplied by it's alpha. Set to false if
399    *                                  there is no alpha
400    * @return                          A TextureId to use as a handle to reference this Texture
401    */
402   TextureId RequestLoadInternal(
403     const VisualUrl&                    url,
404     TextureId                           maskTextureId,
405     float                               contentScale,
406     const ImageDimensions               desiredSize,
407     FittingMode::Type                   fittingMode,
408     Dali::SamplingMode::Type            samplingMode,
409     UseAtlas                            useAtlas,
410     bool                                cropToMask,
411     StorageType                         storageType,
412     TextureUploadObserver*              observer,
413     bool                                orientationCorrection,
414     TextureManager::ReloadPolicy        reloadPolicy,
415     MultiplyOnLoad&                     preMultiplyOnLoad );
416
417   /**
418    * @brief Get the current state of a texture
419    * @param[in] textureId The texture id to query
420    * @return The loading state if the texture is valid, or NOT_STARTED if the textureId
421    * is not valid.
422    */
423   LoadState GetTextureStateInternal( TextureId textureId );
424
425   typedef size_t TextureHash; ///< The type used to store the hash used for Texture caching.
426
427   // Structs:
428
429   /**
430    * @brief This struct is used to manage the life-cycle of Texture loading and caching.
431    */
432   struct TextureInfo
433   {
434     TextureInfo( TextureId textureId,
435                  TextureId maskTextureId,
436                  const VisualUrl& url,
437                  ImageDimensions desiredSize,
438                  float scaleFactor,
439                  FittingMode::Type fittingMode,
440                  Dali::SamplingMode::Type samplingMode,
441                  bool loadSynchronously,
442                  bool cropToMask,
443                  UseAtlas useAtlas,
444                  TextureManager::TextureHash hash,
445                  bool orientationCorrection,
446                  bool preMultiplyOnLoad )
447     : url( url ),
448       desiredSize( desiredSize ),
449       useSize( desiredSize ),
450       atlasRect( 0.0f, 0.0f, 1.0f, 1.0f ), // Full atlas rectangle
451       textureId( textureId ),
452       maskTextureId( maskTextureId ),
453       hash( hash ),
454       scaleFactor( scaleFactor ),
455       referenceCount( 1u ),
456       loadState( NOT_STARTED ),
457       fittingMode( fittingMode ),
458       samplingMode( samplingMode ),
459       storageType( UPLOAD_TO_TEXTURE ),
460       loadSynchronously( loadSynchronously ),
461       useAtlas( useAtlas ),
462       cropToMask( cropToMask ),
463       orientationCorrection( true ),
464       preMultiplyOnLoad( preMultiplyOnLoad ),
465       preMultiplied( false )
466     {
467     }
468
469     /**
470      * Container type used to store all observer clients of this Texture
471      */
472     typedef Dali::Vector< TextureUploadObserver* > ObserverListType;
473
474     ObserverListType observerList; ///< Container used to store all observer clients of this Texture
475     Toolkit::ImageAtlas atlas;     ///< The atlas this Texture lays within (if any)
476     Devel::PixelBuffer pixelBuffer;///< The PixelBuffer holding the image data (May be empty after upload)
477     TextureSet textureSet;         ///< The TextureSet holding the Texture
478     VisualUrl url;                 ///< The URL of the image
479     ImageDimensions desiredSize;   ///< The size requested
480     ImageDimensions useSize;       ///< The size used
481     Vector4 atlasRect;             ///< The atlas rect used if atlased
482     TextureId textureId;           ///< The TextureId associated with this Texture
483     TextureId maskTextureId;       ///< The mask TextureId to be applied on load
484     TextureManager::TextureHash hash; ///< The hash used to cache this Texture
485     float scaleFactor;             ///< The scale factor to apply to the Texture when masking
486     int16_t referenceCount;        ///< The reference count of clients using this Texture
487     LoadState loadState:4;         ///< The load state showing the load progress of the Texture
488     FittingMode::Type fittingMode:2; ///< The requested FittingMode
489     Dali::SamplingMode::Type samplingMode:3; ///< The requested SamplingMode
490     StorageType storageType:2;     ///< CPU storage / GPU upload;
491     bool loadSynchronously:1;      ///< True if synchronous loading was requested
492     UseAtlas useAtlas:2;           ///< USE_ATLAS if an atlas was requested.
493                                    ///< This is updated to false if atlas is not used
494     bool cropToMask:1;             ///< true if the image should be cropped to the mask size.
495     bool orientationCorrection:1;  ///< true if the image should be rotated to match exif orientation data
496     bool preMultiplyOnLoad:1;      ///< true if the image's color should be multiplied by it's alpha
497     bool preMultiplied:1;          ///< true if the image's color was multiplied by it's alpha
498   };
499
500   /**
501    * Structure to hold info about a texture load queued during NotifyObservers
502    */
503   struct LoadQueueElement
504   {
505     LoadQueueElement( TextureId textureId, TextureUploadObserver* observer )
506     : mTextureId( textureId ),
507       mObserver( observer )
508     {
509     }
510
511     TextureId mTextureId; ///< The texture id of the requested load.
512     TextureUploadObserver* mObserver; ///< Observer of texture load.
513   };
514
515   /**
516    * Struct to hold information about a requested Async load.
517    * This is used to look up a TextureManager::TextureId from the returned AsyncLoad Id.
518    */
519   struct AsyncLoadingInfo
520   {
521     AsyncLoadingInfo( TextureId textureId )
522     : textureId( textureId ),
523       loadId( 0 )
524     {
525     }
526
527     TextureId           textureId;   ///< The external Texture Id assigned to this load
528     uint32_t            loadId;      ///< The load Id used by the async loader to reference this load
529   };
530
531   // Private typedefs:
532
533   typedef std::deque<AsyncLoadingInfo>  AsyncLoadingInfoContainerType;  ///< The container type used to manage Asynchronous loads in progress
534   typedef std::vector<TextureInfo>      TextureInfoContainerType;       ///< The container type used to manage the life-cycle and caching of Textures
535
536   /**
537    * @brief Initiate a load or queue load if NotifyObservers is invoking callbacks
538    * @param[in] textureInfo The TextureInfo struct associated with the Texture
539    * @param[in] observer The observer wishing to observe the texture upload
540    */
541   void LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer );
542
543   /**
544    * @brief Queue a texture load to be subsequently handled by ProcessQueuedTextures.
545    * @param[in] textureInfo The TextureInfo struct associated with the Texture
546    * @param[in] observer The observer wishing to observe the texture upload
547    */
548   void QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer );
549
550   /**
551    * @brief Used internally to initiate a load.
552    * @param[in] textureInfo The TextureInfo struct associated with the Texture
553    * @param[in] observer The observer wishing to observe the texture upload
554    */
555   void LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer );
556
557   /**
558    * @brief Initiate load of textures queued whilst NotifyObservers invoking callbacks.
559    */
560   void ProcessQueuedTextures();
561
562   /**
563    * Add the observer to the observer list
564    * @param[in] textureInfo The TextureInfo struct associated with the texture
565    * @param[in] observer The observer wishing to observe the texture upload
566    */
567   void ObserveTexture( TextureInfo & textureInfo, TextureUploadObserver* observer );
568
569   /**
570    * @brief This signal handler is called when the async local loader finishes loading.
571    * @param[in] id        This is the async image loaders Id
572    * @param[in] pixelBuffer The loaded image data
573    */
574   void AsyncLocalLoadComplete( uint32_t id, Devel::PixelBuffer pixelBuffer );
575
576   /**
577    * @brief This signal handler is called when the async local loader finishes loading.
578    * @param[in] id        This is the async image loaders Id
579    * @param[in] pixelBuffer The loaded image data
580    */
581   void AsyncRemoteLoadComplete( uint32_t id, Devel::PixelBuffer pixelBuffer );
582
583   /**
584    * Common method to handle loading completion
585    * @param[in] container The Async loading container
586    * @param[in] id        This is the async image loaders Id
587    * @param[in] pixelBuffer The loaded image data
588    */
589   void AsyncLoadComplete( AsyncLoadingInfoContainerType& container, uint32_t id, Devel::PixelBuffer pixelBuffer );
590
591   /**
592    * @brief Performs Post-Load steps including atlasing.
593    * @param[in] textureInfo The struct associated with this Texture
594    * @param[in] pixelBuffer The image pixelBuffer
595    * @return    True if successful
596    */
597   void PostLoad( TextureManager::TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer );
598
599   /**
600    * Check if there is a texture waiting to be masked. If there
601    * is then apply this mask and upload it.
602    * @param[in] maskTextureInfo The texture info of the mask that has just loaded.
603    */
604   void CheckForWaitingTexture( TextureInfo& maskTextureInfo );
605
606   /**
607    * Apply the mask to the pixelBuffer.
608    * @param[in] pixelBuffer The pixelBuffer to apply the mask to
609    * @param[in] maskTextureId The texture id of the mask.
610    * @param[in] contentScale The factor to scale the content
611    * @param[in] cropToMask Whether to crop the content to the mask size
612    */
613   void ApplyMask( Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
614                   float contentScale, bool cropToMask );
615
616   /**
617    * Upload the texture specified in pixelBuffer to the appropriate location
618    * @param[in] pixelBuffer The image data to upload
619    * @param[in] textureInfo The texture info containing the location to
620    * store the data to.
621    */
622   void UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo );
623
624   /**
625    * Mark the texture as complete, and inform observers
626    * @param[in] textureInfo The struct associated with this Texture
627    */
628   void UploadComplete( TextureInfo& textureInfo );
629
630   /**
631    * Notify the current observers that the texture upload is complete,
632    * then remove the observers from the list.
633    * @param[in] textureInfo The struct associated with this Texture
634    * @param[in] success If the pixel data was retrieved successfully and uploaded to GPU
635    */
636   void NotifyObservers( TextureInfo& textureInfo, bool success );
637
638   /**
639    * @brief Generates a new, unique TextureId
640    * @return A unique TextureId
641    */
642   TextureManager::TextureId GenerateUniqueTextureId();
643
644   /**
645    * @brief Used to lookup an index into the TextureInfoContainer from a TextureId
646    * @param[in] textureId The TextureId to look up
647    * @return              The cache index
648    */
649   int GetCacheIndexFromId( TextureId textureId );
650
651
652   /**
653    * @brief Generates a hash for caching based on the input parameters.
654    * Only applies size, fitting mode andsampling mode if the size is specified.
655    * Only applies maskTextureId if it isn't INVALID_TEXTURE_ID
656    * Always applies useAtlas.
657    * @param[in] url          The URL of the image to load
658    * @param[in] size         The image size
659    * @param[in] fittingMode  The FittingMode to use
660    * @param[in] samplingMode The SamplingMode to use
661    * @param[in] useAtlas     True if atlased
662    * @param[in] maskTextureId The masking texture id (or INVALID_TEXTURE_ID)
663    * @return                 A hash of the provided data for caching.
664    */
665   TextureHash GenerateHash( const std::string& url, const ImageDimensions size,
666                             const FittingMode::Type fittingMode,
667                             const Dali::SamplingMode::Type samplingMode, const UseAtlas useAtlas,
668                             TextureId maskTextureId );
669
670   /**
671    * @brief Looks up a cached texture by its hash.
672    * If found, the given parameters are used to check there is no hash-collision.
673    * @param[in] hash          The hash to look up
674    * @param[in] url           The URL of the image to load
675    * @param[in] size          The image size
676    * @param[in] fittingMode   The FittingMode to use
677    * @param[in] samplingMode  The SamplingMode to use
678    * @param[in] useAtlas      True if atlased
679    * @param[in] maskTextureId Optional texture ID to use to mask this image
680    * @return A TextureId of a cached Texture if found. Or INVALID_TEXTURE_ID if not found.
681    */
682   TextureManager::TextureId FindCachedTexture(
683     const TextureManager::TextureHash hash,
684     const std::string& url,
685     const ImageDimensions size,
686     const FittingMode::Type fittingMode,
687     const Dali::SamplingMode::Type samplingMode,
688     const bool useAtlas,
689     TextureId maskTextureId,
690     MultiplyOnLoad preMultiplyOnLoad);
691
692 private:
693
694   /**
695    * @brief Helper class to keep the relation between AsyncImageLoader and corresponding LoadingInfo container
696    */
697   class AsyncLoadingHelper : public ConnectionTracker
698   {
699   public:
700     /**
701      * @brief Create an AsyncLoadingHelper.
702      * @param[in] textureManager Reference to the texture manager
703      */
704     AsyncLoadingHelper(TextureManager& textureManager);
705
706     /**
707      * @brief Load a new texture.
708      * @param[in] textureId             TextureId to reference the texture that will be loaded
709      * @param[in] url                   The URL of the image to load
710      * @param[in] desiredSize           The size the image is likely to appear at.
711      *                                  This can be set to 0,0 for automatic
712      * @param[in] fittingMode           The FittingMode to use
713      * @param[in] samplingMode          The SamplingMode to use
714      * @param[in] orientationCorrection Whether to use image metadata to rotate or flip the image,
715      *                                  e.g., from portrait to landscape
716      */
717     void Load(TextureId textureId,
718               const VisualUrl& url,
719               ImageDimensions desiredSize,
720               FittingMode::Type fittingMode,
721               SamplingMode::Type samplingMode,
722               bool orientationCorrection);
723
724   public:
725     AsyncLoadingHelper(const AsyncLoadingHelper&) = delete;
726     AsyncLoadingHelper& operator=(const AsyncLoadingHelper&) = delete;
727
728     AsyncLoadingHelper(AsyncLoadingHelper&& rhs);
729     AsyncLoadingHelper& operator=(AsyncLoadingHelper&&rhs) = delete;
730
731   private:
732     /**
733      * @brief Main constructor that used by all other constructors
734      */
735     AsyncLoadingHelper(Toolkit::AsyncImageLoader loader,
736                        TextureManager& textureManager,
737                        AsyncLoadingInfoContainerType&& loadingInfoContainer);
738
739     /**
740      * @brief Callback to be called when texture loading is complete, it passes the pixel buffer on to texture manager.
741      * @param[in] id          Loader id
742      * @param[in] pixelBuffer Image data
743      */
744     void AsyncLoadComplete(uint32_t id, Devel::PixelBuffer pixelBuffer);
745
746   private:
747     Toolkit::AsyncImageLoader     mLoader;
748     TextureManager&               mTextureManager;
749     AsyncLoadingInfoContainerType mLoadingInfoContainer;
750   };
751
752   struct ExternalTextureInfo
753   {
754     TextureId textureId;
755     TextureSet textureSet;
756   };
757
758 private:
759
760   /**
761    * Deleted copy constructor.
762    */
763   TextureManager( const TextureManager& ) = delete;
764
765   /**
766    * Deleted assignment operator.
767    */
768   TextureManager& operator=( const TextureManager& rhs ) = delete;
769
770   /**
771    * This is called by the TextureManagerUploadObserver when an observer is destroyed.
772    * We use the callback to know when to remove an observer from our notify list.
773    * @param[in] observer The observer that generated the callback
774    */
775   void ObserverDestroyed( TextureUploadObserver* observer );
776
777 private:  // Member Variables:
778
779   TextureInfoContainerType                      mTextureInfoContainer; ///< Used to manage the life-cycle and caching of Textures
780   RoundRobinContainerView< AsyncLoadingHelper > mAsyncLocalLoaders;    ///< The Asynchronous image loaders used to provide all local async loads
781   RoundRobinContainerView< AsyncLoadingHelper > mAsyncRemoteLoaders;   ///< The Asynchronous image loaders used to provide all remote async loads
782   std::vector< ExternalTextureInfo >            mExternalTextures;     ///< Externally provided textures
783   Dali::Vector<LifecycleObserver*>              mLifecycleObservers;   ///< Lifecycle observers of texture manager
784   Dali::Vector<LoadQueueElement>                mLoadQueue;            ///< Queue of textures to load after NotifyObservers
785   std::string                                   mBrokenImageUrl;       ///< Broken image url
786   TextureId                                     mCurrentTextureId;     ///< The current value used for the unique Texture Id generation
787   bool                                          mQueueLoadFlag;        ///< Flag that causes Load Textures to be queued.
788 };
789
790
791 } // name Internal
792
793 } // namespace Toolkit
794
795 } // namespace Dali
796
797 #endif // DALI_TOOLKIT_TEXTURE_MANAGER_IMPL_H