Merge "(SVG) Support desired size" into devel/master
[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/common/stage.h>
31 #include <dali/integration-api/debug.h>
32 #include <dali/public-api/rendering/decorated-visual-renderer.h>
33
34 namespace Dali
35 {
36 namespace Toolkit
37 {
38 namespace Internal
39 {
40 namespace
41 {
42 const int CUSTOM_PROPERTY_COUNT(1); // atlas
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, ImageDimensions{}));
52   svgVisual->SetProperties(properties);
53   svgVisual->Initialize();
54   return svgVisual;
55 }
56
57 SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, ImageDimensions size)
58 {
59   SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl, size));
60   svgVisual->Initialize();
61   return svgVisual;
62 }
63
64 SvgVisual::SvgVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, ImageDimensions size)
65 : Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::SVG),
66   mImageVisualShaderFactory(shaderFactory),
67   mAtlasRect(FULL_TEXTURE_RECT),
68   mImageUrl(imageUrl),
69   mVectorRenderer(VectorImageRenderer::New()),
70   mDefaultWidth(0),
71   mDefaultHeight(0),
72   mPlacementActor(),
73   mRasterizedSize(Vector2::ZERO),
74   mDesiredSize(size),
75   mLoadFailed(false),
76   mAttemptAtlasing(false)
77 {
78   // the rasterized image is with pre-multiplied alpha format
79   mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
80 }
81
82 SvgVisual::~SvgVisual()
83 {
84 }
85
86 void SvgVisual::OnInitialize()
87 {
88   Shader   shader   = GenerateShader();
89   Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
90   mImpl->mRenderer  = DecoratedVisualRenderer::New(geometry, shader);
91   mImpl->mRenderer.ReserveCustomProperties(CUSTOM_PROPERTY_COUNT);
92
93   Vector2 dpi     = Stage::GetCurrent().GetDpi();
94   float   meanDpi = (dpi.height + dpi.width) * 0.5f;
95
96   SvgTaskPtr newTask = new SvgLoadingTask(this, mVectorRenderer, mImageUrl, meanDpi);
97
98   if(IsSynchronousLoadingRequired() && mImageUrl.IsLocalResource())
99   {
100     newTask->Process();
101   }
102   else
103   {
104     mFactoryCache.GetSVGRasterizationManager()->AddTask(newTask);
105   }
106 }
107
108 void SvgVisual::DoSetProperties(const Property::Map& propertyMap)
109 {
110   // url already passed in from constructor
111   for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
112   {
113     KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
114     if(keyValue.first.type == Property::Key::INDEX)
115     {
116       DoSetProperty(keyValue.first.indexKey, keyValue.second);
117     }
118     else if(keyValue.first == IMAGE_ATLASING)
119     {
120       DoSetProperty(Toolkit::ImageVisual::Property::ATLASING, keyValue.second);
121     }
122     else if(keyValue.first == SYNCHRONOUS_LOADING)
123     {
124       DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second);
125     }
126     else if(keyValue.first == IMAGE_DESIRED_WIDTH)
127     {
128       DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second);
129     }
130     else if(keyValue.first == IMAGE_DESIRED_HEIGHT)
131     {
132       DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second);
133     }
134   }
135 }
136
137 void SvgVisual::DoSetProperty(Property::Index index, const Property::Value& value)
138 {
139   switch(index)
140   {
141     case Toolkit::ImageVisual::Property::ATLASING:
142     {
143       value.Get(mAttemptAtlasing);
144       break;
145     }
146     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
147     {
148       bool sync = false;
149       if(value.Get(sync))
150       {
151         if(sync)
152         {
153           mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
154         }
155         else
156         {
157           mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
158         }
159       }
160       else
161       {
162         DALI_LOG_ERROR("ImageVisual: synchronousLoading property has incorrect type\n");
163       }
164       break;
165     }
166     case Toolkit::ImageVisual::Property::DESIRED_WIDTH:
167     {
168       int32_t desiredWidth = 0;
169       if(value.Get(desiredWidth))
170       {
171         mDesiredSize.SetWidth(desiredWidth);
172       }
173       break;
174     }
175     case Toolkit::ImageVisual::Property::DESIRED_HEIGHT:
176     {
177       int32_t desiredHeight = 0;
178       if(value.Get(desiredHeight))
179       {
180         mDesiredSize.SetHeight(desiredHeight);
181       }
182       break;
183     }
184   }
185 }
186
187 void SvgVisual::DoSetOnScene(Actor& actor)
188 {
189   TextureSet textureSet = TextureSet::New();
190   mImpl->mRenderer.SetTextures(textureSet);
191
192   // Register transform properties
193   mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
194
195   // Defer the rasterisation task until we get given a size (by Size Negotiation algorithm)
196
197   // Hold the weak handle of the placement actor and delay the adding of renderer until the svg rasterization is finished.
198   mPlacementActor = actor;
199
200   if(mLoadFailed)
201   {
202     Vector2 imageSize = Vector2::ZERO;
203     imageSize         = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
204     mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize);
205     actor.AddRenderer(mImpl->mRenderer);
206
207     ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
208   }
209   else
210   {
211     if(mImpl->mEventObserver)
212     {
213       // SVG visual needs it's size set before it can be rasterized hence request relayout once on stage
214       mImpl->mEventObserver->RelayoutRequest(*this);
215     }
216   }
217 }
218
219 void SvgVisual::DoSetOffScene(Actor& actor)
220 {
221   mFactoryCache.GetSVGRasterizationManager()->RemoveTask(this);
222
223   actor.RemoveRenderer(mImpl->mRenderer);
224   mPlacementActor.Reset();
225
226   // Reset the visual size to zero so that when adding the actor back to stage the SVG rasterization is forced
227   mRasterizedSize = Vector2::ZERO;
228 }
229
230 void SvgVisual::GetNaturalSize(Vector2& naturalSize)
231 {
232   if(mDesiredSize.GetWidth() > 0 && mDesiredSize.GetHeight() > 0)
233   {
234     naturalSize.x = mDesiredSize.GetWidth();
235     naturalSize.y = mDesiredSize.GetHeight();
236   }
237   else if(mLoadFailed && mImpl->mRenderer)
238   {
239     // Load failed, use broken image size
240     auto textureSet = mImpl->mRenderer.GetTextures();
241     if(textureSet && textureSet.GetTextureCount())
242     {
243       auto texture = textureSet.GetTexture(0);
244       if(texture)
245       {
246         naturalSize.x = texture.GetWidth();
247         naturalSize.y = texture.GetHeight();
248         return;
249       }
250     }
251   }
252   else
253   {
254     naturalSize.x = mDefaultWidth;
255     naturalSize.y = mDefaultHeight;
256   }
257 }
258
259 void SvgVisual::DoCreatePropertyMap(Property::Map& map) const
260 {
261   map.Clear();
262   map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG);
263   if(mImageUrl.IsValid())
264   {
265     map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
266     map.Insert(Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing);
267   }
268   map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired());
269   map.Insert(Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth());
270   map.Insert(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight());
271 }
272
273 void SvgVisual::DoCreateInstancePropertyMap(Property::Map& map) const
274 {
275   // Do nothing
276 }
277
278 void SvgVisual::EnablePreMultipliedAlpha(bool preMultiplied)
279 {
280   // Make always enable pre multiplied alpha whether preMultiplied value is false.
281   if(!preMultiplied)
282   {
283     DALI_LOG_WARNING("Note : SvgVisual cannot disable PreMultipliedAlpha\n");
284   }
285 }
286
287 void SvgVisual::AddRasterizationTask(const Vector2& size)
288 {
289   if(mImpl->mRenderer)
290   {
291     unsigned int width  = static_cast<unsigned int>(size.width);
292     unsigned int height = static_cast<unsigned int>(size.height);
293
294     SvgTaskPtr newTask = new SvgRasterizingTask(this, mVectorRenderer, width, height);
295
296     if(IsSynchronousLoadingRequired() && mImageUrl.IsLocalResource())
297     {
298       newTask->Process();
299       ApplyRasterizedImage(newTask->GetPixelData(), newTask->HasSucceeded());
300     }
301     else
302     {
303       mFactoryCache.GetSVGRasterizationManager()->AddTask(newTask);
304     }
305   }
306 }
307
308 void SvgVisual::ApplyRasterizedImage(PixelData rasterizedPixelData, bool success)
309 {
310   if(success)
311   {
312     if(mDefaultWidth == 0 || mDefaultHeight == 0)
313     {
314       mVectorRenderer.GetDefaultSize(mDefaultWidth, mDefaultHeight);
315     }
316
317     // Rasterization success
318     if(rasterizedPixelData && IsOnScene())
319     {
320       mRasterizedSize.x = static_cast<float>(rasterizedPixelData.GetWidth());
321       mRasterizedSize.y = static_cast<float>(rasterizedPixelData.GetHeight());
322
323       TextureSet currentTextureSet = mImpl->mRenderer.GetTextures();
324       if(mImpl->mFlags & Impl::IS_ATLASING_APPLIED)
325       {
326         mFactoryCache.GetAtlasManager()->Remove(currentTextureSet, mAtlasRect);
327       }
328
329       TextureSet textureSet;
330
331       if(mAttemptAtlasing && !mImpl->mCustomShader)
332       {
333         Vector4 atlasRect;
334         textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData);
335         if(textureSet) // atlasing
336         {
337           if(textureSet != currentTextureSet)
338           {
339             mImpl->mRenderer.SetTextures(textureSet);
340           }
341           mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, atlasRect);
342           mAtlasRect = atlasRect;
343           mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
344         }
345       }
346
347       if(!textureSet) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed
348       {
349         Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight());
350         texture.Upload(rasterizedPixelData);
351         mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
352
353         if(mAtlasRect == FULL_TEXTURE_RECT)
354         {
355           textureSet = currentTextureSet;
356         }
357         else
358         {
359           textureSet = TextureSet::New();
360           mImpl->mRenderer.SetTextures(textureSet);
361
362           mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT);
363           mAtlasRect = FULL_TEXTURE_RECT;
364         }
365
366         if(textureSet)
367         {
368           textureSet.SetTexture(0, texture);
369         }
370       }
371
372       // Rasterized pixels are uploaded to texture. If weak handle is holding a placement actor, it is the time to add the renderer to actor.
373       Actor actor = mPlacementActor.GetHandle();
374       if(actor)
375       {
376         actor.AddRenderer(mImpl->mRenderer);
377         // reset the weak handle so that the renderer only get added to actor once
378         mPlacementActor.Reset();
379       }
380
381       // Svg loaded and ready to display
382       ResourceReady(Toolkit::Visual::ResourceStatus::READY);
383     }
384   }
385   else if(!success && !mLoadFailed)
386   {
387     mLoadFailed = true;
388
389     Actor actor = mPlacementActor.GetHandle();
390     if(actor)
391     {
392       Vector2 imageSize = Vector2::ZERO;
393       imageSize         = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
394       mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize);
395       actor.AddRenderer(mImpl->mRenderer);
396     }
397
398     ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
399   }
400 }
401
402 void SvgVisual::OnSetTransform()
403 {
404   if(IsOnScene() && !mLoadFailed)
405   {
406     Vector2 size;
407     if(mDesiredSize.GetWidth() > 0 && mDesiredSize.GetHeight() > 0)
408     {
409       // Use desired size
410       size = Vector2(mDesiredSize.GetWidth(), mDesiredSize.GetHeight());
411     }
412     else
413     {
414       // Use visual size
415       size = mImpl->mTransform.GetVisualSize(mImpl->mControlSize);
416     }
417
418     if(size != mRasterizedSize || mDefaultWidth == 0 || mDefaultHeight == 0)
419     {
420       mRasterizedSize = size;
421       AddRasterizationTask(size);
422     }
423   }
424
425   if(mImpl->mRenderer)
426   {
427     mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
428   }
429 }
430
431 void SvgVisual::UpdateShader()
432 {
433   if(mImpl->mRenderer)
434   {
435     Shader shader = GenerateShader();
436     mImpl->mRenderer.SetShader(shader);
437   }
438 }
439
440 Shader SvgVisual::GenerateShader() const
441 {
442   Shader shader;
443   if(!mImpl->mCustomShader)
444   {
445     shader = mImageVisualShaderFactory.GetShader(
446       mFactoryCache,
447       ImageVisualShaderFeature::FeatureBuilder()
448         .EnableTextureAtlas(mAttemptAtlasing)
449         .EnableRoundedCorner(IsRoundedCornerRequired())
450         .EnableBorderline(IsBorderlineRequired()));
451   }
452   else
453   {
454     shader = Shader::New(mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader,
455                          mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader,
456                          mImpl->mCustomShader->mHints);
457
458     shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
459   }
460   return shader;
461 }
462
463 } // namespace Internal
464
465 } // namespace Toolkit
466
467 } // namespace Dali