Merge "If the currently focused actor is hidden or disabled, it should lose focus...
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / svg / svg-visual.cpp
1 /*
2  * Copyright (c) 2022 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 "svg-visual.h"
20
21 // INTERNAL INCLUDES
22 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
23 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
24 #include <dali-toolkit/internal/visuals/svg/svg-rasterize-thread.h>
25 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
26 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
27 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
28
29 // EXTERNAL INCLUDES
30 #include <dali/devel-api/adaptor-framework/file-loader.h>
31 #include <dali/devel-api/common/stage.h>
32 #include <dali/integration-api/debug.h>
33
34 namespace Dali
35 {
36 namespace Toolkit
37 {
38 namespace Internal
39 {
40 namespace
41 {
42 const int CUSTOM_PROPERTY_COUNT(6); // atlas + corner/border
43
44 // property name
45 const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
46
47 } // namespace
48
49 SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
50 {
51   SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl));
52   svgVisual->Load();
53   svgVisual->SetProperties(properties);
54   svgVisual->Initialize();
55   return svgVisual;
56 }
57
58 SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
59 {
60   SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl));
61   svgVisual->Load();
62   svgVisual->Initialize();
63   return svgVisual;
64 }
65
66 SvgVisual::SvgVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
67 : Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::SVG),
68   mImageVisualShaderFactory(shaderFactory),
69   mAtlasRect(FULL_TEXTURE_RECT),
70   mImageUrl(imageUrl),
71   mVectorRenderer(VectorImageRenderer::New()),
72   mDefaultWidth(0),
73   mDefaultHeight(0),
74   mPlacementActor(),
75   mVisualSize(Vector2::ZERO),
76   mLoadFailed(false),
77   mAttemptAtlasing(false)
78 {
79   // the rasterized image is with pre-multiplied alpha format
80   mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
81 }
82
83 SvgVisual::~SvgVisual()
84 {
85 }
86
87 void SvgVisual::OnInitialize()
88 {
89   Shader   shader   = GenerateShader();
90   Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
91   mImpl->mRenderer  = VisualRenderer::New(geometry, shader);
92   mImpl->mRenderer.ReserveCustomProperties(CUSTOM_PROPERTY_COUNT);
93 }
94
95 void SvgVisual::DoSetProperties(const Property::Map& propertyMap)
96 {
97   // url already passed in from constructor
98   for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
99   {
100     KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
101     if(keyValue.first.type == Property::Key::INDEX)
102     {
103       DoSetProperty(keyValue.first.indexKey, keyValue.second);
104     }
105     else if(keyValue.first == IMAGE_ATLASING)
106     {
107       DoSetProperty(Toolkit::ImageVisual::Property::ATLASING, keyValue.second);
108     }
109     else if(keyValue.first == SYNCHRONOUS_LOADING)
110     {
111       DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second);
112     }
113   }
114 }
115
116 void SvgVisual::DoSetProperty(Property::Index index, const Property::Value& value)
117 {
118   switch(index)
119   {
120     case Toolkit::ImageVisual::Property::ATLASING:
121     {
122       value.Get(mAttemptAtlasing);
123       break;
124     }
125     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
126     {
127       bool sync = false;
128       if(value.Get(sync))
129       {
130         if(sync)
131         {
132           mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
133         }
134         else
135         {
136           mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
137         }
138       }
139       else
140       {
141         DALI_LOG_ERROR("ImageVisual: synchronousLoading property has incorrect type\n");
142       }
143       break;
144     }
145   }
146 }
147
148 void SvgVisual::DoSetOnScene(Actor& actor)
149 {
150   TextureSet textureSet = TextureSet::New();
151   mImpl->mRenderer.SetTextures(textureSet);
152
153   // Register transform properties
154   mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
155
156   // Defer the rasterisation task until we get given a size (by Size Negotiation algorithm)
157
158   // Hold the weak handle of the placement actor and delay the adding of renderer until the svg rasterization is finished.
159   mPlacementActor = actor;
160
161   if(mLoadFailed)
162   {
163     Vector2 imageSize = Vector2::ZERO;
164     imageSize         = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
165     mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize);
166     actor.AddRenderer(mImpl->mRenderer);
167
168     ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
169   }
170   else
171   {
172     // SVG visual needs it's size set before it can be rasterized hence set ResourceReady once on stage
173     ResourceReady(Toolkit::Visual::ResourceStatus::READY);
174   }
175 }
176
177 void SvgVisual::DoSetOffScene(Actor& actor)
178 {
179   mFactoryCache.GetSVGRasterizationThread()->RemoveTask(this);
180
181   actor.RemoveRenderer(mImpl->mRenderer);
182   mPlacementActor.Reset();
183
184   // Reset the visual size to zero so that when adding the actor back to stage the SVG rasterization is forced
185   mVisualSize = Vector2::ZERO;
186 }
187
188 void SvgVisual::GetNaturalSize(Vector2& naturalSize)
189 {
190   naturalSize.x = mDefaultWidth;
191   naturalSize.y = mDefaultHeight;
192 }
193
194 void SvgVisual::DoCreatePropertyMap(Property::Map& map) const
195 {
196   map.Clear();
197   map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG);
198   if(mImageUrl.IsValid())
199   {
200     map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
201     map.Insert(Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing);
202   }
203   map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired());
204 }
205
206 void SvgVisual::DoCreateInstancePropertyMap(Property::Map& map) const
207 {
208   // Do nothing
209 }
210
211 void SvgVisual::EnablePreMultipliedAlpha(bool preMultiplied)
212 {
213   // Make always enable pre multiplied alpha whether preMultiplied value is false.
214   if(!preMultiplied)
215   {
216     DALI_LOG_WARNING("Note : SvgVisual cannot disable PreMultipliedAlpha\n");
217   }
218 }
219
220 void SvgVisual::Load()
221 {
222   // load remote resource on svg rasterize thread.
223   if(mImageUrl.IsLocalResource())
224   {
225     Dali::Vector<uint8_t> buffer;
226     if(Dali::FileLoader::ReadFile(mImageUrl.GetUrl(), buffer))
227     {
228       buffer.PushBack('\0');
229
230       Vector2 dpi     = Stage::GetCurrent().GetDpi();
231       float   meanDpi = (dpi.height + dpi.width) * 0.5f;
232       if(!mVectorRenderer.Load(buffer, meanDpi))
233       {
234         mLoadFailed = true;
235         DALI_LOG_ERROR("SvgVisual::Load: Failed to load file! [%s]\n", mImageUrl.GetUrl().c_str());
236         return;
237       }
238       mVectorRenderer.GetDefaultSize(mDefaultWidth, mDefaultHeight);
239     }
240     else
241     {
242       mLoadFailed = true;
243       DALI_LOG_ERROR("SvgVisual::Load: Failed to read file! [%s]\n", mImageUrl.GetUrl().c_str());
244     }
245   }
246 }
247
248 void SvgVisual::AddRasterizationTask(const Vector2& size)
249 {
250   if(mImpl->mRenderer)
251   {
252     unsigned int width  = static_cast<unsigned int>(size.width);
253     unsigned int height = static_cast<unsigned int>(size.height);
254
255     Vector2 dpi     = Stage::GetCurrent().GetDpi();
256     float   meanDpi = (dpi.height + dpi.width) * 0.5f;
257
258     RasterizingTaskPtr newTask = new RasterizingTask(this, mVectorRenderer, mImageUrl, meanDpi, width, height);
259     if(IsSynchronousLoadingRequired() && mImageUrl.IsLocalResource())
260     {
261       newTask->Load();
262       newTask->Rasterize();
263       ApplyRasterizedImage(newTask->GetVectorRenderer(), newTask->GetPixelData(), newTask->IsLoaded());
264     }
265     else
266     {
267       mFactoryCache.GetSVGRasterizationThread()->AddTask(newTask);
268     }
269   }
270 }
271
272 void SvgVisual::ApplyRasterizedImage(VectorImageRenderer vectorRenderer, PixelData rasterizedPixelData, bool isLoaded)
273 {
274   if(isLoaded && rasterizedPixelData && IsOnScene())
275   {
276     TextureSet currentTextureSet = mImpl->mRenderer.GetTextures();
277     if(mImpl->mFlags & Impl::IS_ATLASING_APPLIED)
278     {
279       mFactoryCache.GetAtlasManager()->Remove(currentTextureSet, mAtlasRect);
280     }
281
282     TextureSet textureSet;
283
284     if(mAttemptAtlasing && !mImpl->mCustomShader)
285     {
286       Vector4 atlasRect;
287       textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData);
288       if(textureSet) // atlasing
289       {
290         if(textureSet != currentTextureSet)
291         {
292           mImpl->mRenderer.SetTextures(textureSet);
293         }
294         mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, atlasRect);
295         mAtlasRect = atlasRect;
296         mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
297       }
298     }
299
300     if(!textureSet) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed
301     {
302       Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight());
303       texture.Upload(rasterizedPixelData);
304       mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
305
306       if(mAtlasRect == FULL_TEXTURE_RECT)
307       {
308         textureSet = currentTextureSet;
309       }
310       else
311       {
312         textureSet = TextureSet::New();
313         mImpl->mRenderer.SetTextures(textureSet);
314
315         mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT);
316         mAtlasRect = FULL_TEXTURE_RECT;
317       }
318
319       if(textureSet)
320       {
321         textureSet.SetTexture(0, texture);
322       }
323     }
324
325     // Rasterized pixels are uploaded to texture. If weak handle is holding a placement actor, it is the time to add the renderer to actor.
326     Actor actor = mPlacementActor.GetHandle();
327     if(actor)
328     {
329       actor.AddRenderer(mImpl->mRenderer);
330       // reset the weak handle so that the renderer only get added to actor once
331       mPlacementActor.Reset();
332     }
333
334     // Svg loaded and ready to display
335     ResourceReady(Toolkit::Visual::ResourceStatus::READY);
336   }
337   else if(!isLoaded || !rasterizedPixelData)
338   {
339     Actor actor = mPlacementActor.GetHandle();
340     if(actor)
341     {
342       Vector2 imageSize = Vector2::ZERO;
343       imageSize         = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
344       mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize);
345       actor.AddRenderer(mImpl->mRenderer);
346     }
347
348     ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
349   }
350 }
351
352 void SvgVisual::OnSetTransform()
353 {
354   Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize);
355
356   if(IsOnScene() && !mLoadFailed)
357   {
358     if(visualSize != mVisualSize)
359     {
360       AddRasterizationTask(visualSize);
361       mVisualSize = visualSize;
362     }
363   }
364
365   if(mImpl->mRenderer)
366   {
367     mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
368   }
369 }
370
371 void SvgVisual::UpdateShader()
372 {
373   if(mImpl->mRenderer)
374   {
375     Shader shader = GenerateShader();
376     mImpl->mRenderer.SetShader(shader);
377   }
378 }
379
380 Shader SvgVisual::GenerateShader() const
381 {
382   Shader shader;
383   if(!mImpl->mCustomShader)
384   {
385     shader = mImageVisualShaderFactory.GetShader(
386       mFactoryCache,
387       ImageVisualShaderFeature::FeatureBuilder()
388         .EnableTextureAtlas(mAttemptAtlasing)
389         .EnableRoundedCorner(IsRoundedCornerRequired())
390         .EnableBorderline(IsBorderlineRequired()));
391   }
392   else
393   {
394     shader = Shader::New(mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader,
395                          mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader,
396                          mImpl->mCustomShader->mHints);
397
398     shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
399   }
400   return shader;
401 }
402
403 } // namespace Internal
404
405 } // namespace Toolkit
406
407 } // namespace Dali