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