[dali_1.2.14] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / npatch-loader.cpp
1  /*
2  * Copyright (c) 2016 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/npatch-loader.h>
20
21 // EXTERNAL HEADER
22 #include <dali/devel-api/common/hash.h>
23 #include <dali/devel-api/images/texture-set-image.h>
24
25 namespace Dali
26 {
27
28 namespace Toolkit
29 {
30
31 namespace Internal
32 {
33
34 NPatchLoader::NPatchLoader()
35 {
36 }
37
38 NPatchLoader::~NPatchLoader()
39 {
40 }
41
42 std::size_t NPatchLoader::Load( const std::string& url )
43 {
44   std::size_t hash = CalculateHash( url );
45   OwnerContainer< Data* >::SizeType index = UNINITIALIZED_ID;
46   const OwnerContainer< Data* >::SizeType count = mCache.Count();
47   for( ; index < count; ++index )
48   {
49     if( mCache[ index ]->hash == hash )
50     {
51       // hash match, check url as well in case of hash collision
52       if( mCache[ index ]->url == url )
53       {
54         return index+1u; // valid indices are from 1 onwards
55       }
56     }
57   }
58   // got to the end so no match, decode N patch and append new item to cache
59   NinePatchImage ninePatch = NinePatchImage::New( url );
60   if( ninePatch )
61   {
62     Data* data = new Data();
63     data->hash = hash;
64     data->url = url;
65     BufferImage croppedImage = ninePatch.CreateCroppedBufferImage();
66     if( croppedImage )
67     {
68       data->textureSet = TextureSet::New();
69       TextureSetImage( data->textureSet, 0u, croppedImage );
70       data->croppedWidth = croppedImage.GetWidth();
71       data->croppedHeight = croppedImage.GetHeight();
72       data->stretchPixelsX = ninePatch.GetStretchPixelsX();
73       data->stretchPixelsY = ninePatch.GetStretchPixelsY();
74       mCache.PushBack( data );
75
76       return mCache.Count(); // valid ids start from 1u
77     }
78   }
79   return 0u;
80 }
81
82 bool NPatchLoader::GetNPatchData( std::size_t id, const Data*& data )
83 {
84   if( ( id > UNINITIALIZED_ID )&&( id <= mCache.Count() ) )
85   {
86     data = mCache[ id - 1u ]; // id's start from 1u
87     return true;
88   }
89   data = NULL;
90   return false;
91 }
92
93 } // namespace Internal
94
95 } // namespace Toolkit
96
97 } // namespace Dali