/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
catch (DaliException& e)
{
- DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION );
}
try
}
catch (DaliException& e)
{
- DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION );
}
try
}
catch (DaliException& e)
{
- DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION );
}
try
}
catch (DaliException& e)
{
- DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION );
}
END_TEST;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
catch(Dali::DaliException& e)
{
DALI_TEST_PRINT_ASSERT( e );
- DALI_TEST_ASSERT(e, "density>0 && density<=9", TEST_LOCATION );
+ DALI_TEST_ASSERT(e, "density > 0 && density <= 9", TEST_LOCATION );
}
END_TEST;
}
/*
-* Copyright (c) 2020 Samsung Electronics Co., Ltd.
+* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
*/
#include "dali-scene-loader/internal/gltf2-asset.h"
-#include "dali/public-api/math/matrix.h"
#include <algorithm>
#include <map>
+#include "dali/public-api/math/matrix.h"
-#define ENUM_STRING_MAPPING(t, x) { #x, t::x }
+#define ENUM_STRING_MAPPING(t, x) \
+ { \
+#x, t::x \
+ }
using namespace Dali;
{
namespace
{
-
constexpr uint32_t ACCESSOR_TYPE_ELEMENT_COUNT[]{
1,
2,
4,
9,
16,
- static_cast<uint32_t>(-1)
-};
+ static_cast<uint32_t>(-1)};
const std::map<std::string_view, AccessorType::Type> ACCESSOR_TYPES{
ENUM_STRING_MAPPING(AccessorType, SCALAR),
ENUM_STRING_MAPPING(Animation::Channel::Target::Type, WEIGHTS),
};
-}
+} // namespace
bool Component::IsUnsigned(Type t)
{
uint32_t Component::Size(Type t)
{
- switch (t)
+ switch(t)
{
- case BYTE:
- case UNSIGNED_BYTE:
- return 1;
- case SHORT:
- case UNSIGNED_SHORT:
- return 2;
- case UNSIGNED_INT:
- case FLOAT:
- return 4;
- default:
- return -1;
+ case BYTE:
+ case UNSIGNED_BYTE:
+ return 1;
+ case SHORT:
+ case UNSIGNED_SHORT:
+ return 2;
+ case UNSIGNED_INT:
+ case FLOAT:
+ return 4;
+ default:
+ return -1;
}
}
AccessorType::Type AccessorType::FromString(const char* s, size_t len)
{
auto iFind = ACCESSOR_TYPES.find(std::string_view(s, len));
- if (iFind != ACCESSOR_TYPES.end())
+ if(iFind != ACCESSOR_TYPES.end())
{
return iFind->second;
}
AlphaMode::Type AlphaMode::FromString(const char* s, size_t len)
{
auto iFind = ALPHA_MODE_TYPES.find(std::string_view(s, len));
- if (iFind != ALPHA_MODE_TYPES.end())
+ if(iFind != ALPHA_MODE_TYPES.end())
{
return iFind->second;
}
Attribute::Type Attribute::FromString(const char* s, size_t len)
{
auto iFind = ATTRIBUTE_TYPES.find(std::string_view(s, len));
- if (iFind != ATTRIBUTE_TYPES.end())
+ if(iFind != ATTRIBUTE_TYPES.end())
{
return iFind->second;
}
Animation::Sampler::Interpolation::Type Animation::Sampler::Interpolation::FromString(const char* s, size_t len)
{
auto iFind = ANIMATION_SAMPLER_INTERPOLATION.find(std::string_view(s, len));
- if (iFind != ANIMATION_SAMPLER_INTERPOLATION.end())
+ if(iFind != ANIMATION_SAMPLER_INTERPOLATION.end())
{
return iFind->second;
}
std::transform(target.begin(), target.end(), target.begin(), ::toupper);
auto iFind = ANIMATION_CHANNEL_TARGET_PATH_TYPES.find(std::string_view(target.c_str(), len));
- if (iFind != ANIMATION_CHANNEL_TARGET_PATH_TYPES.end())
+ if(iFind != ANIMATION_CHANNEL_TARGET_PATH_TYPES.end())
{
return iFind->second;
}
m.GetTransformComponents(mTranslation, mRotation, mScale);
}
-Quaternion ReadQuaternion(const json_value_s & j)
+Quaternion ReadQuaternion(const json_value_s& j)
{
- return Quaternion(ReadDaliVector<Vector4>(j));
+ return Quaternion(ReadDaliVector<Vector4>(j));
}
-}
+} // namespace gltf2
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
Hash::Hash(uint64_t initial)
: mValue(initial)
-{}
+{
+}
Hash& Hash::Add(bool b)
{
return AddObjectBytes(f);
}
-Hash& Hash::Add(const char * cStr)
+Hash& Hash::Add(const char* cStr)
{
return Add(cStr, strlen(cStr));
}
-Hash& Hash::Add(const char * cStr, size_t len)
+Hash& Hash::Add(const char* cStr, size_t len)
{
auto i0 = reinterpret_cast<const uint8_t*>(cStr);
return AddBytes(i0, i0 + len);
}
-Hash& Hash::Add(const std::string & str)
+Hash& Hash::Add(const std::string& str)
{
auto i0 = reinterpret_cast<const uint8_t*>(str.c_str());
return AddBytes(i0, i0 + str.size());
}
-Hash& Hash::AddBytes(const uint8_t * i0, const uint8_t * i1)
+Hash& Hash::AddBytes(const uint8_t* i0, const uint8_t* i1)
{
- while (i0 != i1)
+ while(i0 != i1)
{
mValue = Concatenate(*i0);
++i0;
return mValue * 31 + value;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
-* Copyright (c) 2020 Samsung Electronics Co., Ltd.
+* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace json
{
-
int StrCmp(const json_string_s& js, const char* s)
{
- auto sSize = strlen(s);
+ auto sSize = strlen(s);
auto shorter = std::min(js.string_size, sSize);
- auto base = strncmp(js.string, s, shorter);
- return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ?
- -s[shorter] : js.string[shorter]);
+ auto base = strncmp(js.string, s, shorter);
+ return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? -s[shorter] : js.string[shorter]);
}
int StrCmp(const json_string_s& js, const std::string& s)
{
- auto sSize = s.size();
+ auto sSize = s.size();
auto shorter = std::min(js.string_size, sSize);
- auto base = strncmp(js.string, s.c_str(), shorter);
- return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ?
- -s[shorter] : js.string[shorter]);
+ auto base = strncmp(js.string, s.c_str(), shorter);
+ return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? -s[shorter] : js.string[shorter]);
}
-void Validate(const json_value_s & jv, json_type_e type)
+void Validate(const json_value_s& jv, json_type_e type)
{
- if (jv.type != type)
+ if(jv.type != type)
{
throw std::runtime_error("Invalid type; expected: " + std::to_string(type) + ", got: " + std::to_string(jv.type));
}
json_value_s* FindObjectChild(const std::string& key, json_object_s& obj)
{
auto i = obj.start;
- while (i)
+ while(i)
{
- if (0 == StrCmp(*i->name, key))
+ if(0 == StrCmp(*i->name, key))
{
return i->value;
}
return nullptr;
}
-}
+} // namespace json
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "dali-scene-loader/internal/json-util.h"
// EXTERNAL INCLUDES
+#include <array>
+#include "dali/devel-api/common/map-wrapper.h"
#include "dali/public-api/common/extents.h"
-#include "dali/public-api/math/matrix3.h"
#include "dali/public-api/math/matrix.h"
+#include "dali/public-api/math/matrix3.h"
#include "dali/public-api/math/quaternion.h"
#include "dali/public-api/math/radian.h"
#include "dali/public-api/math/vector2.h"
#include "dali/public-api/math/vector3.h"
#include "dali/public-api/object/property-value.h"
-#include "dali/devel-api/common/map-wrapper.h"
-#include <array>
namespace Dali
{
{
namespace
{
-
-template <typename T>
-Property::Value ReadPrimitiveHelper(const TreeNode* tn, bool(*reader)(const TreeNode*, T&))
+template<typename T>
+Property::Value ReadPrimitiveHelper(const TreeNode* tn, bool (*reader)(const TreeNode*, T&))
{
T value;
- if (reader(tn, value))
+ if(reader(tn, value))
{
return Property::Value(value);
}
return Property::Value();
}
-template <typename T>
+template<typename T>
Property::Value ReadVectorHelper(const TreeNode* tn)
{
static_assert(sizeof(T) % sizeof(float) == 0, "");
T value;
- if (ReadVector(tn, value.AsFloat(), sizeof(T) / sizeof(float)))
+ if(ReadVector(tn, value.AsFloat(), sizeof(T) / sizeof(float)))
{
return Property::Value(value);
}
Property::Value ReadVectorSingleFloatHelper(const TreeNode* tn)
{
float value;
- if (ReadVector(tn, &value, 1u))
+ if(ReadVector(tn, &value, 1u))
{
return Property::Value(value);
}
Property::Value ReadRotationHelper(const TreeNode* tn)
{
- switch (tn->Size())
- {
- case 3:
- {
- // degrees as per spec
- Vector3 rotation;
- ReadVector(tn, rotation.AsFloat(), 3u);
- return Property::Value(Quaternion(Radian(Degree(rotation.x)),
- Radian(Degree(rotation.y)),
- Radian(Degree(rotation.z))));
- }
- case 4:
+ switch(tn->Size())
{
- Vector4 v;
- ReadVector(tn, v.AsFloat(), 4u);
- //Quaternion
- return Property::Value(Quaternion(v));
- }
- default:
- return Property::Value();
+ case 3:
+ {
+ // degrees as per spec
+ Vector3 rotation;
+ ReadVector(tn, rotation.AsFloat(), 3u);
+ return Property::Value(Quaternion(Radian(Degree(rotation.x)),
+ Radian(Degree(rotation.y)),
+ Radian(Degree(rotation.z))));
+ }
+ case 4:
+ {
+ Vector4 v;
+ ReadVector(tn, v.AsFloat(), 4u);
+ //Quaternion
+ return Property::Value(Quaternion(v));
+ }
+ default:
+ return Property::Value();
}
}
-template <typename T>
+template<typename T>
bool ReadQuadHelper(const TreeNode* tn, const std::array<T*, 4>& quad)
{
- auto i = quad.begin();
- auto iEnd = quad.end();
+ auto i = quad.begin();
+ auto iEnd = quad.end();
auto iJson = tn->CBegin();
- while (iJson != tn->CEnd() && i != iEnd)
+ while(iJson != tn->CEnd() && i != iEnd)
{
int value;
- if (ReadInt(&(*iJson).second, value) && value <= std::numeric_limits<T>::max())
+ if(ReadInt(&(*iJson).second, value) && value <= std::numeric_limits<T>::max())
{
**i = value;
++i;
return true;
}
-const std::map<std::string, Property::Value(*)(const TreeNode*)> kTypeIds {
+const std::map<std::string, Property::Value (*)(const TreeNode*)> kTypeIds{
// NONE
- { "boolean", [](const TreeNode* tn) {
- return ReadPrimitiveHelper<bool>(tn, ReadBool);
- }},
- { "float", [](const TreeNode* tn) {
- return ReadPrimitiveHelper<float>(tn, ReadFloat);
- }},
- { "integer", [](const TreeNode* tn) {
- return ReadPrimitiveHelper<int>(tn, ReadInt);
- }},
- { "vector2", ReadVectorHelper<Vector2> },
- { "vector3", ReadVectorHelper<Vector3> },
- { "vector4", ReadVectorHelper<Vector4> },
- { "matrix3", ReadVectorHelper<Matrix3> },
- { "matrix", ReadVectorHelper<Matrix> },
- { "rectangle", [](const TreeNode* tn) {
- Rect<int> value;
- if (ReadQuadHelper<int>(tn, { &value.x, &value.y, &value.width, &value.height }))
- {
- return Property::Value(value);
- }
- return Property::Value();
- }},
- { "rotation", ReadRotationHelper },
+ {"boolean", [](const TreeNode* tn) {
+ return ReadPrimitiveHelper<bool>(tn, ReadBool);
+ }},
+ {"float", [](const TreeNode* tn) {
+ return ReadPrimitiveHelper<float>(tn, ReadFloat);
+ }},
+ {"integer", [](const TreeNode* tn) {
+ return ReadPrimitiveHelper<int>(tn, ReadInt);
+ }},
+ {"vector2", ReadVectorHelper<Vector2>},
+ {"vector3", ReadVectorHelper<Vector3>},
+ {"vector4", ReadVectorHelper<Vector4>},
+ {"matrix3", ReadVectorHelper<Matrix3>},
+ {"matrix", ReadVectorHelper<Matrix>},
+ {"rectangle", [](const TreeNode* tn) {
+ Rect<int> value;
+ if(ReadQuadHelper<int>(tn, {&value.x, &value.y, &value.width, &value.height}))
+ {
+ return Property::Value(value);
+ }
+ return Property::Value();
+ }},
+ {"rotation", ReadRotationHelper},
// STRING - not particularly animatable
// ARRAY - not particularly animatable
// MAP - not particularly animatable
- { "extents", [](const TreeNode* tn) {
- Extents value;
- if (ReadQuadHelper<uint16_t>(tn, { &value.start, &value.end, &value.top, &value.bottom }))
- {
- return Property::Value(value);
- }
- return Property::Value();
- }},
+ {"extents", [](const TreeNode* tn) {
+ Extents value;
+ if(ReadQuadHelper<uint16_t>(tn, {&value.start, &value.end, &value.top, &value.bottom}))
+ {
+ return Property::Value(value);
+ }
+ return Property::Value();
+ }},
};
-Property::Value(* const kArrayPropertyProcessors[])(const TreeNode*) {
+Property::Value (*const kArrayPropertyProcessors[])(const TreeNode*){
ReadVectorHelper<Matrix>,
ReadVectorHelper<Matrix3>,
ReadVectorHelper<Vector4>,
ReadVectorHelper<Vector3>,
ReadVectorHelper<Vector2>,
- ReadVectorSingleFloatHelper
-};
+ ReadVectorSingleFloatHelper};
-} // nonamespace
+} // namespace
bool ReadBool(const TreeNode* node, bool& num)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::BOOLEAN)
+ if(node->GetType() == TreeNode::BOOLEAN)
{
- num = node->GetBoolean();
+ num = node->GetBoolean();
returnValue = true;
}
bool ReadInt(const TreeNode* node, int& num)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::INTEGER)
+ if(node->GetType() == TreeNode::INTEGER)
{
- num = node->GetInteger();
+ num = node->GetInteger();
returnValue = true;
}
- else if (node->GetType() == TreeNode::FLOAT)
+ else if(node->GetType() == TreeNode::FLOAT)
{
- num = static_cast<int>(node->GetFloat());
+ num = static_cast<int>(node->GetFloat());
returnValue = true;
}
bool ReadFloat(const TreeNode* node, float& num)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::FLOAT)
+ if(node->GetType() == TreeNode::FLOAT)
{
- num = node->GetFloat();
+ num = node->GetFloat();
returnValue = true;
}
- else if (node->GetType() == TreeNode::INTEGER)
+ else if(node->GetType() == TreeNode::INTEGER)
{
- num = static_cast<float>(node->GetInteger());
+ num = static_cast<float>(node->GetInteger());
returnValue = true;
}
bool ReadIndex(const Toolkit::TreeNode* node, Index& num)
{
bool returnValue = node && node->GetType() == TreeNode::INTEGER;
- if (returnValue)
+ if(returnValue)
{
num = static_cast<Index>(node->GetInteger());
}
bool ReadBlob(const Toolkit::TreeNode* node, unsigned int& offset, unsigned int& length)
{
- if (!node)
+ if(!node)
{
return false;
}
- int iOffset, iLength;
+ int iOffset, iLength;
bool success = ReadInt(node->GetChild("byteOffset"), iOffset) &&
- ReadInt(node->GetChild("byteLength"), iLength) &&
- iOffset >= 0 && iLength >= 0; // 0 length might not be sensible, but is not an error at this stage.
- if (success)
+ ReadInt(node->GetChild("byteLength"), iLength) &&
+ iOffset >= 0 && iLength >= 0; // 0 length might not be sensible, but is not an error at this stage.
+ if(success)
{
- offset = static_cast<unsigned int>( iOffset );
- length = static_cast<unsigned int>( iLength );
+ offset = static_cast<unsigned int>(iOffset);
+ length = static_cast<unsigned int>(iLength);
}
return success;
}
size_t GetNumericalArraySize(const TreeNode* node)
{
size_t size = 0;
- if (node->GetType() == TreeNode::ARRAY)
+ if(node->GetType() == TreeNode::ARRAY)
{
- for (auto i0 = node->CBegin(), i1 = node->CEnd(); i0 != i1 &&
- ((*i0).second.GetType() == TreeNode::FLOAT || (*i0).second.GetType() == TreeNode::INTEGER);
- ++i0)
+ for(auto i0 = node->CBegin(), i1 = node->CEnd(); i0 != i1 &&
+ ((*i0).second.GetType() == TreeNode::FLOAT || (*i0).second.GetType() == TreeNode::INTEGER);
+ ++i0)
{
++size;
}
bool ReadVector(const TreeNode* node, float* num, unsigned int size)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if ((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
+ if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
{
unsigned int offset = 0u;
- for (TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset)
+ for(TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset)
{
const TreeNode& coord = (*it).second;
- if (!ReadFloat(&coord, *(num + offset)))
+ if(!ReadFloat(&coord, *(num + offset)))
{
return false;
}
bool ReadVector(const Toolkit::TreeNode* node, int* num, unsigned int size)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if ((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
+ if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
{
unsigned int offset = 0u;
- for (TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset)
+ for(TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset)
{
const TreeNode& coord = (*it).second;
- if (!ReadInt(&coord, *(num + offset)))
+ if(!ReadInt(&coord, *(num + offset)))
{
return false;
}
bool ReadColor(const TreeNode* node, Vector4& color)
{
- if (nullptr == node)
+ if(nullptr == node)
{
return false;
}
- if (!ReadVector(node, color.AsFloat(), 4))
+ if(!ReadVector(node, color.AsFloat(), 4))
{
- if (!ReadVector(node, color.AsFloat(), 3))
+ if(!ReadVector(node, color.AsFloat(), 3))
{
return false;
}
bool ReadTimePeriod(const TreeNode* node, TimePeriod& timePeriod)
{
- if (!node)
+ if(!node)
{
return false;
}
- if (!ReadFloat(node->GetChild("delay"), timePeriod.delaySeconds) || !ReadFloat(node->GetChild("duration"), timePeriod.durationSeconds))
+ if(!ReadFloat(node->GetChild("delay"), timePeriod.delaySeconds) || !ReadFloat(node->GetChild("duration"), timePeriod.durationSeconds))
{
return false;
}
bool ReadString(const TreeNode* node, std::string& strValue)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::STRING)
+ if(node->GetType() == TreeNode::STRING)
{
- strValue = node->GetString();
+ strValue = node->GetString();
returnValue = true;
}
return returnValue;
bool ReadStringVector(const TreeNode* node, std::vector<std::string>& strvector)
{
- if (!node)
+ if(!node)
{
return false;
}
bool returnValue = false;
- if (node->GetType() == TreeNode::ARRAY)
+ if(node->GetType() == TreeNode::ARRAY)
{
- for (TreeNode::ConstIterator it = node->CBegin(); it != node->CEnd(); ++it)
+ for(TreeNode::ConstIterator it = node->CBegin(); it != node->CEnd(); ++it)
{
const TreeNode& strNode = (*it).second;
- if (strNode.GetType() == TreeNode::STRING)
+ if(strNode.GetType() == TreeNode::STRING)
{
strvector.push_back(strNode.GetString());
}
Property::Value ReadPropertyValue(const Property::Type& propType, const TreeNode& tn)
{
- switch (propType)
+ switch(propType)
{
- case Property::BOOLEAN:
- return ReadPrimitiveHelper<bool>(&tn, ReadBool);
+ case Property::BOOLEAN:
+ return ReadPrimitiveHelper<bool>(&tn, ReadBool);
- case Property::FLOAT:
- return ReadPrimitiveHelper<float>(&tn, ReadFloat);
+ case Property::FLOAT:
+ return ReadPrimitiveHelper<float>(&tn, ReadFloat);
- case Property::INTEGER:
- return ReadPrimitiveHelper<int>(&tn, ReadInt);
+ case Property::INTEGER:
+ return ReadPrimitiveHelper<int>(&tn, ReadInt);
- case Property::VECTOR2:
- return ReadVectorHelper<Vector2>(&tn);
+ case Property::VECTOR2:
+ return ReadVectorHelper<Vector2>(&tn);
- case Property::VECTOR3:
- return ReadVectorHelper<Vector3>(&tn);
+ case Property::VECTOR3:
+ return ReadVectorHelper<Vector3>(&tn);
- case Property::VECTOR4:
- return ReadVectorHelper<Vector4>(&tn);
+ case Property::VECTOR4:
+ return ReadVectorHelper<Vector4>(&tn);
- case Property::MATRIX3:
- return ReadVectorHelper<Matrix3>(&tn);
+ case Property::MATRIX3:
+ return ReadVectorHelper<Matrix3>(&tn);
- case Property::MATRIX:
- return ReadVectorHelper<Matrix>(&tn);
+ case Property::MATRIX:
+ return ReadVectorHelper<Matrix>(&tn);
- case Property::RECTANGLE:
- {
- Rect<int> value;
- if (ReadQuadHelper<int>(&tn, { &value.x, &value.y, &value.width, &value.height }))
+ case Property::RECTANGLE:
{
- return Property::Value(value);
+ Rect<int> value;
+ if(ReadQuadHelper<int>(&tn, {&value.x, &value.y, &value.width, &value.height}))
+ {
+ return Property::Value(value);
+ }
+ break;
}
- break;
- }
- case Property::ROTATION:
- return ReadRotationHelper(&tn);
+ case Property::ROTATION:
+ return ReadRotationHelper(&tn);
- case Property::EXTENTS:
- {
- Extents value;
- if (ReadQuadHelper<uint16_t>(&tn, { &value.start, &value.end, &value.top, &value.bottom }))
+ case Property::EXTENTS:
{
- return Property::Value(value);
+ Extents value;
+ if(ReadQuadHelper<uint16_t>(&tn, {&value.start, &value.end, &value.top, &value.bottom}))
+ {
+ return Property::Value(value);
+ }
+ break;
}
- break;
- }
- case Property::NONE: // fall
- default:
- {
- DALI_ASSERT_ALWAYS(!"Property type incorrect");
- }
+ case Property::NONE: // fall
+ default:
+ {
+ DALI_ASSERT_ALWAYS(!"Property type incorrect");
+ }
}
return Property::Value();
}
Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn)
{
Property::Value propValue;
- if (tn.GetType() == TreeNode::OBJECT) // attempt to disambiguate type.
+ if(tn.GetType() == TreeNode::OBJECT) // attempt to disambiguate type.
{
auto jsonType = tn.GetChild("type");
- if (jsonType && jsonType->GetType() == TreeNode::STRING)
+ if(jsonType && jsonType->GetType() == TreeNode::STRING)
{
auto iFind = kTypeIds.find(jsonType->GetString());
- if (iFind != kTypeIds.end())
+ if(iFind != kTypeIds.end())
{
propValue = iFind->second(tn.GetChild("value"));
}
}
}
- if (propValue.GetType() == Property::NONE)
+ if(propValue.GetType() == Property::NONE)
{
- if (tn.Size() == 0)
+ if(tn.Size() == 0)
{
- switch (tn.GetType())
+ switch(tn.GetType())
{
- case TreeNode::BOOLEAN:
- propValue = ReadPrimitiveHelper<bool>(&tn, ReadBool);
- break;
+ case TreeNode::BOOLEAN:
+ propValue = ReadPrimitiveHelper<bool>(&tn, ReadBool);
+ break;
- case TreeNode::INTEGER:
- propValue = ReadPrimitiveHelper<int>(&tn, ReadInt);
- break;
+ case TreeNode::INTEGER:
+ propValue = ReadPrimitiveHelper<int>(&tn, ReadInt);
+ break;
- case TreeNode::FLOAT:
- propValue = ReadPrimitiveHelper<float>(&tn, ReadFloat);
- break;
+ case TreeNode::FLOAT:
+ propValue = ReadPrimitiveHelper<float>(&tn, ReadFloat);
+ break;
- default:
- break;
+ default:
+ break;
}
}
else
{
bool allNumbers = true;
- for (auto i0 = tn.CBegin(), i1 = tn.CEnd(); i0 != i1; ++i0)
+ for(auto i0 = tn.CBegin(), i1 = tn.CEnd(); i0 != i1; ++i0)
{
auto type = (*i0).second.GetType();
if(!(type == TreeNode::FLOAT || type == TreeNode::INTEGER))
}
}
- if (allNumbers)
+ if(allNumbers)
{
// NOTE: rotations / rectangles / extents must be disambiguated in all circumstances.
- for (auto& r : kArrayPropertyProcessors)
+ for(auto& r : kArrayPropertyProcessors)
{
propValue = r(&tn);
- if (propValue.GetType() != Property::NONE)
+ if(propValue.GetType() != Property::NONE)
{
break;
}
return propValue;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace
{
-
+// clang-format off
#define DALI_ALPHA_FUNCTION_ENTRY(x) { #x, AlphaFunction::x }
+// clang-format on
-std::unordered_map<std::string, AlphaFunction> sFunctions {
+std::unordered_map<std::string, AlphaFunction> sFunctions{
DALI_ALPHA_FUNCTION_ENTRY(DEFAULT),
DALI_ALPHA_FUNCTION_ENTRY(LINEAR),
DALI_ALPHA_FUNCTION_ENTRY(REVERSE),
#undef DALI_ALPHA_FUNCTION_ENTRY
-} // nonamespace
+} // namespace
AlphaFunction GetAlphaFunction(const std::string& name, bool* found)
{
- auto iFind = sFunctions.find(name);
+ auto iFind = sFunctions.find(name);
bool success = iFind != sFunctions.end();
- if (found)
+ if(found)
{
*found = success;
}
return success ? iFind->second : AlphaFunction(AlphaFunction::DEFAULT);
}
-void RegisterAlphaFunction(const std::string & name, AlphaFunction alphaFn)
+void RegisterAlphaFunction(const std::string& name, AlphaFunction alphaFn)
{
- DALI_ASSERT_ALWAYS(sFunctions.insert({ name, alphaFn }).second &&
- "Function with given key already exists.");
+ DALI_ASSERT_ALWAYS(sFunctions.insert({name, alphaFn}).second &&
+ "Function with given key already exists.");
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
void AnimatedProperty::Animate(Animation& anim, GetActor getActor)
{
- if (Actor actor = getActor(mNodeName))
+ if(Actor actor = getActor(mNodeName))
{
Property prop = GetProperty(actor);
- if (mKeyFrames)
+ if(mKeyFrames)
{
anim.AnimateBetween(prop, mKeyFrames, mAlphaFunction, mTimePeriod);
}
- else if (mValue)
+ else if(mValue)
{
- if (mValue->mIsRelative)
+ if(mValue->mIsRelative)
{
anim.AnimateBy(prop, mValue->mValue, mAlphaFunction, mTimePeriod);
}
}
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
const float AnimationDefinition::DEFAULT_DURATION_SECONDS = 1.f;
-const float AnimationDefinition::MIN_DURATION_SECONDS = 1e-2f;
+const float AnimationDefinition::MIN_DURATION_SECONDS = 1e-2f;
Animation::EndAction AnimationDefinition::StopForModification(Animation& anim)
{
mSpeedFactor(other.mSpeedFactor),
mPlayRange(other.mPlayRange),
mProperties(std::move(other.mProperties))
-{}
+{
+}
void AnimationDefinition::Animate(Animation& animation, AnimatedProperty::GetActor getActor)
{
DALI_ASSERT_ALWAYS(animation);
- for (auto& ap : mProperties)
+ for(auto& ap : mProperties)
{
ap.Animate(animation, getActor);
}
AnimationDefinition& AnimationDefinition::operator=(AnimationDefinition&& other)
{
AnimationDefinition tmp(std::move(other));
- mName = std::move(tmp.mName);
- mDuration = tmp.mDuration;
- mLoopCount = tmp.mLoopCount;
+ mName = std::move(tmp.mName);
+ mDuration = tmp.mDuration;
+ mLoopCount = tmp.mLoopCount;
mDisconnectAction = tmp.mDisconnectAction;
- mEndAction = tmp.mEndAction;
- mSpeedFactor = tmp.mSpeedFactor;
- mPlayRange = tmp.mPlayRange;
+ mEndAction = tmp.mEndAction;
+ mSpeedFactor = tmp.mSpeedFactor;
+ mPlayRange = tmp.mPlayRange;
mProperties.swap(tmp.mProperties);
return *this;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
-* Copyright (c) 2020 Samsung Electronics Co., Ltd.
+* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
const std::string BlendShapes::NUMBER_OF_BLEND_SHAPES("uNumberOfBlendShapes");
const std::string BlendShapes::UNNORMALIZE_FACTOR("uBlendShapeUnnormalizeFactor");
const std::string BlendShapes::COMPONENT_SIZE("uBlendShapeComponentSize");
{
unsigned int index = 0u;
- char weightNameBuffer[32];
- char unnormalizeFactorNameBuffer[64];
+ char weightNameBuffer[32];
+ char unnormalizeFactorNameBuffer[64];
char* const pWeightName = weightNameBuffer + snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s", WEIGHTS_UNIFORM.c_str());
char* const pFactorName = unnormalizeFactorNameBuffer + snprintf(unnormalizeFactorNameBuffer, sizeof(unnormalizeFactorNameBuffer), "%s", UNNORMALIZE_FACTOR.c_str());
- for (const auto& blendShape : mesh.first.mBlendShapes)
+ for(const auto& blendShape : mesh.first.mBlendShapes)
{
snprintf(pWeightName, sizeof(weightNameBuffer) - (pWeightName - weightNameBuffer), "[%d]", index);
- std::string weightName{ weightNameBuffer };
+ std::string weightName{weightNameBuffer};
actor.RegisterProperty(weightName, blendShape.weight);
- if (mesh.first.mBlendShapeVersion == Version::VERSION_1_0)
+ if(mesh.first.mBlendShapeVersion == Version::VERSION_1_0)
{
snprintf(pFactorName, sizeof(unnormalizeFactorNameBuffer) - (pFactorName - unnormalizeFactorNameBuffer), "[%d]", index);
- std::string factorName{ unnormalizeFactorNameBuffer };
+ std::string factorName{unnormalizeFactorNameBuffer};
shader.RegisterProperty(factorName, mesh.second.blendShapeUnnormalizeFactor[index]);
}
++index;
}
- if (Version::VERSION_2_0 == mesh.first.mBlendShapeVersion)
+ if(Version::VERSION_2_0 == mesh.first.mBlendShapeVersion)
{
shader.RegisterProperty(UNNORMALIZE_FACTOR, mesh.second.blendShapeUnnormalizeFactor[0u]);
}
// Create a read only property to preserve the components of the blend shape.
int32_t components = 0x0;
- for (auto& bs : mesh.first.mBlendShapes)
+ for(auto& bs : mesh.first.mBlendShapes)
{
components |= (bs.deltas.IsDefined() * Component::POSITIONS) |
- (bs.normals.IsDefined() * Component::NORMALS) | (bs.tangents.IsDefined() * Component::TANGENTS);
+ (bs.normals.IsDefined() * Component::NORMALS) | (bs.tangents.IsDefined() * Component::TANGENTS);
}
shader.RegisterProperty(COMPONENTS, components, Property::AccessMode::READ_ONLY);
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
#include "dali-scene-loader/public-api/camera-parameters.h"
#include "dali-scene-loader/public-api/utils.h"
+#include "dali/integration-api/debug.h"
#include "dali/public-api/actors/camera-actor.h"
#include "dali/public-api/math/quaternion.h"
-#include "dali/integration-api/debug.h"
namespace Dali
{
* @param[in] far The distance to the far depth clipping plane.
* @param[in] invertYAxis Whether to invert the 'Y' axis.
*/
-void Frustum( Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis )
+void Frustum(Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis)
{
float deltaZ = farPlane - nearPlane;
- if ((nearPlane <= 0.0f) || (farPlane <= 0.0f) || Equals(right, left) || Equals(bottom, top) || (deltaZ <= 0.0f))
+ if((nearPlane <= 0.0f) || (farPlane <= 0.0f) || Equals(right, left) || Equals(bottom, top) || (deltaZ <= 0.0f))
{
DALI_LOG_ERROR("Invalid parameters passed into Frustum!\n");
DALI_ASSERT_DEBUG("Invalid parameters passed into Frustum!");
result.SetIdentity();
float* m = result.AsFloat();
- m[0] = -2.0f * nearPlane / deltaX;
+ m[0] = -2.0f * nearPlane / deltaX;
m[1] = m[2] = m[3] = 0.0f;
m[5] = -2.0f * nearPlane / deltaY;
m[4] = m[6] = m[7] = 0.0f;
- m[8] = (right + left) / deltaX;
- m[9] = (top + bottom) / deltaY;
+ m[8] = (right + left) / deltaX;
+ m[9] = (top + bottom) / deltaY;
m[10] = (nearPlane + farPlane) / deltaZ;
m[11] = 1.0f;
* @param[in] farPlane The distance to the far depth clipping plane.
* @param[in] invertYAxis Whether to invert the 'Y' axis.
*/
-void Perspective( Matrix& result, float fovy, float aspect, float nearPlane, float farPlane, bool invertYAxis )
+void Perspective(Matrix& result, float fovy, float aspect, float nearPlane, float farPlane, bool invertYAxis)
{
- float frustumH = tanf( fovy * 0.5f ) * nearPlane;
+ float frustumH = tanf(fovy * 0.5f) * nearPlane;
float frustumW = frustumH * aspect;
- Frustum( result, -frustumW, frustumW, -frustumH, frustumH, nearPlane, farPlane, invertYAxis );
+ Frustum(result, -frustumW, frustumW, -frustumH, frustumH, nearPlane, farPlane, invertYAxis);
}
/**
*/
void Orthographic(Matrix& result, float left, float right, float bottom, float top, float nearPlane, float farPlane, bool invertYAxis)
{
- if (Equals(right, left) || Equals(top, bottom) || Equals(farPlane, nearPlane))
+ if(Equals(right, left) || Equals(top, bottom) || Equals(farPlane, nearPlane))
{
DALI_LOG_ERROR("Cannot create orthographic projection matrix with a zero dimension.\n");
DALI_ASSERT_DEBUG("Cannot create orthographic projection matrix with a zero dimension.");
float deltaY = invertYAxis ? bottom - top : top - bottom;
float deltaZ = farPlane - nearPlane;
- float *m = result.AsFloat();
- m[0] = -2.0f / deltaX;
- m[1] = 0.0f;
- m[2] = 0.0f;
- m[3] = 0.0f;
+ float* m = result.AsFloat();
+ m[0] = -2.0f / deltaX;
+ m[1] = 0.0f;
+ m[2] = 0.0f;
+ m[3] = 0.0f;
m[4] = 0.0f;
m[5] = -2.0f / deltaY;
m[6] = 0.0f;
m[7] = 0.0f;
- m[8] = 0.0f;
- m[9] = 0.0f;
+ m[8] = 0.0f;
+ m[9] = 0.0f;
m[10] = 2.0f / deltaZ;
m[11] = 0.0f;
m[12] = -(right + left) / deltaX;
m[15] = 1.0f;
}
-} // nonamespace
+} // namespace
ViewProjection CameraParameters::GetViewProjection() const
{
ViewProjection viewProjection;
// The projection matrix.
- if (isPerspective)
+ if(isPerspective)
{
Perspective(viewProjection.GetProjection(),
- Radian(Degree(yFov)),
- 1.f,
- zNear,
- zFar,
- true);
+ Radian(Degree(yFov)),
+ 1.f,
+ zNear,
+ zFar,
+ true);
}
else
{
Orthographic(viewProjection.GetProjection(),
- orthographicSize.x,
- orthographicSize.y,
- orthographicSize.z,
- orthographicSize.w,
- zNear,
- zFar,
- true);
-
+ orthographicSize.x,
+ orthographicSize.y,
+ orthographicSize.z,
+ orthographicSize.w,
+ zNear,
+ zFar,
+ true);
}
// The view matrix.
const Quaternion viewQuaternion(ANGLE_180, Vector3::YAXIS);
- Vector3 translation;
- Quaternion cameraOrientation;
- Vector3 scale;
+ Vector3 translation;
+ Quaternion cameraOrientation;
+ Vector3 scale;
matrix.GetTransformComponents(translation, cameraOrientation, scale);
cameraOrientation *= viewQuaternion;
viewProjection.GetView().SetInverseTransformComponents(scale,
- cameraOrientation,
- translation);
+ cameraOrientation,
+ translation);
viewProjection.Update();
return viewProjection;
}
-void CameraParameters::CalculateTransformComponents(Vector3 & position, Quaternion & orientation, Vector3 & scale) const
+void CameraParameters::CalculateTransformComponents(Vector3& position, Quaternion& orientation, Vector3& scale) const
{
matrix.GetTransformComponents(position, orientation, scale);
{
SetActorCentered(camera);
- if (isPerspective)
+ if(isPerspective)
{
camera.SetProjectionMode(Camera::PERSPECTIVE_PROJECTION);
camera.SetNearClippingPlane(zNear);
{
camera.SetProjectionMode(Camera::ORTHOGRAPHIC_PROJECTION);
camera.SetOrthographicProjection(orthographicSize.x,
- orthographicSize.y,
- orthographicSize.z,
- orthographicSize.w,
- zNear,
- zFar);
+ orthographicSize.y,
+ orthographicSize.z,
+ orthographicSize.w,
+ zNear,
+ zFar);
}
// model
- Vector3 camTranslation;
- Vector3 camScale;
+ Vector3 camTranslation;
+ Vector3 camScale;
Quaternion camOrientation;
CalculateTransformComponents(camTranslation, camOrientation, camScale);
camera.SetProperty(Actor::Property::SCALE, camScale);
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
-struct Customization::Map::Impl {
+struct Customization::Map::Impl
+{
std::map<Tag, Customization> mCustomizations;
};
Customization::Map::Map()
-: mImpl{ new Impl }
-{}
+: mImpl{new Impl}
+{
+}
Customization::Map::~Map() = default;
const Customization* Customization::Map::Get(Tag tag) const
{
auto& customizations = mImpl->mCustomizations;
- auto iFind = customizations.find(tag);
- if (iFind != customizations.end())
+ auto iFind = customizations.find(tag);
+ if(iFind != customizations.end())
{
return &iFind->second;
}
Customization* Customization::Map::Get(Tag tag)
{
auto& customizations = mImpl->mCustomizations;
- auto iFind = customizations.find(tag);
- if (iFind != customizations.end())
+ auto iFind = customizations.find(tag);
+ if(iFind != customizations.end())
{
return &iFind->second;
}
};
Customization::Choices::Choices()
-: mImpl{ new Impl }
-{}
+: mImpl{new Impl}
+{
+}
Customization::Choices::~Choices() = default;
Customization::OptionType Customization::Choices::Get(Tag tag) const
{
auto& options = mImpl->mOptions;
- auto iFind = options.find(tag);
- if (iFind != options.end())
+ auto iFind = options.find(tag);
+ if(iFind != options.end())
{
return iFind->second;
}
mImpl->mOptions.clear();
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "dali-scene-loader/public-api/dli-loader.h"
// EXTERNAL INCLUDES
-#include "dali/public-api/object/property-array.h"
-#include "dali/devel-api/common/map-wrapper.h"
-#include "dali-toolkit/devel-api/builder/json-parser.h"
-#include "dali/integration-api/debug.h"
+#include <algorithm>
+#include <cmath>
#include <fstream>
#include <limits>
-#include <algorithm>
#include <memory>
-#include <cmath>
+#include "dali-toolkit/devel-api/builder/json-parser.h"
+#include "dali/devel-api/common/map-wrapper.h"
+#include "dali/integration-api/debug.h"
+#include "dali/public-api/object/property-array.h"
// INTERNAL INCLUDES
-#include "dali-scene-loader/public-api/parse-renderer-state.h"
-#include "dali-scene-loader/public-api/skinning-details.h"
-#include "dali-scene-loader/public-api/load-result.h"
-#include "dali-scene-loader/public-api/scene-definition.h"
-#include "dali-scene-loader/public-api/animation-definition.h"
+#include "dali-scene-loader/internal/json-util.h"
#include "dali-scene-loader/public-api/alpha-function-helper.h"
-#include "dali-scene-loader/public-api/camera-parameters.h"
-#include "dali-scene-loader/public-api/light-parameters.h"
+#include "dali-scene-loader/public-api/animation-definition.h"
#include "dali-scene-loader/public-api/blend-shape-details.h"
+#include "dali-scene-loader/public-api/camera-parameters.h"
#include "dali-scene-loader/public-api/ktx-loader.h"
+#include "dali-scene-loader/public-api/light-parameters.h"
+#include "dali-scene-loader/public-api/load-result.h"
+#include "dali-scene-loader/public-api/parse-renderer-state.h"
+#include "dali-scene-loader/public-api/scene-definition.h"
+#include "dali-scene-loader/public-api/skinning-details.h"
#include "dali-scene-loader/public-api/utils.h"
-#include "dali-scene-loader/internal/json-util.h"
#define DLI_0_1_COMPATIBILITY
namespace SceneLoader
{
-
namespace rs = RendererState;
namespace
{
-const std::string NODES = "nodes";
-const std::string SCENES = "scenes";
-const std::string NODE = "node";
-const std::string URI = "uri";
-const std::string URL = "url";
+const std::string NODES = "nodes";
+const std::string SCENES = "scenes";
+const std::string NODE = "node";
+const std::string URI = "uri";
+const std::string URL = "url";
const std::string CUSTOMIZATION = "customization";
-const std::string HINTS = "hints";
+const std::string HINTS = "hints";
const std::string NAME("name");
const std::string BLEND_SHAPE_HEADER("blendShapeHeader");
const std::string BLEND_SHAPES("blendShapes");
const std::string BLEND_SHAPE_VERSION_2_0("2.0");
const std::string VERSION("version");
-const char* const SHADOW_MAP_SIZE = "shadowMapSize";
+const char* const SHADOW_MAP_SIZE = "shadowMapSize";
const char* const ORTHOGRAPHIC_SIZE = "orthographicSize";
-const char* const PIXEL_UNITS = "px";
+const char* const PIXEL_UNITS = "px";
const char SLASH = '/';
void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale)
{
- float num[16u] = { .0f };
+ float num[16u] = {.0f};
- if (ReadVector(node->GetChild("matrix"), num, 16u))
+ if(ReadVector(node->GetChild("matrix"), num, 16u))
{
Matrix mat(num);
mat.GetTransformComponents(translation, orientation, scale);
}
else
{
- if (ReadVector(node->GetChild("angle"), num, 3u))
+ if(ReadVector(node->GetChild("angle"), num, 3u))
{
orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u])));
}
- if (ReadVector(node->GetChild("position"), num, 3u))
+ if(ReadVector(node->GetChild("position"), num, 3u))
{
translation = Vector3(num);
}
return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength);
}
-bool ReadColorCode(const TreeNode* node, Vector4& color,
- DliLoader::ConvertColorCode convertColorCode)
+bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
{
- if (!node || !convertColorCode)
+ if(!node || !convertColorCode)
{
return false;
}
return true;
}
-bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color,
- DliLoader::ConvertColorCode convertColorCode)
+bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode)
{
return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) ||
- ReadColor(node->GetChild("color"), color);
+ ReadColor(node->GetChild("color"), color);
}
RendererState::Type ReadRendererState(const TreeNode& tnRendererState)
{
- if (tnRendererState.GetType() == TreeNode::INTEGER)
+ if(tnRendererState.GetType() == TreeNode::INTEGER)
{
return static_cast<RendererState::Type>(tnRendererState.GetInteger());
}
- else if (tnRendererState.GetType() == TreeNode::STRING)
+ else if(tnRendererState.GetType() == TreeNode::STRING)
{
return RendererState::Parse(tnRendererState.GetString());
}
ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees);
}
-const TreeNode *GetNthChild(const TreeNode *node, uint32_t index)
+const TreeNode* GetNthChild(const TreeNode* node, uint32_t index)
{
uint32_t i = 0;
- for (TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
+ for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i)
{
- if (i == index)
+ if(i == index)
{
return &((*it).second);
}
const TreeNode* RequireChild(const TreeNode* node, const std::string& childName)
{
auto child = node->GetChild(childName);
- if (!child)
+ if(!child)
{
ExceptionFlinger flinger(ASSERT_LOCATION);
flinger << "Failed to find child node '" << childName << "'";
- if (auto nodeName = node->GetName())
+ if(auto nodeName = node->GetName())
{
flinger << " on '" << nodeName << "'";
}
void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map)
{
DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT);
- for (auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
+ for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
{
auto kv = *i0;
- switch (kv.second.GetType())
- {
- case TreeNode::ARRAY:
+ switch(kv.second.GetType())
{
- Property::Array array;
- ParseProperties(kv.second, array);
- map.Insert(kv.first, array);
- } break;
+ case TreeNode::ARRAY:
+ {
+ Property::Array array;
+ ParseProperties(kv.second, array);
+ map.Insert(kv.first, array);
+ break;
+ }
- case TreeNode::OBJECT:
- {
- Property::Map innerMap;
- ParseProperties(kv.second, innerMap);
- map.Insert(kv.first, innerMap);
- } break;
+ case TreeNode::OBJECT:
+ {
+ Property::Map innerMap;
+ ParseProperties(kv.second, innerMap);
+ map.Insert(kv.first, innerMap);
+ break;
+ }
- case TreeNode::STRING:
- map.Insert(kv.first, kv.second.GetString());
- break;
+ case TreeNode::STRING:
+ {
+ map.Insert(kv.first, kv.second.GetString());
+ break;
+ }
- case TreeNode::INTEGER:
- map.Insert(kv.first, kv.second.GetInteger());
- break;
+ case TreeNode::INTEGER:
+ {
+ map.Insert(kv.first, kv.second.GetInteger());
+ break;
+ }
- case TreeNode::BOOLEAN:
- map.Insert(kv.first, kv.second.GetBoolean());
- break;
+ case TreeNode::BOOLEAN:
+ {
+ map.Insert(kv.first, kv.second.GetBoolean());
+ break;
+ }
- case TreeNode::FLOAT:
- map.Insert(kv.first, kv.second.GetFloat());
- break;
+ case TreeNode::FLOAT:
+ {
+ map.Insert(kv.first, kv.second.GetFloat());
+ break;
+ }
- case TreeNode::IS_NULL:
- break;
+ case TreeNode::IS_NULL:
+ {
+ break;
+ }
}
}
}
void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array)
{
DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY);
- for (auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
+ for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0)
{
auto kv = *i0;
- switch (kv.second.GetType())
- {
- case TreeNode::ARRAY:
+ switch(kv.second.GetType())
{
- Property::Array innerArray;
- ParseProperties(kv.second, innerArray);
- array.PushBack(innerArray);
- } break;
+ case TreeNode::ARRAY:
+ {
+ Property::Array innerArray;
+ ParseProperties(kv.second, innerArray);
+ array.PushBack(innerArray);
+ break;
+ }
- case TreeNode::OBJECT:
- {
- Property::Map map;
- ParseProperties(kv.second, map);
- array.PushBack(map);
- } break;
+ case TreeNode::OBJECT:
+ {
+ Property::Map map;
+ ParseProperties(kv.second, map);
+ array.PushBack(map);
+ break;
+ }
- case TreeNode::STRING:
- array.PushBack(kv.second.GetString());
- break;
+ case TreeNode::STRING:
+ {
+ array.PushBack(kv.second.GetString());
+ break;
+ }
- case TreeNode::INTEGER:
- array.PushBack(kv.second.GetInteger());
- break;
+ case TreeNode::INTEGER:
+ {
+ array.PushBack(kv.second.GetInteger());
+ break;
+ }
- case TreeNode::BOOLEAN:
- array.PushBack(kv.second.GetBoolean());
- break;
+ case TreeNode::BOOLEAN:
+ {
+ array.PushBack(kv.second.GetBoolean());
+ break;
+ }
- case TreeNode::FLOAT:
- array.PushBack(kv.second.GetFloat());
- break;
+ case TreeNode::FLOAT:
+ {
+ array.PushBack(kv.second.GetFloat());
+ break;
+ }
- case TreeNode::IS_NULL:
- break;
+ case TreeNode::IS_NULL:
+ {
+ break;
+ }
}
}
}
-}//namespace
+} //namespace
struct DliLoader::Impl
{
- StringCallback mOnError = DefaultErrorCallback;
+ StringCallback mOnError = DefaultErrorCallback;
Toolkit::JsonParser mParser;
void ParseScene(LoadParams& params);
private:
- std::map<Index, Matrix> mInverseBindMatrices;
+ std::map<Index, Matrix> mInverseBindMatrices;
/**
* @brief Due to .dli nodes being processed in depth-first traversal with orphans being
* index.
* @return Whether the operation was successful.
*/
- virtual bool Map(Index iDli, Index iScene) =0;
+ virtual bool Map(Index iDli, Index iScene) = 0;
/**
* @return The scene index for the node's @a dli index.
*/
- virtual Index Resolve(Index iDli) =0;
+ virtual Index Resolve(Index iDli) = 0;
};
/**
* @brief Traverses the DOM tree created by LoadDocument() in an attempt to create
* an intermediate representation of resources and nodes.
*/
- void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes,
- const Toolkit::TreeNode* tnNodes, LoadParams& params);
+ void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params);
void ParseSkeletons(const Toolkit::TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources);
void ParseEnvironments(const Toolkit::TreeNode* environments, ResourceBundle& resources);
- void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode,
- ResourceBundle& resources);
+ void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources);
void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params);
- void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index,
- std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
+ void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper);
void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params);
void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params);
};
DliLoader::DliLoader()
-: mImpl{ new Impl }
-{}
+: mImpl{new Impl}
+{
+}
DliLoader::~DliLoader() = default;
std::string daliBuffer = LoadTextFile(uri.c_str());
auto& parser = mImpl->mParser;
- parser = JsonParser::New();
- if (!parser.Parse(daliBuffer))
+ parser = JsonParser::New();
+ if(!parser.Parse(daliBuffer))
{
return false;
}
std::stringstream stream;
auto& parser = mImpl->mParser;
- if (parser.ParseError())
+ if(parser.ParseError())
{
stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << ".";
}
void DliLoader::Impl::ParseScene(LoadParams& params)
{
- auto& input = params.input;
+ auto& input = params.input;
auto& output = params.output;
// get index of root node.
auto docRoot = mParser.GetRoot();
// Process resources first - these are shared
- if (auto environments = docRoot->GetChild("environment"))
+ if(auto environments = docRoot->GetChild("environment"))
{
- ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
+ ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials
}
- if (auto meshes = docRoot->GetChild("meshes"))
+ if(auto meshes = docRoot->GetChild("meshes"))
{
ParseMeshes(meshes, output.mResources);
}
- if (auto shaders = docRoot->GetChild("shaders"))
+ if(auto shaders = docRoot->GetChild("shaders"))
{
ParseShaders(shaders, output.mResources);
}
- if (auto materials = docRoot->GetChild("materials"))
+ if(auto materials = docRoot->GetChild("materials"))
{
ParseMaterials(materials, input.mConvertColorCode, output.mResources);
}
- for (auto& c : input.mPreNodeCategoryProcessors)
+ for(auto& c : input.mPreNodeCategoryProcessors)
{
- if (auto node = docRoot->GetChild(c.first))
+ if(auto node = docRoot->GetChild(c.first))
{
Property::Array array;
ParseProperties(*node, array);
}
// Process scenes
- Index iScene = 0; // default scene
+ Index iScene = 0; // default scene
ReadIndex(docRoot->GetChild("scene"), iScene);
auto tnScenes = RequireChild(docRoot, "scenes");
- auto tnNodes = RequireChild(docRoot, "nodes");
+ auto tnNodes = RequireChild(docRoot, "nodes");
ParseSceneInternal(iScene, tnScenes, tnNodes, params);
ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources);
GetLightParameters(output.mLightParameters);
// Post-node processors and animations last
- for (auto& c : input.mPostNodeCategoryProcessors)
+ for(auto& c : input.mPostNodeCategoryProcessors)
{
- if (auto node = docRoot->GetChild(c.first))
+ if(auto node = docRoot->GetChild(c.first))
{
Property::Array array;
ParseProperties(*node, array);
}
}
- if (auto animations = docRoot->GetChild("animations"))
+ if(auto animations = docRoot->GetChild("animations"))
{
ParseAnimations(animations, params);
}
- if (!output.mAnimationDefinitions.empty())
+ if(!output.mAnimationDefinitions.empty())
{
- if (auto animationGroups = docRoot->GetChild("animationGroups"))
+ if(auto animationGroups = docRoot->GetChild("animationGroups"))
{
ParseAnimationGroups(animationGroups, params);
}
}
}
-void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes,
- const Toolkit::TreeNode* tnNodes, LoadParams& params)
+void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params)
{
auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) {
- auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
- if (!tn)
+ auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object
+ if(!tn)
{
ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << ".";
}
- tn = RequireChild(tn, NODES); // now a "nodes" array
- if (tn->GetType() != TreeNode::ARRAY)
+ tn = RequireChild(tn, NODES); // now a "nodes" array
+ if(tn->GetType() != TreeNode::ARRAY)
{
- ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES <<
- " has an invalid type; array required.";
+ ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required.";
}
- if (tn->Size() < 1)
+ if(tn->Size() < 1)
{
- ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES <<
- " must define a node id.";
+ ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id.";
}
- tn = GetNthChild(tn, 0); // now the first element of the array
+ tn = GetNthChild(tn, 0); // now the first element of the array
Index iRootNode;
- if (!ReadIndex(tn, iRootNode))
+ if(!ReadIndex(tn, iRootNode))
{
- ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES <<
- " has an invalid value for root node index: '" << iRootNode << "'.";
+ ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'.";
}
- if (iRootNode >= tnNodes->Size())
+ if(iRootNode >= tnNodes->Size())
{
ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds.";
}
- tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
- if (tn->GetType() != TreeNode::OBJECT)
+ tn = GetNthChild(tnNodes, iRootNode); // now a "node" object
+ if(tn->GetType() != TreeNode::OBJECT)
{
ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required";
}
auto& scene = params.output.mScene;
scene.AddRootNode(0);
- for (Index i = 0; i < iScene; ++i)
+ for(Index i = 0; i < iScene; ++i)
{
- Index iRootNode = getSceneRootIdx(i);
- const Index iRoot = scene.GetNodeCount();
+ Index iRootNode = getSceneRootIdx(i);
+ const Index iRoot = scene.GetNodeCount();
ParseNodes(tnNodes, iRootNode, params);
scene.AddRootNode(iRoot);
}
auto numScenes = tnScenes->Size();
- for (Index i = iScene + 1; i < numScenes; ++i)
+ for(Index i = iScene + 1; i < numScenes; ++i)
{
- Index iRootNode = getSceneRootIdx(i);
- const Index iRoot = scene.GetNodeCount();
+ Index iRootNode = getSceneRootIdx(i);
+ const Index iRoot = scene.GetNodeCount();
ParseNodes(tnNodes, iRootNode, params);
scene.AddRootNode(iRoot);
}
void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources)
{
- if (skeletons)
+ if(skeletons)
{
auto iStart = skeletons->CBegin();
- for (auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0)
{
- auto& node = (*i0).second;
+ auto& node = (*i0).second;
std::string skeletonRootName;
- if (ReadString(node.GetChild(NODE), skeletonRootName))
+ if(ReadString(node.GetChild(NODE), skeletonRootName))
{
SkeletonDefinition skeleton;
- if (!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
+ if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx))
{
ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str());
}
- uint32_t jointCount = 0;
+ uint32_t jointCount = 0;
std::function<void(Index)> visitFn;
- auto& ibms = mInverseBindMatrices;
- visitFn = [&](Index id) {
+ auto& ibms = mInverseBindMatrices;
+ visitFn = [&](Index id) {
auto node = scene.GetNode(id);
jointCount += ibms.find(id) != ibms.end();
- for (auto i : node->mChildren)
+ for(auto i : node->mChildren)
{
visitFn(i);
}
};
visitFn(skeleton.mRootNodeIdx);
- if (jointCount > Skinning::MAX_JOINTS)
+ if(jointCount > Skinning::MAX_JOINTS)
{
mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size()));
jointCount = Skinning::MAX_JOINTS;
visitFn = [&](Index id) {
auto iFind = ibms.find(id);
- if (iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
+ if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS)
{
- skeleton.mJoints.push_back({ id, iFind->second });
+ skeleton.mJoints.push_back({id, iFind->second});
}
auto node = scene.GetNode(id);
- for (auto i : node->mChildren)
+ for(auto i : node->mChildren)
{
visitFn(i);
}
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) <<
- ": Missing required attribute '"<< NODE <<"'.";
+ ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'.";
}
}
}
{
Matrix cubeOrientation(Matrix::IDENTITY);
- for (auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0)
{
auto& node = (*i0).second;
ToUnixFileSeparators(envDef.mDiffuseMapPath);
envDef.mIblIntensity = 1.0f;
ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity);
- if (ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
+ if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u))
{
envDef.mCubeOrientation = Quaternion(cubeOrientation);
}
}
// NOTE: guarantees environmentMaps to have an empty environment.
- if (resources.mEnvironmentMaps.empty())
+ if(resources.mEnvironmentMaps.empty())
{
resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures());
}
void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources)
{
uint32_t iShader = 0;
- for (auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
+ for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader)
{
- auto& node = (*i0).second;
+ auto& node = (*i0).second;
ShaderDefinition shaderDef;
ReadStringVector(node.GetChild("defines"), shaderDef.mDefines);
// "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs.
// "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations.
- ReadStringVector(node.GetChild( HINTS ), shaderDef.mHints);
+ ReadStringVector(node.GetChild(HINTS), shaderDef.mHints);
- if (ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
- ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
+ if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) &&
+ ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath))
{
ToUnixFileSeparators(shaderDef.mVertexShaderPath);
ToUnixFileSeparators(shaderDef.mFragmentShaderPath);
- for (TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
+ for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0)
{
const TreeNode::KeyNodePair& keyValue = *j0;
- const std::string& key = keyValue.first;
- const TreeNode& value = keyValue.second;
+ const std::string& key = keyValue.first;
+ const TreeNode& value = keyValue.second;
Property::Value uniformValue;
- if (key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
+ if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0)
{
continue;
}
- else if (key.compare("rendererState") == 0)
+ else if(key.compare("rendererState") == 0)
{
shaderDef.mRendererState = ReadRendererState(keyValue.second);
}
- else if (value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
+ else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT)
{
float f = 0.f;
ReadFloat(&value, f);
uniformValue = f;
}
- else if (value.GetType() == TreeNode::BOOLEAN)
+ else if(value.GetType() == TreeNode::BOOLEAN)
{
DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader");
bool value = false;
- if (ReadBool(&keyValue.second, value))
+ if(ReadBool(&keyValue.second, value))
{
uniformValue = value ? 1.0f : 0.0f;
}
}
- else switch (auto size = GetNumericalArraySize(&value))
- {
- case 16:
- {
- Matrix m;
- ReadVector(&value, m.AsFloat(), size);
- uniformValue = m;
- break;
- }
+ else
+ switch(auto size = GetNumericalArraySize(&value))
+ {
+ case 16:
+ {
+ Matrix m;
+ ReadVector(&value, m.AsFloat(), size);
+ uniformValue = m;
+ break;
+ }
- case 9:
- {
- Matrix3 m;
- ReadVector(&value, m.AsFloat(), size);
- uniformValue = m;
- break;
- }
+ case 9:
+ {
+ Matrix3 m;
+ ReadVector(&value, m.AsFloat(), size);
+ uniformValue = m;
+ break;
+ }
- case 4:
- {
- Vector4 v;
- ReadVector(&value, v.AsFloat(), size);
- uniformValue = v;
- break;
- }
+ case 4:
+ {
+ Vector4 v;
+ ReadVector(&value, v.AsFloat(), size);
+ uniformValue = v;
+ break;
+ }
- case 3:
- {
- Vector3 v;
- ReadVector(&value, v.AsFloat(), size);
- uniformValue = v;
- break;
- }
+ case 3:
+ {
+ Vector3 v;
+ ReadVector(&value, v.AsFloat(), size);
+ uniformValue = v;
+ break;
+ }
- case 2:
- {
- Vector2 v;
- ReadVector(&value, v.AsFloat(), size);
- uniformValue = v;
- break;
- }
+ case 2:
+ {
+ Vector2 v;
+ ReadVector(&value, v.AsFloat(), size);
+ uniformValue = v;
+ break;
+ }
- default:
- mOnError(FormatString(
- "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.",
- iShader, key.c_str()));
- break;
- }
+ default:
+ mOnError(FormatString(
+ "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.",
+ iShader,
+ key.c_str()));
+ break;
+ }
- if (Property::NONE != uniformValue.GetType())
+ if(Property::NONE != uniformValue.GetType())
{
shaderDef.mUniforms.Insert(key, uniformValue);
}
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader <<
- ": Missing vertex / fragment shader definition.";
+ ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition.";
}
}
}
void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources)
{
- for (auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0)
{
auto& node = (*i0).second;
- MeshDefinition meshDef;
- if (!ReadString(node.GetChild(URI), meshDef.mUri))
+ MeshDefinition meshDef;
+ if(!ReadString(node.GetChild(URI), meshDef.mUri))
{
- ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() <<
- ": Missing required attribute '" << URI << "'.";
+ ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'.";
}
ToUnixFileSeparators(meshDef.mUri);
std::string primitive;
- if (ReadString(node.GetChild("primitive"), primitive))
+ if(ReadString(node.GetChild("primitive"), primitive))
{
- if (primitive == "LINES")
+ if(primitive == "LINES")
{
meshDef.mPrimitiveType = Geometry::LINES;
}
- else if (primitive == "POINTS")
+ else if(primitive == "POINTS")
{
meshDef.mPrimitiveType = Geometry::POINTS;
}
- else if (primitive != "TRIANGLES")
+ else if(primitive != "TRIANGLES")
{
mOnError(FormatString(
"mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.",
- resources.mMeshes.size(), primitive.c_str()));
+ resources.mMeshes.size(),
+ primitive.c_str()));
}
}
int attributes;
- if (ReadInt(node.GetChild("attributes"), attributes))
+ if(ReadInt(node.GetChild("attributes"), attributes))
{
- if (MaskMatch(attributes, MeshDefinition::INDICES) &&
- !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
+ if(MaskMatch(attributes, MeshDefinition::INDICES) &&
+ !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices))
{
ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
- resources.mMeshes.size(), "indices");
+ resources.mMeshes.size(),
+ "indices");
}
- if (MaskMatch(attributes, MeshDefinition::POSITIONS) &&
- !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
+ if(MaskMatch(attributes, MeshDefinition::POSITIONS) &&
+ !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions))
{
ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.",
- resources.mMeshes.size(), "positions");
+ resources.mMeshes.size(),
+ "positions");
}
- if (MaskMatch(attributes, MeshDefinition::NORMALS) &&
- !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
+ if(MaskMatch(attributes, MeshDefinition::NORMALS) &&
+ !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals))
{
- mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(),
- "normals"));
+ mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals"));
}
- if (MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
- !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
+ if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) &&
+ !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords))
{
- mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(),
- "textures"));
+ mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures"));
}
- if (MaskMatch(attributes, MeshDefinition::TANGENTS) &&
- !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
+ if(MaskMatch(attributes, MeshDefinition::TANGENTS) &&
+ !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents))
{
- mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(),
- "tangents"));
+ mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents"));
}
// NOTE: we're no longer reading bitangents as these are calculated in the shaders.
- if (ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
+ if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx))
{
- if (!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
- !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
+ if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) &&
+ !MaskMatch(attributes, MeshDefinition::WEIGHTS_0))
{
mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.",
- resources.mMeshes.size()));
+ resources.mMeshes.size()));
}
- else if (!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
- !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
+ else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) ||
+ !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0))
{
mOnError(FormatString("mesh %d: Failed to read skinning information.",
- resources.mMeshes.size()));
+ resources.mMeshes.size()));
}
}
- if (auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
+ if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER))
{
std::string blendShapeVersion;
ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion);
- if (0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
+ if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0))
{
meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0;
}
- else if (0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
+ else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0))
{
meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
}
- switch (meshDef.mBlendShapeVersion)
+ switch(meshDef.mBlendShapeVersion)
{
case BlendShapes::Version::VERSION_1_0:
case BlendShapes::Version::VERSION_2_0: // FALL THROUGH
}
}
- if (auto blendShapes = node.GetChild(BLEND_SHAPES) )
+ if(auto blendShapes = node.GetChild(BLEND_SHAPES))
{
meshDef.mBlendShapes.resize(blendShapes->Size());
auto index = 0u;
- for (auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
+ for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index)
{
// Each blend shape is stored as the difference with the original mesh.
auto& blendShape = meshDef.mBlendShapes[index];
ReadString(blendShapeNode.GetChild("name"), blendShape.name);
- if (auto position = blendShapeNode.GetChild("positions"))
+ if(auto position = blendShapeNode.GetChild("positions"))
{
ReadAttribAccessor(position, blendShape.deltas);
}
- if (auto normals = blendShapeNode.GetChild("normals"))
+ if(auto normals = blendShapeNode.GetChild("normals"))
{
ReadAttribAccessor(normals, blendShape.normals);
}
- if (auto tangents = blendShapeNode.GetChild("tangents"))
+ if(auto tangents = blendShapeNode.GetChild("tangents"))
{
ReadAttribAccessor(tangents, blendShape.tangents);
}
}
bool flipV;
- if (ReadBool(node.GetChild("flipV"), flipV))
+ if(ReadBool(node.GetChild("flipV"), flipV))
{
meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL;
}
}
}
-void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode,
- ResourceBundle& resources)
+void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources)
{
- for (auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0)
{
auto& node = (*i0).second;
MaterialDefinition materialDef;
- if (auto eEnvironment = node.GetChild("environment"))
+ if(auto eEnvironment = node.GetChild("environment"))
{
ReadIndex(eEnvironment, materialDef.mEnvironmentIdx);
- if (static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
+ if(static_cast<unsigned int>(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size())
{
- ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() <<
- ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" <<
- resources.mEnvironmentMaps.size() << ").";
+ ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ").";
}
}
//TODO : need to consider AGIF
std::vector<std::string> texturePaths;
- std::string texturePath;
- if (ReadString(node.GetChild("albedoMap"), texturePath))
+ std::string texturePath;
+ if(ReadString(node.GetChild("albedoMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
const auto semantic = MaterialDefinition::ALBEDO;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
- materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
+ materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY.
}
- if (ReadString(node.GetChild("albedoMetallicMap"), texturePath))
+ if(ReadString(node.GetChild("albedoMetallicMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo"));
}
const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic;
}
- if (ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
+ if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic"));
}
const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic |
- // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
- (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
+ // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow.
+ (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
}
- if (ReadString(node.GetChild("normalMap"), texturePath))
+ if(ReadString(node.GetChild("normalMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
const auto semantic = MaterialDefinition::NORMAL;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic |
- // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
- (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
+ // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow.
+ (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY);
}
- if (ReadString(node.GetChild("normalRoughnessMap"), texturePath))
+ if(ReadString(node.GetChild("normalRoughnessMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal"));
}
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness"));
}
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY))
{
mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency"));
}
const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic;
}
- if (ReadString(node.GetChild("subsurfaceMap"), texturePath))
+ if(ReadString(node.GetChild("subsurfaceMap"), texturePath))
{
ToUnixFileSeparators(texturePath);
const auto semantic = MaterialDefinition::SUBSURFACE;
- materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } });
+ materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}});
materialDef.mFlags |= semantic;
}
- if (ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
- materialDef.mColor.a < 1.0f)
+ if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) &&
+ materialDef.mColor.a < 1.0f)
{
materialDef.mFlags |= MaterialDefinition::TRANSPARENCY;
}
ReadFloat(node.GetChild("roughness"), materialDef.mRoughness);
bool mipmaps;
- if (ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
+ if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps)
{
- for (auto& ts : materialDef.mTextureStages)
+ for(auto& ts : materialDef.mTextureStages)
{
ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR;
}
virtual bool Map(Index iDli, Index iScene) override
{
- Entry idx{ iDli, iScene };
- auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
- if (iInsert == mIndices.end() || iInsert->iDli != iDli)
+ Entry idx{iDli, iScene};
+ auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx);
+ if(iInsert == mIndices.end() || iInsert->iDli != iDli)
{
mIndices.insert(iInsert, idx);
}
- else if (iInsert->iScene != iScene)
+ else if(iInsert->iScene != iScene)
{
return false;
}
virtual unsigned int Resolve(Index iDli) override
{
- auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli,
- [](const Entry& idx, Index iDli) {
- return idx.iDli < iDli;
- });
+ auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) {
+ return idx.iDli < iDli;
+ });
DALI_ASSERT_ALWAYS(iFind != mIndices.end());
return iFind->iScene;
}
ParseNodesInternal(nodes, index, parents, params, mapper);
auto& scene = params.output.mScene;
- for (size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
+ for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0)
{
- for (auto& c : scene.GetNode(i0)->mConstraints)
+ for(auto& c : scene.GetNode(i0)->mConstraints)
{
c.mSourceIdx = mapper.Resolve(c.mSourceIdx);
}
}
}
-void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index,
- std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
+void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector<Index>& inOutParentStack, LoadParams& params, IIndexMapper& mapper)
{
// Properties that may be resolved from a JSON value with ReadInt() -- or default to 0.
- struct IndexProperty { ResourceType::Value type; const TreeNode* source; Index& target; };
+ struct IndexProperty
+ {
+ ResourceType::Value type;
+ const TreeNode* source;
+ Index& target;
+ };
std::vector<IndexProperty> resourceIds;
resourceIds.reserve(4);
- if (auto node = GetNthChild(nodes, index))
+ if(auto node = GetNthChild(nodes, index))
{
NodeDefinition nodeDef;
nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back();
// not successful then reads it as a vector2.
ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) ||
ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) ||
- ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
- ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
+ ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) ||
+ ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2);
// visibility
ReadBool(node->GetChild("visible"), nodeDef.mIsVisible);
// type classification
- if (auto eCustomization = node->GetChild("customization")) // customization
+ if(auto eCustomization = node->GetChild("customization")) // customization
{
std::string tag;
- if (ReadString(eCustomization->GetChild("tag"), tag))
+ if(ReadString(eCustomization->GetChild("tag"), tag))
{
- nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{ tag });
+ nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag});
}
}
else // something renderable maybe
{
std::unique_ptr<NodeDefinition::Renderable> renderable;
- ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type.
+ ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type.
- const TreeNode* eRenderable = nullptr;
- if ((eRenderable = node->GetChild("model")))
+ const TreeNode* eRenderable = nullptr;
+ if((eRenderable = node->GetChild("model")))
{
// check for mesh before allocating - this can't be missing.
auto eMesh = eRenderable->GetChild("mesh");
- if (!eMesh)
+ if(!eMesh)
{
ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
}
modelNode = new ModelNode();
renderable.reset(modelNode);
- resourceIds.push_back({ ResourceType::Mesh, eMesh, modelNode->mMeshIdx });
+ resourceIds.push_back({ResourceType::Mesh, eMesh, modelNode->mMeshIdx});
}
- else if ((eRenderable = node->GetChild("arc")))
+ else if((eRenderable = node->GetChild("arc")))
{
// check for mesh before allocating - this can't be missing.
auto eMesh = eRenderable->GetChild("mesh");
- if (!eMesh)
+ if(!eMesh)
{
ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition.";
}
renderable.reset(arcNode);
modelNode = arcNode;
- resourceIds.push_back({ ResourceType::Mesh, eMesh, arcNode->mMeshIdx });
+ resourceIds.push_back({ResourceType::Mesh, eMesh, arcNode->mMeshIdx});
ReadArcField(eRenderable, *arcNode);
}
- if (renderable) // process common properties of all renderables + register payload
+ if(renderable) // process common properties of all renderables + register payload
{
// shader
renderable->mShaderIdx = 0;
- auto eShader = eRenderable->GetChild("shader");
- resourceIds.push_back({ ResourceType::Shader, eShader, renderable->mShaderIdx });
+ auto eShader = eRenderable->GetChild("shader");
+ resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx});
// color
- if (modelNode)
+ if(modelNode)
{
- modelNode->mMaterialIdx = 0; // must offer default of 0
- auto eMaterial = eRenderable->GetChild("material");
- resourceIds.push_back({ ResourceType::Material, eMaterial, modelNode->mMaterialIdx });
+ modelNode->mMaterialIdx = 0; // must offer default of 0
+ auto eMaterial = eRenderable->GetChild("material");
+ resourceIds.push_back({ResourceType::Material, eMaterial, modelNode->mMaterialIdx});
- if (!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode))
+ if(!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode))
{
ReadColorCodeOrColor(node, modelNode->mColor, params.input.mConvertColorCode);
}
// Resolve ints - default to 0 if undefined
auto& output = params.output;
- for (auto& idRes : resourceIds)
+ for(auto& idRes : resourceIds)
{
Index iCheck = 0;
- switch (idRes.type)
+ switch(idRes.type)
{
- case ResourceType::Shader:
- iCheck = output.mResources.mShaders.size();
- break;
+ case ResourceType::Shader:
+ iCheck = output.mResources.mShaders.size();
+ break;
- case ResourceType::Mesh:
- iCheck = output.mResources.mMeshes.size();
- break;
+ case ResourceType::Mesh:
+ iCheck = output.mResources.mMeshes.size();
+ break;
- case ResourceType::Material:
- iCheck = output.mResources.mMaterials.size();
- break;
+ case ResourceType::Material:
+ iCheck = output.mResources.mMaterials.size();
+ break;
- default:
- ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " <<
- idRes.type << " (Programmer error)";
+ default:
+ ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)";
}
- if (!idRes.source)
+ if(!idRes.source)
{
idRes.target = 0;
}
- else if (idRes.source->GetType() != TreeNode::INTEGER)
+ else if(idRes.source->GetType() != TreeNode::INTEGER)
{
- ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " <<
- GetResourceTypeName(idRes.type) << " index type.";
+ ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type.";
}
else
{
idRes.target = idRes.source->GetInteger();
}
- if (idRes.target >= iCheck)
+ if(idRes.target >= iCheck)
{
- ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " <<
- GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" <<
- iCheck << ").";
+ ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ").";
}
}
resourceIds.clear();
// Extra properties
- if (auto eExtras = node->GetChild("extras"))
+ if(auto eExtras = node->GetChild("extras"))
{
auto& extras = nodeDef.mExtras;
extras.reserve(eExtras->Size());
NodeDefinition::Extra e;
- for (auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0)
{
auto eExtra = *i0;
- e.mKey = eExtra.first;
- if (e.mKey.empty())
+ e.mKey = eExtra.first;
+ if(e.mKey.empty())
{
mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.",
- index, extras.size()));
+ index,
+ extras.size()));
continue;
}
e.mValue = ReadPropertyValue(eExtra.second);
- if (e.mValue.GetType() == Property::Type::NONE)
+ if(e.mValue.GetType() == Property::Type::NONE)
{
mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.",
- index, e.mKey.c_str(), eExtra.second.GetString()));
+ index,
+ e.mKey.c_str(),
+ eExtra.second.GetString()));
}
else
{
auto iInsert = std::lower_bound(extras.begin(), extras.end(), e);
- if (iInsert != extras.end() && iInsert->mKey == e.mKey)
+ if(iInsert != extras.end() && iInsert->mKey == e.mKey)
{
mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.",
- index, e.mKey.c_str(), eExtra.second.GetString()));
+ index,
+ e.mKey.c_str(),
+ eExtra.second.GetString()));
*iInsert = std::move(e);
}
else
}
// Constraints
- if (auto eConstraints = node->GetChild("constraints"))
+ if(auto eConstraints = node->GetChild("constraints"))
{
auto& constraints = nodeDef.mConstraints;
constraints.reserve(eConstraints->Size());
ConstraintDefinition cDef;
- for (auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0)
{
auto eConstraint = *i0;
- if (!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
+ if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx))
{
mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.",
- index, eConstraint.second.GetString(), constraints.size()));
+ index,
+ eConstraint.second.GetString(),
+ constraints.size()));
}
else
{
cDef.mProperty = eConstraint.first;
auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef);
- if (iInsert != constraints.end() && *iInsert == cDef)
+ if(iInsert != constraints.end() && *iInsert == cDef)
{
mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.",
- index, cDef.mProperty.c_str(), cDef.mSourceIdx));
+ index,
+ cDef.mProperty.c_str(),
+ cDef.mSourceIdx));
}
else
{
// Determine index for mapping
const unsigned int myIndex = output.mScene.GetNodeCount();
- if (!mapper.Map(index, myIndex))
+ if(!mapper.Map(index, myIndex))
{
mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree."));
return;
}
// if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix.
- Matrix invBindMatrix{ false };
- if (ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
+ Matrix invBindMatrix{false};
+ if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking?
{
mInverseBindMatrices[myIndex] = invBindMatrix;
}
// Register nodeDef
auto rawDef = output.mScene.AddNode(std::make_unique<NodeDefinition>(std::move(nodeDef)));
- if (rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
+ if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope.
{
// ...And only then parse children.
- if (auto children = node->GetChild("children"))
+ if(auto children = node->GetChild("children"))
{
inOutParentStack.push_back(myIndex);
rawDef->mChildren.reserve(children->Size());
uint32_t iChild = 0;
- for (auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
+ for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild)
{
auto& child = (*j0).second;
- if (child.GetType() == TreeNode::INTEGER)
+ if(child.GetType() == TreeNode::INTEGER)
{
ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition.
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild <<
- ": invalid index type.";
+ ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type.";
}
}
inOutParentStack.pop_back();
}
- else if (rawDef->mCustomization)
+ else if(rawDef->mCustomization)
{
mOnError(FormatString("node %d: not an actual customization without children.", index));
}
- if (auto proc = params.input.mNodePropertyProcessor) // optional processing
+ if(auto proc = params.input.mNodePropertyProcessor) // optional processing
{
// WARNING: constraint IDs are not resolved at this point.
Property::Map nodeData;
auto& definitions = params.output.mAnimationDefinitions;
definitions.reserve(definitions.size() + tnAnimations->Size());
- for (TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
- iAnim != iAnimEnd; ++iAnim)
+ for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd();
+ iAnim != iAnimEnd;
+ ++iAnim)
{
- const TreeNode& tnAnim = (*iAnim).second;
+ const TreeNode& tnAnim = (*iAnim).second;
AnimationDefinition animDef;
ReadString(tnAnim.GetChild(NAME), animDef.mName);
- auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef,
- [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) {
+ auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) {
return ad0.mName < ad1.mName;
});
const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName;
- if (overwrite)
+ if(overwrite)
{
mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str()));
}
// than our frame delay) to not be restrictive WRT replaying. If anything needs
// to occur more frequently, then Animations are likely not your solution anyway.
animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS;
- if (!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
+ if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration))
{
mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.",
- animDef.mName.c_str(), "duration", animDef.mDuration));
+ animDef.mName.c_str(),
+ "duration",
+ animDef.mDuration));
}
// Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely.
animDef.mLoopCount = 1;
- if (ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
- animDef.mLoopCount < 0)
+ if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) &&
+ animDef.mLoopCount < 0)
{
animDef.mLoopCount = 0;
}
std::string endAction;
- if (ReadString(tnAnim.GetChild("endAction"), endAction))
+ if(ReadString(tnAnim.GetChild("endAction"), endAction))
{
- if ("BAKE" == endAction)
+ if("BAKE" == endAction)
{
animDef.mEndAction = Animation::BAKE;
}
- else if ("DISCARD" == endAction)
+ else if("DISCARD" == endAction)
{
animDef.mEndAction = Animation::DISCARD;
}
- else if ("BAKE_FINAL" == endAction)
+ else if("BAKE_FINAL" == endAction)
{
animDef.mEndAction = Animation::BAKE_FINAL;
}
}
- if (ReadString(tnAnim.GetChild("disconnectAction"), endAction))
+ if(ReadString(tnAnim.GetChild("disconnectAction"), endAction))
{
- if ("BAKE" == endAction)
+ if("BAKE" == endAction)
{
animDef.mDisconnectAction = Animation::BAKE;
}
- else if ("DISCARD" == endAction)
+ else if("DISCARD" == endAction)
{
animDef.mDisconnectAction = Animation::DISCARD;
}
- else if ("BAKE_FINAL" == endAction)
+ else if("BAKE_FINAL" == endAction)
{
animDef.mDisconnectAction = Animation::BAKE_FINAL;
}
}
- if (const TreeNode* tnProperties = tnAnim.GetChild("properties"))
+ if(const TreeNode* tnProperties = tnAnim.GetChild("properties"))
{
animDef.mProperties.reserve(tnProperties->Size());
- for (TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
- iProperty != iPropertyEnd; ++iProperty)
+ for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd();
+ iProperty != iPropertyEnd;
+ ++iProperty)
{
- const TreeNode &tnProperty = (*iProperty).second;
+ const TreeNode& tnProperty = (*iProperty).second;
AnimatedProperty animProp;
- if (!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
+ if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName))
{
mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str()));
continue;
}
- if (!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
+ if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName))
{
mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str()));
continue;
}
// these are the defaults
- animProp.mTimePeriod.delaySeconds = 0.f;
+ animProp.mTimePeriod.delaySeconds = 0.f;
animProp.mTimePeriod.durationSeconds = animDef.mDuration;
- if (!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
+ if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod))
{
mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.",
- animDef.mName.c_str(), animDef.mProperties.size(), animProp.mTimePeriod.durationSeconds));
+ animDef.mName.c_str(),
+ animDef.mProperties.size(),
+ animProp.mTimePeriod.durationSeconds));
}
std::string alphaFunctionValue;
- if (ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
+ if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue))
{
animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue);
}
- if (const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
+ if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin"))
{
DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
std::ifstream binAniFile;
- std::string animationFilename;
- if (ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
+ std::string animationFilename;
+ if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename))
{
std::string animationFullPath = params.input.mAnimationsPath + animationFilename;
binAniFile.open(animationFullPath, std::ios::binary);
- if (binAniFile.fail())
+ if(binAniFile.fail())
{
- ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" <<
- animationFullPath << "'";
+ ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'";
}
}
//so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation,
// otherwise are blend shape weight keys.
// TODO support for binary header with size information
- Property::Type propType = Property::FLOAT; // assume blend shape weights
- if (animProp.mPropertyName == "orientation")
+ Property::Type propType = Property::FLOAT; // assume blend shape weights
+ if(animProp.mPropertyName == "orientation")
{
propType = Property::VECTOR4;
}
- else if ((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
+ else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale"))
{
propType = Property::VECTOR3;
}
// NOTE: right now we're just using AlphaFunction::LINEAR.
unsigned char dummyAlphaFunction;
- float progress;
+ float progress;
Property::Value propValue;
- for (int key = 0; key < numKeys; key++)
+ for(int key = 0; key < numKeys; key++)
{
binAniFile.read(reinterpret_cast<char*>(&progress), sizeof(float));
- if (propType == Property::VECTOR3)
+ if(propType == Property::VECTOR3)
{
Vector3 value;
binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 3);
propValue = Property::Value(value);
}
- else if (propType == Property::VECTOR4)
+ else if(propType == Property::VECTOR4)
{
Vector4 value;
binAniFile.read(reinterpret_cast<char*>(value.AsFloat()), sizeof(float) * 4);
animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR);
}
}
- else if (const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
+ else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames"))
{
DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name");
animProp.mKeyFrames = KeyFrames::New();
float progress = 0.0f;
- for (auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
+ for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0)
{
const TreeNode::KeyNodePair& kfKeyChild = *i0;
- bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
+ bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress);
DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'");
const TreeNode* tnValue = kfKeyChild.second.GetChild("value");
// For the "orientation" property, convert from Vector4 -> Rotation value
// This work-around is preferable to a null-pointer exception in the DALi update thread
Property::Value propValue(ReadPropertyValue(*tnValue));
- if (propValue.GetType() == Property::VECTOR4 &&
- animProp.mPropertyName == "orientation")
+ if(propValue.GetType() == Property::VECTOR4 &&
+ animProp.mPropertyName == "orientation")
{
Vector4 v;
propValue.Get(v);
}
AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
- std::string alphaFuncStr;
- if (ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
+ std::string alphaFuncStr;
+ if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr))
{
kfAlphaFunction = GetAlphaFunction(alphaFuncStr);
}
else
{
const TreeNode* tnValue = tnProperty.GetChild("value");
- if (tnValue)
+ if(tnValue)
{
- animProp.mValue.reset(new AnimatedProperty::Value{ ReadPropertyValue(*tnValue) });
+ animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)});
}
else
{
mOnError(FormatString("Property '%s' fails to define target value.",
- animProp.mPropertyName.c_str()));
+ animProp.mPropertyName.c_str()));
}
ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative);
}
}
- if (overwrite)
+ if(overwrite)
{
*iFind = std::move(animDef);
}
iFind = definitions.insert(iFind, std::move(animDef));
}
- if (auto proc = params.input.mAnimationPropertyProcessor) // optional processing
+ if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing
{
Property::Map map;
ParseProperties(tnAnim, map);
auto& animGroups = params.output.mAnimationGroupDefinitions;
int numGroups = 0;
- for (auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
- iGroups != iGroupsEnd; ++iGroups, ++numGroups)
+ for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd();
+ iGroups != iGroupsEnd;
+ ++iGroups, ++numGroups)
{
const auto& tnGroup = *iGroups;
- auto tnName = tnGroup.second.GetChild(NAME);
+ auto tnName = tnGroup.second.GetChild(NAME);
std::string groupName;
- if (!tnName || !ReadString(tnName, groupName))
+ if(!tnName || !ReadString(tnName, groupName))
{
mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups));
continue;
}
- auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName,
- [](const AnimationGroupDefinition& group, const std::string& name) {
+ auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) {
return group.mName < name;
});
- if (iFind != animGroups.end() && iFind->mName == groupName)
+ if(iFind != animGroups.end() && iFind->mName == groupName)
{
mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str()));
}
iFind->mName = groupName;
auto tnAnims = tnGroup.second.GetChild("animations");
- if (tnAnims && tnAnims->Size() > 0)
+ if(tnAnims && tnAnims->Size() > 0)
{
auto& anims = iFind->mAnimations;
anims.reserve(anims.size() + tnAnims->Size());
- for (auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
+ for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims)
{
anims.push_back((*iAnims).second.GetString());
}
void DliLoader::Impl::GetCameraParameters(std::vector<CameraParameters>& cameras) const
{
- if (const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
+ if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras"))
{
cameras.resize(jsonCameras->Size());
auto iCamera = cameras.begin();
- for (auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0)
{
auto& jsonCamera = (*i0).second;
ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov);
ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear);
ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar);
- if (ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u))
+ if(ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u))
{
iCamera->isPerspective = false;
}
- if (auto jsonMatrix = jsonCamera.GetChild("matrix"))
+ if(auto jsonMatrix = jsonCamera.GetChild("matrix"))
{
ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u);
}
void DliLoader::Impl::GetLightParameters(std::vector<LightParameters>& lights) const
{
- if (const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
+ if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights"))
{
lights.resize(jsonLights->Size());
auto iLight = lights.begin();
- for (auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
+ for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0)
{
auto& jsonLight = (*i0).second;
- if (!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
+ if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16))
{
mOnError(
FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n",
- std::distance(jsonLights->CBegin(), i0)));
+ std::distance(jsonLights->CBegin(), i0)));
continue;
}
int shadowMapSize = 0;
- if (ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
+ if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0)
{
mOnError(
FormatString("Failed to parse light %d - %s has an invalid value.",
- std::distance(jsonLights->CBegin(), i0), SHADOW_MAP_SIZE));
+ std::distance(jsonLights->CBegin(), i0),
+ SHADOW_MAP_SIZE));
continue;
}
iLight->shadowMapSize = shadowMapSize;
float orthoSize = 0.f;
- if (ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
- (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
+ if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) &&
+ (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize)))
{
mOnError(
FormatString("Failed to parse light %d - %s has an invalid value.",
- std::distance(jsonLights->CBegin(), i0), ORTHOGRAPHIC_SIZE));
+ std::distance(jsonLights->CBegin(), i0),
+ ORTHOGRAPHIC_SIZE));
continue;
}
iLight->orthographicSize = orthoSize;
- if ((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
+ if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f))
{
mOnError(FormatString(
"Light %d: Both shadow map size and orthographic size must be set for shadows to work.",
- std::distance(jsonLights->CBegin(), i0)));
+ std::distance(jsonLights->CBegin(), i0)));
}
- if (!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
+ if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional
{
- iLight->color = Vector3::ONE; // default to white
+ iLight->color = Vector3::ONE; // default to white
}
- if (!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
+ if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional
{
- iLight->intensity = 1.0f; // default to 1.0
+ iLight->intensity = 1.0f; // default to 1.0
}
- if (!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
+ if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional
{
- iLight->shadowIntensity = 1.0f; // default to 1.0
+ iLight->shadowIntensity = 1.0f; // default to 1.0
}
++iLight;
}
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
EnvironmentDefinition::RawData
- EnvironmentDefinition::LoadRaw(const std::string& environmentsPath) const
+EnvironmentDefinition::LoadRaw(const std::string& environmentsPath) const
{
RawData raw;
- auto loadFn = [&environmentsPath](const std::string& path, CubeData& cd) {
- if (path.empty())
+ auto loadFn = [&environmentsPath](const std::string& path, CubeData& cd) {
+ if(path.empty())
{
cd.data.resize(6);
- for (auto& face : cd.data)
+ for(auto& face : cd.data)
{
- face.push_back(PixelData::New(new uint8_t[3]{ 0xff, 0xff, 0xff }, 3, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY));
+ face.push_back(PixelData::New(new uint8_t[3]{0xff, 0xff, 0xff}, 3, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY));
}
}
else if(!LoadCubeMapData(environmentsPath + path, cd))
{
- ExceptionFlinger(ASSERT_LOCATION) << "Failed to load cubemap texture from '" <<
- path << "'.";
+ ExceptionFlinger(ASSERT_LOCATION) << "Failed to load cubemap texture from '" << path << "'.";
}
};
Textures textures;
// This texture should have 6 faces and only one mipmap
- if (!raw.mDiffuse.data.empty())
+ if(!raw.mDiffuse.data.empty())
{
textures.mDiffuse = raw.mDiffuse.CreateTexture();
}
// This texture should have 6 faces and 6 mipmaps
- if (!raw.mSpecular.data.empty())
+ if(!raw.mSpecular.data.empty())
{
textures.mSpecular = raw.mSpecular.CreateTexture();
}
return textures;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*
*/
+#include "dali-scene-loader/public-api/gltf2-loader.h"
+#include <fstream>
+#include "dali-scene-loader/internal/gltf2-asset.h"
#include "dali-scene-loader/public-api/load-result.h"
-#include "dali-scene-loader/public-api/scene-definition.h"
#include "dali-scene-loader/public-api/resource-bundle.h"
-#include "dali-scene-loader/public-api/gltf2-loader.h"
-#include "dali-scene-loader/public-api/utils.h"
+#include "dali-scene-loader/public-api/scene-definition.h"
#include "dali-scene-loader/public-api/shader-definition-factory.h"
-#include "dali-scene-loader/internal/gltf2-asset.h"
+#include "dali-scene-loader/public-api/utils.h"
#include "dali/public-api/math/quaternion.h"
-#include <fstream>
-#define ENUM_STRING_MAPPING(t, x) { #x, t::x }
+#define ENUM_STRING_MAPPING(t, x) \
+ { \
+#x, t::x \
+ }
namespace gt = gltf2;
namespace js = json;
Geometry::LINE_STRIP,
Geometry::TRIANGLES,
Geometry::TRIANGLE_STRIP,
- Geometry::TRIANGLE_FAN
-}; //...because Dali swaps the last two.
+ Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
struct AttributeMapping
{
- gt::Attribute::Type mType;
- MeshDefinition::Accessor MeshDefinition::* mAccessor;
- uint16_t mElementSizeRequired;
+ gt::Attribute::Type mType;
+ MeshDefinition::Accessor MeshDefinition::*mAccessor;
+ uint16_t mElementSizeRequired;
} ATTRIBUTE_MAPPINGS[]{
- { gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3) },
- { gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3) },
- { gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2) },
- { gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4) },
- { gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4) },
+ {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
+ {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
+ {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
+ {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
+ {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
};
std::vector<gt::Animation> ReadAnimationArray(const json_value_s& j)
auto results = js::Read::Array<gt::Animation, js::ObjectReader<gt::Animation>::Read>(j);
- for (auto& animation : results)
+ for(auto& animation : results)
{
- for (auto& channel : animation.mChannels)
+ for(auto& channel : animation.mChannels)
{
channel.mSampler.UpdateVector(animation.mSamplers);
}
}
const auto BUFFER_READER = std::move(js::Reader<gt::Buffer>()
- .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::Buffer::mByteLength))
- .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri))
-);
+ .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::Buffer::mByteLength))
+ .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri)));
const auto BUFFER_VIEW_READER = std::move(js::Reader<gt::BufferView>()
- .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, >::Document::mBuffers>, >::BufferView::mBuffer))
- .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferView::mByteOffset))
- .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::BufferView::mByteLength))
- .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, >::BufferView::mByteStride))
- .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, >::BufferView::mTarget))
-);
+ .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, >::Document::mBuffers>, >::BufferView::mBuffer))
+ .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferView::mByteOffset))
+ .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, >::BufferView::mByteLength))
+ .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, >::BufferView::mByteStride))
+ .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, >::BufferView::mTarget)));
const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::BufferViewClient>()
- .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::BufferViewClient::mBufferView))
- .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferViewClient::mByteOffset))
-);
+ .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::BufferViewClient::mBufferView))
+ .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, >::BufferViewClient::mByteOffset)));
const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::ComponentTypedBufferViewClient>()
- .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::ComponentTypedBufferViewClient::mBufferView))
- .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, >::ComponentTypedBufferViewClient::mByteOffset))
- .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, >::ComponentTypedBufferViewClient::mComponentType))
-);
+ .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::ComponentTypedBufferViewClient::mBufferView))
+ .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, >::ComponentTypedBufferViewClient::mByteOffset))
+ .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, >::ComponentTypedBufferViewClient::mComponentType)));
const auto ACCESSOR_SPARSE_READER = std::move(js::Reader<gt::Accessor::Sparse>()
- .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::Sparse::mCount))
- .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read,
- >::Accessor::Sparse::mIndices))
- .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read,
- >::Accessor::Sparse::mValues))
-);
+ .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::Sparse::mCount))
+ .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read, >::Accessor::Sparse::mIndices))
+ .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read, >::Accessor::Sparse::mValues)));
const auto ACCESSOR_READER = std::move(js::Reader<gt::Accessor>()
- .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
- gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Accessor::mBufferView))
- .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
- js::Read::Number<uint32_t>, >::Accessor::mByteOffset))
- .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
- js::Read::Enum<gt::Component::Type>, >::Accessor::mComponentType))
- .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, >::Accessor::mName))
- .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::mCount))
- .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized))
- .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, >::Accessor::mType))
- .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, >::Accessor::mMin))
- .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, >::Accessor::mMax))
- .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read,
- >::Accessor::SetSparse))
-);
+ .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
+ gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>,
+ >::Accessor::mBufferView))
+ .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
+ js::Read::Number<uint32_t>,
+ >::Accessor::mByteOffset))
+ .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
+ js::Read::Enum<gt::Component::Type>,
+ >::Accessor::mComponentType))
+ .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, >::Accessor::mName))
+ .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, >::Accessor::mCount))
+ .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized))
+ .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, >::Accessor::mType))
+ .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, >::Accessor::mMin))
+ .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, >::Accessor::mMax))
+ .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read, >::Accessor::SetSparse)));
const auto IMAGE_READER = std::move(js::Reader<gt::Image>()
- .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, >::Material::mName))
- .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri))
- .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType))
- .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Image::mBufferView))
-);
+ .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, >::Material::mName))
+ .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri))
+ .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType))
+ .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, >::Document::mBufferViews>, >::Image::mBufferView)));
const auto SAMPLER_READER = std::move(js::Reader<gt::Sampler>()
- .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMinFilter))
- .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMagFilter))
- .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapS))
- .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapT))
-);
+ .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMinFilter))
+ .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, >::Sampler::mMagFilter))
+ .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapS))
+ .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, >::Sampler::mWrapT)));
const auto TEXURE_READER = std::move(js::Reader<gt::Texture>()
- .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, >::Document::mImages>, >::Texture::mSource))
- .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, >::Document::mSamplers>, >::Texture::mSampler))
-);
+ .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, >::Document::mImages>, >::Texture::mSource))
+ .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, >::Document::mSamplers>, >::Texture::mSampler)));
const auto TEXURE_INFO_READER = std::move(js::Reader<gt::TextureInfo>()
- .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, >::Document::mTextures>, >::TextureInfo::mTexture))
- .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, >::TextureInfo::mTexCoord))
- .Register(*js::MakeProperty("scale", js::Read::Number<float>, >::TextureInfo::mScale))
-);
+ .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, >::Document::mTextures>, >::TextureInfo::mTexture))
+ .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, >::TextureInfo::mTexCoord))
+ .Register(*js::MakeProperty("scale", js::Read::Number<float>, >::TextureInfo::mScale)));
const auto MATERIAL_PBR_READER = std::move(js::Reader<gt::Material::Pbr>()
- .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, >::Material::Pbr::mBaseColorFactor))
- .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read,
- >::Material::Pbr::mBaseColorTexture))
- .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, >::Material::Pbr::mMetallicFactor))
- .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, >::Material::Pbr::mRoughnessFactor))
- .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read,
- >::Material::Pbr::mMetallicRoughnessTexture))
-);
+ .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, >::Material::Pbr::mBaseColorFactor))
+ .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mBaseColorTexture))
+ .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, >::Material::Pbr::mMetallicFactor))
+ .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, >::Material::Pbr::mRoughnessFactor))
+ .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::Pbr::mMetallicRoughnessTexture)));
const auto MATERIAL_READER = std::move(js::Reader<gt::Material>()
- .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, >::Material::mName))
- .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, >::Material::mPbrMetallicRoughness))
- .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mNormalTexture))
- .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mOcclusionTexture))
- .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mEmissiveTexture))
- .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, >::Material::mEmissiveFactor))
- .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, >::Material::mAlphaMode))
- .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, >::Material::mAlphaCutoff))
-);
+ .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, >::Material::mName))
+ .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, >::Material::mPbrMetallicRoughness))
+ .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mNormalTexture))
+ .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mOcclusionTexture))
+ .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, >::Material::mEmissiveTexture))
+ .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, >::Material::mEmissiveFactor))
+ .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, >::Material::mAlphaMode))
+ .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, >::Material::mAlphaCutoff)));
std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
{
- auto& jo = js::Cast<json_object_s>(j);
+ auto& jo = js::Cast<json_object_s>(j);
std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> result;
auto i = jo.start;
- while (i)
+ while(i)
{
- auto jstr = *i->name;
+ auto jstr = *i->name;
result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>(*i->value);
- i = i->next;
+ i = i->next;
}
return result;
}
std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
{
- auto& jo = js::Cast<json_array_s>(j);
+ auto& jo = js::Cast<json_array_s>(j);
std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> result;
result.reserve(jo.length);
auto i = jo.start;
- while (i)
+ while(i)
{
result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value)));
i = i->next;
}
const auto MESH_PRIMITIVE_READER = std::move(js::Reader<gt::Mesh::Primitive>()
- .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes))
- .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Mesh::Primitive::mIndices))
- .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, >::Document::mMaterials>, >::Mesh::Primitive::mMaterial))
- .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, >::Mesh::Primitive::mMode))
- .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets))
-);
+ .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes))
+ .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Mesh::Primitive::mIndices))
+ .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, >::Document::mMaterials>, >::Mesh::Primitive::mMaterial))
+ .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, >::Mesh::Primitive::mMode))
+ .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets)));
const auto MESH_READER = std::move(js::Reader<gt::Mesh>()
- .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, >::Mesh::mName))
- .Register(*js::MakeProperty("primitives",
- js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>, >::Mesh::mPrimitives))
- .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, >::Mesh::mWeights))
-);
+ .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, >::Mesh::mName))
+ .Register(*js::MakeProperty("primitives",
+ js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>,
+ >::Mesh::mPrimitives))
+ .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, >::Mesh::mWeights)));
const auto SKIN_READER = std::move(js::Reader<gt::Skin>()
- .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, >::Skin::mName))
- .Register(*js::MakeProperty("inverseBindMatrices",
- gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Skin::mInverseBindMatrices))
- .Register(*js::MakeProperty("skeleton",
- gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>, >::Skin::mSkeleton))
- .Register(*js::MakeProperty("joints",
- js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Skin::mJoints))
-);
+ .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, >::Skin::mName))
+ .Register(*js::MakeProperty("inverseBindMatrices",
+ gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
+ >::Skin::mInverseBindMatrices))
+ .Register(*js::MakeProperty("skeleton",
+ gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>,
+ >::Skin::mSkeleton))
+ .Register(*js::MakeProperty("joints",
+ js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
+ >::Skin::mJoints)));
const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader<gt::Camera::Perspective>()
- .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, >::Camera::Perspective::mAspectRatio))
- .Register(*js::MakeProperty("yfov", js::Read::Number<float>, >::Camera::Perspective::mYFov))
- .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Perspective::mZFar))
- .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Perspective::mZNear))
-); // TODO: infinite perspective projection, where znear is omitted
+ .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, >::Camera::Perspective::mAspectRatio))
+ .Register(*js::MakeProperty("yfov", js::Read::Number<float>, >::Camera::Perspective::mYFov))
+ .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Perspective::mZFar))
+ .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader<gt::Camera::Orthographic>()
- .Register(*js::MakeProperty("xmag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
- .Register(*js::MakeProperty("ymag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
- .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Orthographic::mZFar))
- .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Orthographic::mZNear))
-);
+ .Register(*js::MakeProperty("xmag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
+ .Register(*js::MakeProperty("ymag", js::Read::Number<float>, >::Camera::Orthographic::mXMag))
+ .Register(*js::MakeProperty("zfar", js::Read::Number<float>, >::Camera::Orthographic::mZFar))
+ .Register(*js::MakeProperty("znear", js::Read::Number<float>, >::Camera::Orthographic::mZNear)));
const auto CAMERA_READER = std::move(js::Reader<gt::Camera>()
- .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, >::Camera::mName))
- .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType))
- .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, >::Camera::mPerspective))
- .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, >::Camera::mOrthographic))
-);
+ .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, >::Camera::mName))
+ .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType))
+ .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, >::Camera::mPerspective))
+ .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, >::Camera::mOrthographic)));
const auto NODE_READER = std::move(js::Reader<gt::Node>()
- .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, >::Node::mName))
- .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, >::Node::mTranslation))
- .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation))
- .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, >::Node::mScale))
- .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, >::Node::SetMatrix))
- .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, >::Document::mCameras>,
- >::Node::mCamera))
- .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
- >::Node::mChildren))
- .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, >::Document::mMeshes>, >::Node::mMesh))
- .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, >::Document::mSkins>, >::Node::mSkin))
-);
+ .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, >::Node::mName))
+ .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, >::Node::mTranslation))
+ .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation))
+ .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, >::Node::mScale))
+ .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, >::Node::SetMatrix))
+ .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, >::Document::mCameras>, >::Node::mCamera))
+ .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Node::mChildren))
+ .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, >::Document::mMeshes>, >::Node::mMesh))
+ .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, >::Document::mSkins>, >::Node::mSkin)));
const auto ANIMATION_SAMPLER_READER = std::move(js::Reader<gt::Animation::Sampler>()
- .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
- >::Animation::Sampler::mInput))
- .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>,
- >::Animation::Sampler::mOutput))
- .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, >::Animation::Sampler::mInterpolation))
-);
+ .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mInput))
+ .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, >::Document::mAccessors>, >::Animation::Sampler::mOutput))
+ .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, >::Animation::Sampler::mInterpolation)));
const auto ANIMATION_TARGET_READER = std::move(js::Reader<gt::Animation::Channel::Target>()
- .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>,
- >::Animation::Channel::Target::mNode))
- .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>,
- >::Animation::Channel::Target::mPath))
-);
+ .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>, >::Animation::Channel::Target::mNode))
+ .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>, >::Animation::Channel::Target::mPath)));
const auto ANIMATION_CHANNEL_READER = std::move(js::Reader<gt::Animation::Channel>()
- .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, >::Animation::Channel::mTarget))
- .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, >::Animation::mSamplers>, >::Animation::Channel::mSampler))
-);
+ .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, >::Animation::Channel::mTarget))
+ .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, >::Animation::mSamplers>, >::Animation::Channel::mSampler)));
const auto ANIMATION_READER = std::move(js::Reader<gt::Animation>()
- .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, >::Animation::mName))
- .Register(*js::MakeProperty("samplers",
- js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>, >::Animation::mSamplers))
- .Register(*js::MakeProperty("channels",
- js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>, >::Animation::mChannels))
-);
+ .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, >::Animation::mName))
+ .Register(*js::MakeProperty("samplers",
+ js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>,
+ >::Animation::mSamplers))
+ .Register(*js::MakeProperty("channels",
+ js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>,
+ >::Animation::mChannels)));
const auto SCENE_READER = std::move(js::Reader<gt::Scene>()
- .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, >::Scene::mName))
- .Register(*js::MakeProperty("nodes",
- js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>, >::Scene::mNodes))
-);
+ .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, >::Scene::mName))
+ .Register(*js::MakeProperty("nodes",
+ js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, >::Document::mNodes>>,
+ >::Scene::mNodes)));
const auto DOCUMENT_READER = std::move(js::Reader<gt::Document>()
- .Register(*js::MakeProperty("buffers",
- js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>, >::Document::mBuffers))
- .Register(*js::MakeProperty("bufferViews",
- js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>, >::Document::mBufferViews))
- .Register(*js::MakeProperty("accessors",
- js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>, >::Document::mAccessors))
- .Register(*js::MakeProperty("images",
- js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>, >::Document::mImages))
- .Register(*js::MakeProperty("samplers",
- js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>, >::Document::mSamplers))
- .Register(*js::MakeProperty("textures",
- js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>, >::Document::mTextures))
- .Register(*js::MakeProperty("materials",
- js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>, >::Document::mMaterials))
- .Register(*js::MakeProperty("meshes",
- js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>, >::Document::mMeshes))
- .Register(*js::MakeProperty("skins",
- js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>, >::Document::mSkins))
- .Register(*js::MakeProperty("cameras",
- js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>, >::Document::mCameras))
- .Register(*js::MakeProperty("nodes",
- js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>, >::Document::mNodes))
- .Register(*js::MakeProperty("animations",
- ReadAnimationArray, >::Document::mAnimations))
- .Register(*js::MakeProperty("scenes",
- js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>, >::Document::mScenes))
- .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, >::Document::mScenes>, >::Document::mScene))
-);
+ .Register(*js::MakeProperty("buffers",
+ js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>,
+ >::Document::mBuffers))
+ .Register(*js::MakeProperty("bufferViews",
+ js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>,
+ >::Document::mBufferViews))
+ .Register(*js::MakeProperty("accessors",
+ js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>,
+ >::Document::mAccessors))
+ .Register(*js::MakeProperty("images",
+ js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>,
+ >::Document::mImages))
+ .Register(*js::MakeProperty("samplers",
+ js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>,
+ >::Document::mSamplers))
+ .Register(*js::MakeProperty("textures",
+ js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>,
+ >::Document::mTextures))
+ .Register(*js::MakeProperty("materials",
+ js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>,
+ >::Document::mMaterials))
+ .Register(*js::MakeProperty("meshes",
+ js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>,
+ >::Document::mMeshes))
+ .Register(*js::MakeProperty("skins",
+ js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>,
+ >::Document::mSkins))
+ .Register(*js::MakeProperty("cameras",
+ js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>,
+ >::Document::mCameras))
+ .Register(*js::MakeProperty("nodes",
+ js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>,
+ >::Document::mNodes))
+ .Register(*js::MakeProperty("animations",
+ ReadAnimationArray,
+ >::Document::mAnimations))
+ .Register(*js::MakeProperty("scenes",
+ js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>,
+ >::Document::mScenes))
+ .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, >::Document::mScenes>, >::Document::mScene)));
struct NodeMapping
{
class NodeIndexMapper
{
public:
- NodeIndexMapper() = default;
+ NodeIndexMapper() = default;
NodeIndexMapper(const NodeIndexMapper&) = delete;
NodeIndexMapper& operator=(const NodeIndexMapper&) = delete;
/// save growing a vector.
void RegisterMapping(Index gltfIdx, Index runtimeIdx)
{
- if (gltfIdx != runtimeIdx)
+ if(gltfIdx != runtimeIdx)
{
auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx);
DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx);
- mNodes.insert(iInsert, NodeMapping{ gltfIdx, runtimeIdx });
+ mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx});
}
}
///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx.
Index GetRuntimeId(Index gltfIdx) const
{
- auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
+ auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx;
}
struct ConversionContext
{
- LoadResult& mOutput;
+ LoadResult& mOutput;
std::string mPath;
- Index mDefaultMaterial;
+ Index mDefaultMaterial;
- std::vector<Index> mMeshIds;
- NodeIndexMapper mNodeIndices;
+ std::vector<Index> mMeshIds;
+ NodeIndexMapper mNodeIndices;
};
SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w)
{
- switch (w)
+ switch(w)
{
- case gt::Wrap::REPEAT:
- return SamplerFlags::WRAP_REPEAT;
- case gt::Wrap::CLAMP_TO_EDGE:
- return SamplerFlags::WRAP_CLAMP;
- case gt::Wrap::MIRRORED_REPEAT:
- return SamplerFlags::WRAP_MIRROR;
- default:
- throw std::runtime_error("Invalid wrap type.");
+ case gt::Wrap::REPEAT:
+ return SamplerFlags::WRAP_REPEAT;
+ case gt::Wrap::CLAMP_TO_EDGE:
+ return SamplerFlags::WRAP_CLAMP;
+ case gt::Wrap::MIRRORED_REPEAT:
+ return SamplerFlags::WRAP_MIRROR;
+ default:
+ throw std::runtime_error("Invalid wrap type.");
}
}
SamplerFlags::Type ConvertSampler(const gt::Ref<gt::Sampler>& s)
{
- if (s)
+ if(s)
{
- return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) :
- ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) |
- ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) |
- (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) |
- (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
+ return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) | ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
}
else
{
// "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
// properties, if not in some extension -, we will simply assume linear filtering.
return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
- (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
+ (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
}
}
TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm)
{
- return TextureDefinition{ std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler) };
+ return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler)};
}
void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials)& outMaterials)
MaterialDefinition matDef;
auto& pbr = m.mPbrMetallicRoughness;
- if (m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f)
+ if(m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f)
{
matDef.mFlags |= MaterialDefinition::TRANSPARENCY;
}
- if (m.mAlphaMode == gt::AlphaMode::MASK)
+ if(m.mAlphaMode == gt::AlphaMode::MASK)
{
matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, m.mAlphaCutoff)));
}
matDef.mColor = pbr.mBaseColorFactor;
matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!m.mNormalTexture);
- if (pbr.mBaseColorTexture)
+ if(pbr.mBaseColorTexture)
{
const auto semantic = MaterialDefinition::ALBEDO;
- matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(pbr.mBaseColorTexture) });
+ matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture)});
// TODO: and there had better be one
matDef.mFlags |= semantic;
}
- matDef.mMetallic = pbr.mMetallicFactor;
+ matDef.mMetallic = pbr.mMetallicFactor;
matDef.mRoughness = pbr.mRoughnessFactor;
- if (pbr.mMetallicRoughnessTexture)
+ if(pbr.mMetallicRoughnessTexture)
{
const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
- MaterialDefinition::GLTF_CHANNELS;
- matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture) });
+ MaterialDefinition::GLTF_CHANNELS;
+ matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture)});
// TODO: and there had better be one
matDef.mFlags |= semantic;
}
- if (m.mNormalTexture)
+ if(m.mNormalTexture)
{
const auto semantic = MaterialDefinition::NORMAL;
- matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(m.mNormalTexture) });
+ matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mNormalTexture)});
// TODO: and there had better be one
matDef.mFlags |= semantic;
}
auto& outMaterials = cctx.mOutput.mResources.mMaterials;
outMaterials.reserve(doc.mMaterials.size());
- for (auto& m : doc.mMaterials)
+ for(auto& m : doc.mMaterials)
{
ConvertMaterial(m, outMaterials);
}
MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc)
{
DALI_ASSERT_ALWAYS((acc.mBufferView &&
- (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
- (acc.mSparse && !acc.mBufferView));
+ (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
+ (acc.mSparse && !acc.mBufferView));
DALI_ASSERT_ALWAYS(!acc.mSparse ||
- ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
- (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
-
+ ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
+ (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
MeshDefinition::SparseBlob sparseBlob;
- if (acc.mSparse)
+ if(acc.mSparse)
{
- const gt::Accessor::Sparse& sparse = *acc.mSparse;
+ const gt::Accessor::Sparse& sparse = *acc.mSparse;
const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices;
- const gt::BufferViewClient& values = sparse.mValues;
+ const gt::BufferViewClient& values = sparse.mValues;
MeshDefinition::Blob indicesBlob(
indices.mBufferView->mByteOffset + indices.mByteOffset,
sparse.mCount * indices.GetBytesPerComponent(),
static_cast<uint16_t>(indices.mBufferView->mByteStride),
static_cast<uint16_t>(indices.GetBytesPerComponent()),
- {}, {}
- );
+ {},
+ {});
MeshDefinition::Blob valuesBlob(
values.mBufferView->mByteOffset + values.mByteOffset,
sparse.mCount * acc.GetElementSizeBytes(),
static_cast<uint16_t>(values.mBufferView->mByteStride),
static_cast<uint16_t>(acc.GetElementSizeBytes()),
- {}, {}
- );
+ {},
+ {});
sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount));
}
uint32_t bufferViewOffset = 0u;
uint32_t bufferViewStride = 0u;
- if (acc.mBufferView)
+ if(acc.mBufferView)
{
bufferViewOffset = acc.mBufferView->mByteOffset;
bufferViewStride = acc.mBufferView->mByteStride;
return MeshDefinition::Accessor{
std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset,
- acc.GetBytesLength(),
- static_cast<uint16_t>(bufferViewStride),
- static_cast<uint16_t>(acc.GetElementSizeBytes()),
- acc.mMin,
- acc.mMax}),
- std::move(sparseBlob) };
+ acc.GetBytesLength(),
+ static_cast<uint16_t>(bufferViewStride),
+ static_cast<uint16_t>(acc.GetElementSizeBytes()),
+ acc.mMin,
+ acc.mMax}),
+ std::move(sparseBlob)};
}
void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx)
{
uint32_t meshCount = 0;
cctx.mMeshIds.reserve(doc.mMeshes.size());
- for (auto& m : doc.mMeshes)
+ for(auto& m : doc.mMeshes)
{
cctx.mMeshIds.push_back(meshCount);
meshCount += m.mPrimitives.size();
auto& outMeshes = cctx.mOutput.mResources.mMeshes;
outMeshes.reserve(meshCount);
- for (auto& m : doc.mMeshes)
+ for(auto& m : doc.mMeshes)
{
- for (auto& p : m.mPrimitives)
+ for(auto& p : m.mPrimitives)
{
MeshDefinition meshDef;
- auto& attribs = p.mAttributes;
- meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri;
+ auto& attribs = p.mAttributes;
+ meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri;
meshDef.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[p.mMode];
auto& accPositions = *attribs.find(gt::Attribute::POSITION)->second;
meshDef.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3;
- for (auto& am : ATTRIBUTE_MAPPINGS)
+ for(auto& am : ATTRIBUTE_MAPPINGS)
{
auto iFind = attribs.find(am.mType);
- if (iFind != attribs.end())
+ if(iFind != attribs.end())
{
DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDef.mUri) == 0);
auto& accessor = meshDef.*(am.mAccessor);
- accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
+ accessor = ConvertMeshPrimitiveAccessor(*iFind->second);
// Fixing up -- a few of glTF2 sample models have VEC4 tangents; we need VEC3s.
- if (iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired))
+ if(iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired))
{
- accessor.mBlob.mStride = std::max(static_cast<uint16_t>(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired),
- accessor.mBlob.mElementSizeHint);
+ accessor.mBlob.mStride = std::max(static_cast<uint16_t>(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired),
+ accessor.mBlob.mElementSizeHint);
accessor.mBlob.mElementSizeHint = am.mElementSizeRequired;
}
- if (iFind->first == gt::Attribute::JOINTS_0)
+ if(iFind->first == gt::Attribute::JOINTS_0)
{
meshDef.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT);
}
}
- else if (needNormalsTangents)
+ else if(needNormalsTangents)
{
- switch (am.mType)
+ switch(am.mType)
{
- case gt::Attribute::NORMAL:
- meshDef.RequestNormals();
- break;
+ case gt::Attribute::NORMAL:
+ meshDef.RequestNormals();
+ break;
- case gt::Attribute::TANGENT:
- meshDef.RequestTangents();
- break;
+ case gt::Attribute::TANGENT:
+ meshDef.RequestTangents();
+ break;
- default:
- break;
+ default:
+ break;
}
}
}
- if (p.mIndices)
+ if(p.mIndices)
{
meshDef.mIndices = ConvertMeshPrimitiveAccessor(*p.mIndices);
meshDef.mFlags |= (p.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U32_INDICES) || p.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT);
}
- if (!p.mTargets.empty())
+ if(!p.mTargets.empty())
{
meshDef.mBlendShapes.reserve(p.mTargets.size());
meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
- for (const auto& target : p.mTargets)
+ for(const auto& target : p.mTargets)
{
MeshDefinition::BlendShape blendShape;
auto endIt = target.end();
- auto it = target.find(gt::Attribute::POSITION);
- if (it != endIt)
+ auto it = target.find(gt::Attribute::POSITION);
+ if(it != endIt)
{
blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
}
it = target.find(gt::Attribute::NORMAL);
- if (it != endIt)
+ if(it != endIt)
{
blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
}
it = target.find(gt::Attribute::TANGENT);
- if (it != endIt)
+ if(it != endIt)
{
blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
}
- if (!m.mWeights.empty())
+ if(!m.mWeights.empty())
{
blendShape.weight = m.mWeights[meshDef.mBlendShapes.size()];
}
}
}
- outMeshes.push_back({ std::move(meshDef), MeshGeometry{} });
+ outMeshes.push_back({std::move(meshDef), MeshGeometry{}});
}
}
}
{
auto modelNode = new ModelNode();
- modelNode->mShaderIdx = 0; // TODO: further thought
+ modelNode->mShaderIdx = 0; // TODO: further thought
auto materialIdx = prim.mMaterial.GetIndex();
- if (INVALID_INDEX == materialIdx)
+ if(INVALID_INDEX == materialIdx)
{
// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
- if (INVALID_INDEX == cctx.mDefaultMaterial)
+ if(INVALID_INDEX == cctx.mDefaultMaterial)
{
- auto& outMaterials = cctx.mOutput.mResources.mMaterials;
+ auto& outMaterials = cctx.mOutput.mResources.mMaterials;
cctx.mDefaultMaterial = outMaterials.size();
ConvertMaterial(gt::Material{}, outMaterials);
void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams)
{
camParams.isPerspective = camera.mType.compare("perspective") == 0;
- if (camParams.isPerspective)
+ if(camParams.isPerspective)
{
auto& perspective = camera.mPerspective;
- camParams.yFov = Degree(Radian(perspective.mYFov)).degree;
- camParams.zNear = perspective.mZNear;
- camParams.zFar = perspective.mZFar;
+ camParams.yFov = Degree(Radian(perspective.mYFov)).degree;
+ camParams.zNear = perspective.mZNear;
+ camParams.zFar = perspective.mZFar;
// TODO: yes, we seem to ignore aspectRatio in CameraParameters.
}
else
{
- auto& ortho = camera.mOrthographic;
+ auto& ortho = camera.mOrthographic;
camParams.orthographicSize = Vector4(-ortho.mXMag, ortho.mXMag, ortho.mYMag, -ortho.mYMag) * .5f;
- camParams.zNear = ortho.mZNear;
- camParams.zFar = ortho.mZFar;
+ camParams.zNear = ortho.mZNear;
+ camParams.zFar = ortho.mZFar;
}
}
void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& cctx)
{
- auto& output = cctx.mOutput;
- auto& scene = output.mScene;
+ auto& output = cctx.mOutput;
+ auto& scene = output.mScene;
auto& resources = output.mResources;
- const auto idx = scene.GetNodeCount();
- auto weakNode = scene.AddNode([&]() {
- std::unique_ptr<NodeDefinition> nodeDef{ new NodeDefinition() };
+ const auto idx = scene.GetNodeCount();
+ auto weakNode = scene.AddNode([&]() {
+ std::unique_ptr<NodeDefinition> nodeDef{new NodeDefinition()};
nodeDef->mParentIdx = parentIdx;
- nodeDef->mName = node.mName;
- if (nodeDef->mName.empty())
+ nodeDef->mName = node.mName;
+ if(nodeDef->mName.empty())
{
// TODO: Production quality generation of unique names.
nodeDef->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDef.get()));
}
- if (!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
+ if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
{
- nodeDef->mPosition = node.mTranslation;
+ nodeDef->mPosition = node.mTranslation;
nodeDef->mOrientation = node.mRotation;
- nodeDef->mScale = node.mScale;
+ nodeDef->mScale = node.mScale;
}
return nodeDef;
}());
- if (!weakNode)
+ if(!weakNode)
{
ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
}
cctx.mNodeIndices.RegisterMapping(gltfIdx, idx);
Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
- if (node.mMesh && !node.mMesh->mPrimitives.empty())
+ if(node.mMesh && !node.mMesh->mPrimitives.empty())
{
auto& mesh = *node.mMesh;
- auto iPrim = mesh.mPrimitives.begin();
- auto modelNode = MakeModelNode(*iPrim, cctx);
- auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()];
+ auto iPrim = mesh.mPrimitives.begin();
+ auto modelNode = MakeModelNode(*iPrim, cctx);
+ auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()];
modelNode->mMeshIdx = meshIdx;
weakNode->mRenderable.reset(modelNode);
DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX ||
- resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
+ resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx;
// As does model-exporter, we'll create anonymous child nodes for additional mesh( primitiv)es.
- while (++iPrim != mesh.mPrimitives.end())
+ while(++iPrim != mesh.mPrimitives.end())
{
- std::unique_ptr<NodeDefinition> child{ new NodeDefinition };
+ std::unique_ptr<NodeDefinition> child{new NodeDefinition};
child->mParentIdx = idx;
auto childModel = MakeModelNode(*iPrim, cctx);
scene.AddNode(std::move(child));
DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX ||
- resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
+ resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx);
resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx;
}
}
- if (node.mCamera)
+ if(node.mCamera)
{
CameraParameters camParams;
ConvertCamera(*node.mCamera, camParams);
output.mCameraParameters.push_back(camParams);
}
- for (auto& n : node.mChildren)
+ for(auto& n : node.mChildren)
{
ConvertNode(*n, n.GetIndex(), idx, cctx);
}
void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& cctx)
{
auto& outScene = cctx.mOutput.mScene;
- Index rootIdx = outScene.GetNodeCount();
- switch (scene.mNodes.size())
+ Index rootIdx = outScene.GetNodeCount();
+ switch(scene.mNodes.size())
{
- case 0:
- break;
+ case 0:
+ break;
- case 1:
- ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx);
- outScene.AddRootNode(rootIdx);
- break;
+ case 1:
+ ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx);
+ outScene.AddRootNode(rootIdx);
+ break;
- default:
+ default:
{
- std::unique_ptr<NodeDefinition> sceneRoot{ new NodeDefinition() };
+ std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
outScene.AddNode(std::move(sceneRoot));
outScene.AddRootNode(rootIdx);
- for (auto& n : scene.mNodes)
+ for(auto& n : scene.mNodes)
{
ConvertNode(*n, n.GetIndex(), rootIdx, cctx);
}
{
ConvertSceneNodes(*doc.mScene, cctx);
- for (uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i)
+ for(uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i)
{
ConvertSceneNodes(doc.mScenes[i], cctx);
}
- for (uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i)
+ for(uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i)
{
ConvertSceneNodes(doc.mScenes[i], cctx);
}
}
-template <typename T>
+template<typename T>
void LoadDataFromAccessor(const std::string& path, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
{
std::ifstream animationBinaryFile(path, std::ifstream::binary);
- if (!animationBinaryFile.is_open())
+ if(!animationBinaryFile.is_open())
{
throw std::runtime_error("Failed to load " + path);
}
animationBinaryFile.close();
}
-template <typename T>
+template<typename T>
float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
{
inputDataBuffer.Resize(input.mCount);
outputDataBuffer.Resize(output.mCount);
- const uint32_t inputDataBufferSize = input.GetBytesLength();
+ const uint32_t inputDataBufferSize = input.GetBytesLength();
const uint32_t outputDataBufferSize = output.GetBytesLength();
- LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer,
- input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
- LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer,
- output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
+ LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
+ LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
return inputDataBuffer[input.mCount - 1u];
template<typename T>
float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type)
{
- const gltf2::Accessor& input = *channel.mSampler->mInput;
+ const gltf2::Accessor& input = *channel.mSampler->mInput;
const gltf2::Accessor& output = *channel.mSampler->mOutput;
Vector<float> inputDataBuffer;
- Vector<T> outputDataBuffer;
+ Vector<T> outputDataBuffer;
const float duration = LoadDataFromAccessors<T>(path, input, output, inputDataBuffer, outputDataBuffer);
- for (uint32_t i = 0; i < input.mCount; ++i)
+ for(uint32_t i = 0; i < input.mCount; ++i)
{
keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
}
float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Channel& channel, const std::string& nodeName, uint32_t& propertyIndex, std::vector<SceneLoader::AnimatedProperty>& properties)
{
- const gltf2::Accessor& input = *channel.mSampler->mInput;
+ const gltf2::Accessor& input = *channel.mSampler->mInput;
const gltf2::Accessor& output = *channel.mSampler->mOutput;
Vector<float> inputDataBuffer;
const float duration = LoadDataFromAccessors<float>(path, input, output, inputDataBuffer, outputDataBuffer);
- char weightNameBuffer[32];
- auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
- char* const pWeightName = weightNameBuffer + prefixSize;
- const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
- for (uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
+ char weightNameBuffer[32];
+ auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
+ char* const pWeightName = weightNameBuffer + prefixSize;
+ const auto remainingSize = sizeof(weightNameBuffer) - prefixSize;
+ for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
{
AnimatedProperty& animatedProperty = properties[propertyIndex++];
animatedProperty.mPropertyName = std::string(weightNameBuffer);
animatedProperty.mKeyFrames = KeyFrames::New();
- for (uint32_t i = 0; i < input.mCount; ++i)
+ for(uint32_t i = 0; i < input.mCount; ++i)
{
- animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i*endWeightIndex + weightIndex]);
+ animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
}
- animatedProperty.mTimePeriod = { 0.f, duration };
+ animatedProperty.mTimePeriod = {0.f, duration};
}
return duration;
output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size());
- for (const auto& animation : doc.mAnimations)
+ for(const auto& animation : doc.mAnimations)
{
AnimationDefinition animationDef;
- if (!animation.mName.empty())
+ if(!animation.mName.empty())
{
animationDef.mName = animation.mName;
}
uint32_t numberOfProperties = 0u;
- for (const auto& channel : animation.mChannels)
+ for(const auto& channel : animation.mChannels)
{
numberOfProperties += channel.mSampler->mOutput->mCount;
}
animationDef.mProperties.resize(numberOfProperties);
Index propertyIndex = 0u;
- for (const auto& channel : animation.mChannels)
+ for(const auto& channel : animation.mChannels)
{
std::string nodeName;
- if (!channel.mTarget.mNode->mName.empty())
+ if(!channel.mTarget.mNode->mName.empty())
{
nodeName = channel.mTarget.mNode->mName;
}
else
{
Index index = cctx.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
- nodeName = cctx.mOutput.mScene.GetNode(index)->mName;
+ nodeName = cctx.mOutput.mScene.GetNode(index)->mName;
}
float duration = 0.f;
- switch (channel.mTarget.mPath)
+ switch(channel.mTarget.mPath)
{
case gt::Animation::Channel::Target::TRANSLATION:
{
AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
- animatedProperty.mNodeName = nodeName;
+ animatedProperty.mNodeName = nodeName;
animatedProperty.mPropertyName = POSITION_PROPERTY;
animatedProperty.mKeyFrames = KeyFrames::New();
- duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
+ duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
- animatedProperty.mTimePeriod = { 0.f, duration };
+ animatedProperty.mTimePeriod = {0.f, duration};
break;
}
case gt::Animation::Channel::Target::ROTATION:
{
AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
- animatedProperty.mNodeName = nodeName;
+ animatedProperty.mNodeName = nodeName;
animatedProperty.mPropertyName = ORIENTATION_PROPERTY;
animatedProperty.mKeyFrames = KeyFrames::New();
- duration = LoadKeyFrames<Quaternion>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
+ duration = LoadKeyFrames<Quaternion>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
- animatedProperty.mTimePeriod = { 0.f, duration };
+ animatedProperty.mTimePeriod = {0.f, duration};
break;
}
case gt::Animation::Channel::Target::SCALE:
{
AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
- animatedProperty.mNodeName = nodeName;
+ animatedProperty.mNodeName = nodeName;
animatedProperty.mPropertyName = SCALE_PROPERTY;
animatedProperty.mKeyFrames = KeyFrames::New();
- duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
+ duration = LoadKeyFrames<Vector3>(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
- animatedProperty.mTimePeriod = { 0.f, duration };
+ animatedProperty.mTimePeriod = {0.f, duration};
break;
}
case gt::Animation::Channel::Target::WEIGHTS:
// otherwise we'll set identity matrices for inverse bind pose.
struct IInverseBindMatrixProvider
{
- virtual ~IInverseBindMatrixProvider() {}
+ virtual ~IInverseBindMatrixProvider()
+ {
+ }
virtual void Provide(Matrix& ibm) = 0;
};
struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
{
- std::ifstream mStream;
+ std::ifstream mStream;
const uint32_t mElementSizeBytes;
InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path)
auto& resources = cctx.mOutput.mResources;
resources.mSkeletons.reserve(doc.mSkins.size());
- for (auto& s : doc.mSkins)
+ for(auto& s : doc.mSkins)
{
std::unique_ptr<IInverseBindMatrixProvider> ibmProvider;
- if (s.mInverseBindMatrices)
+ if(s.mInverseBindMatrices)
{
ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, cctx.mPath));
}
}
SkeletonDefinition skeleton;
- if (s.mSkeleton.GetIndex() != INVALID_INDEX)
+ if(s.mSkeleton.GetIndex() != INVALID_INDEX)
{
skeleton.mRootNodeIdx = cctx.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex());
}
skeleton.mJoints.resize(s.mJoints.size());
auto iJoint = skeleton.mJoints.begin();
- for (auto& j : s.mJoints)
+ for(auto& j : s.mJoints)
{
iJoint->mNodeIdx = cctx.mNodeIndices.GetRuntimeId(j.GetIndex());
void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene)
{
- for (size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0)
+ for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0)
{
auto nodeDef = scene.GetNode(i0);
- if (auto renderable = nodeDef->mRenderable.get())
+ if(auto renderable = nodeDef->mRenderable.get())
{
renderable->mShaderIdx = shaderFactory.ProduceShader(*nodeDef);
}
js::SetObjectReader(SCENE_READER);
}
-} // nonamespace
+} // namespace
void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params)
{
bool failed = false;
- auto js = LoadTextFile(url.c_str(), &failed);
- if (failed)
+ auto js = LoadTextFile(url.c_str(), &failed);
+ if(failed)
{
throw std::runtime_error("Failed to load " + url);
}
json::unique_ptr root(json_parse(js.c_str(), js.size()));
- if (!root)
+ if(!root)
{
throw std::runtime_error("Failed to parse " + url);
}
static bool setObjectReaders = true;
- if (setObjectReaders)
+ if(setObjectReaders)
{
// NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
SetObjectReaders();
gt::Document doc;
- auto& rootObj = js::Cast<json_object_s>(*root);
- auto jsAsset = js::FindObjectChild("asset", rootObj);
- auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
- doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
+ auto& rootObj = js::Cast<json_object_s>(*root);
+ auto jsAsset = js::FindObjectChild("asset", rootObj);
+ auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
+ doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
gt::SetRefReaderObject(doc);
DOCUMENT_READER.Read(rootObj, doc);
- auto path = url.substr(0, url.rfind('/') + 1);
- ConversionContext cctx{ params, path, INVALID_INDEX };
+ auto path = url.substr(0, url.rfind('/') + 1);
+ ConversionContext cctx{params, path, INVALID_INDEX};
ConvertMaterials(doc, cctx);
ConvertMeshes(doc, cctx);
params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources);
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
*/
- // FILE HEADER
+// FILE HEADER
#include "dali-scene-loader/public-api/ktx-loader.h"
- // EXTERNAL INCLUDES
-#include "dali/public-api/rendering/texture.h"
+// EXTERNAL INCLUDES
#include <fstream>
#include <memory>
+#include "dali/public-api/rendering/texture.h"
namespace Dali
{
-
namespace
{
-
// http://github.khronos.org/KTX-Specification/
-const uint8_t KTX_ID_HEAD[] = { 0xAB, 0x4B, 0x54, 0x58, 0x20 };
-const uint8_t KTX_ID_TAIL[] = { 0xBB, 0x0D, 0x0A, 0x1A, 0x0A };
+const uint8_t KTX_ID_HEAD[] = {0xAB, 0x4B, 0x54, 0x58, 0x20};
+const uint8_t KTX_ID_TAIL[] = {0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
-const uint8_t KTX_VERSION_1_1[] = { 0x31, 0x31 };
-const uint8_t KTX_VERSION_2_0[] = { 0x32, 0x30 };
+const uint8_t KTX_VERSION_1_1[] = {0x31, 0x31};
+const uint8_t KTX_VERSION_2_0[] = {0x32, 0x30};
static_assert(sizeof(KTX_ID_HEAD) + sizeof(KTX_ID_TAIL) == 10);
static_assert(sizeof(KTX_VERSION_1_1) == 2);
{
struct KtxFileHeader
{
- uint8_t identifier[12];
- uint32_t endianness;
- uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.)
- uint32_t glTypeSize;
- uint32_t glFormat; //(RGB, RGBA, BGRA, etc.)
- uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D
- uint32_t glBaseInternalFormat;
- uint32_t pixelWidth;
- uint32_t pixelHeight;
- uint32_t pixelDepth;
- uint32_t numberOfArrayElements;
- uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
- uint32_t numberOfMipmapLevels;
- uint32_t bytesOfKeyValueData;
+ uint8_t identifier[12];
+ uint32_t endianness;
+ uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.)
+ uint32_t glTypeSize;
+ uint32_t glFormat; //(RGB, RGBA, BGRA, etc.)
+ uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D
+ uint32_t glBaseInternalFormat;
+ uint32_t pixelWidth;
+ uint32_t pixelHeight;
+ uint32_t pixelDepth;
+ uint32_t numberOfArrayElements;
+ uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
+ uint32_t numberOfMipmapLevels;
+ uint32_t bytesOfKeyValueData;
bool IsIdentifierValid() const
{
return std::equal(KTX_ID_HEAD, std::end(KTX_ID_HEAD), identifier) &&
- (std::equal(KTX_VERSION_1_1, std::end(KTX_VERSION_1_1), identifier + sizeof(KTX_ID_HEAD)) ||
- std::equal(KTX_VERSION_2_0, std::end(KTX_VERSION_2_0), identifier + sizeof(KTX_ID_HEAD))) &&
- std::equal(KTX_ID_TAIL, std::end(KTX_ID_TAIL), identifier + (sizeof(KTX_ID_HEAD) + sizeof(KTX_VERSION_1_1)));
+ (std::equal(KTX_VERSION_1_1, std::end(KTX_VERSION_1_1), identifier + sizeof(KTX_ID_HEAD)) ||
+ std::equal(KTX_VERSION_2_0, std::end(KTX_VERSION_2_0), identifier + sizeof(KTX_ID_HEAD))) &&
+ std::equal(KTX_ID_TAIL, std::end(KTX_ID_TAIL), identifier + (sizeof(KTX_ID_HEAD) + sizeof(KTX_VERSION_1_1)));
}
};
*/
bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Pixel::Format& format)
{
- switch (ktxPixelFormat)
- {
- case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR;
- break;
- }
- case 0x93B1: // GL_COMPRESSED_RGBA_ASTC_5x4
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR;
- break;
- }
- case 0x93B2: // GL_COMPRESSED_RGBA_ASTC_5x5
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR;
- break;
- }
- case 0x93B3: // GL_COMPRESSED_RGBA_ASTC_6x5
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR;
- break;
- }
- case 0x93B4: // GL_COMPRESSED_RGBA_ASTC_6x6
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR;
- break;
- }
- case 0x93B5: // GL_COMPRESSED_RGBA_ASTC_8x5
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR;
- break;
- }
- case 0x93B6: // GL_COMPRESSED_RGBA_ASTC_8x6
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR;
- break;
- }
- case 0x93B7: // GL_COMPRESSED_RGBA_ASTC_8x8
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR;
- break;
- }
- case 0x93B8: // GL_COMPRESSED_RGBA_ASTC_10x5
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR;
- break;
- }
- case 0x93B9: // GL_COMPRESSED_RGBA_ASTC_10x6
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR;
- break;
- }
- case 0x93BA: // GL_COMPRESSED_RGBA_ASTC_10x8
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR;
- break;
- }
- case 0x93BB: // GL_COMPRESSED_RGBA_ASTC_10x10
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR;
- break;
- }
- case 0x93BC: // GL_COMPRESSED_RGBA_ASTC_12x10
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR;
- break;
- }
- case 0x93BD: // GL_COMPRESSED_RGBA_ASTC_12x12
- {
- format = Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR;
- break;
- }
- case 0x881B: // GL_RGB16F
+ switch(ktxPixelFormat)
{
- format = Pixel::RGB16F;
- break;
- }
- case 0x8815: // GL_RGB32F
- {
- format = Pixel::RGB32F;
- break;
- }
- case 0x8C3A: // GL_R11F_G11F_B10F
- {
- format = Pixel::RGB32F;
- break;
- }
- case 0x8D7C: // GL_RGBA8UI
- {
- format = Pixel::RGBA8888;
- break;
- }
- case 0x8D7D: // GL_RGB8UI
- {
- format = Pixel::RGB888;
- break;
- }
- default:
- {
- return false;
- }
+ case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR;
+ break;
+ }
+ case 0x93B1: // GL_COMPRESSED_RGBA_ASTC_5x4
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR;
+ break;
+ }
+ case 0x93B2: // GL_COMPRESSED_RGBA_ASTC_5x5
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR;
+ break;
+ }
+ case 0x93B3: // GL_COMPRESSED_RGBA_ASTC_6x5
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR;
+ break;
+ }
+ case 0x93B4: // GL_COMPRESSED_RGBA_ASTC_6x6
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR;
+ break;
+ }
+ case 0x93B5: // GL_COMPRESSED_RGBA_ASTC_8x5
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR;
+ break;
+ }
+ case 0x93B6: // GL_COMPRESSED_RGBA_ASTC_8x6
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR;
+ break;
+ }
+ case 0x93B7: // GL_COMPRESSED_RGBA_ASTC_8x8
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR;
+ break;
+ }
+ case 0x93B8: // GL_COMPRESSED_RGBA_ASTC_10x5
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR;
+ break;
+ }
+ case 0x93B9: // GL_COMPRESSED_RGBA_ASTC_10x6
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR;
+ break;
+ }
+ case 0x93BA: // GL_COMPRESSED_RGBA_ASTC_10x8
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR;
+ break;
+ }
+ case 0x93BB: // GL_COMPRESSED_RGBA_ASTC_10x10
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR;
+ break;
+ }
+ case 0x93BC: // GL_COMPRESSED_RGBA_ASTC_12x10
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR;
+ break;
+ }
+ case 0x93BD: // GL_COMPRESSED_RGBA_ASTC_12x12
+ {
+ format = Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR;
+ break;
+ }
+ case 0x881B: // GL_RGB16F
+ {
+ format = Pixel::RGB16F;
+ break;
+ }
+ case 0x8815: // GL_RGB32F
+ {
+ format = Pixel::RGB32F;
+ break;
+ }
+ case 0x8C3A: // GL_R11F_G11F_B10F
+ {
+ format = Pixel::RGB32F;
+ break;
+ }
+ case 0x8D7C: // GL_RGBA8UI
+ {
+ format = Pixel::RGBA8888;
+ break;
+ }
+ case 0x8D7D: // GL_RGB8UI
+ {
+ format = Pixel::RGB888;
+ break;
+ }
+ default:
+ {
+ return false;
+ }
}
return true;
Texture CubeData::CreateTexture() const
{
- Texture texture = Texture::New(TextureType::TEXTURE_CUBE, data[0][0].GetPixelFormat(),
- data[0][0].GetWidth(), data[0][0].GetHeight());
- for (size_t iSide = 0u, iEndSize = data.size(); iSide < iEndSize; ++iSide)
+ Texture texture = Texture::New(TextureType::TEXTURE_CUBE, data[0][0].GetPixelFormat(), data[0][0].GetWidth(), data[0][0].GetHeight());
+ for(size_t iSide = 0u, iEndSize = data.size(); iSide < iEndSize; ++iSide)
{
auto& side = data[iSide];
- for (size_t iMipLevel = 0u, iEndMipLevel = data[0].size(); iMipLevel < iEndMipLevel; ++iMipLevel)
+ for(size_t iMipLevel = 0u, iEndMipLevel = data[0].size(); iMipLevel < iEndMipLevel; ++iMipLevel)
{
- texture.Upload(side[iMipLevel], CubeMapLayer::POSITIVE_X + iSide, iMipLevel,
- 0u, 0u, side[iMipLevel].GetWidth(), side[iMipLevel].GetHeight());
+ texture.Upload(side[iMipLevel], CubeMapLayer::POSITIVE_X + iSide, iMipLevel, 0u, 0u, side[iMipLevel].GetWidth(), side[iMipLevel].GetHeight());
}
}
bool LoadCubeMapData(const std::string& path, CubeData& cubedata)
{
std::fstream fp(path, std::ios::in | std::ios::binary);
- if (fp.is_open() == false)
+ if(fp.is_open() == false)
{
return false;
}
KtxFileHeader header;
- if (fp.read(reinterpret_cast<char*>(&header), sizeof(KtxFileHeader)).good() == false)
+ if(fp.read(reinterpret_cast<char*>(&header), sizeof(KtxFileHeader)).good() == false)
{
return false;
}
- if (!header.IsIdentifierValid())
+ if(!header.IsIdentifierValid())
{
return false;
}
// Skip the key-values:
- if (fp.seekg(header.bytesOfKeyValueData, fp.cur).good() == false)
+ if(fp.seekg(header.bytesOfKeyValueData, fp.cur).good() == false)
{
return false;
}
- header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u);
+ header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u);
header.numberOfArrayElements = std::max(header.numberOfArrayElements, 1u);
- header.pixelDepth = std::max(header.pixelDepth, 1u);
- header.pixelHeight = std::max(header.pixelHeight, 1u);
+ header.pixelDepth = std::max(header.pixelDepth, 1u);
+ header.pixelHeight = std::max(header.pixelHeight, 1u);
cubedata.data.resize(header.numberOfFaces);
- for (uint32_t face = 0u; face < header.numberOfFaces; ++face)
+ for(uint32_t face = 0u; face < header.numberOfFaces; ++face)
{
cubedata.data[face].resize(header.numberOfMipmapLevels);
}
ConvertPixelFormat(header.glInternalFormat, daliformat);
- for (uint32_t mipmapLevel = 0u; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel)
+ for(uint32_t mipmapLevel = 0u; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel)
{
uint32_t byteSize = 0u;
- if (fp.read(reinterpret_cast<char*>(&byteSize), sizeof(byteSize)).good() == false)
+ if(fp.read(reinterpret_cast<char*>(&byteSize), sizeof(byteSize)).good() == false)
{
return false;
}
- if (0u != byteSize % 4u)
+ if(0u != byteSize % 4u)
{
byteSize += 4u - byteSize % 4u;
}
- for (uint32_t arrayElement = 0u; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1
+ for(uint32_t arrayElement = 0u; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1
{
- for (uint32_t face = 0u; face < header.numberOfFaces; ++face)
+ for(uint32_t face = 0u; face < header.numberOfFaces; ++face)
{
- std::unique_ptr<uint8_t, void(*)(uint8_t*)>img(new uint8_t[byteSize], FreeBuffer);
- if (fp.read(reinterpret_cast<char*>(img.get()), byteSize).good() == false)
+ std::unique_ptr<uint8_t, void (*)(uint8_t*)> img(new uint8_t[byteSize], FreeBuffer);
+ if(fp.read(reinterpret_cast<char*>(img.get()), byteSize).good() == false)
{
return false;
}
return true;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace
{
-
constexpr SamplerFlags::Type FILTER_MODES_FROM_DALI[]{
SamplerFlags::FILTER_LINEAR | SamplerFlags::FILTER_MIPMAP_NEAREST,
SamplerFlags::FILTER_LINEAR,
SamplerFlags::WRAP_MIRROR,
};
-constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{
+constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{
FilterMode::NEAREST,
FilterMode::LINEAR,
FilterMode::NEAREST_MIPMAP_NEAREST,
constexpr WrapMode::Type WRAP_MODES_TO_DALI[]{
WrapMode::REPEAT,
WrapMode::CLAMP_TO_EDGE,
- WrapMode::MIRRORED_REPEAT
-};
+ WrapMode::MIRRORED_REPEAT};
const SamplerFlags::Type SINGLE_VALUE_SAMPLER = SamplerFlags::Encode(FilterMode::NEAREST, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE);
-}
+} // namespace
SamplerFlags::Type SamplerFlags::Encode(FilterMode::Type minFilter, FilterMode::Type magFilter, WrapMode::Type wrapS, WrapMode::Type wrapT)
{
return FILTER_MODES_FROM_DALI[minFilter] | ((FILTER_MODES_FROM_DALI[magFilter] & FILTER_MAG_BITS) << FILTER_MAG_SHIFT) |
- (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT);
+ (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT);
}
FilterMode::Type SamplerFlags::GetMinFilter(Type flags)
TextureDefinition::TextureDefinition(const std::string& imageUri, SamplerFlags::Type samplerFlags)
: mImageUri(imageUri),
mSamplerFlags(samplerFlags)
-{}
+{
+}
MaterialDefinition::RawData
- MaterialDefinition::LoadRaw(const std::string& imagesPath) const
+MaterialDefinition::LoadRaw(const std::string& imagesPath) const
{
RawData raw;
const bool hasTransparency = MaskMatch(mFlags, TRANSPARENCY);
- uint32_t numBuffers = mTextureStages.size() + (hasTransparency ?
- !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL) :
- !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS));
- if (numBuffers == 0)
+ uint32_t numBuffers = mTextureStages.size() + (hasTransparency ? !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL) : !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS));
+ if(numBuffers == 0)
{
return raw;
}
raw.mTextures.reserve(numBuffers);
// Load textures
- auto iTexture = mTextureStages.cbegin();
+ auto iTexture = mTextureStages.cbegin();
auto checkStage = [&](uint32_t flags) {
return iTexture != mTextureStages.end() && MaskMatch(iTexture->mSemantic, flags);
};
// Check for compulsory textures: Albedo, Metallic, Roughness, Normal
- if (checkStage(ALBEDO | METALLIC))
+ if(checkStage(ALBEDO | METALLIC))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
- if (checkStage(NORMAL | ROUGHNESS))
+ if(checkStage(NORMAL | ROUGHNESS))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
else // single value normal-roughness
{
const auto bufferSize = 4;
- uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff, 0xff }; // normal of (0, 0, 1), roughness of 1
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff, 0xff}; // normal of (0, 0, 1), roughness of 1
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
}
else
{
- if (checkStage(ALBEDO))
+ if(checkStage(ALBEDO))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
else // single value albedo, albedo-alpha or albedo-metallic
{
uint32_t bufferSize = 4;
- uint8_t* buffer = nullptr;
- auto format = Pixel::Format::RGBA8888;
- if (hasTransparency) // albedo-alpha
+ uint8_t* buffer = nullptr;
+ auto format = Pixel::Format::RGBA8888;
+ if(hasTransparency) // albedo-alpha
{
- buffer = new uint8_t[bufferSize];
+ buffer = new uint8_t[bufferSize];
buffer[3] = static_cast<uint8_t>(mColor.a * 255.f);
}
- else if (!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic
+ else if(!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic
{
- buffer = new uint8_t[bufferSize];
- buffer[3] = 0xff; // metallic of 1.0
+ buffer = new uint8_t[bufferSize];
+ buffer[3] = 0xff; // metallic of 1.0
}
- else // albedo
+ else // albedo
{
bufferSize = 3;
- buffer = new uint8_t[bufferSize];
- format = Pixel::Format::RGB888;
+ buffer = new uint8_t[bufferSize];
+ format = Pixel::Format::RGB888;
}
buffer[0] = static_cast<uint8_t>(mColor.r * 255.f);
buffer[1] = static_cast<uint8_t>(mColor.g * 255.f);
buffer[2] = static_cast<uint8_t>(mColor.b * 255.f);
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, format, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, format, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
// If we have transparency, or an image based albedo map, we will have to continue with separate metallicRoughness + normal.
const bool createMetallicRoughnessAndNormal = hasTransparency || std::distance(mTextureStages.begin(), iTexture) > 0;
- if (checkStage(METALLIC | ROUGHNESS))
+ if(checkStage(METALLIC | ROUGHNESS))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
- else if (createMetallicRoughnessAndNormal)
+ else if(createMetallicRoughnessAndNormal)
{
// NOTE: we want to set both metallic and roughness to 1.0; dli uses the R & A channels,
// glTF2 uses B & G, so we might as well just set all components to 1.0.
const auto bufferSize = 4;
- uint8_t* buffer = new uint8_t[bufferSize]{ 0xff, 0xff, 0xff, 0xff };
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ uint8_t* buffer = new uint8_t[bufferSize]{0xff, 0xff, 0xff, 0xff};
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
- if (checkStage(NORMAL))
+ if(checkStage(NORMAL))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
- else if (createMetallicRoughnessAndNormal)
+ else if(createMetallicRoughnessAndNormal)
{
const auto bufferSize = 3;
- uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff }; // normal of (0, 0, 1)
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff}; // normal of (0, 0, 1)
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
else // single-value normal-roughness
{
const auto bufferSize = 4;
- uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff, 0xff }; // normal of (0, 0, 1), roughness of 1.0
- raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER });
+ uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff, 0xff}; // normal of (0, 0, 1), roughness of 1.0
+ raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER});
}
}
// Extra textures. TODO: emissive, occlusion etc.
- if (checkStage(SUBSURFACE))
+ if(checkStage(SUBSURFACE))
{
- raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags });
+ raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
auto textureSet = TextureSet::New();
uint32_t n = 0;
- for (auto& tData : raw.mTextures)
+ for(auto& tData : raw.mTextures)
{
- auto& pixels = tData.mPixels;
- auto texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight());
+ auto& pixels = tData.mPixels;
+ auto texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight());
texture.Upload(tData.mPixels, 0, 0, 0, 0, pixels.GetWidth(), pixels.GetHeight());
- if (tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK)
+ if(tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK)
{
texture.GenerateMipmaps();
}
}
// Assign textures to slots -- starting with 2D ones, then cubemaps, if any.
- if (mEnvironmentIdx < environments.size())
+ if(mEnvironmentIdx < environments.size())
{
auto& envTextures = environments[mEnvironmentIdx].second;
- if (envTextures.mDiffuse)
+ if(envTextures.mDiffuse)
{
textureSet.SetTexture(n, envTextures.mDiffuse);
++n;
}
- if (envTextures.mSpecular)
+ if(envTextures.mSpecular)
{
auto specularSampler = Sampler::New();
specularSampler.SetWrapMode(WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE);
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" <<
- environments.size() << ").";
+ ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" << environments.size() << ").";
}
return textureSet;
bool MaterialDefinition::CheckTextures(uint32_t flags) const
{
return std::find_if(mTextureStages.begin(), mTextureStages.end(), [flags](const TextureStage& ts) {
- return MaskMatch(ts.mSemantic, flags);
- }) != mTextureStages.end();
+ return MaskMatch(ts.mSemantic, flags);
+ }) != mTextureStages.end();
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
-* Copyright (c) 2020 Samsung Electronics Co., Ltd.
+* Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
MatrixStack::MatrixStack()
{
mStack.reserve(16);
void MatrixStack::Push(const Matrix& model)
{
- if (mStack.empty())
+ if(mStack.empty())
{
mStack.push_back(model);
}
else
{
- Matrix m{ false };
+ Matrix m{false};
Matrix::Multiply(m, model, mStack.back());
mStack.push_back(m);
}
mStack.clear();
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "dali-scene-loader/public-api/mesh-definition.h"
// EXTERNAL INCLUDES
-#include "dali/devel-api/adaptor-framework/pixel-buffer.h"
-#include <fstream>
#include <cstring>
+#include <fstream>
+#include "dali/devel-api/adaptor-framework/pixel-buffer.h"
namespace Dali
{
{
namespace
{
-
using Uint16Vector4 = uint16_t[4];
class IndexProvider
IndexProvider(const uint16_t* indices)
: mData(reinterpret_cast<uintptr_t>(indices)),
mFunc(indices ? IncrementPointer : Increment)
- {}
+ {
+ }
uint16_t operator()()
{
static uint16_t IncrementPointer(uintptr_t& data)
{
- auto iPtr = reinterpret_cast<const uint16_t*>(data);
+ auto iPtr = reinterpret_cast<const uint16_t*>(data);
auto result = *iPtr;
- data = reinterpret_cast<uintptr_t>(++iPtr);
+ data = reinterpret_cast<uintptr_t>(++iPtr);
return result;
}
uintptr_t mData;
- uint16_t(*mFunc)(uintptr_t&);
+ uint16_t (*mFunc)(uintptr_t&);
};
-
const std::string QUAD("quad");
///@brief Reads a blob from the given stream @a source into @a target, which must have
/// at least @a descriptor.length bytes.
bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target)
{
- if (!source.seekg(descriptor.mOffset, std::istream::beg))
+ if(!source.seekg(descriptor.mOffset, std::istream::beg))
{
return false;
}
- if (descriptor.IsConsecutive())
+ if(descriptor.IsConsecutive())
{
return !!source.read(reinterpret_cast<char*>(target), descriptor.mLength);
}
else
{
DALI_ASSERT_DEBUG(descriptor.mStride > descriptor.mElementSizeHint);
- const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint;
- uint32_t readSize = 0;
- while (readSize < descriptor.mLength &&
- source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
- source.seekg(diff, std::istream::cur))
+ const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint;
+ uint32_t readSize = 0;
+ while(readSize < descriptor.mLength &&
+ source.read(reinterpret_cast<char*>(target), descriptor.mElementSizeHint) &&
+ source.seekg(diff, std::istream::cur))
{
readSize += descriptor.mStride;
target += descriptor.mElementSizeHint;
}
}
-template <typename T>
+template<typename T>
void ReadValues(const std::vector<uint8_t>& valuesBuffer, const std::vector<uint8_t>& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint)
{
const T* const indicesPtr = reinterpret_cast<const T* const>(indicesBuffer.data());
- for (uint32_t index = 0u; index < count; ++index)
+ for(uint32_t index = 0u; index < count; ++index)
{
uint32_t valuesIndex = indicesPtr[index] * elementSizeHint;
memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint);
{
bool success = false;
- if (accessor.mBlob.IsDefined())
+ if(accessor.mBlob.IsDefined())
{
success = ReadBlob(accessor.mBlob, source, target);
- if (!success)
+ if(!success)
{
return false;
}
}
- if (accessor.mSparse)
+ if(accessor.mSparse)
{
const MeshDefinition::Blob& indices = accessor.mSparse->mIndices;
- const MeshDefinition::Blob& values = accessor.mSparse->mValues;
+ const MeshDefinition::Blob& values = accessor.mSparse->mValues;
- if (!indices.IsDefined() || !values.IsDefined())
+ if(!indices.IsDefined() || !values.IsDefined())
{
return false;
}
- const auto indicesBufferSize = indices.GetBufferSize();
+ const auto indicesBufferSize = indices.GetBufferSize();
std::vector<uint8_t> indicesBuffer(indicesBufferSize);
success = ReadBlob(indices, source, indicesBuffer.data());
- if (!success)
+ if(!success)
{
return false;
}
- const auto valuesBufferSize = values.GetBufferSize();
+ const auto valuesBufferSize = values.GetBufferSize();
std::vector<uint8_t> valuesBuffer(valuesBufferSize);
success = ReadBlob(values, source, valuesBuffer.data());
- if (!success)
+ if(!success)
{
return false;
}
- switch (indices.mElementSizeHint)
+ switch(indices.mElementSizeHint)
{
- case 1u:
- {
- ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
- break;
- }
- case 2u:
- {
- ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
- break;
- }
- case 4u:
- {
- ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
- break;
- }
- default:
- DALI_ASSERT_DEBUG(!"Unsupported type for an index");
+ case 1u:
+ {
+ ReadValues<uint8_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
+ break;
+ }
+ case 2u:
+ {
+ ReadValues<uint16_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
+ break;
+ }
+ case 4u:
+ {
+ ReadValues<uint32_t>(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint);
+ break;
+ }
+ default:
+ DALI_ASSERT_DEBUG(!"Unsupported type for an index");
}
}
void GenerateNormals(MeshDefinition::RawData& raw)
{
auto& attribs = raw.mAttribs;
- DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
+ DALI_ASSERT_DEBUG(attribs.size() > 0); // positions
IndexProvider getIndex(raw.mIndices.data());
const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
- auto normals = reinterpret_cast<Vector3*>(buffer.data());
+ auto normals = reinterpret_cast<Vector3*>(buffer.data());
- for (uint32_t i = 0; i < numIndices; i += 3)
+ for(uint32_t i = 0; i < numIndices; i += 3)
{
- uint16_t indices[]{ getIndex(), getIndex(), getIndex() };
- Vector3 pos[]{ positions[indices[0]], positions[indices[1]], positions[indices[2]] };
+ uint16_t indices[]{getIndex(), getIndex(), getIndex()};
+ Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
Vector3 a = pos[1] - pos[0];
Vector3 b = pos[2] - pos[0];
}
auto iEnd = normals + attribs[0].mNumElements;
- while (normals != iEnd)
+ while(normals != iEnd)
{
normals->Normalize();
++normals;
}
- attribs.push_back({ "aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) });
+ attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
}
void GenerateTangentsWithUvs(MeshDefinition::RawData& raw)
{
auto& attribs = raw.mAttribs;
- DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
+ DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs
IndexProvider getIndex(raw.mIndices.data());
const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size();
auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
- auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
+ auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
- auto tangents = reinterpret_cast<Vector3*>(buffer.data());
+ auto tangents = reinterpret_cast<Vector3*>(buffer.data());
- for (uint32_t i = 0; i < numIndices; i += 3)
+ for(uint32_t i = 0; i < numIndices; i += 3)
{
- uint16_t indices[]{ getIndex(), getIndex(), getIndex() };
- Vector3 pos[]{ positions[indices[0]], positions[indices[1]], positions[indices[2]] };
- Vector2 uv[]{ uvs[indices[0]], uvs[indices[1]], uvs[indices[2]] };
+ uint16_t indices[]{getIndex(), getIndex(), getIndex()};
+ Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]};
+ Vector2 uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]};
float x0 = pos[1].x - pos[0].x;
float y0 = pos[1].y - pos[0].y;
float s1 = uv[2].x - uv[0].x;
float t1 = uv[2].y - uv[0].y;
- float r = 1.f / (s0 * t1 - t0 * s1);
+ float r = 1.f / (s0 * t1 - t0 * s1);
Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
tangents[indices[0]] += tangent;
tangents[indices[1]] += tangent;
}
auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
- auto iEnd = normals + attribs[1].mNumElements;
- while (normals != iEnd)
+ auto iEnd = normals + attribs[1].mNumElements;
+ while(normals != iEnd)
{
*tangents -= *normals * normals->Dot(*tangents);
tangents->Normalize();
++tangents;
++normals;
}
- attribs.push_back({ "aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) });
+ attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
}
void GenerateTangents(MeshDefinition::RawData& raw)
{
auto& attribs = raw.mAttribs;
- DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
+ DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals
auto* normals = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
- auto tangents = reinterpret_cast<Vector3*>(buffer.data());
+ auto tangents = reinterpret_cast<Vector3*>(buffer.data());
auto iEnd = normals + attribs[1].mNumElements;
- while (normals != iEnd)
+ while(normals != iEnd)
{
- Vector3 t[]{ normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS) };
+ Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)};
*tangents = t[t[1].LengthSquared() > t[0].LengthSquared()];
*tangents -= *normals * normals->Dot(*tangents);
++tangents;
++normals;
}
- attribs.push_back({ "aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) });
+ attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
}
void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight)
// Calculate the dimensions of the texture.
// The total size of the texture is the length of the blend shapes blob.
- textureWidth = 0u;
+ textureWidth = 0u;
textureHeight = 0u;
- if (0u == totalTextureSize)
+ if(0u == totalTextureSize)
{
// nothing to do.
return;
}
- const uint32_t pow2 = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
- const uint32_t powWidth = pow2 >> 1u;
+ const uint32_t pow2 = static_cast<uint32_t>(ceil(log2(totalTextureSize)));
+ const uint32_t powWidth = pow2 >> 1u;
const uint32_t powHeight = pow2 - powWidth;
- textureWidth = 1u << powWidth;
+ textureWidth = 1u << powWidth;
textureHeight = 1u << powHeight;
}
void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector<MeshDefinition::BlendShape>& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor)
{
uint32_t geometryBufferIndex = 0u;
- float maxDistance = 0.f;
- Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
- for (const auto& blendShape : blendShapes)
+ float maxDistance = 0.f;
+ Vector3* geometryBufferV3 = reinterpret_cast<Vector3*>(geometryBuffer);
+ for(const auto& blendShape : blendShapes)
{
- if (blendShape.deltas.IsDefined())
+ if(blendShape.deltas.IsDefined())
{
DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) ||
- blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
- "Blend Shape position buffer length not a multiple of element size");
+ blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) &&
+ "Blend Shape position buffer length not a multiple of element size");
- const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
+ const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (ReadAccessor(blendShape.deltas, binFile, buffer.data()))
+ if(ReadAccessor(blendShape.deltas, binFile, buffer.data()))
{
blendShape.deltas.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
// Calculate the difference with the original mesh.
// Find the max distance to normalize the deltas.
const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
- for (uint32_t index = 0u; index < numberOfVertices; ++index)
+ for(uint32_t index = 0u; index < numberOfVertices; ++index)
{
Vector3& delta = geometryBufferV3[geometryBufferIndex++];
- delta = deltasBuffer[index];
+ delta = deltasBuffer[index];
maxDistance = std::max(maxDistance, delta.LengthSquared());
}
}
}
- if (blendShape.normals.IsDefined())
+ if(blendShape.normals.IsDefined())
{
DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) ||
- blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
- "Blend Shape normals buffer length not a multiple of element size");
+ blendShape.normals.mBlob.mStride >= sizeof(Vector3)) &&
+ "Blend Shape normals buffer length not a multiple of element size");
- const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
+ const auto bufferSize = blendShape.normals.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (ReadAccessor(blendShape.normals, binFile, buffer.data()))
+ if(ReadAccessor(blendShape.normals, binFile, buffer.data()))
{
blendShape.normals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
// Calculate the difference with the original mesh, and translate to make all values positive.
const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
- for (uint32_t index = 0u; index < numberOfVertices; ++index)
+ for(uint32_t index = 0u; index < numberOfVertices; ++index)
{
Vector3& delta = geometryBufferV3[geometryBufferIndex++];
- delta = deltasBuffer[index];
+ delta = deltasBuffer[index];
delta.x *= 0.5f;
delta.y *= 0.5f;
}
}
- if (blendShape.tangents.IsDefined())
+ if(blendShape.tangents.IsDefined())
{
DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) ||
- blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
- "Blend Shape tangents buffer length not a multiple of element size");
+ blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) &&
+ "Blend Shape tangents buffer length not a multiple of element size");
- const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
+ const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (ReadAccessor(blendShape.tangents, binFile, buffer.data()))
+ if(ReadAccessor(blendShape.tangents, binFile, buffer.data()))
{
blendShape.tangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
// Calculate the difference with the original mesh, and translate to make all values positive.
const Vector3* const deltasBuffer = reinterpret_cast<const Vector3* const>(buffer.data());
- for (uint32_t index = 0u; index < numberOfVertices; ++index)
+ for(uint32_t index = 0u; index < numberOfVertices; ++index)
{
Vector3& delta = geometryBufferV3[geometryBufferIndex++];
- delta = deltasBuffer[index];
+ delta = deltasBuffer[index];
delta.x *= 0.5f;
delta.y *= 0.5f;
}
geometryBufferIndex = 0u;
- for (const auto& blendShape : blendShapes)
+ for(const auto& blendShape : blendShapes)
{
// Normalize all the deltas and translate to a possitive value.
// Deltas are going to be passed to the shader in a color texture
// whose values that are less than zero are clamped.
- if (blendShape.deltas.IsDefined())
+ if(blendShape.deltas.IsDefined())
{
-
const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance));
- for (uint32_t index = 0u; index < numberOfVertices; ++index)
+ for(uint32_t index = 0u; index < numberOfVertices; ++index)
{
Vector3& delta = geometryBufferV3[geometryBufferIndex++];
- delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
- delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
- delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
+ delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f);
+ delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f);
+ delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f);
}
// Calculate and store the unnormalize factor.
blendShapeUnnormalizeFactor = 1.f / normalizeFactor;
}
- if (blendShape.normals.IsDefined())
+ if(blendShape.normals.IsDefined())
{
geometryBufferIndex += numberOfVertices;
}
- if (blendShape.tangents.IsDefined())
+ if(blendShape.tangents.IsDefined())
{
geometryBufferIndex += numberOfVertices;
}
}
}
-}
+} // namespace
MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count)
: mIndices{indices},
mValues{values},
mCount{count}
-{}
+{
+}
-MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
- const MeshDefinition::SparseBlob& sparse)
+MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob,
+ const MeshDefinition::SparseBlob& sparse)
: mBlob{blob},
mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr}
-{}
+{
+}
-void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max,
- uint32_t count, float* values)
+void MeshDefinition::Blob::ApplyMinMax(const std::vector<float>& min, const std::vector<float>& max, uint32_t count, float* values)
{
DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0);
const auto numComponents = std::max(min.size(), max.size());
- using ClampFn = void(*)(const float*, const float*, uint32_t, float&);
- ClampFn clampFn = min.empty() ?
- (max.empty() ?
- static_cast<ClampFn>(nullptr) :
- [](const float* min, const float* max, uint32_t i, float& value) {
- value = std::min(max[i], value);
- }) :
- (max.empty() ?
- [](const float* min, const float* max, uint32_t i, float& value) {
- value = std::max(min[i], value);
- } :
- [](const float* min, const float* max, uint32_t i, float& value) {
- value = std::min(std::max(min[i], value), max[i]);
- });
+ using ClampFn = void (*)(const float*, const float*, uint32_t, float&);
+ ClampFn clampFn = min.empty() ? (max.empty() ? static_cast<ClampFn>(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) {
+ value = std::min(max[i], value);
+ })
+ : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) {
+ value = std::max(min[i], value);
+ }
+ : [](const float* min, const float* max, uint32_t i, float& value) {
+ value = std::min(std::max(min[i], value), max[i]);
+ });
auto end = values + count * numComponents;
- while (values != end)
+ while(values != end)
{
- auto nextElement = values + numComponents;
- uint32_t i = 0;
- while (values != nextElement)
+ auto nextElement = values + numComponents;
+ uint32_t i = 0;
+ while(values != nextElement)
{
clampFn(min.data(), max.data(), i, *values);
++values;
mElementSizeHint(elementSizeHint),
mMin(min),
mMax(max)
-{}
+{
+}
uint32_t MeshDefinition::Blob::GetBufferSize() const
{
void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const
{
Property::Map attribMap;
- attribMap[mName] = mType;
+ attribMap[mName] = mType;
VertexBuffer attribBuffer = VertexBuffer::New(attribMap);
attribBuffer.SetData(mData.data(), mNumElements);
}
MeshDefinition::RawData
- MeshDefinition::LoadRaw(const std::string& modelsPath) const
+MeshDefinition::LoadRaw(const std::string& modelsPath) const
{
RawData raw;
- if (IsQuad())
+ if(IsQuad())
{
return raw;
}
const std::string meshPath = modelsPath + mUri;
- std::ifstream binFile(meshPath, std::ios::binary);
- if (!binFile)
+ std::ifstream binFile(meshPath, std::ios::binary);
+ if(!binFile)
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'";
}
- if (mIndices.IsDefined())
+ if(mIndices.IsDefined())
{
- if (MaskMatch(mFlags, U32_INDICES))
+ if(MaskMatch(mFlags, U32_INDICES))
{
DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) ||
- mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
- "Index buffer length not a multiple of element size");
+ mIndices.mBlob.mStride >= sizeof(uint32_t)) &&
+ "Index buffer length not a multiple of element size");
const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t);
- raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
- if (!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
+ raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially.
+ if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
}
auto u16s = raw.mIndices.data();
auto u32s = reinterpret_cast<uint32_t*>(raw.mIndices.data());
- auto end = u32s + indexCount;
- while (u32s != end)
+ auto end = u32s + indexCount;
+ while(u32s != end)
{
*u16s = static_cast<uint16_t>(*u32s);
++u16s;
else
{
DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) ||
- mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
- "Index buffer length not a multiple of element size");
+ mIndices.mBlob.mStride >= sizeof(unsigned short)) &&
+ "Index buffer length not a multiple of element size");
raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short));
- if (!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
+ if(!ReadAccessor(mIndices, binFile, reinterpret_cast<uint8_t*>(raw.mIndices.data())))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'.";
}
}
std::vector<Vector3> positions;
- if (mPositions.IsDefined())
+ if(mPositions.IsDefined())
{
DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) ||
- mPositions.mBlob.mStride >= sizeof(Vector3)) &&
- "Position buffer length not a multiple of element size");
- const auto bufferSize = mPositions.mBlob.GetBufferSize();
+ mPositions.mBlob.mStride >= sizeof(Vector3)) &&
+ "Position buffer length not a multiple of element size");
+ const auto bufferSize = mPositions.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (!ReadAccessor(mPositions, binFile, buffer.data()))
+ if(!ReadAccessor(mPositions, binFile, buffer.data()))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'.";
}
uint32_t numVector3 = bufferSize / sizeof(Vector3);
mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast<float*>(buffer.data()));
- if (HasBlendShapes())
+ if(HasBlendShapes())
{
positions.resize(numVector3);
std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast<uint8_t*>(positions.data()));
}
- raw.mAttribs.push_back({ "aPosition", Property::VECTOR3, numVector3, std::move(buffer) });
+ raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)});
}
const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES;
- auto hasNormals = mNormals.IsDefined();
- if (hasNormals)
+ auto hasNormals = mNormals.IsDefined();
+ if(hasNormals)
{
DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) ||
- mNormals.mBlob.mStride >= sizeof(Vector3)) &&
- "Normal buffer length not a multiple of element size");
- const auto bufferSize = mNormals.mBlob.GetBufferSize();
+ mNormals.mBlob.mStride >= sizeof(Vector3)) &&
+ "Normal buffer length not a multiple of element size");
+ const auto bufferSize = mNormals.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (!ReadAccessor(mNormals, binFile, buffer.data()))
+ if(!ReadAccessor(mNormals, binFile, buffer.data()))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'.";
}
mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
- raw.mAttribs.push_back({ "aNormal", Property::VECTOR3,
- static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer) });
+ raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
}
- else if (mNormals.mBlob.mLength != 0 && isTriangles)
+ else if(mNormals.mBlob.mLength != 0 && isTriangles)
{
DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize());
GenerateNormals(raw);
}
const auto hasUvs = mTexCoords.IsDefined();
- if (hasUvs)
+ if(hasUvs)
{
DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) ||
- mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
- "Normal buffer length not a multiple of element size");
- const auto bufferSize = mTexCoords.mBlob.GetBufferSize();
+ mTexCoords.mBlob.mStride >= sizeof(Vector2)) &&
+ "Normal buffer length not a multiple of element size");
+ const auto bufferSize = mTexCoords.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (!ReadAccessor(mTexCoords, binFile, buffer.data()))
+ if(!ReadAccessor(mTexCoords, binFile, buffer.data()))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'.";
}
const auto uvCount = bufferSize / sizeof(Vector2);
- if (MaskMatch(mFlags, FLIP_UVS_VERTICAL))
+ if(MaskMatch(mFlags, FLIP_UVS_VERTICAL))
{
- auto uv = reinterpret_cast<Vector2*>(buffer.data());
+ auto uv = reinterpret_cast<Vector2*>(buffer.data());
auto uvEnd = uv + uvCount;
- while (uv != uvEnd)
+ while(uv != uvEnd)
{
uv->y = 1.0f - uv->y;
++uv;
mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast<float*>(buffer.data()));
- raw.mAttribs.push_back({ "aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount),
- std::move(buffer) });
+ raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(uvCount), std::move(buffer)});
}
- if (mTangents.IsDefined())
+ if(mTangents.IsDefined())
{
DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % sizeof(Vector3) == 0) ||
- mTangents.mBlob.mStride >= sizeof(Vector3)) &&
- "Tangents buffer length not a multiple of element size");
- const auto bufferSize = mTangents.mBlob.GetBufferSize();
+ mTangents.mBlob.mStride >= sizeof(Vector3)) &&
+ "Tangents buffer length not a multiple of element size");
+ const auto bufferSize = mTangents.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (!ReadAccessor(mTangents, binFile, buffer.data()))
+ if(!ReadAccessor(mTangents, binFile, buffer.data()))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'.";
}
mTangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast<float*>(buffer.data()));
- raw.mAttribs.push_back({ "aTangent", Property::VECTOR3,
- static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer) });
+ raw.mAttribs.push_back({"aTangent", Property::VECTOR3, static_cast<uint32_t>(bufferSize / sizeof(Vector3)), std::move(buffer)});
}
- else if (mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
+ else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles)
{
DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize());
hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw);
}
- if (IsSkinned())
+ if(IsSkinned())
{
- if (MaskMatch(mFlags, U16_JOINT_IDS))
+ if(MaskMatch(mFlags, U16_JOINT_IDS))
{
DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Uint16Vector4) == 0) ||
- mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) &&
- "Joints buffer length not a multiple of element size");
- const auto inBufferSize = mJoints0.mBlob.GetBufferSize();
+ mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) &&
+ "Joints buffer length not a multiple of element size");
+ const auto inBufferSize = mJoints0.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(inBufferSize * 2);
- auto u16s = buffer.data() + inBufferSize;
- if (!ReadAccessor(mJoints0, binFile, u16s))
+ auto u16s = buffer.data() + inBufferSize;
+ if(!ReadAccessor(mJoints0, binFile, u16s))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
}
auto floats = reinterpret_cast<float*>(buffer.data());
- auto end = u16s + inBufferSize;
- while (u16s != end)
+ auto end = u16s + inBufferSize;
+ while(u16s != end)
{
auto value = *reinterpret_cast<uint16_t*>(u16s);
- *floats = static_cast<float>(value);
+ *floats = static_cast<float>(value);
u16s += sizeof(uint16_t);
++floats;
}
- raw.mAttribs.push_back({ "aJoints", Property::VECTOR4,
- static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer) });
+ raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(buffer.size() / sizeof(Vector4)), std::move(buffer)});
}
else
{
DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Vector4) == 0) ||
- mJoints0.mBlob.mStride >= sizeof(Vector4)) &&
- "Joints buffer length not a multiple of element size");
- const auto bufferSize = mJoints0.mBlob.GetBufferSize();
+ mJoints0.mBlob.mStride >= sizeof(Vector4)) &&
+ "Joints buffer length not a multiple of element size");
+ const auto bufferSize = mJoints0.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (!ReadAccessor(mJoints0, binFile, buffer.data()))
+ if(!ReadAccessor(mJoints0, binFile, buffer.data()))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'.";
}
- raw.mAttribs.push_back({ "aJoints", Property::VECTOR4,
- static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer) });
+ raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
}
DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) ||
- mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
- "Weights buffer length not a multiple of element size");
- const auto bufferSize = mWeights0.mBlob.GetBufferSize();
+ mWeights0.mBlob.mStride >= sizeof(Vector4)) &&
+ "Weights buffer length not a multiple of element size");
+ const auto bufferSize = mWeights0.mBlob.GetBufferSize();
std::vector<uint8_t> buffer(bufferSize);
- if (!ReadAccessor(mWeights0, binFile, buffer.data()))
+ if(!ReadAccessor(mWeights0, binFile, buffer.data()))
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'.";
}
- raw.mAttribs.push_back({ "aWeights", Property::VECTOR4,
- static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer) });
+ raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast<uint32_t>(bufferSize / sizeof(Vector4)), std::move(buffer)});
}
// Calculate the Blob for the blend shapes.
blendShapesBlob.mOffset = std::numeric_limits<unsigned int>::max();
blendShapesBlob.mLength = 0u;
- for (const auto& blendShape : mBlendShapes)
+ for(const auto& blendShape : mBlendShapes)
{
- for (auto i : { &blendShape.deltas, &blendShape.normals, &blendShape.tangents })
+ for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents})
{
- if (i->IsDefined())
+ if(i->IsDefined())
{
blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset);
blendShapesBlob.mLength += i->mBlob.mLength;
}
}
- if (HasBlendShapes())
+ if(HasBlendShapes())
{
const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3);
// Calculate the size of one buffer inside the texture.
raw.mBlendShapeBufferOffset = numberOfVertices;
- bool calculateGltf2BlendShapes = false;
- uint32_t textureWidth = 0u;
- uint32_t textureHeight = 0u;
+ bool calculateGltf2BlendShapes = false;
+ uint32_t textureWidth = 0u;
+ uint32_t textureHeight = 0u;
- if (!mBlendShapeHeader.IsDefined())
+ if(!mBlendShapeHeader.IsDefined())
{
CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight);
calculateGltf2BlendShapes = true;
{
uint16_t header[2u];
ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast<uint8_t*>(header));
- textureWidth = header[0u];
+ textureWidth = header[0u];
textureHeight = header[1u];
}
raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes);
Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F);
- uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
+ uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer();
- if (calculateGltf2BlendShapes)
+ if(calculateGltf2BlendShapes)
{
CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]);
}
Blob unnormalizeFactorBlob;
unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes);
- if (blendShapesBlob.IsDefined())
+ if(blendShapesBlob.IsDefined())
{
- if (ReadBlob(blendShapesBlob, binFile, geometryBuffer))
+ if(ReadBlob(blendShapesBlob, binFile, geometryBuffer))
{
unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength;
}
}
// Read the unnormalize factors.
- if (unnormalizeFactorBlob.IsDefined())
+ if(unnormalizeFactorBlob.IsDefined())
{
ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast<uint8_t*>(&raw.mBlendShapeUnnormalizeFactor[0u]));
}
meshGeometry.geometry = Geometry::New();
meshGeometry.geometry.SetType(mPrimitiveType);
- if (IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
+ if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers.
{
- auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
+ auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0;
meshGeometry.geometry = MakeTexturedQuadGeometry(options);
}
else
{
- if (!raw.mIndices.empty())
+ if(!raw.mIndices.empty())
{
meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size());
}
- for (auto& a : raw.mAttribs)
+ for(auto& a : raw.mAttribs)
{
a.AttachBuffer(meshGeometry.geometry);
}
- if (HasBlendShapes())
+ if(HasBlendShapes())
{
- meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
+ meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset;
meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor);
- meshGeometry.blendShapeGeometry = Texture::New( TextureType::TEXTURE_2D,
- raw.mBlendShapeData.GetPixelFormat(),
- raw.mBlendShapeData.GetWidth(),
- raw.mBlendShapeData.GetHeight());
+ meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D,
+ raw.mBlendShapeData.GetPixelFormat(),
+ raw.mBlendShapeData.GetWidth(),
+ raw.mBlendShapeData.GetHeight());
meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData);
}
}
return meshGeometry;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
void NodeDefinition::Renderable::RegisterResources(IResourceReceiver& receiver) const
{
receiver.Register(ResourceType::Shader, mShaderIdx);
reflector.Reflect(ResourceType::Shader, mShaderIdx);
}
-void NodeDefinition::Renderable::OnCreate(const NodeDefinition& node, CreateParams& params,
- Actor& actor) const
+void NodeDefinition::Renderable::OnCreate(const NodeDefinition& node, CreateParams& params, Actor& actor) const
{
DALI_ASSERT_DEBUG(mShaderIdx != INVALID_INDEX);
- auto& resources = params.mResources;
- Shader shader = resources.mShaders[mShaderIdx].second;
+ auto& resources = params.mResources;
+ Shader shader = resources.mShaders[mShaderIdx].second;
static Geometry defaultGeometry = Geometry::New();
- Renderer renderer = Renderer::New(defaultGeometry, shader);
+ Renderer renderer = Renderer::New(defaultGeometry, shader);
RendererState::Apply(resources.mShaders[mShaderIdx].first.mRendererState, renderer);
actor.RegisterProperty(ORIGINAL_MATRIX_PROPERTY_NAME, GetLocalSpace(), Property::AccessMode::READ_ONLY);
- if (mRenderable)
+ if(mRenderable)
{
mRenderable->OnCreate(*this, params, actor);
}
- for (auto& e : mExtras)
+ for(auto& e : mExtras)
{
actor.RegisterProperty(e.mKey, e.mValue);
}
- for (auto& c : mConstraints)
+ for(auto& c : mConstraints)
{
- params.mConstrainables.push_back(ConstraintRequest{ &c, actor });
+ params.mConstrainables.push_back(ConstraintRequest{&c, actor});
}
return actor;
Matrix NodeDefinition::GetLocalSpace() const
{
- Matrix localSpace{ false };
+ Matrix localSpace{false};
localSpace.SetTransformComponents(mScale, mOrientation, mPosition);
return localSpace;
}
Renderable::OnCreate(node, params, actor);
auto& resources = params.mResources;
- auto& mesh = resources.mMeshes[mMeshIdx];
+ auto& mesh = resources.mMeshes[mMeshIdx];
- auto renderer = actor.GetRendererAt(0);
+ auto renderer = actor.GetRendererAt(0);
Geometry geometry = mesh.second.geometry;
renderer.SetGeometry(geometry);
auto shader = renderer.GetShader();
- if (mesh.first.IsSkinned())
+ if(mesh.first.IsSkinned())
{
- params.mSkinnables.push_back(SkinningShaderConfigurationRequest{ mesh.first.mSkeletonIdx, shader });
+ params.mSkinnables.push_back(SkinningShaderConfigurationRequest{mesh.first.mSkeletonIdx, shader});
}
- if (mesh.first.HasBlendShapes())
+ if(mesh.first.HasBlendShapes())
{
- params.mBlendshapeRequests.push_back(BlendshapeShaderConfigurationRequest{ node.mName, mMeshIdx, shader });
+ params.mBlendshapeRequests.push_back(BlendshapeShaderConfigurationRequest{node.mName, mMeshIdx, shader});
}
TextureSet textures = resources.mMaterials[mMaterialIdx].second;
// Set the blend shape texture.
- if (mesh.second.blendShapeGeometry)
+ if(mesh.second.blendShapeGeometry)
{
TextureSet newTextureSet = TextureSet::New();
newTextureSet.SetTexture(0u, mesh.second.blendShapeGeometry);
const unsigned int numberOfTextures = textures.GetTextureCount();
- for (unsigned int index = 0u; index < numberOfTextures; ++index)
+ for(unsigned int index = 0u; index < numberOfTextures; ++index)
{
const unsigned int newIndex = index + 1u;
newTextureSet.SetTexture(newIndex, textures.GetTexture(index));
actor.RegisterProperty("uIblIntensity", resources.mEnvironmentMaps[envIdx].first.mIblIntensity);
const auto alphaCutoff = matDef.GetAlphaCutoff();
- if (alphaCutoff > 0.f)
+ if(alphaCutoff > 0.f)
{
actor.RegisterProperty("uAlphaThreshold", alphaCutoff);
}
}
-void ArcNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& params,
- Actor& actor) const
+void ArcNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& params, Actor& actor) const
{
ModelNode::OnCreate(node, params, actor);
actor.RegisterProperty("radius", mRadius);
const float startAngleRadians = mStartAngleDegrees * Math::PI_OVER_180;
- Vector2 startPolar{ std::cos(startAngleRadians), std::sin(startAngleRadians) };
+ Vector2 startPolar{std::cos(startAngleRadians), std::sin(startAngleRadians)};
actor.RegisterProperty("startAngle", startPolar);
const float endAngleRadians = mEndAngleDegrees * Math::PI_OVER_180;
- Vector2 endPolar{ std::cos(endAngleRadians), std::sin(endAngleRadians) };
+ Vector2 endPolar{std::cos(endAngleRadians), std::sin(endAngleRadians)};
actor.RegisterProperty("endAngle", endPolar);
}
{
float endAngle = 0.f;
- if (diffAngle <= 0.001f)
+ if(diffAngle <= 0.001f)
{
//0.001 is used to ensure is empty arc when startAngle = endAngle + 360 * N
endAngle = startAngle + 0.001f;
}
- else if (diffAngle >= 360.f)
+ else if(diffAngle >= 360.f)
{
endAngle = diffAngle + 359.99f;
}
endVector.y = sinf(endAngle * Math::PI_OVER_180);
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
#include "dali-scene-loader/public-api/parse-renderer-state.h"
-#include "dali/devel-api/common/map-wrapper.h"
#include <cstring>
+#include "dali/devel-api/common/map-wrapper.h"
namespace Dali
{
{
namespace
{
-
std::map<std::string_view, Type> COMPARISONS{
-#define DECL_COMPARISON(x) { #x, Comparison::x }
+#define DECL_COMPARISON(x) {#x, Comparison::x}
DECL_COMPARISON(NEVER),
DECL_COMPARISON(ALWAYS),
DECL_COMPARISON(LESS),
{
Type value = 0x0;
auto iFind = COMPARISONS.find(str);
- if (iFind != COMPARISONS.end())
+ if(iFind != COMPARISONS.end())
{
value = iFind->second;
}
}
std::map<std::string_view, Type> BLEND_FACTORS{
-#define DECL_BLEND_FACTOR(x) { #x, SceneLoader::BlendFactor::x }
+#define DECL_BLEND_FACTOR(x) {#x, SceneLoader::BlendFactor::x}
DECL_BLEND_FACTOR(ZERO),
DECL_BLEND_FACTOR(ONE),
DECL_BLEND_FACTOR(SRC_COLOR),
{
Type value = 0x0;
auto iFind = BLEND_FACTORS.find(str);
- if (iFind != BLEND_FACTORS.end())
+ if(iFind != BLEND_FACTORS.end())
{
value = iFind->second << (BLEND_FACTOR_BASE_SHIFT + BLEND_FACTOR_ITEM_BITS * item);
}
}
std::map<std::string_view, Type> BUFFER_MODES{
-#define DECL_BUFFER_MODE(x) { #x, BufferMode::x }
+#define DECL_BUFFER_MODE(x) {#x, BufferMode::x}
DECL_BUFFER_MODE(NONE),
DECL_BUFFER_MODE(AUTO),
DECL_BUFFER_MODE(COLOR),
{
Type value = 0x0;
auto iFind = BUFFER_MODES.find(str);
- if (iFind != BUFFER_MODES.end())
+ if(iFind != BUFFER_MODES.end())
{
value = iFind->second << BUFFER_MODE_SHIFT;
}
return value;
}
-std::map<std::string_view, Type(*)(const std::string_view&)> RENDERER_STATE_PROCESSORS{
- { "DEPTH_WRITE", [](const std::string_view&) -> Type { return DEPTH_WRITE; } },
- { "DEPTH_TEST", [](const std::string_view&) -> Type { return DEPTH_TEST; } },
- { "CULL_FRONT", [](const std::string_view&) -> Type { return CULL_FRONT; } },
- { "CULL_BACK", [](const std::string_view&) -> Type { return CULL_BACK; } },
- { "ALPHA_BLEND", [](const std::string_view&) -> Type { return ALPHA_BLEND; } },
- { "DEPTH_FUNC", [](const std::string_view& arg) -> Type {
- Type value = (arg[0] == ':') ?
- (InterpretComparison(std::string_view(arg.data() + 1, arg.size() - 1)) << DEPTH_FUNCTION_SHIFT) : 0x0;
- return value;
- } },
- { "BLEND_SRC_RGB", [](const std::string_view& arg) -> Type {
- Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 0) : 0x0;
- return value;
- }},
- { "BLEND_DST_RGB", [](const std::string_view& arg) -> Type {
- Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 1) : 0x0;
- return value;
- }},
- { "BLEND_SRC_ALPHA", [](const std::string_view& arg) -> Type {
- Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 2) : 0x0;
- return value;
- }},
- { "BLEND_DST_ALPHA", [](const std::string_view& arg) -> Type {
- Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 3) : 0x0;
- return value;
- }},
- { "BUFFER_MODE", [](const std::string_view& arg) -> Type {
- Type value = (arg[0] == ':') ? InterpretBufferMode(std::string_view(arg.data() + 1, arg.size() - 1)) : 0x0;
- return value;
- }},
+std::map<std::string_view, Type (*)(const std::string_view&)> RENDERER_STATE_PROCESSORS{
+ {"DEPTH_WRITE", [](const std::string_view&) -> Type { return DEPTH_WRITE; }},
+ {"DEPTH_TEST", [](const std::string_view&) -> Type { return DEPTH_TEST; }},
+ {"CULL_FRONT", [](const std::string_view&) -> Type { return CULL_FRONT; }},
+ {"CULL_BACK", [](const std::string_view&) -> Type { return CULL_BACK; }},
+ {"ALPHA_BLEND", [](const std::string_view&) -> Type { return ALPHA_BLEND; }},
+ {"DEPTH_FUNC", [](const std::string_view& arg) -> Type {
+ Type value = (arg[0] == ':') ? (InterpretComparison(std::string_view(arg.data() + 1, arg.size() - 1)) << DEPTH_FUNCTION_SHIFT) : 0x0;
+ return value;
+ }},
+ {"BLEND_SRC_RGB", [](const std::string_view& arg) -> Type {
+ Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 0) : 0x0;
+ return value;
+ }},
+ {"BLEND_DST_RGB", [](const std::string_view& arg) -> Type {
+ Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 1) : 0x0;
+ return value;
+ }},
+ {"BLEND_SRC_ALPHA", [](const std::string_view& arg) -> Type {
+ Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 2) : 0x0;
+ return value;
+ }},
+ {"BLEND_DST_ALPHA", [](const std::string_view& arg) -> Type {
+ Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 3) : 0x0;
+ return value;
+ }},
+ {"BUFFER_MODE", [](const std::string_view& arg) -> Type {
+ Type value = (arg[0] == ':') ? InterpretBufferMode(std::string_view(arg.data() + 1, arg.size() - 1)) : 0x0;
+ return value;
+ }},
};
-}
+} // namespace
Type Parse(const char* string, size_t length, StringCallback onError)
{
- if (length == 0)
+ if(length == 0)
{
length = strlen(string);
}
Type value = 0x0;
- auto iEnd = string + length;
- while (string != iEnd)
+ auto iEnd = string + length;
+ while(string != iEnd)
{
auto iNextToken = std::find(string, iEnd, '|');
- auto iColon = std::find(string, iNextToken, ':');
- auto i = RENDERER_STATE_PROCESSORS.find(std::string_view(string, iColon - string));
- if (i != RENDERER_STATE_PROCESSORS.end() && size_t(std::distance(string, iNextToken)) >= i->first.size())
+ auto iColon = std::find(string, iNextToken, ':');
+ auto i = RENDERER_STATE_PROCESSORS.find(std::string_view(string, iColon - string));
+ if(i != RENDERER_STATE_PROCESSORS.end() && size_t(std::distance(string, iNextToken)) >= i->first.size())
{
value |= i->second(std::string_view(string + i->first.size(), iNextToken - iColon));
}
return value;
}
-} // RendererState
-}
-}
+} // namespace RendererState
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace
{
// NOTE: values for BlendFactor aren't contiguous, hence we need a mapping.
-const Dali::BlendFactor::Type kBlendFactors[] = {
+const Dali::BlendFactor::Type kBlendFactors[] = {
Dali::BlendFactor::ZERO,
Dali::BlendFactor::ONE,
Dali::BlendFactor::SRC_COLOR,
Dali::BlendFactor::CONSTANT_ALPHA,
Dali::BlendFactor::ONE_MINUS_CONSTANT_ALPHA,
};
-}
+} // namespace
namespace RendererState
{
RENDERER_SET_PROPERTY(BLEND_MODE, MaskMatch(rendererState, ALPHA_BLEND) ? BlendMode::ON : BlendMode::OFF);
const bool cullBack = MaskMatch(rendererState, CULL_BACK);
- RENDERER_SET_PROPERTY(FACE_CULLING_MODE, MaskMatch(rendererState, CULL_FRONT) ?
- (cullBack ? FaceCullingMode::FRONT_AND_BACK : FaceCullingMode::FRONT) :
- (cullBack ? FaceCullingMode::BACK : FaceCullingMode::NONE));
+ RENDERER_SET_PROPERTY(FACE_CULLING_MODE, MaskMatch(rendererState, CULL_FRONT) ? (cullBack ? FaceCullingMode::FRONT_AND_BACK : FaceCullingMode::FRONT) : (cullBack ? FaceCullingMode::BACK : FaceCullingMode::NONE));
- if (auto depthFunc = (rendererState & DEPTH_FUNCTION_MASK) >> DEPTH_FUNCTION_SHIFT)
+ if(auto depthFunc = (rendererState & DEPTH_FUNCTION_MASK) >> DEPTH_FUNCTION_SHIFT)
{
RENDERER_SET_PROPERTY(DEPTH_FUNCTION, static_cast<DepthFunction::Type>(depthFunc - 1));
}
- if (auto blendFactors = (rendererState & BLEND_FACTOR_MASK) >> BLEND_FACTOR_BASE_SHIFT)
+ if(auto blendFactors = (rendererState & BLEND_FACTOR_MASK) >> BLEND_FACTOR_BASE_SHIFT)
{
- if (auto srcRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK))
+ if(auto srcRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK))
{
RENDERER_SET_PROPERTY(BLEND_FACTOR_SRC_RGB, kBlendFactors[static_cast<BlendFactor::Type>(srcRgb - 1)]);
}
blendFactors >>= BLEND_FACTOR_ITEM_BITS;
- if (auto dstRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK))
+ if(auto dstRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK))
{
RENDERER_SET_PROPERTY(BLEND_FACTOR_DEST_RGB, kBlendFactors[static_cast<BlendFactor::Type>(dstRgb - 1)]);
}
blendFactors >>= BLEND_FACTOR_ITEM_BITS;
- if (auto srcAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK))
+ if(auto srcAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK))
{
RENDERER_SET_PROPERTY(BLEND_FACTOR_SRC_ALPHA, kBlendFactors[static_cast<BlendFactor::Type>(srcAlpha - 1)]);
}
blendFactors >>= BLEND_FACTOR_ITEM_BITS;
- if (auto dstAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK))
+ if(auto dstAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK))
{
RENDERER_SET_PROPERTY(BLEND_FACTOR_DEST_ALPHA, kBlendFactors[static_cast<BlendFactor::Type>(dstAlpha - 1)]);
}
}
- if (auto bufferMode = (rendererState & BUFFER_MODE_MASK) >> BUFFER_MODE_SHIFT)
+ if(auto bufferMode = (rendererState & BUFFER_MODE_MASK) >> BUFFER_MODE_SHIFT)
{
RENDERER_SET_PROPERTY(RENDER_MODE, static_cast<RenderMode::Type>(bufferMode - 1));
}
}
-} // RendererState
+} // namespace RendererState
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "dali-scene-loader/public-api/resource-bundle.h"
// EXTERNAL
-#include "dali/public-api/rendering/sampler.h"
-#include "dali-toolkit/public-api/image-loader/sync-image-loader.h"
-#include <fstream>
-#include <istream>
#include <cstring>
#include <fstream>
+#include <istream>
+#include "dali-toolkit/public-api/image-loader/sync-image-loader.h"
+#include "dali/public-api/rendering/sampler.h"
namespace Dali
{
{
namespace
{
-
const char* const RESOURCE_TYPE_NAMES[] = {
"Environment",
"Shader",
"Material",
};
-} // nonamespace
+} // namespace
const char* GetResourceTypeName(ResourceType::Value type)
{
auto& environmentRefCounts = refCounts[ResourceType::Environment];
const auto& materialRefs = refCounts[ResourceType::Material];
- for (uint32_t i = 0, iEnd = materialRefs.Size(); i != iEnd; ++i)
+ for(uint32_t i = 0, iEnd = materialRefs.Size(); i != iEnd; ++i)
{
- if (materialRefs[i] > 0)
+ if(materialRefs[i] > 0)
{
++environmentRefCounts[mMaterials[i].first.mEnvironmentIdx];
}
void ResourceBundle::LoadResources(const ResourceRefCounts& refCounts, PathProvider pathProvider, Options::Type options)
{
- const auto kForceLoad = MaskMatch(options, Options::ForceReload);
+ const auto kForceLoad = MaskMatch(options, Options::ForceReload);
const auto kKeepUnused = MaskMatch(options, Options::KeepUnused);
- const auto& refCountEnvMaps = refCounts[ResourceType::Environment];
- auto environmentsPath = pathProvider(ResourceType::Environment);
- for (uint32_t i = 0, iEnd = refCountEnvMaps.Size(); i != iEnd; ++i)
+ const auto& refCountEnvMaps = refCounts[ResourceType::Environment];
+ auto environmentsPath = pathProvider(ResourceType::Environment);
+ for(uint32_t i = 0, iEnd = refCountEnvMaps.Size(); i != iEnd; ++i)
{
- auto refCount = refCountEnvMaps[i];
- auto& iEnvMap = mEnvironmentMaps[i];
- if (refCount > 0 && (kForceLoad || !iEnvMap.second.IsLoaded()))
+ auto refCount = refCountEnvMaps[i];
+ auto& iEnvMap = mEnvironmentMaps[i];
+ if(refCount > 0 && (kForceLoad || !iEnvMap.second.IsLoaded()))
{
- auto raw = iEnvMap.first.LoadRaw(environmentsPath);
+ auto raw = iEnvMap.first.LoadRaw(environmentsPath);
iEnvMap.second = iEnvMap.first.Load(std::move(raw));
}
- else if (!kKeepUnused && refCount == 0 && iEnvMap.second.IsLoaded())
+ else if(!kKeepUnused && refCount == 0 && iEnvMap.second.IsLoaded())
{
- iEnvMap.second.mDiffuse = Texture();
+ iEnvMap.second.mDiffuse = Texture();
iEnvMap.second.mSpecular = Texture();
}
}
const auto& refCountShaders = refCounts[ResourceType::Shader];
- auto shadersPath = pathProvider(ResourceType::Shader);
- for (uint32_t i = 0, iEnd = refCountShaders.Size(); i != iEnd; ++i)
+ auto shadersPath = pathProvider(ResourceType::Shader);
+ for(uint32_t i = 0, iEnd = refCountShaders.Size(); i != iEnd; ++i)
{
- auto refCount = refCountShaders[i];
- auto& iShader = mShaders[i];
- if (refCount > 0 && (kForceLoad || !iShader.second))
+ auto refCount = refCountShaders[i];
+ auto& iShader = mShaders[i];
+ if(refCount > 0 && (kForceLoad || !iShader.second))
{
- auto raw = iShader.first.LoadRaw(shadersPath);
+ auto raw = iShader.first.LoadRaw(shadersPath);
iShader.second = iShader.first.Load(std::move(raw));
}
else if(!kKeepUnused && refCount == 0 && iShader.second)
}
const auto& refCountMeshes = refCounts[ResourceType::Mesh];
- auto modelsPath = pathProvider(ResourceType::Mesh);
- for (uint32_t i = 0, iEnd = refCountMeshes.Size(); i != iEnd; ++i)
+ auto modelsPath = pathProvider(ResourceType::Mesh);
+ for(uint32_t i = 0, iEnd = refCountMeshes.Size(); i != iEnd; ++i)
{
- auto refCount = refCountMeshes[i];
- auto& iMesh = mMeshes[i];
- if (refCount > 0 && (kForceLoad || !iMesh.second.geometry))
+ auto refCount = refCountMeshes[i];
+ auto& iMesh = mMeshes[i];
+ if(refCount > 0 && (kForceLoad || !iMesh.second.geometry))
{
- auto raw = iMesh.first.LoadRaw(modelsPath);
+ auto raw = iMesh.first.LoadRaw(modelsPath);
iMesh.second = iMesh.first.Load(std::move(raw));
}
- else if (!kKeepUnused && refCount == 0 && iMesh.second.geometry)
+ else if(!kKeepUnused && refCount == 0 && iMesh.second.geometry)
{
iMesh.second.geometry = Geometry();
}
}
const auto& refCountMaterials = refCounts[ResourceType::Material];
- auto imagesPath = pathProvider(ResourceType::Material);
- for (uint32_t i = 0, iEnd = refCountMaterials.Size(); i != iEnd; ++i)
+ auto imagesPath = pathProvider(ResourceType::Material);
+ for(uint32_t i = 0, iEnd = refCountMaterials.Size(); i != iEnd; ++i)
{
- auto refCount = refCountMaterials[i];
+ auto refCount = refCountMaterials[i];
auto& iMaterial = mMaterials[i];
- if (refCount > 0 && (kForceLoad || !iMaterial.second))
+ if(refCount > 0 && (kForceLoad || !iMaterial.second))
{
- auto raw = iMaterial.first.LoadRaw(imagesPath);
+ auto raw = iMaterial.first.LoadRaw(imagesPath);
iMaterial.second = iMaterial.first.Load(mEnvironmentMaps, std::move(raw));
}
- else if (!kKeepUnused && refCount == 0 && iMaterial.second)
+ else if(!kKeepUnused && refCount == 0 && iMaterial.second)
{
iMaterial.second = TextureSet();
}
}
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
*/
// EXTERNAL
-#include "dali/public-api/animation/constraints.h"
#include "dali/devel-api/common/map-wrapper.h"
+#include "dali/public-api/animation/constraints.h"
// INTERNAL
-#include "dali-scene-loader/public-api/scene-definition.h"
+#include "dali-scene-loader/internal/graphics/builtin-shader-extern-gen.h"
#include "dali-scene-loader/public-api/blend-shape-details.h"
-#include "dali-scene-loader/public-api/utils.h"
+#include "dali-scene-loader/public-api/scene-definition.h"
#include "dali-scene-loader/public-api/skinning-details.h"
-#include "dali-scene-loader/internal/graphics/builtin-shader-extern-gen.h"
+#include "dali-scene-loader/public-api/utils.h"
//#define DEBUG_SCENE_DEFINITION
//#define DEBUG_JOINTS
#define DEBUG_ONLY(x)
#endif
-#define LOGD(x) DEBUG_ONLY(printf x ; printf("\n"); fflush(stdout))
+#define LOGD(x) DEBUG_ONLY(printf x; printf("\n"); fflush(stdout))
namespace Dali
{
{
namespace
{
-
-const std::string JOINT_MATRIX{ "jointMatrix" };
-
-const std::map<Property::Type, Constraint(*)(Actor&, Property::Index)> sConstraintFactory = {
- {
- Property::Type::BOOLEAN,
- [](Actor& a, Property::Index i) {
- return Constraint::New<bool>(a, i, [](bool& current, const PropertyInputContainer& inputs) {
- current = inputs[0]->GetBoolean();
- });
- }
- },
- {
- Property::Type::INTEGER,
- [](Actor& a, Property::Index i) {
- return Constraint::New<int>(a, i, [](int& current, const PropertyInputContainer& inputs) {
- current = inputs[0]->GetInteger();
- });
- }
- },
- {
- Property::Type::FLOAT,
- [](Actor& a, Property::Index i) {
- return Constraint::New<float>(a, i, EqualToConstraint());
- }
- },
- {
- Property::Type::VECTOR2,
- [](Actor& a, Property::Index i) {
- return Constraint::New<Vector2>(a, i, EqualToConstraint());
- }
- },
- {
- Property::Type::VECTOR3,
- [](Actor& a, Property::Index i) {
- return Constraint::New<Vector3>(a, i, EqualToConstraint());
- }
- },
- {
- Property::Type::VECTOR4,
- [](Actor& a, Property::Index i) {
- return Constraint::New<Vector4>(a, i, EqualToConstraint());
- }
- },
- {
- Property::Type::MATRIX,
- [](Actor& a, Property::Index i) {
- return Constraint::New<Matrix>(a, i, EqualToConstraint());
- }
- },
- {
- Property::Type::MATRIX3,
- [](Actor& a, Property::Index i) {
- return Constraint::New<Matrix3>(a, i, EqualToConstraint());
- }
- },
- {
- Property::Type::ROTATION,
- [](Actor& a, Property::Index i) {
- return Constraint::New<Quaternion>(a, i, EqualToConstraint());
- }
- },
+const std::string JOINT_MATRIX{"jointMatrix"};
+
+const std::map<Property::Type, Constraint (*)(Actor&, Property::Index)> sConstraintFactory = {
+ {Property::Type::BOOLEAN,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<bool>(a, i, [](bool& current, const PropertyInputContainer& inputs) {
+ current = inputs[0]->GetBoolean();
+ });
+ }},
+ {Property::Type::INTEGER,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<int>(a, i, [](int& current, const PropertyInputContainer& inputs) {
+ current = inputs[0]->GetInteger();
+ });
+ }},
+ {Property::Type::FLOAT,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<float>(a, i, EqualToConstraint());
+ }},
+ {Property::Type::VECTOR2,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<Vector2>(a, i, EqualToConstraint());
+ }},
+ {Property::Type::VECTOR3,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<Vector3>(a, i, EqualToConstraint());
+ }},
+ {Property::Type::VECTOR4,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<Vector4>(a, i, EqualToConstraint());
+ }},
+ {Property::Type::MATRIX,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<Matrix>(a, i, EqualToConstraint());
+ }},
+ {Property::Type::MATRIX3,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<Matrix3>(a, i, EqualToConstraint());
+ }},
+ {Property::Type::ROTATION,
+ [](Actor& a, Property::Index i) {
+ return Constraint::New<Quaternion>(a, i, EqualToConstraint());
+ }},
};
struct ResourceReflector : IResourceReflector
{
- Index* iMesh = nullptr;
+ Index* iMesh = nullptr;
Index* iShader = nullptr;
void Reflect(ResourceType::Value type, Index& id)
{
- switch (type)
+ switch(type)
{
- case ResourceType::Shader:
- DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!");
- iShader = &id;
- break;
+ case ResourceType::Shader:
+ DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!");
+ iShader = &id;
+ break;
- case ResourceType::Mesh:
- DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!");
- iMesh = &id;
- break;
+ case ResourceType::Mesh:
+ DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!");
+ iMesh = &id;
+ break;
- default: // Other resource types are not relevant to the problem at hand.
- break;
+ default: // Other resource types are not relevant to the problem at hand.
+ break;
}
}
};
-
#ifdef DEBUG_JOINTS
Shader sJointDebugShader;
-int sNumScenes = 0;
+int sNumScenes = 0;
void EnsureJointDebugShaderCreated()
{
- if (0 == sNumScenes)
+ if(0 == sNumScenes)
{
sJointDebugShader = Shader::New(SHADER_SCENE_LOADER_JOINT_DEBUG_VERT, SHADER_SCENE_LOADER_JOINT_DEBUG_FRAG);
}
{
Property::Map attribs;
attribs["aPosition"] = Property::Type::VECTOR3;
- attribs["aColor"] = Property::Type::FLOAT;
+ attribs["aColor"] = Property::Type::FLOAT;
PropertyBuffer vbo = PropertyBuffer::New(attribs);
struct Vertex
{
Vector3 pos;
- float color;
+ float color;
} vertices[] = {
- { Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f },
- { Vector3::XAXIS, .999f },
- { Vector3::YAXIS, .999f * 256.f },
- { Vector3::ZAXIS, .999f * 256.f * 256.f },
+ {Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f},
+ {Vector3::XAXIS, .999f},
+ {Vector3::YAXIS, .999f * 256.f},
+ {Vector3::ZAXIS, .999f * 256.f * 256.f},
};
vbo.SetData(&vertices, std::extent<decltype(vertices)>::value);
- uint16_t indices[] = { 0, 1, 0, 2, 0, 3 };
+ uint16_t indices[] = {0, 1, 0, 2, 0, 3};
Geometry geo = Geometry::New();
geo.AddVertexBuffer(vbo);
aJoint.SetVisible(true);
}
-#endif //DEBUG_JOINTS
+#endif //DEBUG_JOINTS
class ActorCreatorVisitor : public NodeDefinition::IConstVisitor
{
public:
ActorCreatorVisitor(NodeDefinition::CreateParams& params)
: mCreationContext(params)
- {}
+ {
+ }
void Start(const NodeDefinition& n)
{
mCreationContext.mXforms.modelStack.Push(n.GetLocalSpace());
Actor a = n.CreateActor(mCreationContext);
- if (!mActorStack.empty())
+ if(!mActorStack.empty())
{
mActorStack.back().Add(a);
}
private:
NodeDefinition::CreateParams& mCreationContext;
- std::vector<Actor> mActorStack;
- Actor mRoot;
+ std::vector<Actor> mActorStack;
+ Actor mRoot;
};
bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index rootHint = INVALID_INDEX)
{
bool isAncestor = false;
- while (node != rootHint && !isAncestor)
+ while(node != rootHint && !isAncestor)
{
- node = scene.GetNode(node)->mParentIdx;
+ node = scene.GetNode(node)->mParentIdx;
isAncestor = ancestor == node;
}
return isAncestor;
void InsertUniqueSorted(std::vector<Index>& data, Index value)
{
auto iInsert = std::lower_bound(data.begin(), data.end(), value);
- if (iInsert == data.end() || *iInsert != value)
+ if(iInsert == data.end() || *iInsert != value)
{
data.insert(iInsert, value);
}
void RemoveFromSorted(std::vector<Index>& data, Index value)
{
auto iRemove = std::lower_bound(data.begin(), data.end(), value);
- if (iRemove != data.end() && *iRemove == value)
+ if(iRemove != data.end() && *iRemove == value)
{
data.erase(iRemove);
}
Property::Index ConfigureJointMatrix(Actor actor, Actor ancestor, Property::Index propJointMatrix)
{
Actor parent = actor.GetParent();
- if (parent != ancestor)
+ if(parent != ancestor)
{
propJointMatrix = ConfigureJointMatrix(parent, ancestor, propJointMatrix);
}
auto myPropJointMatrix = actor.GetPropertyIndex(JOINT_MATRIX);
- if (myPropJointMatrix == Property::INVALID_INDEX)
+ if(myPropJointMatrix == Property::INVALID_INDEX)
{
- myPropJointMatrix = actor.RegisterProperty(JOINT_MATRIX, Matrix{ false });
- Constraint constraint = Constraint::New<Matrix>(actor, propJointMatrix,
- [](Matrix& output, const PropertyInputContainer& inputs)
- {
- Matrix jointMatrix{ false };
- jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
-
- Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix());
- });
- constraint.AddSource(Source{ actor, Actor::Property::ORIENTATION });
- constraint.AddSource(Source{ actor, Actor::Property::POSITION });
- constraint.AddSource(Source{ parent, propJointMatrix });
+ myPropJointMatrix = actor.RegisterProperty(JOINT_MATRIX, Matrix{false});
+ Constraint constraint = Constraint::New<Matrix>(actor, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
+ Matrix jointMatrix{false};
+ jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
+
+ Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix());
+ });
+ constraint.AddSource(Source{actor, Actor::Property::ORIENTATION});
+ constraint.AddSource(Source{actor, Actor::Property::POSITION});
+ constraint.AddSource(Source{parent, propJointMatrix});
constraint.Apply();
}
std::sort(requests.begin(), requests.end());
// Remove duplicates.
- auto i = requests.begin();
- auto iEnd = requests.end();
- Shader s = i->mShader;
- Index skeletonIdx = i->mSkeletonIdx;
+ auto i = requests.begin();
+ auto iEnd = requests.end();
+ Shader s = i->mShader;
+ Index skeletonIdx = i->mSkeletonIdx;
++i;
do
{
// Multiple identical shader instances are removed.
- while (i != iEnd && i->mShader == s)
+ while(i != iEnd && i->mShader == s)
{
// Cannot have multiple skeletons input to the same shader.
// NOTE: DliModel now makes sure this doesn't happen.
DALI_ASSERT_ALWAYS(i->mSkeletonIdx == skeletonIdx &&
- "Skinning shader must not be shared between different skeletons.");
+ "Skinning shader must not be shared between different skeletons.");
i->mShader = Shader();
++i;
}
- if (i == iEnd)
+ if(i == iEnd)
{
break;
}
- s = i->mShader;
+ s = i->mShader;
skeletonIdx = i->mSkeletonIdx;
++i;
- } while (true);
+ } while(true);
- requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr)
- {
- return !sscr.mShader;
- }), requests.end());
+ requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) {
+ return !sscr.mShader;
+ }),
+ requests.end());
}
void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& boneIdx)
char propertyNameBuffer[32];
snprintf(propertyNameBuffer, sizeof(propertyNameBuffer), "%s[%d]", Skinning::BONE_UNIFORM_NAME.c_str(), boneIdx);
DALI_ASSERT_DEBUG(shader.GetPropertyIndex(propertyNameBuffer) == Property::INVALID_INDEX);
- auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{ false });
+ auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{false});
// Constrain bone matrix to joint transform.
- Constraint constraint = Constraint::New<Matrix>(shader, propBoneXform,
- [ibm](Matrix& output, const PropertyInputContainer& inputs)
- {
- Matrix::Multiply(output, ibm, inputs[0]->GetMatrix());
- });
+ Constraint constraint = Constraint::New<Matrix>(shader, propBoneXform, [ibm](Matrix& output, const PropertyInputContainer& inputs) {
+ Matrix::Multiply(output, ibm, inputs[0]->GetMatrix());
+ });
auto propJointMatrix = joint.GetPropertyIndex(JOINT_MATRIX);
- constraint.AddSource(Source{ joint, propJointMatrix });
+ constraint.AddSource(Source{joint, propJointMatrix});
constraint.Apply();
++boneIdx;
}
-template <class Visitor, class SceneDefinition>
+template<class Visitor, class SceneDefinition>
void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v, SceneDefinition& sd)
{
auto& node = *sd.GetNode(iNode);
v.Start(node);
- if (node.mCustomization)
+ if(node.mCustomization)
{
- if (!node.mChildren.empty())
+ if(!node.mChildren.empty())
{
- auto choice = choices.Get(node.mCustomization->mTag);
- Index i = std::min(choice != Customization::NONE ? choice : 0, static_cast<Index>(node.mChildren.size() - 1));
+ auto choice = choices.Get(node.mCustomization->mTag);
+ Index i = std::min(choice != Customization::NONE ? choice : 0, static_cast<Index>(node.mChildren.size() - 1));
sd.Visit(node.mChildren[i], choices, v);
}
}
else
{
- for (auto i : node.mChildren)
+ for(auto i : node.mChildren)
{
sd.Visit(i, choices, v);
}
v.Finish(node);
}
-} // nonamespace
+} // namespace
SceneDefinition::SceneDefinition()
{
{
#ifdef DEBUG_JOINTS
--sNumScenes;
- if (sNumScenes == 0)
+ if(sNumScenes == 0)
{
sJointDebugShader = Shader();
}
uint32_t SceneLoader::SceneDefinition::AddRootNode(Index iNode)
{
- if (iNode < mNodes.size())
+ if(iNode < mNodes.size())
{
uint32_t result = mRootNodeIds.size();
mRootNodeIds.push_back(iNode);
void SceneDefinition::RemoveRootNode(Index iRoot)
{
- if (iRoot < mRootNodeIds.size())
+ if(iRoot < mRootNodeIds.size())
{
mRootNodeIds.erase(mRootNodeIds.begin() + iRoot);
}
void Start(const NodeDefinition& n)
{
- if (n.mRenderable)
+ if(n.mRenderable)
{
n.mRenderable->RegisterResources(counter);
}
}
void Finish(const NodeDefinition& n)
- {}
+ {
+ }
} refCounterVisitor;
refCounterVisitor.counter.refCounts = &refCounts;
Visit(iNode, choices, refCounterVisitor);
}
-Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices & choices,
- NodeDefinition::CreateParams& params) const
+Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params) const
{
ActorCreatorVisitor actorCreatorVisitor(params);
}
void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choices,
- Customization::Map& outCustomizationOptions, Customization::Choices* outMissingChoices) const
+ Customization::Map& outCustomizationOptions,
+ Customization::Choices* outMissingChoices) const
{
struct : NodeDefinition::IConstVisitor
{
- const Customization::Choices* choices; // choices that we know about.
- Customization::Map* options; // tags are registered here. NO OWNERSHIP.
- Customization::Choices* missingChoices; // tags will be registered with the default 0. NO OWNERSHIP.
+ const Customization::Choices* choices; // choices that we know about.
+ Customization::Map* options; // tags are registered here. NO OWNERSHIP.
+ Customization::Choices* missingChoices; // tags will be registered with the default 0. NO OWNERSHIP.
void Start(const NodeDefinition& n)
{
- if (n.mCustomization)
+ if(n.mCustomization)
{
const std::string& tag = n.mCustomization->mTag;
- if (missingChoices != nullptr && choices->Get(tag) == Customization::NONE)
+ if(missingChoices != nullptr && choices->Get(tag) == Customization::NONE)
{
missingChoices->Set(tag, 0);
}
auto customization = options->Get(tag);
- if (!customization)
+ if(!customization)
{
customization = options->Set(tag, {});
}
customization->nodes.push_back(n.mName);
customization->numOptions = std::max(customization->numOptions,
- static_cast<uint32_t>(n.mChildren.size()));
+ static_cast<uint32_t>(n.mChildren.size()));
}
}
void Finish(const NodeDefinition& n)
- {}
+ {
+ }
} customizationRegistrationVisitor;
- customizationRegistrationVisitor.choices = &choices;
- customizationRegistrationVisitor.options = &outCustomizationOptions;
+ customizationRegistrationVisitor.choices = &choices;
+ customizationRegistrationVisitor.options = &outCustomizationOptions;
customizationRegistrationVisitor.missingChoices = outMissingChoices;
- for (auto i : mRootNodeIds)
+ for(auto i : mRootNodeIds)
{
Visit(i, choices, customizationRegistrationVisitor);
}
NodeDefinition* SceneDefinition::AddNode(std::unique_ptr<NodeDefinition>&& nodeDef)
{
- if (FindNode(nodeDef->mName))
+ if(FindNode(nodeDef->mName))
{
return nullptr;
}
// add next index (to which we're about to push) as a child to the designated parent, if any.
- if (nodeDef->mParentIdx != INVALID_INDEX)
+ if(nodeDef->mParentIdx != INVALID_INDEX)
{
mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size());
}
{
LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder));
- std::unique_ptr<NodeDefinition>* nodePtr = nullptr;
+ std::unique_ptr<NodeDefinition>* nodePtr = nullptr;
std::unique_ptr<NodeDefinition>* newParentPtr = nullptr;
- if (!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr))
+ if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr))
{
return false;
}
- auto& node = *nodePtr;
- auto iNode = std::distance(mNodes.data(), nodePtr);
+ auto& node = *nodePtr;
+ auto iNode = std::distance(mNodes.data(), nodePtr);
DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) {
std::ostringstream stream;
stream << n.mName << " (" << n.mParentIdx << "):";
- for (auto i : n.mChildren)
+ for(auto i : n.mChildren)
{
stream << i << ", ";
}
};)
// Remove node from children of previous parent (if any).
- if (node->mParentIdx != INVALID_INDEX)
+ if(node->mParentIdx != INVALID_INDEX)
{
LOGD(("old parent:"));
DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);)
LOGD(("new parent:"));
DEBUG_ONLY(dumpNode(**newParentPtr);)
auto& children = (*newParentPtr)->mChildren;
- if (siblingOrder > children.size())
+ if(siblingOrder > children.size())
{
siblingOrder = children.size();
}
// Update parent index.
LOGD(("node:"));
DEBUG_ONLY(dumpNode(*node);)
- auto iParent = std::distance(mNodes.data(), newParentPtr);
+ auto iParent = std::distance(mNodes.data(), newParentPtr);
node->mParentIdx = iParent;
DEBUG_ONLY(dumpNode(*node);)
return true;
bool SceneDefinition::RemoveNode(const std::string& name)
{
std::unique_ptr<NodeDefinition>* node = nullptr;
- if (!FindNode(name, &node))
+ if(!FindNode(name, &node))
{
return false;
}
// Reset node def pointers recursively.
- auto& thisNodes = mNodes;
- unsigned int numReset = 0;
+ auto& thisNodes = mNodes;
+ unsigned int numReset = 0;
std::function<void(std::unique_ptr<NodeDefinition>&)> resetFn =
[&thisNodes, &resetFn, &numReset](std::unique_ptr<NodeDefinition>& nd) {
- LOGD(("resetting %d", &nd - thisNodes.data()));
- for (auto i : nd->mChildren)
- {
- resetFn(thisNodes[i]);
- }
- nd.reset();
- ++numReset;
- };
+ LOGD(("resetting %d", &nd - thisNodes.data()));
+ for(auto i : nd->mChildren)
+ {
+ resetFn(thisNodes[i]);
+ }
+ nd.reset();
+ ++numReset;
+ };
resetFn(*node);
// Gather indices of dead nodes into a vector which we sort on insertion.
std::vector<Index> offsets;
offsets.reserve(numReset);
- for (auto& n : mNodes)
+ for(auto& n : mNodes)
{
- if (!n)
+ if(!n)
{
offsets.push_back(std::distance(mNodes.data(), &n));
}
mNodes.erase(std::remove(mNodes.begin(), mNodes.end(), decltype(mNodes)::value_type()), mNodes.end());
// Offset all indices (parent and child) by the index they'd sort into in offsets.
- enum { INDEX_FOR_REMOVAL = INVALID_INDEX };
+ enum
+ {
+ INDEX_FOR_REMOVAL = INVALID_INDEX
+ };
auto offsetter = [&offsets](Index& i) {
auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i);
- if (iFind != offsets.end() && *iFind == i)
+ if(iFind != offsets.end() && *iFind == i)
{
LOGD(("marking %d for removal.", i));
i = INDEX_FOR_REMOVAL;
else
{
auto distance = std::distance(offsets.begin(), iFind);
- if (distance > 0)
+ if(distance > 0)
{
LOGD(("offsetting %d by %d.", i, distance));
i -= distance;
}
};
- for (auto& nd : mNodes)
+ for(auto& nd : mNodes)
{
bool parentOffsetResult = offsetter(nd->mParentIdx);
- DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point.
+ DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point.
auto& children = nd->mChildren;
- for (auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0)
+ for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0)
{
offsetter(*i0);
}
void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const
{
- auto& thisNodes = mNodes;
+ auto& thisNodes = mNodes;
std::function<void(int)> buildStack = [&model, &thisNodes, &buildStack](int i) {
auto node = thisNodes[i].get();
- if (node->mParentIdx != INVALID_INDEX)
+ if(node->mParentIdx != INVALID_INDEX)
{
buildStack(node->mParentIdx);
}
buildStack(index);
}
-NodeDefinition* SceneDefinition::FindNode(const std::string &name, Index* outIndex)
+NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex)
{
auto iBegin = mNodes.begin();
- auto iEnd = mNodes.end();
- auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
+ auto iEnd = mNodes.end();
+ auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
return nd->mName == name;
});
auto result = iFind != iEnd ? iFind->get() : nullptr;
- if (result && outIndex)
+ if(result && outIndex)
{
*outIndex = std::distance(iBegin, iFind);
}
return result;
}
-const NodeDefinition* SceneDefinition::FindNode(const std::string &name, Index* outIndex) const
+const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const
{
auto iBegin = mNodes.begin();
- auto iEnd = mNodes.end();
- auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
+ auto iEnd = mNodes.end();
+ auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr<NodeDefinition>& nd) {
return nd->mName == name;
});
auto result = iFind != iEnd ? iFind->get() : nullptr;
- if (result && outIndex)
+ if(result && outIndex)
{
*outIndex = std::distance(iBegin, iFind);
}
Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const
{
auto iBegin = mNodes.begin();
- auto iEnd = mNodes.end();
- auto iFind = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr<NodeDefinition>& n) {
+ auto iEnd = mNodes.end();
+ auto iFind = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr<NodeDefinition>& n) {
return n.get() == &node;
});
return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX;
}
-void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer,
- unsigned int limit)
+void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit)
{
unsigned int n = 0;
- for (auto& defp : mNodes)
+ for(auto& defp : mNodes)
{
- if (predicate(*defp))
+ if(predicate(*defp))
{
consumer(*defp);
++n;
- if (n == limit)
+ if(n == limit)
{
break;
}
}
}
-void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer,
- unsigned int limit) const
+void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const
{
unsigned int n = 0;
- for (auto& defp : mNodes)
+ for(auto& defp : mNodes)
{
- if (predicate(*defp))
+ if(predicate(*defp))
{
consumer(*defp);
++n;
- if (n == limit)
+ if(n == limit)
{
break;
}
}
}
-void SceneDefinition::ApplyConstraints(Actor& root,
- std::vector<ConstraintRequest>&& constrainables, StringCallback onError) const
+void SceneDefinition::ApplyConstraints(Actor& root,
+ std::vector<ConstraintRequest>&& constrainables,
+ StringCallback onError) const
{
- for (auto& cr : constrainables)
+ for(auto& cr : constrainables)
{
- auto& nodeDef = mNodes[cr.mConstraint->mSourceIdx];
- auto sourceName = nodeDef->mName.c_str();
- Property::Index iTarget = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty);
- if (iTarget != Property::INVALID_INDEX)
+ auto& nodeDef = mNodes[cr.mConstraint->mSourceIdx];
+ auto sourceName = nodeDef->mName.c_str();
+ Property::Index iTarget = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty);
+ if(iTarget != Property::INVALID_INDEX)
{
auto propertyType = cr.mTarget.GetPropertyType(iTarget);
- auto iFind = sConstraintFactory.find(propertyType);
- if (iFind == sConstraintFactory.end())
+ auto iFind = sConstraintFactory.find(propertyType);
+ if(iFind == sConstraintFactory.end())
{
onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.",
- sourceName, cr.mConstraint->mProperty.c_str(), PropertyTypes::GetName(propertyType)));
+ sourceName,
+ cr.mConstraint->mProperty.c_str(),
+ PropertyTypes::GetName(propertyType)));
continue;
}
Constraint constraint = iFind->second(cr.mTarget, iTarget);
Actor source = root.FindChildByName(nodeDef->mName);
- if (!source)
+ if(!source)
{
auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
onError(FormatString("node '%s': Failed to locate constraint source %s@%s; ignored.",
- sourceName, cr.mConstraint->mProperty.c_str(), targetName.c_str()));
+ sourceName,
+ cr.mConstraint->mProperty.c_str(),
+ targetName.c_str()));
continue;
}
- else if (source == cr.mTarget)
+ else if(source == cr.mTarget)
{
onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.",
- sourceName, cr.mConstraint->mProperty.c_str()));
+ sourceName,
+ cr.mConstraint->mProperty.c_str()));
continue;
}
Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty);
- constraint.AddSource(Source{ source, iSource });
+ constraint.AddSource(Source{source, iSource});
constraint.Apply();
}
else
{
auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get<std::string>();
onError(FormatString("node '%s': Failed to create constraint for property %s@%s; ignored.",
- sourceName, cr.mConstraint->mProperty.c_str(), targetName.c_str()));
+ sourceName,
+ cr.mConstraint->mProperty.c_str(),
+ targetName.c_str()));
}
}
}
// to the refcount of each node we have visited, in our temporary registry. Those with refcount 1
// are the leaves, while the most descendant node with the highest refcount is the root of the skeleton.
std::map<Index, std::vector<Index>> rootsJoints;
- std::vector<Index> path;
+ std::vector<Index> path;
path.reserve(16);
- for (auto& s : skeletons)
+ for(auto& s : skeletons)
{
- std::map<uint32_t, uint32_t> jointRefs;
- for (auto& j : s.mJoints)
+ std::map<uint32_t, uint32_t> jointRefs;
+ for(auto& j : s.mJoints)
{
auto nodeIdx = j.mNodeIdx;
do // Traverse upwards and record each node we have visited until we reach the scene root.
{
path.push_back(nodeIdx);
- if (nodeIdx == iRoot)
+ if(nodeIdx == iRoot)
{
break;
}
auto node = GetNode(nodeIdx);
- nodeIdx = node->mParentIdx;
- }
- while (nodeIdx != INVALID_INDEX);
+ nodeIdx = node->mParentIdx;
+ } while(nodeIdx != INVALID_INDEX);
- if (nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes.
+ if(nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes.
{
- for (auto i : path)
+ for(auto i : path)
{
++jointRefs[i];
}
}
// Only record the skeleton if we have encountered the root of the current scene.
- if (jointRefs.empty())
+ if(jointRefs.empty())
{
continue;
}
- Index root = s.mRootNodeIdx;
+ Index root = s.mRootNodeIdx;
uint32_t maxRef = 0;
- auto iFind = jointRefs.find(root);
- if (iFind != jointRefs.end())
+ auto iFind = jointRefs.find(root);
+ if(iFind != jointRefs.end())
{
maxRef = iFind->second;
}
std::vector<Index> joints;
- for (auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be.
+ for(auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be.
{
// The most descendant node with the highest ref count is the root of the skeleton.
- if (j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot)))
+ if(j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot)))
{
maxRef = j.second;
RemoveFromSorted(joints, root);
root = j.first;
}
- else if (j.second == 1) // This one's a leaf.
+ else if(j.second == 1) // This one's a leaf.
{
InsertUniqueSorted(joints, j.first);
}
// Merge skeletons that share the same root.
auto& finalJoints = rootsJoints[root];
- for (auto j : joints)
+ for(auto j : joints)
{
- if (std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) {
- return IsAncestor(*this, j, jj, root);
- }) != finalJoints.end())
+ if(std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) {
+ return IsAncestor(*this, j, jj, root);
+ }) != finalJoints.end())
{
- continue; // if the joint is found to be an ancestor of another joint already registered, move on.
+ continue; // if the joint is found to be an ancestor of another joint already registered, move on.
}
auto i = j;
- while (i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove.
+ while(i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove.
{
auto node = GetNode(i);
- i = node->mParentIdx;
+ i = node->mParentIdx;
RemoveFromSorted(finalJoints, i);
}
// 2, Merge records where one root joint is descendant of another. Handle leaf node changes - remove previous
// leaf nodes that now have descendants, and add new ones.
- auto iRoots = rootsJoints.begin();
+ auto iRoots = rootsJoints.begin();
auto iRootsEnd = rootsJoints.end();
- while (iRoots != iRootsEnd)
+ while(iRoots != iRootsEnd)
{
- auto i = iRoots->first;
+ auto i = iRoots->first;
bool merged = false;
- while (i != iRoot) // Starting with the root joint of the skeleton, traverse upwards.
+ while(i != iRoot) // Starting with the root joint of the skeleton, traverse upwards.
{
auto node = GetNode(i);
- i = node->mParentIdx;
+ i = node->mParentIdx;
auto iFind = rootsJoints.find(i);
- if (iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton.
+ if(iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton.
{
// Now find out which leaf of iFind is an ancestor, if any.
auto iFindLeaf = std::find_if(iFind->second.begin(), iFind->second.end(), [this, iRoots, iFind](Index j) {
return IsAncestor(*this, j, iRoots->first, iFind->first);
});
- if (iFindLeaf != iFind->second.end())
+ if(iFindLeaf != iFind->second.end())
{
- iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it.
+ iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it.
}
// Merge iRoots with iFind
auto& targetJoints = iFind->second;
- if (iRoots->second.empty()) // The root is a leaf.
+ if(iRoots->second.empty()) // The root is a leaf.
{
InsertUniqueSorted(targetJoints, iRoots->first);
}
- else for (auto j : iRoots->second)
- {
- InsertUniqueSorted(targetJoints, j);
- }
+ else
+ for(auto j : iRoots->second)
+ {
+ InsertUniqueSorted(targetJoints, j);
+ }
merged = true;
- break; // Traverse no more
+ break; // Traverse no more
}
}
}
// 3, For each root, register joint matrices and constraints
- for (auto r : rootsJoints)
+ for(auto r : rootsJoints)
{
- auto node = GetNode(r.first);
+ auto node = GetNode(r.first);
auto rootJoint = root.FindChildByName(node->mName);
DALI_ASSERT_ALWAYS(!!rootJoint);
DALI_ASSERT_DEBUG(rootJoint.GetPropertyIndex(JOINT_MATRIX) == Property::INVALID_INDEX);
- auto propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{ false });
- Constraint constraint = Constraint::New<Matrix>(rootJoint, propJointMatrix,
- [](Matrix& output, const PropertyInputContainer& inputs)
- {
- output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
- });
+ auto propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{false});
+ Constraint constraint = Constraint::New<Matrix>(rootJoint, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) {
+ output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3());
+ });
constraint.AddSource(Source(rootJoint, Actor::Property::ORIENTATION));
constraint.AddSource(Source(rootJoint, Actor::Property::POSITION));
constraint.Apply();
- for (auto j : r.second)
+ for(auto j : r.second)
{
- node = GetNode(j);
+ node = GetNode(j);
auto joint = rootJoint.FindChildByName(node->mName);
ConfigureJointMatrix(joint, rootJoint, propJointMatrix);
}
void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const
{
std::map<Index, std::map<Index, std::vector<Index*>>> skinningShaderUsers;
- for (auto& node : mNodes)
+ for(auto& node : mNodes)
{
- if (node->mRenderable)
+ if(node->mRenderable)
{
ResourceReflector reflector;
node->mRenderable->ReflectResources(reflector);
- if (reflector.iMesh)
+ if(reflector.iMesh)
{
const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
- if (mesh.IsSkinned())
+ if(mesh.IsSkinned())
{
skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader);
}
// For each shader, and each skeleton using the same shader as the first skeleton,
// update the shader references (from nodes with skinned meshes) with a new copy of
// the shader definition from the node using the first skeleton.
- for (auto& users : skinningShaderUsers)
+ for(auto& users : skinningShaderUsers)
{
- auto& skeletons = users.second;
- auto iterSkeleton = skeletons.begin();
+ auto& skeletons = users.second;
+ auto iterSkeleton = skeletons.begin();
// skipping the first skeleton.
++iterSkeleton;
resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end()));
const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
- while (iterSkeleton != skeletons.end())
+ while(iterSkeleton != skeletons.end())
{
Index iShader = resources.mShaders.size();
- resources.mShaders.push_back({ shaderDef, Shader() });
+ resources.mShaders.push_back({shaderDef, Shader()});
- for (auto& i : iterSkeleton->second)
+ for(auto& i : iterSkeleton->second)
{
*i = iShader;
}
}
}
-void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources,
- Actor rootActor, std::vector<SkinningShaderConfigurationRequest>&& requests) const
+void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources,
+ Actor rootActor,
+ std::vector<SkinningShaderConfigurationRequest>&& requests) const
{
- if (requests.empty())
+ if(requests.empty())
{
return;
}
SortAndDeduplicateSkinningRequests(requests);
- for (auto& i : requests)
+ for(auto& i : requests)
{
auto& skeleton = resources.mSkeletons[i.mSkeletonIdx];
- if (skeleton.mJoints.empty())
+ if(skeleton.mJoints.empty())
{
LOGD(("Skeleton %d has no joints.", i.mSkeletonIdx));
continue;
}
Index boneIdx = 0;
- for (auto& j : skeleton.mJoints)
+ for(auto& j : skeleton.mJoints)
{
- auto node = GetNode(j.mNodeIdx);
+ auto node = GetNode(j.mNodeIdx);
Actor actor = rootActor.FindChildByName(node->mName);
ConfigureBoneMatrix(j.mInverseBindMatrix, actor, i.mShader, boneIdx);
}
}
}
-bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources,
- Actor rootActor, std::vector<BlendshapeShaderConfigurationRequest>&& requests,
- StringCallback onError ) const
+bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources,
+ Actor rootActor,
+ std::vector<BlendshapeShaderConfigurationRequest>&& requests,
+ StringCallback onError) const
{
- if (requests.empty())
+ if(requests.empty())
{
return true;
}
std::sort(requests.begin(), requests.end());
// Remove duplicates.
- auto i = requests.begin();
- auto iEnd = requests.end();
- Shader s = i->mShader;
+ auto i = requests.begin();
+ auto iEnd = requests.end();
+ Shader s = i->mShader;
++i;
do
{
// Multiple identical shader instances are removed.
- while (i != iEnd && i->mShader == s)
+ while(i != iEnd && i->mShader == s)
{
i->mShader = Shader();
++i;
}
- if (i == iEnd)
+ if(i == iEnd)
{
break;
}
s = i->mShader;
++i;
- } while (true);
+ } while(true);
- requests.erase(std::remove_if(requests.begin(), requests.end(), [](const BlendshapeShaderConfigurationRequest& bscr)
- {
- return !bscr.mShader;
- }), requests.end());
+ requests.erase(std::remove_if(requests.begin(), requests.end(), [](const BlendshapeShaderConfigurationRequest& bscr) {
+ return !bscr.mShader;
+ }),
+ requests.end());
// Configure the rest.
bool ok = true;
- for (auto& i : requests)
+ for(auto& i : requests)
{
Index iNode;
- if (FindNode(i.mNodeName, &iNode))
+ if(FindNode(i.mNodeName, &iNode))
{
const auto& node = GetNode(iNode);
const auto& mesh = resources.mMeshes[i.mMeshIdx];
- if (mesh.first.HasBlendShapes())
+ if(mesh.first.HasBlendShapes())
{
Actor actor = rootActor.FindChildByName(node->mName);
void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const
{
std::map<Index, std::map<std::string, std::vector<Index*>>> blendShapeShaderUsers;
- for (auto& node : mNodes)
+ for(auto& node : mNodes)
{
- if (node->mRenderable)
+ if(node->mRenderable)
{
ResourceReflector reflector;
node->mRenderable->ReflectResources(reflector);
- if (reflector.iMesh)
+ if(reflector.iMesh)
{
const auto& mesh = resources.mMeshes[*reflector.iMesh].first;
- if (mesh.HasBlendShapes())
+ if(mesh.HasBlendShapes())
{
blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader);
}
}
}
- for (auto& users : blendShapeShaderUsers)
+ for(auto& users : blendShapeShaderUsers)
{
resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u);
const ShaderDefinition& shaderDef = resources.mShaders[users.first].first;
- auto nodesIt = users.second.begin();
+ auto nodesIt = users.second.begin();
auto nodesEndIt = users.second.end();
// skipping the first node.
++nodesIt;
while(nodesIt != nodesEndIt)
{
Index iShader = resources.mShaders.size();
- resources.mShaders.push_back({ shaderDef, Shader() });
+ resources.mShaders.push_back({shaderDef, Shader()});
auto& nodes = *nodesIt;
- for (auto& shader : nodes.second)
+ for(auto& shader : nodes.second)
{
*shader = iShader;
}
// We're searching from the end assuming a higher probability of operations targeting
// recently added nodes. (conf.: root, which is immovable, cannot be removed, and was
// the first to be added, is index 0.)
- auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(),
- [&name](const std::unique_ptr<NodeDefinition>& nd) {
- return nd->mName == name;
- }).base();
+ auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(), [&name](const std::unique_ptr<NodeDefinition>& nd) {
+ return nd->mName == name;
+ }).base();
const bool success = iFind != mNodes.begin();
- if (success && result)
+ if(success && result)
{
--iFind;
*result = &*iFind;
return success;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*
*/
-#include "dali-scene-loader/internal/hash.h"
#include "dali-scene-loader/public-api/shader-definition-factory.h"
-#include "dali-scene-loader/public-api/node-definition.h"
+#include <cstring>
+#include "dali-scene-loader/internal/hash.h"
#include "dali-scene-loader/public-api/blend-shape-details.h"
+#include "dali-scene-loader/public-api/node-definition.h"
#include "dali/devel-api/common/map-wrapper.h"
-#include <cstring>
namespace Dali
{
{
struct ResourceReceiver : IResourceReceiver
{
- const ResourceBundle& mResources;
- const MeshDefinition* mMeshDef = nullptr;
+ const ResourceBundle& mResources;
+ const MeshDefinition* mMeshDef = nullptr;
const MaterialDefinition* mMaterialDef = nullptr;
ResourceReceiver(const ResourceBundle& resources)
: mResources(resources)
- {}
+ {
+ }
void Register(ResourceType::Value type, Index id) override
{
- switch (type)
+ switch(type)
{
- case ResourceType::Mesh:
- mMeshDef = &mResources.mMeshes[id].first;
- break;
+ case ResourceType::Mesh:
+ mMeshDef = &mResources.mMeshes[id].first;
+ break;
- case ResourceType::Material:
- mMaterialDef = &mResources.mMaterials[id].first;
- break;
+ case ResourceType::Material:
+ mMaterialDef = &mResources.mMaterials[id].first;
+ break;
- default:
- break;
+ default:
+ break;
}
}
};
void RetrieveBlendShapeComponents(const std::vector<MeshDefinition::BlendShape>& blendShapes, bool& hasPositions, bool& hasNormals, bool& hasTangents)
{
- for (const auto& blendShape : blendShapes)
+ for(const auto& blendShape : blendShapes)
{
hasPositions = hasPositions || blendShape.deltas.IsDefined();
- hasNormals = hasNormals || blendShape.normals.IsDefined();
- hasTangents = hasTangents || blendShape.tangents.IsDefined();
+ hasNormals = hasNormals || blendShape.normals.IsDefined();
+ hasTangents = hasTangents || blendShape.tangents.IsDefined();
}
}
const bool hasTransparency = MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY);
hash.Add(hasTransparency);
- if (hasTransparency ||
- materialDef.CheckTextures(MaterialDefinition::ALBEDO) ||
- materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) ||
- materialDef.CheckTextures(MaterialDefinition::NORMAL))
+ if(hasTransparency ||
+ materialDef.CheckTextures(MaterialDefinition::ALBEDO) ||
+ materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) ||
+ materialDef.CheckTextures(MaterialDefinition::NORMAL))
{
hash.Add("3TEX");
}
- if (materialDef.GetAlphaCutoff() > 0.f)
+ if(materialDef.GetAlphaCutoff() > 0.f)
{
- hash.Add("ALPH"/*A_TEST*/);
+ hash.Add("ALPH" /*A_TEST*/);
}
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE))
{
hash.Add("SSS");
}
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::GLTF_CHANNELS))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::GLTF_CHANNELS))
{
- hash.Add("GLTF"/*_CHANNELS*/);
+ hash.Add("GLTF" /*_CHANNELS*/);
}
- if (meshDef.IsSkinned())
+ if(meshDef.IsSkinned())
{
- hash.Add("SKIN"/*NING*/);
+ hash.Add("SKIN" /*NING*/);
}
- if (MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL))
+ if(MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL))
{
- hash.Add("FLIP"/*_V*/);
+ hash.Add("FLIP" /*_V*/);
}
- if (meshDef.HasBlendShapes())
+ if(meshDef.HasBlendShapes())
{
bool hasPositions = false;
- bool hasNormals = false;
- bool hasTangents = false;
+ bool hasNormals = false;
+ bool hasTangents = false;
RetrieveBlendShapeComponents(meshDef.mBlendShapes, hasPositions, hasNormals, hasTangents);
- if (hasPositions)
+ if(hasPositions)
{
hash.Add("MORPHPOS");
}
- if (hasNormals)
+ if(hasNormals)
{
hash.Add("MORPHNOR");
}
- if (hasTangents)
+ if(hasTangents)
{
hash.Add("MORPHTAN");
}
- if (hasPositions || hasNormals || hasTangents)
+ if(hasPositions || hasNormals || hasTangents)
{
hash.Add("MORPH");
- if (BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion)
+ if(BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion)
{
hash.Add("MORPHV2");
}
return hash;
}
-}
+} // namespace
struct ShaderDefinitionFactory::Impl
{
- ResourceBundle* mResources; // no ownership
+ ResourceBundle* mResources; // no ownership
std::map<uint64_t, Index> mShaderMap;
};
ShaderDefinitionFactory::ShaderDefinitionFactory()
-: mImpl{ new Impl() }
-{}
+: mImpl{new Impl()}
+{
+}
ShaderDefinitionFactory::~ShaderDefinitionFactory() = default;
{
DALI_ASSERT_DEBUG(nodeDef.mRenderable);
- auto& resources = *mImpl->mResources;
- ResourceReceiver receiver{ resources };
+ auto& resources = *mImpl->mResources;
+ ResourceReceiver receiver{resources};
nodeDef.mRenderable->RegisterResources(receiver);
- if (!(receiver.mMeshDef && receiver.mMaterialDef))
+ if(!(receiver.mMeshDef && receiver.mMaterialDef))
{
return INVALID_INDEX;
}
- auto& shaderMap = mImpl->mShaderMap;
- uint64_t hash = HashNode(nodeDef, *receiver.mMaterialDef, *receiver.mMeshDef);
- auto iFind = shaderMap.find(hash);
- if (iFind != shaderMap.end())
+ auto& shaderMap = mImpl->mShaderMap;
+ uint64_t hash = HashNode(nodeDef, *receiver.mMaterialDef, *receiver.mMeshDef);
+ auto iFind = shaderMap.find(hash);
+ if(iFind != shaderMap.end())
{
return iFind->second;
}
ShaderDefinition shaderDef;
- shaderDef.mVertexShaderPath = PBR_SHADER_NAME + ".vsh";
+ shaderDef.mVertexShaderPath = PBR_SHADER_NAME + ".vsh";
shaderDef.mFragmentShaderPath = PBR_SHADER_NAME + ".fsh";
- shaderDef.mRendererState = RendererState::DEPTH_TEST | RendererState::DEPTH_WRITE | RendererState::CULL_BACK;
+ shaderDef.mRendererState = RendererState::DEPTH_TEST | RendererState::DEPTH_WRITE | RendererState::CULL_BACK;
- auto& materialDef = *receiver.mMaterialDef;
+ auto& materialDef = *receiver.mMaterialDef;
const bool hasTransparency = MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY);
- if (hasTransparency)
+ if(hasTransparency)
{
// TODO: this requires more granularity
shaderDef.mRendererState = (shaderDef.mRendererState | RendererState::ALPHA_BLEND) & ~RendererState::DEPTH_WRITE;
}
- if (hasTransparency ||
- materialDef.CheckTextures(MaterialDefinition::ALBEDO) ||
- materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) ||
- materialDef.CheckTextures(MaterialDefinition::NORMAL))
+ if(hasTransparency ||
+ materialDef.CheckTextures(MaterialDefinition::ALBEDO) ||
+ materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) ||
+ materialDef.CheckTextures(MaterialDefinition::NORMAL))
{
shaderDef.mDefines.push_back("THREE_TEX");
}
- if (materialDef.GetAlphaCutoff() > 0.f)
+ if(materialDef.GetAlphaCutoff() > 0.f)
{
shaderDef.mDefines.push_back("ALPHA_TEST");
}
- if (MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE))
+ if(MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE))
{
shaderDef.mDefines.push_back("SSS");
}
- if (MaskMatch(receiver.mMaterialDef->mFlags, MaterialDefinition::GLTF_CHANNELS))
+ if(MaskMatch(receiver.mMaterialDef->mFlags, MaterialDefinition::GLTF_CHANNELS))
{
shaderDef.mDefines.push_back("GLTF_CHANNELS");
}
const auto& meshDef = *receiver.mMeshDef;
- if (meshDef.IsSkinned())
+ if(meshDef.IsSkinned())
{
shaderDef.mDefines.push_back("SKINNING");
}
- if (MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL))
+ if(MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL))
{
shaderDef.mDefines.push_back("FLIP_V");
}
- if (meshDef.HasBlendShapes())
+ if(meshDef.HasBlendShapes())
{
bool hasPositions = false;
- bool hasNormals = false;
- bool hasTangents = false;
+ bool hasNormals = false;
+ bool hasTangents = false;
RetrieveBlendShapeComponents(meshDef.mBlendShapes, hasPositions, hasNormals, hasTangents);
- if (hasPositions)
+ if(hasPositions)
{
shaderDef.mDefines.push_back("MORPH_POSITION");
}
- if (hasNormals)
+ if(hasNormals)
{
shaderDef.mDefines.push_back("MORPH_NORMAL");
}
- if (hasTangents)
+ if(hasTangents)
{
shaderDef.mDefines.push_back("MORPH_TANGENT");
}
- if (hasPositions || hasNormals || hasTangents)
+ if(hasPositions || hasNormals || hasTangents)
{
shaderDef.mDefines.push_back("MORPH");
- if (BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion)
+ if(BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion)
{
shaderDef.mDefines.push_back("MORPH_VERSION_2_0");
}
}
}
- shaderDef.mUniforms["uMaxLOD"] = 6.f;
+ shaderDef.mUniforms["uMaxLOD"] = 6.f;
shaderDef.mUniforms["uCubeMatrix"] = Matrix::IDENTITY;
- Index result = resources.mShaders.size();
+ Index result = resources.mShaders.size();
shaderMap[hash] = result;
resources.mShaders.emplace_back(std::move(shaderDef), Shader());
return result;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace
{
-
const std::string SHADER_HINT_OUTPUT_IS_TRANSPARENT("OUTPUT_IS_TRANSPARENT"); ///< Might generate transparent alpha from opaque inputs.
-const std::string SHADER_HINT_MODIFIES_GEOMETRY("MODIFIES_GEOMETRY"); ///< Might change position of vertices, this option disables any culling optimizations.
+const std::string SHADER_HINT_MODIFIES_GEOMETRY("MODIFIES_GEOMETRY"); ///< Might change position of vertices, this option disables any culling optimizations.
-}
+} // namespace
ShaderDefinition::ShaderDefinition(const ShaderDefinition& other)
: mRendererState(other.mRendererState),
mDefines(other.mDefines),
mHints(other.mHints),
mUniforms(other.mUniforms)
-{}
+{
+}
void ShaderDefinition::ApplyDefine(std::string& shaderCode, const std::string& definevar)
{
const std::string IF_1 = "#if 1";
std::size_t found = shaderCode.find(definevar);
- while (found != std::string::npos)
+ while(found != std::string::npos)
{
// Greater then "@" character means is a letter,
// therefore is not has the definevar we looking for.
- if ((found + definevar.length()) < shaderCode.length() && shaderCode.at(found + definevar.length()) > '@')
+ if((found + definevar.length()) < shaderCode.length() && shaderCode.at(found + definevar.length()) > '@')
{
found = shaderCode.find(definevar, found + definevar.length());
continue;
}
- if (found > 0u && shaderCode.at(found - 1) > '@')
+ if(found > 0u && shaderCode.at(found - 1) > '@')
{
found = shaderCode.find(definevar, found + definevar.length());
continue;
}
- std::size_t defidx = shaderCode.rfind("#ifdef", found);
+ std::size_t defidx = shaderCode.rfind("#ifdef", found);
std::size_t newlineidx = shaderCode.rfind("\n", found);
- if (newlineidx < defidx && defidx != std::string::npos)
+ if(newlineidx < defidx && defidx != std::string::npos)
{
shaderCode.replace(defidx, found - defidx + definevar.length(), IF_1);
found = defidx + IF_1.length();
}
ShaderDefinition::RawData
- ShaderDefinition::LoadRaw(const std::string& shadersPath) const
+ShaderDefinition::LoadRaw(const std::string& shadersPath) const
{
RawData raw;
- bool fail = false;
+ bool fail = false;
raw.mVertexShaderSource = LoadTextFile((shadersPath + mVertexShaderPath).c_str(), &fail);
- if (!fail)
+ if(!fail)
{
raw.mFragmentShaderSource = LoadTextFile((shadersPath + mFragmentShaderPath).c_str(), &fail);
- if (!fail)
+ if(!fail)
{
- for (auto definevar : mDefines)
+ for(auto definevar : mDefines)
{
ApplyDefine(raw.mVertexShaderSource, definevar);
ApplyDefine(raw.mFragmentShaderSource, definevar);
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" <<
- shadersPath + mFragmentShaderPath << "'.";
+ ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << shadersPath + mFragmentShaderPath << "'.";
}
}
else
{
- ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" <<
- shadersPath + mVertexShaderPath << "'.";
+ ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << shadersPath + mVertexShaderPath << "'.";
}
return raw;
}
Shader ShaderDefinition::Load(RawData&& raw) const
{
uint32_t hints = Shader::Hint::NONE;
- for (const auto& hint : mHints)
+ for(const auto& hint : mHints)
{
- if (hint == SHADER_HINT_OUTPUT_IS_TRANSPARENT)
+ if(hint == SHADER_HINT_OUTPUT_IS_TRANSPARENT)
{
hints |= Shader::Hint::OUTPUT_IS_TRANSPARENT;
}
- else if (hint == SHADER_HINT_MODIFIES_GEOMETRY)
+ else if(hint == SHADER_HINT_MODIFIES_GEOMETRY)
{
hints |= Shader::Hint::MODIFIES_GEOMETRY;
}
}
- Shader shader = Shader::New(raw.mVertexShaderSource, raw.mFragmentShaderSource,
- static_cast<Shader::Hint::Value>(hints));
- for (Property::Map::SizeType i0 = 0, i1 = mUniforms.Count(); i0 != i1; ++i0)
+ Shader shader = Shader::New(raw.mVertexShaderSource, raw.mFragmentShaderSource, static_cast<Shader::Hint::Value>(hints));
+ for(Property::Map::SizeType i0 = 0, i1 = mUniforms.Count(); i0 != i1; ++i0)
{
auto pair = mUniforms.GetKeyValue(i0);
DALI_ASSERT_ALWAYS(pair.first.type == Property::Key::STRING);
return shader;
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
*/
#include "dali-scene-loader/public-api/skinning-details.h"
-#include "dali/public-api/rendering/shader.h"
-#include "dali/public-api/object/property.h"
#include "dali/public-api/animation/constraints.h"
+#include "dali/public-api/object/property.h"
+#include "dali/public-api/rendering/shader.h"
namespace Dali
{
namespace SceneLoader
{
-
const unsigned int Skinning::MAX_JOINTS = 64;
const std::string Skinning::BONE_UNIFORM_NAME = "uBone";
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
void DefaultErrorCallback(const std::string& message)
{
DALI_LOG_ERROR("%s", message.c_str());
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "dali-scene-loader/public-api/utils.h"
// EXTERNAL
-#include "dali/public-api/common/vector-wrapper.h"
-#include "dali/public-api/animation/constraints.h"
-#include <iostream>
-#include <fstream>
-#include <cstring>
#include <stdarg.h>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include "dali/public-api/animation/constraints.h"
+#include "dali/public-api/common/vector-wrapper.h"
namespace Dali
{
}
ExceptionFlinger::ExceptionFlinger(const char* location) noexcept(true)
-: mImpl{ location },
+: mImpl{location},
mStreamBuffer(GetMessageBuffer(), MESSAGE_BUFFER_SIZE - 1),
mStream(&mStreamBuffer)
-{}
+{
+}
ExceptionFlinger::~ExceptionFlinger() noexcept(false)
{
return result;
}
-std::string LoadTextFile(const char * path, bool* fail)
+std::string LoadTextFile(const char* path, bool* fail)
{
std::ifstream inFile(path);
- if (inFile)
+ if(inFile)
{
std::istreambuf_iterator<char> eos;
std::istreambuf_iterator<char> i(inFile.rdbuf());
return std::string(i, eos);
}
- else if (fail)
+ else if(fail)
{
*fail = true;
}
properties.Insert("aTexCoord", Property::VECTOR2);
std::vector<uint8_t> bytes;
- size_t stride = 0;
- size_t uvOffset = 0;
+ size_t stride = 0;
+ size_t uvOffset = 0;
struct
{
Vector3 aPosition;
Vector2 aTexCoord;
} vertices[] = {
- { Vector3(-0.5f, 0.5f, 0.0f), Vector2(0.0f, .0f) },
- { Vector3(0.5f, 0.5f, 0.0f), Vector2(1.0f, .0f) },
- { Vector3(-0.5f, -0.5f, 0.0f), Vector2(0.0f, 1.0f) },
- { Vector3(0.5f, -0.5f, 0.0f), Vector2(1.0f, 1.0f) }
- };
+ {Vector3(-0.5f, 0.5f, 0.0f), Vector2(0.0f, .0f)},
+ {Vector3(0.5f, 0.5f, 0.0f), Vector2(1.0f, .0f)},
+ {Vector3(-0.5f, -0.5f, 0.0f), Vector2(0.0f, 1.0f)},
+ {Vector3(0.5f, -0.5f, 0.0f), Vector2(1.0f, 1.0f)}};
bytes.resize(sizeof(vertices));
- stride = sizeof(vertices[0]);
+ stride = sizeof(vertices[0]);
uvOffset = reinterpret_cast<const uint8_t*>(&vertices[0].aTexCoord) - reinterpret_cast<const uint8_t*>(&vertices[0]);
std::memcpy(bytes.data(), vertices, sizeof(vertices));
- if (MaskMatch(options, TexturedQuadOptions::FLIP_VERTICAL))
+ if(MaskMatch(options, TexturedQuadOptions::FLIP_VERTICAL))
{
Vector2* uv = reinterpret_cast<Vector2*>(reinterpret_cast<uint8_t*>(bytes.data()) + uvOffset);
- for (int i = 0; i < 4; ++i)
+ for(int i = 0; i < 4; ++i)
{
uv->y = 1.0f - uv->y;
- uv = reinterpret_cast<Vector2*>(reinterpret_cast<uint8_t*>(uv) + stride);
+ uv = reinterpret_cast<Vector2*>(reinterpret_cast<uint8_t*>(uv) + stride);
}
}
std::replace(path.begin(), path.end(), '\\', '/');
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace SceneLoader
{
-
void ViewProjection::Update()
{
Matrix::Multiply(mViewProjection, mView, mProjection);
mInvProjection = mProjection;
- if (!mInvProjection.Invert())
+ if(!mInvProjection.Invert())
{
ExceptionFlinger(ASSERT_LOCATION) << "Failed to find inverse of projection matrix " << mProjection << ".";
}
}
-}
-}
+} // namespace SceneLoader
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
/**
* return true if the lower cased ASCII strings are equal.
*/
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/visual-factory/transition-data.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
-#include <dali-toolkit/public-api/controls/control.h>
#include <dali-toolkit/public-api/controls/control-impl.h>
+#include <dali-toolkit/public-api/controls/control.h>
namespace Dali
{
return controlDataImpl.GetVisualProperty(index, visualPropertyKey);
}
-static Toolkit::Internal::Control::Impl *GetControlImplementationIfAny( Dali::Actor actor)
+static Toolkit::Internal::Control::Impl* GetControlImplementationIfAny(Dali::Actor actor)
{
- Dali::Toolkit::Control c = Toolkit::Control::DownCast( actor );
- if ( c )
+ Dali::Toolkit::Control c = Toolkit::Control::DownCast(actor);
+ if(c)
{
- auto &impl1 = Toolkit::Internal::GetImplementation( c );
- auto &impl2 = Toolkit::Internal::Control::Impl::Get( impl1 );
+ auto& impl1 = Toolkit::Internal::GetImplementation(c);
+ auto& impl2 = Toolkit::Internal::Control::Impl::Get(impl1);
return &impl2;
}
return nullptr;
}
-Toolkit::DevelControl::AccessibilityActivateSignalType &AccessibilityActivateSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityActivateSignalType& AccessibilityActivateSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityActivateSignal;
}
-Toolkit::DevelControl::AccessibilityReadingSkippedSignalType &AccessibilityReadingSkippedSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityReadingSkippedSignalType& AccessibilityReadingSkippedSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityReadingSkippedSignal;
}
-Toolkit::DevelControl::AccessibilityReadingPausedSignalType &AccessibilityReadingPausedSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityReadingPausedSignalType& AccessibilityReadingPausedSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityReadingPausedSignal;
}
-Toolkit::DevelControl::AccessibilityReadingResumedSignalType &AccessibilityReadingResumedSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityReadingResumedSignalType& AccessibilityReadingResumedSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityReadingResumedSignal;
}
-Toolkit::DevelControl::AccessibilityReadingCancelledSignalType &AccessibilityReadingCancelledSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityReadingCancelledSignalType& AccessibilityReadingCancelledSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityReadingCancelledSignal;
}
-Toolkit::DevelControl::AccessibilityReadingStoppedSignalType &AccessibilityReadingStoppedSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityReadingStoppedSignalType& AccessibilityReadingStoppedSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityReadingStoppedSignal;
}
-Toolkit::DevelControl::AccessibilityGetNameSignalType &AccessibilityGetNameSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityGetNameSignalType& AccessibilityGetNameSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityGetNameSignal;
}
-Toolkit::DevelControl::AccessibilityGetDescriptionSignalType &AccessibilityGetDescriptionSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityGetDescriptionSignalType& AccessibilityGetDescriptionSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityGetDescriptionSignal;
}
-Toolkit::DevelControl::AccessibilityDoGestureSignalType &AccessibilityDoGestureSignal( Toolkit::Control control )
+Toolkit::DevelControl::AccessibilityDoGestureSignalType& AccessibilityDoGestureSignal(Toolkit::Control control)
{
- auto ac = GetControlImplementationIfAny ( control );
+ auto ac = GetControlImplementationIfAny(control);
return ac->mAccessibilityDoGestureSignal;
}
-void AppendAccessibilityRelation( Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation)
+void AppendAccessibilityRelation(Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
auto index = static_cast<Dali::Property::Array::SizeType>(relation);
- if (index >= ac->mAccessibilityRelations.size())
+ if(index >= ac->mAccessibilityRelations.size())
{
- DALI_LOG_ERROR( "Relation index exceeds vector size." );
- return;
+ DALI_LOG_ERROR("Relation index exceeds vector size.");
+ return;
}
auto obj = ac->GetAccessibilityObject(destination);
- if (obj)
+ if(obj)
ac->mAccessibilityRelations[index].push_back(obj->GetAddress());
}
}
-void RemoveAccessibilityRelation( Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation)
+void RemoveAccessibilityRelation(Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
auto index = static_cast<Dali::Property::Array::SizeType>(relation);
- if (index >= ac->mAccessibilityRelations.size())
+ if(index >= ac->mAccessibilityRelations.size())
{
- DALI_LOG_ERROR( "Relation index exceeds vector size." );
- return;
+ DALI_LOG_ERROR("Relation index exceeds vector size.");
+ return;
}
auto obj = ac->GetAccessibilityObject(destination);
- if (!obj)
+ if(!obj)
return;
auto address = obj->GetAddress();
- auto &targets = ac->mAccessibilityRelations[index];
- for (auto i = 0u; i < targets.size(); ++i) {
- if (targets[i].ToString() == address.ToString())
- {
- targets[i] = targets.back();
- targets.erase(targets.end() - 1);
- }
+ auto& targets = ac->mAccessibilityRelations[index];
+ for(auto i = 0u; i < targets.size(); ++i)
+ {
+ if(targets[i].ToString() == address.ToString())
+ {
+ targets[i] = targets.back();
+ targets.erase(targets.end() - 1);
+ }
}
}
}
-std::vector<std::vector<Accessibility::Address>> GetAccessibilityRelations( Dali::Actor control )
+std::vector<std::vector<Accessibility::Address>> GetAccessibilityRelations(Dali::Actor control)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
return ac->mAccessibilityRelations;
}
return {};
}
-void ClearAccessibilityRelations( Dali::Actor control )
+void ClearAccessibilityRelations(Dali::Actor control)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
- for (auto &it : ac->mAccessibilityRelations)
+ for(auto& it : ac->mAccessibilityRelations)
it.clear();
}
}
-void SetAccessibilityConstructor( Dali::Actor control,
- std::function< std::unique_ptr< Dali::Accessibility::Accessible >( Dali::Actor ) > constructor )
+void SetAccessibilityConstructor(Dali::Actor control,
+ std::function<std::unique_ptr<Dali::Accessibility::Accessible>(Dali::Actor)> constructor)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
ac->accessibilityConstructor = constructor;
}
}
-void AppendAccessibilityAttribute( Dali::Actor control, const std::string& key,
- const std::string value )
+void AppendAccessibilityAttribute(Dali::Actor control, const std::string& key, const std::string value)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
- ac->AppendAccessibilityAttribute( key, value );
+ ac->AppendAccessibilityAttribute(key, value);
}
}
-void RemoveAccessibilityAttribute( Dali::Actor control, const std::string& key )
+void RemoveAccessibilityAttribute(Dali::Actor control, const std::string& key)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
- ac->RemoveAccessibilityAttribute( key );
+ ac->RemoveAccessibilityAttribute(key);
}
}
-void ClearAccessibilityAttributes( Dali::Actor control )
+void ClearAccessibilityAttributes(Dali::Actor control)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
ac->ClearAccessibilityAttributes();
}
}
-void SetAccessibilityReadingInfoType( Dali::Actor control, const Dali::Accessibility::ReadingInfoTypes types )
+void SetAccessibilityReadingInfoType(Dali::Actor control, const Dali::Accessibility::ReadingInfoTypes types)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
- ac->SetAccessibilityReadingInfoType( types );
+ ac->SetAccessibilityReadingInfoType(types);
}
}
-Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingInfoType(Dali::Actor control )
+Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingInfoType(Dali::Actor control)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
return ac->GetAccessibilityReadingInfoType();
}
return {};
}
-bool ClearAccessibilityHighlight( Dali::Actor control )
+bool ClearAccessibilityHighlight(Dali::Actor control)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
- auto ptr = dynamic_cast<Dali::Accessibility::Component*>( ac->GetAccessibilityObject() );
- if( ptr )
+ auto ptr = dynamic_cast<Dali::Accessibility::Component*>(ac->GetAccessibilityObject());
+ if(ptr)
return ptr->ClearHighlight();
}
return false;
}
-bool GrabAccessibilityHighlight( Dali::Actor control )
+bool GrabAccessibilityHighlight(Dali::Actor control)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
- auto ptr = dynamic_cast<Dali::Accessibility::Component*>( ac->GetAccessibilityObject() );
- if( ptr )
+ auto ptr = dynamic_cast<Dali::Accessibility::Component*>(ac->GetAccessibilityObject());
+ if(ptr)
return ptr->GrabHighlight();
}
return false;
}
-Dali::Accessibility::States GetAccessibilityStates( Dali::Actor control )
+Dali::Accessibility::States GetAccessibilityStates(Dali::Actor control)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
- auto ptr = dynamic_cast<Dali::Accessibility::Component*>( ac->GetAccessibilityObject() );
+ auto ptr = dynamic_cast<Dali::Accessibility::Component*>(ac->GetAccessibilityObject());
if(ptr)
return ptr->GetStates();
}
return {};
}
-void NotifyAccessibilityStateChange( Dali::Actor control, Dali::Accessibility::States states, bool doRecursive )
+void NotifyAccessibilityStateChange(Dali::Actor control, Dali::Accessibility::States states, bool doRecursive)
{
- if ( auto ac = GetControlImplementationIfAny ( control ) )
+ if(auto ac = GetControlImplementationIfAny(control))
{
- ac->GetAccessibilityObject()->NotifyAccessibilityStateChange( std::move(states), doRecursive );
+ ac->GetAccessibilityObject()->NotifyAccessibilityStateChange(std::move(states), doRecursive);
}
}
-Dali::Accessibility::Accessible *GetBoundAccessibilityObject( Dali::Actor control )
+Dali::Accessibility::Accessible* GetBoundAccessibilityObject(Dali::Actor control)
{
- return Dali::Accessibility::Accessible::Get( control );
+ return Dali::Accessibility::Accessible::Get(control);
}
} // namespace DevelControl
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Toolkit
{
-
const std::string EMPTY_STRING;
-WebBackForwardListItem::WebBackForwardListItem( const Dali::WebEngineBackForwardListItem* item )
-: mWebEngineBackForwardListItem( item )
+WebBackForwardListItem::WebBackForwardListItem(const Dali::WebEngineBackForwardListItem* item)
+: mWebEngineBackForwardListItem(item)
{
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Toolkit
{
-
-WebBackForwardList::WebBackForwardList( const Dali::WebEngineBackForwardList& list )
-: mWebEngineBackForwardList( list )
-, mWebBackForwardListItem( 0 )
+WebBackForwardList::WebBackForwardList(const Dali::WebEngineBackForwardList& list)
+: mWebEngineBackForwardList(list),
+ mWebBackForwardListItem(0)
{
}
WebBackForwardListItem* WebBackForwardList::GetCurrentItem()
{
- mWebBackForwardListItem = WebBackForwardListItem( &mWebEngineBackForwardList.GetCurrentItem() );
+ mWebBackForwardListItem = WebBackForwardListItem(&mWebEngineBackForwardList.GetCurrentItem());
return &mWebBackForwardListItem;
}
-WebBackForwardListItem* WebBackForwardList::GetItemAtIndex( uint32_t index )
+WebBackForwardListItem* WebBackForwardList::GetItemAtIndex(uint32_t index)
{
- mWebBackForwardListItem = WebBackForwardListItem( &mWebEngineBackForwardList.GetItemAtIndex( index ) );
+ mWebBackForwardListItem = WebBackForwardListItem(&mWebEngineBackForwardList.GetItemAtIndex(index));
return &mWebBackForwardListItem;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Toolkit
{
-
-WebContext::WebContext( Dali::WebEngineContext& context)
-: mWebEngineContext( context )
+WebContext::WebContext(Dali::WebEngineContext& context)
+: mWebEngineContext(context)
{
}
return mWebEngineContext.GetCacheModel();
}
-void WebContext::SetCacheModel(Dali::WebEngineContext::CacheModel cacheModel )
+void WebContext::SetCacheModel(Dali::WebEngineContext::CacheModel cacheModel)
{
- mWebEngineContext.SetCacheModel( cacheModel );
+ mWebEngineContext.SetCacheModel(cacheModel);
}
-void WebContext::SetProxyUri( const std::string& uri )
+void WebContext::SetProxyUri(const std::string& uri)
{
- mWebEngineContext.SetProxyUri( uri );
+ mWebEngineContext.SetProxyUri(uri);
}
-void WebContext::SetCertificateFilePath( const std::string& certificatePath )
+void WebContext::SetCertificateFilePath(const std::string& certificatePath)
{
- mWebEngineContext.SetCertificateFilePath( certificatePath );
+ mWebEngineContext.SetCertificateFilePath(certificatePath);
}
-void WebContext::DisableCache( bool cacheDisabled )
+void WebContext::DisableCache(bool cacheDisabled)
{
- mWebEngineContext.DisableCache( cacheDisabled );
+ mWebEngineContext.DisableCache(cacheDisabled);
}
-void WebContext::SetDefaultProxyAuth( const std::string& username, const std::string& password )
+void WebContext::SetDefaultProxyAuth(const std::string& username, const std::string& password)
{
- mWebEngineContext.SetDefaultProxyAuth( username, password );
+ mWebEngineContext.SetDefaultProxyAuth(username, password);
}
void WebContext::DeleteWebDatabase()
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Toolkit
{
-
-WebCookieManager::WebCookieManager( Dali::WebEngineCookieManager& manager )
-: mWebEngineCookieManager( manager )
+WebCookieManager::WebCookieManager(Dali::WebEngineCookieManager& manager)
+: mWebEngineCookieManager(manager)
{
}
{
}
-void WebCookieManager::SetCookieAcceptPolicy( Dali::WebEngineCookieManager::CookieAcceptPolicy cookieAcceptPolicy )
+void WebCookieManager::SetCookieAcceptPolicy(Dali::WebEngineCookieManager::CookieAcceptPolicy cookieAcceptPolicy)
{
- mWebEngineCookieManager.SetCookieAcceptPolicy( cookieAcceptPolicy );
+ mWebEngineCookieManager.SetCookieAcceptPolicy(cookieAcceptPolicy);
}
Dali::WebEngineCookieManager::CookieAcceptPolicy WebCookieManager::GetCookieAcceptPolicy() const
mWebEngineCookieManager.ClearCookies();
}
-void WebCookieManager::SetPersistentStorage( const std::string& path, Dali::WebEngineCookieManager::CookiePersistentStorage storage )
+void WebCookieManager::SetPersistentStorage(const std::string& path, Dali::WebEngineCookieManager::CookiePersistentStorage storage)
{
- mWebEngineCookieManager.SetPersistentStorage( path, storage );
+ mWebEngineCookieManager.SetPersistentStorage(path, storage);
}
} // namespace Toolkit
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Toolkit
{
-
-WebSettings::WebSettings( Dali::WebEngineSettings& settings )
-: mWebEngineSettings( settings )
+WebSettings::WebSettings(Dali::WebEngineSettings& settings)
+: mWebEngineSettings(settings)
{
}
{
}
-void WebSettings::AllowMixedContents( bool allowed )
+void WebSettings::AllowMixedContents(bool allowed)
{
- mWebEngineSettings.AllowMixedContents( allowed );
+ mWebEngineSettings.AllowMixedContents(allowed);
}
-void WebSettings::EnableSpatialNavigation( bool enabled )
+void WebSettings::EnableSpatialNavigation(bool enabled)
{
- mWebEngineSettings.AllowMixedContents( enabled );
+ mWebEngineSettings.AllowMixedContents(enabled);
}
int WebSettings::GetDefaultFontSize() const
return mWebEngineSettings.GetDefaultFontSize();
}
-void WebSettings::SetDefaultFontSize( int defaultFontSize )
+void WebSettings::SetDefaultFontSize(int defaultFontSize)
{
- mWebEngineSettings.SetDefaultFontSize( defaultFontSize );
+ mWebEngineSettings.SetDefaultFontSize(defaultFontSize);
}
-void WebSettings::EnableWebSecurity( bool enabled )
+void WebSettings::EnableWebSecurity(bool enabled)
{
- mWebEngineSettings.EnableWebSecurity( enabled );
+ mWebEngineSettings.EnableWebSecurity(enabled);
}
-void WebSettings::AllowFileAccessFromExternalUrl( bool allowed )
+void WebSettings::AllowFileAccessFromExternalUrl(bool allowed)
{
- mWebEngineSettings.AllowFileAccessFromExternalUrl( allowed );
+ mWebEngineSettings.AllowFileAccessFromExternalUrl(allowed);
}
bool WebSettings::IsJavaScriptEnabled() const
return mWebEngineSettings.IsJavaScriptEnabled();
}
-void WebSettings::EnableJavaScript( bool enabled )
+void WebSettings::EnableJavaScript(bool enabled)
{
- mWebEngineSettings.EnableJavaScript( enabled );
+ mWebEngineSettings.EnableJavaScript(enabled);
}
-void WebSettings::AllowScriptsOpenWindows( bool allowed )
+void WebSettings::AllowScriptsOpenWindows(bool allowed)
{
- mWebEngineSettings.AllowScriptsOpenWindows( allowed );
+ mWebEngineSettings.AllowScriptsOpenWindows(allowed);
}
bool WebSettings::AreImagesLoadedAutomatically() const
return mWebEngineSettings.AreImagesLoadedAutomatically();
}
-void WebSettings::AllowImagesLoadAutomatically( bool automatic )
+void WebSettings::AllowImagesLoadAutomatically(bool automatic)
{
- mWebEngineSettings.AllowImagesLoadAutomatically( automatic );
+ mWebEngineSettings.AllowImagesLoadAutomatically(automatic);
}
std::string WebSettings::GetDefaultTextEncodingName() const
return mWebEngineSettings.GetDefaultTextEncodingName();
}
-void WebSettings::SetDefaultTextEncodingName( const std::string& defaultTextEncodingName )
+void WebSettings::SetDefaultTextEncodingName(const std::string& defaultTextEncodingName)
{
- mWebEngineSettings.SetDefaultTextEncodingName( defaultTextEncodingName );
+ mWebEngineSettings.SetDefaultTextEncodingName(defaultTextEncodingName);
}
} // namespace Toolkit
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
return Internal::WebView::New(locale, timezoneId);
}
-WebView WebView::New( int argc, char** argv )
+WebView WebView::New(int argc, char** argv)
{
- return Internal::WebView::New( argc, argv );
+ return Internal::WebView::New(argc, argv);
}
WebView WebView::DownCast(BaseHandle handle)
Dali::Toolkit::WebSettings* WebView::GetSettings() const
{
- return Dali::Toolkit::GetImpl( *this ).GetSettings();
+ return Dali::Toolkit::GetImpl(*this).GetSettings();
}
Dali::Toolkit::WebContext* WebView::GetContext() const
{
- return Dali::Toolkit::GetImpl( *this ).GetContext();
+ return Dali::Toolkit::GetImpl(*this).GetContext();
}
Dali::Toolkit::WebCookieManager* WebView::GetCookieManager() const
{
- return Dali::Toolkit::GetImpl( *this ).GetCookieManager();
+ return Dali::Toolkit::GetImpl(*this).GetCookieManager();
}
Dali::Toolkit::WebBackForwardList* WebView::GetBackForwardList() const
{
- return Dali::Toolkit::GetImpl( *this ).GetBackForwardList();
+ return Dali::Toolkit::GetImpl(*this).GetBackForwardList();
}
Dali::Toolkit::ImageView& WebView::GetFavicon()
{
- return Dali::Toolkit::GetImpl( *this ).GetFavicon();
+ return Dali::Toolkit::GetImpl(*this).GetFavicon();
}
void WebView::LoadUrl(const std::string& url)
Dali::Toolkit::GetImpl(*this).Resume();
}
-void WebView::ScrollBy( int deltaX, int deltaY )
+void WebView::ScrollBy(int deltaX, int deltaY)
{
- Dali::Toolkit::GetImpl( *this ).ScrollBy( deltaX, deltaY );
+ Dali::Toolkit::GetImpl(*this).ScrollBy(deltaX, deltaY);
}
bool WebView::CanGoForward()
void WebView::ClearAllTilesResources()
{
- Dali::Toolkit::GetImpl( *this ).ClearAllTilesResources();
+ Dali::Toolkit::GetImpl(*this).ClearAllTilesResources();
}
void WebView::ClearHistory()
WebView::WebViewScrollEdgeReachedSignalType& WebView::ScrollEdgeReachedSignal()
{
- return Dali::Toolkit::GetImpl( *this ).ScrollEdgeReachedSignal();
+ return Dali::Toolkit::GetImpl(*this).ScrollEdgeReachedSignal();
}
WebView::WebView(Internal::WebView& implementation)
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Toolkit::Flex::SizeTuple nodeSize{8, 8}; // Default size set to 8,8 to aid bug detection.
if(mImpl->mMeasureCallback && mImpl->mActor.GetHandle())
{
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode MeasureCallback executing on %s\n", mImpl->mActor.GetHandle().GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str());
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode MeasureCallback executing on %s\n", mImpl->mActor.GetHandle().GetProperty<std::string>(Dali::Actor::Property::NAME).c_str());
mImpl->mMeasureCallback(mImpl->mActor.GetHandle(), width, widthMode, height, heightMode, &nodeSize);
}
DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode nodeSize width:%f height:%f\n", nodeSize.width, nodeSize.height);
#include <dali-toolkit/devel-api/shader-effects/alpha-discard-effect.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
namespace Toolkit
{
-
Property::Map CreateAlphaDiscardEffect()
{
Property::Map map;
namespace Dali
{
-
namespace Toolkit
{
-
-void DissolveEffectSetCentralLine( Actor& actor, const Vector2& position, const Vector2& displacement, float initialProgress )
+void DissolveEffectSetCentralLine(Actor& actor, const Vector2& position, const Vector2& displacement, float initialProgress)
{
// the line passes through 'position' and has the direction of 'displacement'
float coefA, coefB, coefC; //line equation: Ax+By+C=0;
actor.RegisterProperty("uPercentage", initialProgress, Dali::Property::ANIMATABLE);
}
-Property::Map CreateDissolveEffect( bool useHighPrecision )
+Property::Map CreateDissolveEffect(bool useHighPrecision)
{
const char* prefixHighPrecision("precision highp float;\n");
const char* prefixMediumPrecision("precision mediump float;\n");
- const char* vertexShader = SHADER_DISSOLVE_EFFECT_VERT.data();
+ const char* vertexShader = SHADER_DISSOLVE_EFFECT_VERT.data();
const char* fragmentShader = SHADER_DISSOLVE_EFFECT_FRAG.data();
Property::Map map;
#include <dali-toolkit/devel-api/shader-effects/distance-field-effect.h>
// EXTERNAL INCLUDES
-#include <string.h>
#include <dali/public-api/rendering/shader.h>
+#include <string.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
Dali::Property::Map CreateDistanceFieldEffect()
{
const char* fragmentShaderPrefix("#extension GL_OES_standard_derivatives : enable\n");
#include <dali-toolkit/devel-api/shader-effects/image-region-effect.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
namespace Toolkit
{
-
Property::Map CreateImageRegionEffect()
{
Property::Map map;
return map;
}
-} // Toolkit
+} // namespace Toolkit
-} // Dali
+} // namespace Dali
#include <dali/public-api/rendering/shader.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
namespace Toolkit
{
-
-void SetMotionBlurProperties( Actor& actor, unsigned int numBlurSamples )
+void SetMotionBlurProperties(Actor& actor, unsigned int numBlurSamples)
{
actor.RegisterProperty("uBlurTexCoordScale", 0.125f);
actor.RegisterProperty("uGeometryStretchFactor", 0.05f);
constraint.Apply();
}
-
Property::Map CreateMotionBlurEffect()
{
Property::Map map;
return map;
}
-} // Toolkit
-} // Dali
+} // namespace Toolkit
+} // namespace Dali
#include <dali/public-api/rendering/shader.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
namespace Toolkit
{
-
-void SetMotionStretchProperties( Actor& actor )
+void SetMotionStretchProperties(Actor& actor)
{
actor.RegisterProperty("uGeometryStretchFactor", 0.5f);
actor.RegisterProperty("uSpeedScalingFactor", 0.5f);
return map;
}
-
-} // Toolkit
-} // Dali
+} // namespace Toolkit
+} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// Set the layout parameters.
Size textLayoutArea = Size(static_cast<float>(textParameters.textWidth),
- static_cast<float>(textParameters.textHeight));
+ static_cast<float>(textParameters.textHeight));
// padding
- Extents padding = textParameters.padding;
- internalDataModel.textLayoutArea = Size(textLayoutArea.x - ( padding.start + padding.end ), textLayoutArea.y - ( padding.top + padding.bottom ) );
-
+ Extents padding = textParameters.padding;
+ internalDataModel.textLayoutArea = Size(textLayoutArea.x - (padding.start + padding.end), textLayoutArea.y - (padding.top + padding.bottom));
if(isCircularTextLayout)
{
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "accessibility-manager-impl.h"
// EXTERNAL INCLUDES
-#include <dali/devel-api/adaptor-framework/accessibility.h>
#include <dali/devel-api/adaptor-framework/accessibility-impl.h>
+#include <dali/devel-api/adaptor-framework/accessibility.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/control.h>
-#include <dali-toolkit/public-api/controls/control-impl.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
+#include <dali-toolkit/public-api/controls/control-impl.h>
+#include <dali-toolkit/public-api/controls/control.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
AccessibilityManager::AccessibilityManager()
{
- mFocusOrder.push_back( {} ); // zero has a special meaning
+ mFocusOrder.push_back({}); // zero has a special meaning
}
AccessibilityManager::~AccessibilityManager()
void AccessibilityManager::SetAccessibilityAttribute(Actor actor, Toolkit::AccessibilityManager::AccessibilityAttribute type, const std::string& text)
{
- switch ( type )
+ switch(type)
{
- case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL:
- actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, text );
- break;
-
- case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT:
- actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, text );
- break;
-
- case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT:
- case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE:
- default:
- break;
+ case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL:
+ actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, text);
+ break;
+
+ case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT:
+ actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, text);
+ break;
+
+ case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT:
+ case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE:
+ default:
+ break;
}
}
std::string AccessibilityManager::GetAccessibilityAttribute(Actor actor, Toolkit::AccessibilityManager::AccessibilityAttribute type) const
{
- switch ( type )
+ switch(type)
{
- case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL:
- return actor.GetProperty< std::string >( Toolkit::DevelControl::Property::ACCESSIBILITY_NAME );
+ case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL:
+ return actor.GetProperty<std::string>(Toolkit::DevelControl::Property::ACCESSIBILITY_NAME);
- case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT:
- return actor.GetProperty< std::string >( Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION );
+ case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT:
+ return actor.GetProperty<std::string>(Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION);
- case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT:
- case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE:
- default:
- return "";
+ case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT:
+ case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE:
+ default:
+ return "";
}
}
void AccessibilityManager::SetFocusOrder(Actor actor, const unsigned int order)
{
- if (order == 0)
+ if(order == 0)
return;
- if (order >= mFocusOrder.size())
+ if(order >= mFocusOrder.size())
mFocusOrder.resize(order + 1);
auto it = mFocusOrder.begin() + order;
mFocusOrder.insert(it, actor);
- if (order > 0)
+ if(order > 0)
{
Actor prev = mFocusOrder[order - 1];
- DevelControl::AppendAccessibilityRelation( prev, actor, Accessibility::RelationType::FLOWS_TO );
- DevelControl::AppendAccessibilityRelation( actor, prev, Accessibility::RelationType::FLOWS_FROM );
+ DevelControl::AppendAccessibilityRelation(prev, actor, Accessibility::RelationType::FLOWS_TO);
+ DevelControl::AppendAccessibilityRelation(actor, prev, Accessibility::RelationType::FLOWS_FROM);
}
- if (order + 1 < mFocusOrder.size())
+ if(order + 1 < mFocusOrder.size())
{
Actor next = mFocusOrder[order + 1];
- DevelControl::AppendAccessibilityRelation( actor, next, Accessibility::RelationType::FLOWS_TO );
- DevelControl::AppendAccessibilityRelation( next, actor, Accessibility::RelationType::FLOWS_FROM );
+ DevelControl::AppendAccessibilityRelation(actor, next, Accessibility::RelationType::FLOWS_TO);
+ DevelControl::AppendAccessibilityRelation(next, actor, Accessibility::RelationType::FLOWS_FROM);
}
}
unsigned int AccessibilityManager::GetFocusOrder(Actor actor) const
{
- for (auto it = mFocusOrder.begin(); it != mFocusOrder.end(); ++it)
+ for(auto it = mFocusOrder.begin(); it != mFocusOrder.end(); ++it)
{
- if (actor == *it)
+ if(actor == *it)
return it - mFocusOrder.begin();
}
{
Actor actor;
- if (order > 0 && order < mFocusOrder.size())
+ if(order > 0 && order < mFocusOrder.size())
actor = mFocusOrder[order];
return actor;
unsigned int AccessibilityManager::GetCurrentFocusOrder()
{
- auto actor = GetCurrentFocusActor();
+ auto actor = GetCurrentFocusActor();
unsigned order = 0;
- if (actor)
- order = GetFocusOrder( actor );
+ if(actor)
+ order = GetFocusOrder(actor);
return order;
}
{
unsigned current = GetCurrentFocusOrder();
- if (current + 1 < mFocusOrder.size())
+ if(current + 1 < mFocusOrder.size())
return SetCurrentFocusActor(mFocusOrder[current + 1]);
return false;
{
unsigned current = GetCurrentFocusOrder();
- if (current > 1) // zero has a special meaning
+ if(current > 1) // zero has a special meaning
return SetCurrentFocusActor(mFocusOrder[current - 1]);
return false;
void AccessibilityManager::ClearFocus()
{
auto actor = GetCurrentFocusActor();
- Toolkit::DevelControl::ClearAccessibilityHighlight( actor );
+ Toolkit::DevelControl::ClearAccessibilityHighlight(actor);
}
void AccessibilityManager::Reset()
{
ClearFocus();
- for (std::size_t i = 2; i < mFocusOrder.size(); ++i)
+ for(std::size_t i = 2; i < mFocusOrder.size(); ++i)
{
Actor prev = mFocusOrder[i - 1];
Actor next = mFocusOrder[i];
- DevelControl::RemoveAccessibilityRelation( prev, next, Accessibility::RelationType::FLOWS_TO );
- DevelControl::RemoveAccessibilityRelation( next, prev, Accessibility::RelationType::FLOWS_FROM );
+ DevelControl::RemoveAccessibilityRelation(prev, next, Accessibility::RelationType::FLOWS_TO);
+ DevelControl::RemoveAccessibilityRelation(next, prev, Accessibility::RelationType::FLOWS_FROM);
}
mFocusOrder.clear();
- mFocusOrder.push_back( {} );
+ mFocusOrder.push_back({});
}
void AccessibilityManager::SetFocusGroup(Actor actor, bool isFocusGroup)
void AccessibilityManager::SetFocusIndicatorActor(Actor indicator)
{
- Dali::Accessibility::Accessible::SetHighlightActor( indicator );
+ Dali::Accessibility::Accessible::SetHighlightActor(indicator);
}
Actor AccessibilityManager::GetFocusIndicatorActor()
*/
// EXTERNAL INCLUDES
-#include <dali/public-api/actors/layer.h>
#include <dali/devel-api/common/stage.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/actors/layer.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/builder/builder-impl.h>
#include <dali-toolkit/internal/builder/builder-get-is.inl.h>
+#include <dali-toolkit/internal/builder/builder-impl.h>
#include <dali-toolkit/internal/builder/replacement.h>
namespace // unnamed namespace
{
-
using namespace Dali;
-TimePeriod GetTimePeriod( const TreeNode& child, const Toolkit::Internal::Replacement& constant )
+TimePeriod GetTimePeriod(const TreeNode& child, const Toolkit::Internal::Replacement& constant)
{
- OptionalFloat delay = constant.IsFloat( IsChild(child, "delay" ) );
- OptionalFloat duration = constant.IsFloat( IsChild(child, "duration" ) );
- DALI_ASSERT_ALWAYS( duration && "Time period must have at least a duration" );
+ OptionalFloat delay = constant.IsFloat(IsChild(child, "delay"));
+ OptionalFloat duration = constant.IsFloat(IsChild(child, "duration"));
+ DALI_ASSERT_ALWAYS(duration && "Time period must have at least a duration");
- if( delay )
+ if(delay)
{
- return TimePeriod( *delay, *duration );
+ return TimePeriod(*delay, *duration);
}
else
{
- return TimePeriod( *duration );
+ return TimePeriod(*duration);
}
}
-Property::Value GetPropertyValue( const Property::Type& propType, const TreeNode& child )
+Property::Value GetPropertyValue(const Property::Type& propType, const TreeNode& child)
{
- switch ( propType )
+ switch(propType)
{
case Property::BOOLEAN:
{
- return Property::Value( GetBoolean( child ) );
+ return Property::Value(GetBoolean(child));
}
case Property::FLOAT:
{
- return Property::Value( GetFloat( child ) );
+ return Property::Value(GetFloat(child));
}
case Property::VECTOR2:
{
- return Property::Value( GetVector2( child ) );
+ return Property::Value(GetVector2(child));
}
case Property::VECTOR3:
{
- return Property::Value( GetVector3( child ) );
+ return Property::Value(GetVector3(child));
}
case Property::VECTOR4:
{
- return Property::Value( GetVector4( child ) );
+ return Property::Value(GetVector4(child));
}
case Property::ROTATION:
{
- if( 4 == child.Size() )
+ if(4 == child.Size())
{
Vector4 v(GetVector4(child));
// angle, axis as per spec
- return Property::Value( Quaternion(Radian(Degree(v[3])),
- Vector3(v[0],v[1],v[2])) );
+ return Property::Value(Quaternion(Radian(Degree(v[3])),
+ Vector3(v[0], v[1], v[2])));
}
else
{
// degrees as per spec
- Vector3 rotation = GetVector3( child );
- return Property::Value( Quaternion(Radian(Degree(rotation.x)),
- Radian(Degree(rotation.y)),
- Radian(Degree(rotation.z))) );
+ Vector3 rotation = GetVector3(child);
+ return Property::Value(Quaternion(Radian(Degree(rotation.x)),
+ Radian(Degree(rotation.y)),
+ Radian(Degree(rotation.z))));
}
}
case Property::NONE: // fall
default:
{
- DALI_ASSERT_ALWAYS( !"Property type incorrect" );
+ DALI_ASSERT_ALWAYS(!"Property type incorrect");
}
}
}
-AlphaFunction GetAlphaFunction( const std::string& alphaFunction )
+AlphaFunction GetAlphaFunction(const std::string& alphaFunction)
{
- typedef std::map< const std::string, Dali::AlphaFunction > AlphaFunctionLut;
- static AlphaFunctionLut alphaFunctionLut;
+ typedef std::map<const std::string, Dali::AlphaFunction> AlphaFunctionLut;
+ static AlphaFunctionLut alphaFunctionLut;
- if( 0 == alphaFunctionLut.size() )
+ if(0 == alphaFunctionLut.size())
{
// coding convention is uppercase enums
- alphaFunctionLut["DEFAULT"] = AlphaFunction(AlphaFunction::DEFAULT);
- alphaFunctionLut["LINEAR"] = AlphaFunction(AlphaFunction::LINEAR);
- alphaFunctionLut["REVERSE"] = AlphaFunction(AlphaFunction::REVERSE);
- alphaFunctionLut["EASE_IN_SQUARE"] = AlphaFunction(AlphaFunction::EASE_IN_SQUARE);
- alphaFunctionLut["EASE_OUT_SQUARE"] = AlphaFunction(AlphaFunction::EASE_OUT_SQUARE);
- alphaFunctionLut["EASE_IN"] = AlphaFunction(AlphaFunction::EASE_IN);
- alphaFunctionLut["EASE_OUT"] = AlphaFunction(AlphaFunction::EASE_OUT);
- alphaFunctionLut["EASE_IN_OUT"] = AlphaFunction(AlphaFunction::EASE_IN_OUT);
- alphaFunctionLut["EASE_IN_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_SINE);
- alphaFunctionLut["EASE_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_OUT_SINE);
- alphaFunctionLut["EASE_IN_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_OUT_SINE);
- alphaFunctionLut["BOUNCE"] = AlphaFunction(AlphaFunction::BOUNCE);
- alphaFunctionLut["SIN"] = AlphaFunction(AlphaFunction::SIN);
- alphaFunctionLut["EASE_OUT_BACK"] = AlphaFunction(AlphaFunction::EASE_OUT_BACK);
+ alphaFunctionLut["DEFAULT"] = AlphaFunction(AlphaFunction::DEFAULT);
+ alphaFunctionLut["LINEAR"] = AlphaFunction(AlphaFunction::LINEAR);
+ alphaFunctionLut["REVERSE"] = AlphaFunction(AlphaFunction::REVERSE);
+ alphaFunctionLut["EASE_IN_SQUARE"] = AlphaFunction(AlphaFunction::EASE_IN_SQUARE);
+ alphaFunctionLut["EASE_OUT_SQUARE"] = AlphaFunction(AlphaFunction::EASE_OUT_SQUARE);
+ alphaFunctionLut["EASE_IN"] = AlphaFunction(AlphaFunction::EASE_IN);
+ alphaFunctionLut["EASE_OUT"] = AlphaFunction(AlphaFunction::EASE_OUT);
+ alphaFunctionLut["EASE_IN_OUT"] = AlphaFunction(AlphaFunction::EASE_IN_OUT);
+ alphaFunctionLut["EASE_IN_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_SINE);
+ alphaFunctionLut["EASE_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_OUT_SINE);
+ alphaFunctionLut["EASE_IN_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_OUT_SINE);
+ alphaFunctionLut["BOUNCE"] = AlphaFunction(AlphaFunction::BOUNCE);
+ alphaFunctionLut["SIN"] = AlphaFunction(AlphaFunction::SIN);
+ alphaFunctionLut["EASE_OUT_BACK"] = AlphaFunction(AlphaFunction::EASE_OUT_BACK);
}
- const AlphaFunctionLut::const_iterator iter( alphaFunctionLut.find( alphaFunction ) );
+ const AlphaFunctionLut::const_iterator iter(alphaFunctionLut.find(alphaFunction));
- if( iter != alphaFunctionLut.end() )
+ if(iter != alphaFunctionLut.end())
{
return iter->second;
}
else
{
- DALI_ASSERT_ALWAYS( iter != alphaFunctionLut.end() && "Unknown Alpha Constant" );
+ DALI_ASSERT_ALWAYS(iter != alphaFunctionLut.end() && "Unknown Alpha Constant");
return Dali::AlphaFunction::DEFAULT;
}
}
} // unnamed namespace
-
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-Animation CreateAnimation( const TreeNode& child, const Replacement& constant, Dali::Actor searchRoot, Builder* const builder )
+Animation CreateAnimation(const TreeNode& child, const Replacement& constant, Dali::Actor searchRoot, Builder* const builder)
{
float durationSum = 0.f;
Dali::Actor searchActor = searchRoot ? searchRoot : Dali::Stage::GetCurrent().GetRootLayer();
- Animation animation( Animation::New( 0.f ) );
+ Animation animation(Animation::New(0.f));
// duration needs to be set before AnimateTo calls for correct operation when AnimateTo has no "timePeriod".
- OptionalFloat duration = constant.IsFloat( IsChild(child, "duration" ) );
+ OptionalFloat duration = constant.IsFloat(IsChild(child, "duration"));
- if( duration )
+ if(duration)
{
- animation.SetDuration( *duration );
+ animation.SetDuration(*duration);
}
- if( OptionalBoolean looping = constant.IsBoolean( IsChild(child, "loop" ) ) )
+ if(OptionalBoolean looping = constant.IsBoolean(IsChild(child, "loop")))
{
- animation.SetLooping( *looping );
+ animation.SetLooping(*looping);
}
- if( OptionalString endAction = constant.IsString( IsChild(child, "endAction" ) ) )
+ if(OptionalString endAction = constant.IsString(IsChild(child, "endAction")))
{
if("BAKE" == *endAction)
{
- animation.SetEndAction( Animation::BAKE );
+ animation.SetEndAction(Animation::BAKE);
}
else if("DISCARD" == *endAction)
{
- animation.SetEndAction( Animation::DISCARD );
+ animation.SetEndAction(Animation::DISCARD);
}
else if("BAKE_FINAL" == *endAction)
{
- animation.SetEndAction( Animation::BAKE_FINAL );
+ animation.SetEndAction(Animation::BAKE_FINAL);
}
}
- if( OptionalString endAction = constant.IsString( IsChild(child, "disconnectAction" ) ) )
+ if(OptionalString endAction = constant.IsString(IsChild(child, "disconnectAction")))
{
if("BAKE" == *endAction)
{
- animation.SetDisconnectAction( Animation::BAKE );
+ animation.SetDisconnectAction(Animation::BAKE);
}
else if("DISCARD" == *endAction)
{
- animation.SetDisconnectAction( Animation::DISCARD );
+ animation.SetDisconnectAction(Animation::DISCARD);
}
else if("BAKE_FINAL" == *endAction)
{
- animation.SetDisconnectAction( Animation::BAKE_FINAL );
+ animation.SetDisconnectAction(Animation::BAKE_FINAL);
}
}
- OptionalChild propertiesNode = IsChild(child, "properties" );
+ OptionalChild propertiesNode = IsChild(child, "properties");
if(propertiesNode)
{
const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd();
- for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter )
+ for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter)
{
const TreeNode::KeyNodePair& pKeyChild = *iter;
- OptionalString actorName( constant.IsString( IsChild(pKeyChild.second, "actor" ) ) );
- OptionalString property( constant.IsString( IsChild(pKeyChild.second, "property" ) ) );
- DALI_ASSERT_ALWAYS( actorName && "Animation must specify actor name" );
+ OptionalString actorName(constant.IsString(IsChild(pKeyChild.second, "actor")));
+ OptionalString property(constant.IsString(IsChild(pKeyChild.second, "property")));
+ DALI_ASSERT_ALWAYS(actorName && "Animation must specify actor name");
- Handle targetHandle = searchActor.FindChildByName( *actorName );
- DALI_ASSERT_ALWAYS( targetHandle && "Actor must exist for property" );
+ Handle targetHandle = searchActor.FindChildByName(*actorName);
+ DALI_ASSERT_ALWAYS(targetHandle && "Actor must exist for property");
Property::Value propValue;
Property::Index propIndex = Property::INVALID_INDEX;
- if( property )
+ if(property)
{
- propIndex = targetHandle.GetPropertyIndex( *property );
+ propIndex = targetHandle.GetPropertyIndex(*property);
// if the property is not found from the (actor) handle, try to downcast it to renderable actor
// to allow animating shader uniforms
- if( propIndex == Property::INVALID_INDEX )
+ if(propIndex == Property::INVALID_INDEX)
{
- DALI_SCRIPT_WARNING( "Cannot find property on object\n" );
- continue;
+ DALI_SCRIPT_WARNING("Cannot find property on object\n");
+ continue;
}
}
// these are the defaults
- AlphaFunction alphaFunction( AlphaFunction::DEFAULT );
- TimePeriod timePeriod( 0.f );
+ AlphaFunction alphaFunction(AlphaFunction::DEFAULT);
+ TimePeriod timePeriod(0.f);
- OptionalChild timeChild = IsChild( pKeyChild.second, "timePeriod" );
+ OptionalChild timeChild = IsChild(pKeyChild.second, "timePeriod");
- if( timeChild )
+ if(timeChild)
{
- timePeriod = GetTimePeriod( *timeChild, constant );
+ timePeriod = GetTimePeriod(*timeChild, constant);
}
- durationSum = std::max( durationSum, timePeriod.delaySeconds + timePeriod.durationSeconds );
+ durationSum = std::max(durationSum, timePeriod.delaySeconds + timePeriod.durationSeconds);
- if( OptionalString alphaChild = constant.IsString( IsChild(pKeyChild.second, "alphaFunction" ) ) )
+ if(OptionalString alphaChild = constant.IsString(IsChild(pKeyChild.second, "alphaFunction")))
{
- alphaFunction = GetAlphaFunction( *alphaChild );
+ alphaFunction = GetAlphaFunction(*alphaChild);
}
- if( OptionalChild keyFrameChild = IsChild(pKeyChild.second, "keyFrames") )
+ if(OptionalChild keyFrameChild = IsChild(pKeyChild.second, "keyFrames"))
{
- DALI_ASSERT_ALWAYS( property && "Animation must specify a property name" );
- Property prop = Property( targetHandle, propIndex );
+ DALI_ASSERT_ALWAYS(property && "Animation must specify a property name");
+ Property prop = Property(targetHandle, propIndex);
KeyFrames keyframes = KeyFrames::New();
const TreeNode::ConstIterator endIter = (*keyFrameChild).CEnd();
- for( TreeNode::ConstIterator iter = (*keyFrameChild).CBegin(); endIter != iter; ++iter )
+ for(TreeNode::ConstIterator iter = (*keyFrameChild).CBegin(); endIter != iter; ++iter)
{
const TreeNode::KeyNodePair& kfKeyChild = *iter;
- OptionalFloat kfProgress = constant.IsFloat( IsChild(kfKeyChild.second, "progress" ) );
- DALI_ASSERT_ALWAYS( kfProgress && "Key frame entry must have 'progress'" );
+ OptionalFloat kfProgress = constant.IsFloat(IsChild(kfKeyChild.second, "progress"));
+ DALI_ASSERT_ALWAYS(kfProgress && "Key frame entry must have 'progress'");
- OptionalChild kfValue = IsChild( kfKeyChild.second, "value" );
- DALI_ASSERT_ALWAYS( kfValue && "Key frame entry must have 'value'" );
+ OptionalChild kfValue = IsChild(kfKeyChild.second, "value");
+ DALI_ASSERT_ALWAYS(kfValue && "Key frame entry must have 'value'");
try
{
- propValue = GetPropertyValue( prop.object.GetPropertyType(prop.propertyIndex), *kfValue );
+ propValue = GetPropertyValue(prop.object.GetPropertyType(prop.propertyIndex), *kfValue);
}
catch(...)
{
- DALI_LOG_WARNING( "Property:'%s' type does not match value type '%s'\n",
- (*property).c_str(),
- PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex)) );
+ DALI_LOG_WARNING("Property:'%s' type does not match value type '%s'\n",
+ (*property).c_str(),
+ PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex)));
throw;
}
- AlphaFunction kfAlphaFunction( AlphaFunction::DEFAULT );
- if( OptionalString alphaFuncStr = constant.IsString( IsChild(pKeyChild.second, "alphaFunction") ) )
+ AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT);
+ if(OptionalString alphaFuncStr = constant.IsString(IsChild(pKeyChild.second, "alphaFunction")))
{
- kfAlphaFunction = GetAlphaFunction( *alphaFuncStr );
+ kfAlphaFunction = GetAlphaFunction(*alphaFuncStr);
}
- keyframes.Add( *kfProgress, propValue, kfAlphaFunction );
+ keyframes.Add(*kfProgress, propValue, kfAlphaFunction);
}
- if( timeChild )
+ if(timeChild)
{
- animation.AnimateBetween( prop, keyframes, alphaFunction, timePeriod );
+ animation.AnimateBetween(prop, keyframes, alphaFunction, timePeriod);
}
else
{
- animation.AnimateBetween( prop, keyframes, alphaFunction );
+ animation.AnimateBetween(prop, keyframes, alphaFunction);
}
}
- else if( OptionalString pathChild = IsString(pKeyChild.second, "path") )
+ else if(OptionalString pathChild = IsString(pKeyChild.second, "path"))
{
//Get path
Path path = builder->GetPath(*pathChild);
- if( path )
+ if(path)
{
//Get forward vector if specified
- Vector3 forward( 0.0f, 0.0f, 0.0f );
- OptionalVector3 forwardProperty = constant.IsVector3( IsChild(pKeyChild.second, "forward" ) );
- if( forwardProperty )
+ Vector3 forward(0.0f, 0.0f, 0.0f);
+ OptionalVector3 forwardProperty = constant.IsVector3(IsChild(pKeyChild.second, "forward"));
+ if(forwardProperty)
{
forward = *forwardProperty;
}
- Actor actor = Actor::DownCast( targetHandle );
- if( actor )
+ Actor actor = Actor::DownCast(targetHandle);
+ if(actor)
{
- if( timeChild )
+ if(timeChild)
{
- animation.Animate( actor, path, forward, alphaFunction, timePeriod );
+ animation.Animate(actor, path, forward, alphaFunction, timePeriod);
}
else
{
- animation.Animate( actor, path, forward, alphaFunction );
+ animation.Animate(actor, path, forward, alphaFunction);
}
-
}
}
else
{
//Path not found
- DALI_SCRIPT_WARNING( "Cannot find animation path '%s'\n", (*pathChild).c_str() );
+ DALI_SCRIPT_WARNING("Cannot find animation path '%s'\n", (*pathChild).c_str());
}
}
else
{
- DALI_ASSERT_ALWAYS( property && "Animation must specify a property name" );
+ DALI_ASSERT_ALWAYS(property && "Animation must specify a property name");
- Property prop = Property( targetHandle, propIndex );
+ Property prop = Property(targetHandle, propIndex);
try
{
- propValue = GetPropertyValue( prop.object.GetPropertyType(prop.propertyIndex), *IsChild(pKeyChild.second, "value") );
+ propValue = GetPropertyValue(prop.object.GetPropertyType(prop.propertyIndex), *IsChild(pKeyChild.second, "value"));
}
catch(...)
{
- DALI_LOG_WARNING( "Property:'%s' type does not match value type '%s'\n", (*property).c_str(),
- PropertyTypes::GetName( prop.object.GetPropertyType(prop.propertyIndex) ) );
+ DALI_LOG_WARNING("Property:'%s' type does not match value type '%s'\n", (*property).c_str(), PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex)));
throw;
}
- if( OptionalBoolean relative = constant.IsBoolean( IsChild(pKeyChild.second, "relative") ) )
+ if(OptionalBoolean relative = constant.IsBoolean(IsChild(pKeyChild.second, "relative")))
{
- if( timeChild )
+ if(timeChild)
{
- animation.AnimateBy( prop, propValue, alphaFunction, timePeriod );
+ animation.AnimateBy(prop, propValue, alphaFunction, timePeriod);
}
else
{
- animation.AnimateBy( prop, propValue, alphaFunction );
+ animation.AnimateBy(prop, propValue, alphaFunction);
}
}
else
{
- if( timeChild )
+ if(timeChild)
{
- animation.AnimateTo( prop, propValue, alphaFunction, timePeriod );
+ animation.AnimateTo(prop, propValue, alphaFunction, timePeriod);
}
else
{
- animation.AnimateTo( prop, propValue, alphaFunction );
+ animation.AnimateTo(prop, propValue, alphaFunction);
}
}
}
}
}
- if( !duration )
+ if(!duration)
{
- animation.SetDuration( durationSum );
+ animation.SetDuration(durationSum);
}
return animation;
}
-Animation CreateAnimation( const TreeNode& child, Builder* const builder )
+Animation CreateAnimation(const TreeNode& child, Builder* const builder)
{
Replacement replacement;
- return CreateAnimation( child, replacement, Stage::GetCurrent().GetRootLayer(), builder );
+ return CreateAnimation(child, replacement, Stage::GetCurrent().GetRootLayer(), builder);
}
} // namespace Internal
} // namespace Toolkit
} // namespace Dali
-
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
#ifdef DEBUG_ENABLED
+#include <dali-toolkit/internal/builder/builder-get-is.inl.h>
#include <dali-toolkit/internal/builder/builder-impl-debug.h>
#include <dali-toolkit/internal/builder/builder-impl.h>
-#include <dali-toolkit/internal/builder/builder-get-is.inl.h>
-#include <iostream>
#include <cstring>
+#include <iostream>
namespace Dali
{
{
namespace Internal
{
-
-void LogTree( const Toolkit::JsonParser& parser )
+void LogTree(const Toolkit::JsonParser& parser)
{
- if( OptionalChild constants = IsChild(parser.GetRoot(), "constants") )
+ if(OptionalChild constants = IsChild(parser.GetRoot(), "constants"))
{
for(TreeNode::ConstIterator iter = (*constants).CBegin();
- iter != (*constants).CEnd(); ++iter)
+ iter != (*constants).CEnd();
+ ++iter)
{
- if( ( (*iter).first && strcmp( (*iter).first, "DUMP_TREE" ) == 0 ) ||
- ( (*iter).second.GetType() == TreeNode::STRING && strcmp( (*iter).second.GetString(), "DUMP_TREE" ) == 0 ) )
+ if(((*iter).first && strcmp((*iter).first, "DUMP_TREE") == 0) ||
+ ((*iter).second.GetType() == TreeNode::STRING && strcmp((*iter).second.GetString(), "DUMP_TREE") == 0))
{
std::ostringstream oss;
parser.Write(oss, 2);
}
}
-std::string PropertyValueToString( const Property::Value& value )
+std::string PropertyValueToString(const Property::Value& value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
-} // Internal
-} // Toolkit
-} // Dali
+} // namespace Internal
+} // namespace Toolkit
+} // namespace Dali
#endif // DEBUG_ENABLED
#include <sys/stat.h>
#include <sstream>
+#include <dali-toolkit/devel-api/controls/control-devel.h>
+#include <dali/devel-api/common/stage.h>
+#include <dali/devel-api/scripting/scripting.h>
+#include <dali/integration-api/debug.h>
#include <dali/public-api/actors/camera-actor.h>
#include <dali/public-api/actors/layer.h>
#include <dali/public-api/object/property-array.h>
#include <dali/public-api/render-tasks/render-task-list.h>
#include <dali/public-api/rendering/shader.h>
#include <dali/public-api/signals/functor-delegate.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/devel-api/scripting/scripting.h>
-#include <dali/integration-api/debug.h>
-#include <dali-toolkit/devel-api/controls/control-devel.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/control.h>
#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
#include <dali-toolkit/devel-api/builder/json-parser.h>
+#include <dali-toolkit/public-api/controls/control.h>
#include <dali-toolkit/internal/builder/builder-declarations.h>
#include <dali-toolkit/internal/builder/builder-filesystem.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
class Replacement;
-extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder );
+extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder);
-extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
-
-extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
+extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
+extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
#if defined(DEBUG_ENABLED)
-Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT");
+Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT");
#endif
namespace
{
-
#define TOKEN_STRING(x) #x
const std::string KEYNAME_ACTORS = "actors";
const std::string KEYNAME_TYPE = "type";
const std::string KEYNAME_VISUALS = "visuals";
-const std::string PROPERTIES = "properties";
+const std::string PROPERTIES = "properties";
const std::string ANIMATABLE_PROPERTIES = "animatableProperties";
typedef std::vector<const TreeNode*> TreeNodeList;
-
-bool GetMappingKey( const std::string& str, std::string& key )
+bool GetMappingKey(const std::string& str, std::string& key)
{
- bool result = false;
- std::string test( str );
- if( ! test.empty() )
+ bool result = false;
+ std::string test(str);
+ if(!test.empty())
{
- if( test.at(0) == '<' )
+ if(test.at(0) == '<')
{
- if( test.at(test.length()-1) == '>' )
+ if(test.at(test.length() - 1) == '>')
{
- key = test.substr( 1, test.length()-2 );
+ key = test.substr(1, test.length() - 2);
result = true;
}
}
* style The style array to begin the collection from
* styleList The style list to add nodes to apply
*/
-void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList )
+void CollectAllStyles(const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList)
{
// style is an array of style names
- if( TreeNode::ARRAY == style.GetType() )
+ if(TreeNode::ARRAY == style.GetType())
{
for(TreeNode::ConstIterator iter = style.CBegin(); iter != style.CEnd(); ++iter)
{
- if( OptionalString styleName = IsString( (*iter).second ) )
+ if(OptionalString styleName = IsString((*iter).second))
{
- if( OptionalChild node = IsChildIgnoreCase( stylesCollection, *styleName) )
+ if(OptionalChild node = IsChildIgnoreCase(stylesCollection, *styleName))
{
- styleList.push_back( &(*node) );
+ styleList.push_back(&(*node));
- OptionalChild subStyle = IsChild( *node, KEYNAME_INHERIT );
- if( ! subStyle )
+ OptionalChild subStyle = IsChild(*node, KEYNAME_INHERIT);
+ if(!subStyle)
{
- subStyle = IsChild( *node, KEYNAME_STYLES );
+ subStyle = IsChild(*node, KEYNAME_STYLES);
}
- if( subStyle )
+ if(subStyle)
{
- CollectAllStyles( stylesCollection, *subStyle, styleList );
+ CollectAllStyles(stylesCollection, *subStyle, styleList);
}
}
}
}
}
-
-} // namespace anon
-
+} // namespace
Builder::Builder()
-: mSlotDelegate( this )
+: mSlotDelegate(this)
{
mParser = Dali::Toolkit::JsonParser::New();
AddConstants(defaultConstants);
}
-void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format )
+void Builder::LoadFromString(std::string const& data, Dali::Toolkit::Builder::UIFormat format)
{
// parser to get constants and includes only
Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New();
- if( !parser.Parse( data ) )
+ if(!parser.Parse(data))
{
- DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
- parser.GetErrorLineNumber(),
- parser.GetErrorColumn(),
- parser.GetErrorDescription().c_str() );
+ DALI_LOG_WARNING("JSON Parse Error:%d:%d:'%s'\n",
+ parser.GetErrorLineNumber(),
+ parser.GetErrorColumn(),
+ parser.GetErrorDescription().c_str());
DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
}
else
{
// load constant map (allows the user to override the constants in the json after loading)
- LoadConstants( *parser.GetRoot(), mReplacementMap );
+ LoadConstants(*parser.GetRoot(), mReplacementMap);
// load configuration map
- LoadConfiguration( *parser.GetRoot(), mConfigurationMap );
+ LoadConfiguration(*parser.GetRoot(), mConfigurationMap);
// merge includes
- if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) )
+ if(OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES))
{
- Replacement replacer( mReplacementMap );
+ Replacement replacer(mReplacementMap);
for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter)
{
- OptionalString filename = replacer.IsString( (*iter).second );
+ OptionalString filename = replacer.IsString((*iter).second);
- if( filename )
+ if(filename)
{
#if defined(DEBUG_ENABLED)
DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str());
#endif
- LoadFromString( GetFileContents(*filename) );
+ LoadFromString(GetFileContents(*filename));
}
}
}
- if( mParser.Parse( data ) )
+ if(mParser.Parse(data))
{
// Drop the styles and get them to be rebuilt against the new parse tree as required.
mStyles.Clear();
}
else
{
- DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
- mParser.GetErrorLineNumber(),
- mParser.GetErrorColumn(),
- mParser.GetErrorDescription().c_str() );
+ DALI_LOG_WARNING("JSON Parse Error:%d:%d:'%s'\n",
+ mParser.GetErrorLineNumber(),
+ mParser.GetErrorColumn(),
+ mParser.GetErrorDescription().c_str());
DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
}
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
}
-void Builder::AddConstants( const Property::Map& map )
+void Builder::AddConstants(const Property::Map& map)
{
- mReplacementMap.Merge( map );
+ mReplacementMap.Merge(map);
}
-void Builder::AddConstant( const std::string& key, const Property::Value& value )
+void Builder::AddConstant(const std::string& key, const Property::Value& value)
{
mReplacementMap[key] = value;
}
return mReplacementMap;
}
-const Property::Value& Builder::GetConstant( const std::string& key ) const
+const Property::Value& Builder::GetConstant(const std::string& key) const
{
- Property::Value* match = mReplacementMap.Find( key );
- if( match )
+ Property::Value* match = mReplacementMap.Find(key);
+ if(match)
{
return (*match);
}
}
}
-Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
+Animation Builder::CreateAnimation(const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor)
{
Replacement replacement(map, mReplacementMap);
- return CreateAnimation( animationName, replacement, sourceActor);
+ return CreateAnimation(animationName, replacement, sourceActor);
}
-Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
+Animation Builder::CreateAnimation(const std::string& animationName, const Property::Map& map)
{
Replacement replacement(map, mReplacementMap);
- return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
+ return CreateAnimation(animationName, replacement, Stage::GetCurrent().GetRootLayer());
}
-Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
+Animation Builder::CreateAnimation(const std::string& animationName, Dali::Actor sourceActor)
{
- Replacement replacement( mReplacementMap );
+ Replacement replacement(mReplacementMap);
- return CreateAnimation( animationName, replacement, sourceActor );
+ return CreateAnimation(animationName, replacement, sourceActor);
}
-Animation Builder::CreateAnimation( const std::string& animationName )
+Animation Builder::CreateAnimation(const std::string& animationName)
{
- Replacement replacement( mReplacementMap );
+ Replacement replacement(mReplacementMap);
- return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
+ return CreateAnimation(animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer());
}
-BaseHandle Builder::Create( const std::string& templateName )
+BaseHandle Builder::Create(const std::string& templateName)
{
- Replacement replacement( mReplacementMap );
- return Create( templateName, replacement );
+ Replacement replacement(mReplacementMap);
+ return Create(templateName, replacement);
}
-BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
+BaseHandle Builder::Create(const std::string& templateName, const Property::Map& map)
{
- Replacement replacement( map, mReplacementMap );
- return Create( templateName, replacement );
+ Replacement replacement(map, mReplacementMap);
+ return Create(templateName, replacement);
}
-BaseHandle Builder::CreateFromJson( const std::string& json )
+BaseHandle Builder::CreateFromJson(const std::string& json)
{
BaseHandle ret;
// merge in new template, hoping no one else has one named '@temp@'
std::string newTemplate =
- std::string("{\"templates\":{\"@temp@\":") + \
- json + \
+ std::string("{\"templates\":{\"@temp@\":") +
+ json +
std::string("}}");
- if( mParser.Parse(newTemplate) )
+ if(mParser.Parse(newTemplate))
{
- Replacement replacement( mReplacementMap );
- ret = Create( "@temp@", replacement );
+ Replacement replacement(mReplacementMap);
+ ret = Create("@temp@", replacement);
}
return ret;
}
-bool Builder::ApplyFromJson( Handle& handle, const std::string& json )
+bool Builder::ApplyFromJson(Handle& handle, const std::string& json)
{
bool ret = false;
// merge new style, hoping no one else has one named '@temp@'
std::string newStyle =
- std::string("{\"styles\":{\"@temp@\":") + \
- json + \
+ std::string("{\"styles\":{\"@temp@\":") +
+ json +
std::string("}}");
- if( mParser.Parse(newStyle) )
+ if(mParser.Parse(newStyle))
{
- Replacement replacement( mReplacementMap );
- ret = ApplyStyle( "@temp@", handle, replacement );
+ Replacement replacement(mReplacementMap);
+ ret = ApplyStyle("@temp@", handle, replacement);
}
return ret;
}
-bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
+bool Builder::ApplyStyle(const std::string& styleName, Handle& handle)
{
- Replacement replacer( mReplacementMap );
- return ApplyStyle( styleName, handle, replacer );
+ Replacement replacer(mReplacementMap);
+ return ApplyStyle(styleName, handle, replacer);
}
-bool Builder::LookupStyleName( const std::string& styleName )
+bool Builder::LookupStyleName(const std::string& styleName)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
- OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
- OptionalChild style = IsChildIgnoreCase( *styles, styleName );
+ OptionalChild styles = IsChild(*mParser.GetRoot(), KEYNAME_STYLES);
+ OptionalChild style = IsChildIgnoreCase(*styles, styleName);
- if( styles && style )
+ if(styles && style)
{
return true;
}
return false;
}
-const StylePtr Builder::GetStyle( const std::string& styleName )
+const StylePtr Builder::GetStyle(const std::string& styleName)
{
- const StylePtr* style = mStyles.FindConst( styleName );
+ const StylePtr* style = mStyles.FindConst(styleName);
- if( style==NULL )
+ if(style == NULL)
{
return StylePtr(NULL);
}
}
}
-void Builder::AddActors( Actor toActor )
+void Builder::AddActors(Actor toActor)
{
// 'stage' is the default/by convention section to add from
- AddActors( "stage", toActor );
+ AddActors("stage", toActor);
}
-void Builder::AddActors( const std::string §ionName, Actor toActor )
+void Builder::AddActors(const std::string& sectionName, Actor toActor)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
Property::Map overrideMap;
- Replacement replacements(overrideMap, mReplacementMap);
+ Replacement replacements(overrideMap, mReplacementMap);
OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
- if( add )
+ if(add)
{
- for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
+ for(TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter)
{
// empty actor adds directly to the stage
- BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
- Actor actor = Actor::DownCast(baseHandle);
+ BaseHandle baseHandle = DoCreate(*mParser.GetRoot(), (*iter).second, Actor(), replacements);
+ Actor actor = Actor::DownCast(baseHandle);
if(actor)
{
- toActor.Add( actor );
+ toActor.Add(actor);
}
}
// if were adding the 'stage' section then also check for a render task called stage
// to add automatically
- if( "stage" == sectionName )
+ if("stage" == sectionName)
{
- if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
+ if(OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks"))
{
- if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
+ if(OptionalChild tasks = IsChild(*renderTasks, "stage"))
{
- CreateRenderTask( "stage" );
+ CreateRenderTask("stage");
}
}
}
}
}
-void Builder::CreateRenderTask( const std::string &name )
+void Builder::CreateRenderTask(const std::string& name)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
// to setup task zero and onwards. Although this does overwrite
// the properties of the current task.
//
- if( OptionalChild renderTask = IsChild(*tasks, name ) )
+ if(OptionalChild renderTask = IsChild(*tasks, name))
{
- RenderTaskList list = stage.GetRenderTaskList();
- unsigned int start = list.GetTaskCount();
+ RenderTaskList list = stage.GetRenderTaskList();
+ unsigned int start = list.GetTaskCount();
RenderTask task;
if(0 == start)
}
TreeNode::ConstIterator iter = (*renderTask).CBegin();
- task = list.GetTask( start - 1 );
+ task = list.GetTask(start - 1);
- SetupTask( task, (*iter).second, constant );
+ SetupTask(task, (*iter).second, constant);
++iter;
- for(; iter != (*renderTask).CEnd(); ++iter )
+ for(; iter != (*renderTask).CEnd(); ++iter)
{
task = list.CreateTask();
- SetupTask( task, (*iter).second, constant );
+ SetupTask(task, (*iter).second, constant);
}
}
}
}
-Path Builder::GetPath( const std::string& name )
+Path Builder::GetPath(const std::string& name)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
Path ret;
- PathLut::const_iterator iter( mPathLut.find( name ) );
- if( iter != mPathLut.end() )
+ PathLut::const_iterator iter(mPathLut.find(name));
+ if(iter != mPathLut.end())
{
ret = iter->second;
}
else
{
- if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") )
+ if(OptionalChild paths = IsChild(*mParser.GetRoot(), "paths"))
{
- if( OptionalChild path = IsChild( *paths, name ) )
+ if(OptionalChild path = IsChild(*paths, name))
{
//points property
- if( OptionalChild pointsProperty = IsChild( *path, "points") )
+ if(OptionalChild pointsProperty = IsChild(*path, "points"))
{
Dali::Property::Value points(Property::ARRAY);
- if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
+ if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points))
{
ret = Path::New();
- ret.SetProperty( Path::Property::POINTS, points);
+ ret.SetProperty(Path::Property::POINTS, points);
//controlPoints property
- if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") )
+ if(OptionalChild pointsProperty = IsChild(*path, "controlPoints"))
{
Dali::Property::Value points(Property::ARRAY);
- if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
+ if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points))
{
- ret.SetProperty( Path::Property::CONTROL_POINTS, points);
+ ret.SetProperty(Path::Property::CONTROL_POINTS, points);
}
}
else
{
//Curvature
float curvature(0.25f);
- if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") )
+ if(OptionalFloat pointsProperty = IsFloat(*path, "curvature"))
{
curvature = *pointsProperty;
}
}
//Add the new path to the hash table for paths
- mPathLut[ name ] = ret;
+ mPathLut[name] = ret;
}
}
else
{
//Interpolation points not specified
- DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() );
+ DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str());
}
}
-
}
}
return ret;
}
-PathConstrainer Builder::GetPathConstrainer( const std::string& name )
+PathConstrainer Builder::GetPathConstrainer(const std::string& name)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
//Search the pathConstrainer in the LUT
- size_t count( mPathConstrainerLut.size() );
- for( size_t i(0); i!=count; ++i )
+ size_t count(mPathConstrainerLut.size());
+ for(size_t i(0); i != count; ++i)
{
- if( mPathConstrainerLut[i].name == name )
+ if(mPathConstrainerLut[i].name == name)
{
//PathConstrainer has already been created
return mPathConstrainerLut[i].pathConstrainer;
//Create a new PathConstrainer
PathConstrainer ret;
- if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
+ if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers"))
{
- if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) )
+ if(OptionalChild pathConstrainer = IsChild(*constrainers, name))
{
OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type")));
if(!constrainerType)
{
- DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
+ DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str());
}
- else if( *constrainerType == "PathConstrainer")
+ else if(*constrainerType == "PathConstrainer")
{
//points property
- if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") )
+ if(OptionalChild pointsProperty = IsChild(*pathConstrainer, "points"))
{
Dali::Property::Value points(Property::ARRAY);
- if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
+ if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points))
{
ret = PathConstrainer::New();
- ret.SetProperty( PathConstrainer::Property::POINTS, points);
+ ret.SetProperty(PathConstrainer::Property::POINTS, points);
//controlPoints property
- if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") )
+ if(OptionalChild pointsProperty = IsChild(*pathConstrainer, "controlPoints"))
{
Dali::Property::Value points(Property::ARRAY);
- if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
+ if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points))
{
- ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points);
+ ret.SetProperty(PathConstrainer::Property::CONTROL_POINTS, points);
}
//Forward vector
- OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) );
- if( forward )
+ OptionalVector3 forward(IsVector3(IsChild(*pathConstrainer, "forward")));
+ if(forward)
{
- ret.SetProperty( PathConstrainer::Property::FORWARD, *forward);
+ ret.SetProperty(PathConstrainer::Property::FORWARD, *forward);
}
//Add the new constrainer to the vector of PathConstrainer
- PathConstrainerEntry entry = {name,ret};
- mPathConstrainerLut.push_back( entry );
+ PathConstrainerEntry entry = {name, ret};
+ mPathConstrainerLut.push_back(entry);
}
else
{
//Control points not specified
- DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() );
+ DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str());
}
}
}
else
{
//Interpolation points not specified
- DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() );
+ DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str());
}
}
else
{
- DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() );
+ DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str());
}
}
}
return ret;
}
-
-bool Builder::IsPathConstrainer( const std::string& name )
+bool Builder::IsPathConstrainer(const std::string& name)
{
- size_t count( mPathConstrainerLut.size() );
- for( size_t i(0); i!=count; ++i )
+ size_t count(mPathConstrainerLut.size());
+ for(size_t i(0); i != count; ++i)
{
- if( mPathConstrainerLut[i].name == name )
+ if(mPathConstrainerLut[i].name == name)
{
return true;
}
}
- if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
+ if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers"))
{
- if( OptionalChild constrainer = IsChild( *constrainers, name ) )
+ if(OptionalChild constrainer = IsChild(*constrainers, name))
{
OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
if(!constrainerType)
}
else
{
- return *constrainerType == "PathConstrainer";
+ return *constrainerType == "PathConstrainer";
}
}
}
return false;
}
-Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name )
+Dali::LinearConstrainer Builder::GetLinearConstrainer(const std::string& name)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
//Search the LinearConstrainer in the LUT
- size_t count( mLinearConstrainerLut.size() );
- for( size_t i(0); i!=count; ++i )
+ size_t count(mLinearConstrainerLut.size());
+ for(size_t i(0); i != count; ++i)
{
- if( mLinearConstrainerLut[i].name == name )
+ if(mLinearConstrainerLut[i].name == name)
{
//LinearConstrainer has already been created
return mLinearConstrainerLut[i].linearConstrainer;
//Create a new LinearConstrainer
LinearConstrainer ret;
- if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
+ if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers"))
{
- if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) )
+ if(OptionalChild linearConstrainer = IsChild(*constrainers, name))
{
OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type")));
if(!constrainerType)
{
- DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
+ DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str());
}
- else if( *constrainerType == "LinearConstrainer")
+ else if(*constrainerType == "LinearConstrainer")
{
//points property
- if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") )
+ if(OptionalChild pointsProperty = IsChild(*linearConstrainer, "value"))
{
Dali::Property::Value points(Property::ARRAY);
- if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
+ if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points))
{
ret = Dali::LinearConstrainer::New();
- ret.SetProperty( LinearConstrainer::Property::VALUE, points);
+ ret.SetProperty(LinearConstrainer::Property::VALUE, points);
//controlPoints property
- if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") )
+ if(OptionalChild pointsProperty = IsChild(*linearConstrainer, "progress"))
{
Dali::Property::Value points(Property::ARRAY);
- if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
+ if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points))
{
- ret.SetProperty( LinearConstrainer::Property::PROGRESS, points);
+ ret.SetProperty(LinearConstrainer::Property::PROGRESS, points);
}
}
//Add the new constrainer to vector of LinearConstrainer
- LinearConstrainerEntry entry = {name,ret};
- mLinearConstrainerLut.push_back( entry );
+ LinearConstrainerEntry entry = {name, ret};
+ mLinearConstrainerLut.push_back(entry);
}
}
else
{
//Interpolation points not specified
- DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() );
+ DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str());
}
}
else
{
- DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() );
+ DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str());
}
}
}
return ret;
}
-bool Builder::IsLinearConstrainer( const std::string& name )
+bool Builder::IsLinearConstrainer(const std::string& name)
{
// Search the LinearConstrainer in the LUT
- size_t count( mLinearConstrainerLut.size() );
- for( size_t i(0); i!=count; ++i )
+ size_t count(mLinearConstrainerLut.size());
+ for(size_t i(0); i != count; ++i)
{
- if( mLinearConstrainerLut[i].name == name )
+ if(mLinearConstrainerLut[i].name == name)
{
return true;
}
}
- if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
+ if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers"))
{
- if( OptionalChild constrainer = IsChild( *constrainers, name ) )
+ if(OptionalChild constrainer = IsChild(*constrainers, name))
{
OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
if(!constrainerType)
}
else
{
- return *constrainerType == "LinearConstrainer";
+ return *constrainerType == "LinearConstrainer";
}
}
}
{
}
-void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap )
+void Builder::LoadConfiguration(const TreeNode& root, Property::Map& intoMap)
{
Replacement replacer(intoMap);
- if( OptionalChild constants = IsChild(root, "config") )
+ if(OptionalChild constants = IsChild(root, "config"))
{
for(TreeNode::ConstIterator iter = (*constants).CBegin();
- iter != (*constants).CEnd(); ++iter)
+ iter != (*constants).CEnd();
+ ++iter)
{
Dali::Property::Value property;
- if( (*iter).second.GetName() )
+ if((*iter).second.GetName())
{
- DeterminePropertyFromNode( (*iter).second, property, replacer );
+ DeterminePropertyFromNode((*iter).second, property, replacer);
// If config is string, find constant and replace it to original value.
- if( (*iter).second.GetType() == TreeNode::STRING )
+ if((*iter).second.GetType() == TreeNode::STRING)
{
std::string stringConfigValue;
- if( property.Get( stringConfigValue ) )
+ if(property.Get(stringConfigValue))
{
std::size_t pos = 0;
- while( pos < stringConfigValue.size() )
+ while(pos < stringConfigValue.size())
{
// If we can't find "{","}" pair in stringConfigValue, will out loop.
- std::size_t leftPos = stringConfigValue.find( "{", pos );
- if( leftPos != std::string::npos )
+ std::size_t leftPos = stringConfigValue.find("{", pos);
+ if(leftPos != std::string::npos)
{
- std::size_t rightPos = stringConfigValue.find( "}", pos+1 );
+ std::size_t rightPos = stringConfigValue.find("}", pos + 1);
- if( rightPos != std::string::npos )
+ if(rightPos != std::string::npos)
{
// If we find "{","}" pair but can't find matched constant
// try to find other "{","}" pair after current left position.
- pos = leftPos+1;
+ pos = leftPos + 1;
- for( uint32_t i = 0; i < mReplacementMap.Count() ; i++ )
+ for(uint32_t i = 0; i < mReplacementMap.Count(); i++)
{
Property::Key constant = mReplacementMap.GetKeyAt(i);
// Compare string which is between "{" and "}" with constant string
// If they are same, change string in stringConfigValue to mapped constant value.
- if ( 0 == stringConfigValue.compare( leftPos+1, rightPos-leftPos-1, constant.stringKey ) )
+ if(0 == stringConfigValue.compare(leftPos + 1, rightPos - leftPos - 1, constant.stringKey))
{
std::string replaceString;
- mReplacementMap.GetValue(i).Get( replaceString );
+ mReplacementMap.GetValue(i).Get(replaceString);
- stringConfigValue.replace( leftPos, rightPos-leftPos+1, replaceString );
+ stringConfigValue.replace(leftPos, rightPos - leftPos + 1, replaceString);
pos = leftPos + replaceString.size();
break;
}
pos = stringConfigValue.size();
}
}
- property = Property::Value( stringConfigValue );
+ property = Property::Value(stringConfigValue);
}
}
- intoMap[ (*iter).second.GetName() ] = property;
+ intoMap[(*iter).second.GetName()] = property;
}
}
}
}
-void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
+void Builder::LoadConstants(const TreeNode& root, Property::Map& intoMap)
{
Replacement replacer(intoMap);
- if( OptionalChild constants = IsChild(root, "constants") )
+ if(OptionalChild constants = IsChild(root, "constants"))
{
for(TreeNode::ConstIterator iter = (*constants).CBegin();
- iter != (*constants).CEnd(); ++iter)
+ iter != (*constants).CEnd();
+ ++iter)
{
Dali::Property::Value property;
- if( (*iter).second.GetName() )
+ if((*iter).second.GetName())
{
#if defined(DEBUG_ENABLED)
DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
#endif
- DeterminePropertyFromNode( (*iter).second, property, replacer );
- intoMap[ (*iter).second.GetName() ] = property;
+ DeterminePropertyFromNode((*iter).second, property, replacer);
+ intoMap[(*iter).second.GetName()] = property;
}
}
}
#if defined(DEBUG_ENABLED)
- Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
- if( iter && iter->GetType() == Property::STRING )
+ Property::Value* iter = intoMap.Find("CONFIG_SCRIPT_LOG_LEVEL");
+ if(iter && iter->GetType() == Property::STRING)
{
- std::string logLevel( iter->Get< std::string >() );
- if( logLevel == "NoLogging" )
+ std::string logLevel(iter->Get<std::string>());
+ if(logLevel == "NoLogging")
{
- gFilterScript->SetLogLevel( Integration::Log::NoLogging );
+ gFilterScript->SetLogLevel(Integration::Log::NoLogging);
}
- else if( logLevel == "Concise" )
+ else if(logLevel == "Concise")
{
- gFilterScript->SetLogLevel( Integration::Log::Concise );
+ gFilterScript->SetLogLevel(Integration::Log::Concise);
}
- else if( logLevel == "General" )
+ else if(logLevel == "General")
{
- gFilterScript->SetLogLevel( Integration::Log::General );
+ gFilterScript->SetLogLevel(Integration::Log::General);
}
- else if( logLevel == "Verbose" )
+ else if(logLevel == "Verbose")
{
- gFilterScript->SetLogLevel( Integration::Log::Verbose );
+ gFilterScript->SetLogLevel(Integration::Log::Verbose);
}
}
#endif
}
-Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
+Animation Builder::CreateAnimation(const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
Animation anim;
- if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
+ if(OptionalChild animations = IsChild(*mParser.GetRoot(), "animations"))
{
- if( OptionalChild animation = IsChild(*animations, animationName) )
+ if(OptionalChild animation = IsChild(*animations, animationName))
{
- anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
+ anim = Dali::Toolkit::Internal::CreateAnimation(*animation, replacement, sourceActor, this);
}
else
{
- DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
+ DALI_SCRIPT_WARNING("Request for Animation called '%s' failed\n", animationName.c_str());
}
}
else
{
- DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
+ DALI_SCRIPT_WARNING("Request for Animation called '%s' failed (no animation section)\n", animationName.c_str());
}
return anim;
}
-BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
+BaseHandle Builder::Create(const std::string& templateName, const Replacement& constant)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
- if( !templates )
+ if(!templates)
{
DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
}
}
else
{
- OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
+ OptionalString type = constant.IsString(IsChild(*childTemplate, KEYNAME_TYPE));
if(!type)
{
}
else
{
- baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
+ baseHandle = DoCreate(*mParser.GetRoot(), *childTemplate, Actor(), constant);
}
}
}
* If parent given and an actor type was created then add it to the parent and
* recursively add nodes children.
*/
-BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
- Actor parent, const Replacement& replacements )
+BaseHandle Builder::DoCreate(const TreeNode& root, const TreeNode& node, Actor parent, const Replacement& replacements)
{
- BaseHandle baseHandle;
- TypeInfo typeInfo;
+ BaseHandle baseHandle;
+ TypeInfo typeInfo;
const TreeNode* templateNode = NULL;
- if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
+ if(OptionalString typeName = IsString(node, KEYNAME_TYPE))
{
- typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
+ typeInfo = TypeRegistry::Get().GetTypeInfo(*typeName);
- if( !typeInfo )
+ if(!typeInfo)
{
// a template name is also allowed inplace of the type name
- OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
+ OptionalChild templates = IsChild(root, KEYNAME_TEMPLATES);
- if( templates )
+ if(templates)
{
- if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
+ if(OptionalChild isTemplate = IsChild(*templates, *typeName))
{
templateNode = &(*isTemplate);
- if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
+ if(OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE))
{
- typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
+ typeInfo = TypeRegistry::Get().GetTypeInfo(*templateTypeName);
}
}
}
}
else
{
- baseHandle = typeInfo.CreateInstance();
- Handle handle = Handle::DownCast(baseHandle);
- Actor actor = Actor::DownCast(handle);
+ baseHandle = typeInfo.CreateInstance();
+ Handle handle = Handle::DownCast(baseHandle);
+ Actor actor = Actor::DownCast(handle);
if(handle)
{
-
DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
#if defined(DEBUG_ENABLED)
if(actor)
{
- DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetProperty< int >( Actor::Property::ID ));
+ DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetProperty<int>(Actor::Property::ID));
}
- Toolkit::Control control = Toolkit::Control::DownCast(handle);
+ Toolkit::Control control = Toolkit::Control::DownCast(handle);
if(control)
{
- DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetProperty< int >( Actor::Property::ID ));
+ DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetProperty<int>(Actor::Property::ID));
}
#endif // DEBUG_ENABLED
- if( templateNode )
+ if(templateNode)
{
- ApplyProperties( root, *templateNode, handle, replacements );
+ ApplyProperties(root, *templateNode, handle, replacements);
- if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
+ if(OptionalChild actors = IsChild(*templateNode, KEYNAME_ACTORS))
{
- for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
+ for(TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter)
{
- DoCreate( root, (*iter).second, actor, replacements );
+ DoCreate(root, (*iter).second, actor, replacements);
}
}
}
- if( actor )
+ if(actor)
{
// add children of all the styles
- if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
+ if(OptionalChild actors = IsChild(node, KEYNAME_ACTORS))
{
- for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
+ for(TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter)
{
- DoCreate( root, (*iter).second, actor, replacements );
+ DoCreate(root, (*iter).second, actor, replacements);
}
}
// apply style on top as they need the children to exist
- ApplyAllStyleProperties( root, node, actor, replacements );
+ ApplyAllStyleProperties(root, node, actor, replacements);
// then add to parent
- if( parent )
+ if(parent)
{
- parent.Add( actor );
+ parent.Add(actor);
}
}
else
{
- ApplyProperties( root, node, handle, replacements );
+ ApplyProperties(root, node, handle, replacements);
}
}
else
return baseHandle;
}
-void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
+void Builder::SetupTask(RenderTask& task, const TreeNode& node, const Replacement& constant)
{
const Stage& stage = Stage::GetCurrent();
- Layer root = stage.GetRootLayer();
+ Layer root = stage.GetRootLayer();
- if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
+ if(OptionalString s = constant.IsString(IsChild(node, "sourceActor")))
{
Actor actor = root.FindChildByName(*s);
if(actor)
{
- task.SetSourceActor( actor );
+ task.SetSourceActor(actor);
}
else
{
- DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
+ DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str());
}
}
- if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
+ if(OptionalString s = constant.IsString(IsChild(node, "cameraActor")))
{
- CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
+ CameraActor actor = CameraActor::DownCast(root.FindChildByName(*s));
if(actor)
{
- task.SetCameraActor( actor );
+ task.SetCameraActor(actor);
}
else
{
- DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
+ DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str());
}
}
- if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
+ if(OptionalString s = constant.IsString(IsChild(node, "screenToFrameBufferFunction")))
{
if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
{
- task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
+ task.SetScreenToFrameBufferFunction(RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION);
}
else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
{
- task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
+ task.SetScreenToFrameBufferFunction(RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION);
}
else
{
}
// other setup is via the property system
- SetProperties( node, task, constant );
+ SetProperties(node, task, constant);
}
-bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
+bool Builder::ApplyStyle(const std::string& styleName, Handle& handle, const Replacement& replacement)
{
DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
- OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
+ OptionalChild styles = IsChild(*mParser.GetRoot(), KEYNAME_STYLES);
- std::string styleNameLower(styleName);
- OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower );
+ std::string styleNameLower(styleName);
+ OptionalChild style = IsChildIgnoreCase(*styles, styleNameLower);
- if( styles && style )
+ if(styles && style)
{
- ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
+ ApplyAllStyleProperties(*mParser.GetRoot(), *style, handle, replacement);
return true;
}
else
}
}
-void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
- Dali::Handle& handle, const Replacement& constant )
+void Builder::ApplyAllStyleProperties(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant)
{
const char* styleName = node.GetName();
StylePtr style = Style::New();
StylePtr* matchedStyle = NULL;
- if( styleName )
+ if(styleName)
{
- matchedStyle = mStyles.Find( styleName );
- if( ! matchedStyle )
+ matchedStyle = mStyles.Find(styleName);
+ if(!matchedStyle)
{
- OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
+ OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
- if( !inheritFromNode )
+ if(!inheritFromNode)
{
- inheritFromNode = IsChild( node, KEYNAME_STYLES );
+ inheritFromNode = IsChild(node, KEYNAME_STYLES);
}
- if( styleNodes )
+ if(styleNodes)
{
- if( inheritFromNode )
+ if(inheritFromNode)
{
TreeNodeList additionalStyleNodes;
- CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
+ CollectAllStyles(*styleNodes, *inheritFromNode, additionalStyleNodes);
#if defined(DEBUG_ENABLED)
for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
{
- if( OptionalString styleName = IsString( (*iter).second ) )
+ if(OptionalString styleName = IsString((*iter).second))
{
DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
}
// a style may have other styles, which has other styles etc so we apply in reverse by convention.
for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
{
- RecordStyle( style, *(*iter), handle, constant );
- ApplySignals( root, *(*iter), handle );
- ApplyStylesByActor( root, *(*iter), handle, constant );
+ RecordStyle(style, *(*iter), handle, constant);
+ ApplySignals(root, *(*iter), handle);
+ ApplyStylesByActor(root, *(*iter), handle, constant);
}
}
- RecordStyle( style, node, handle, constant );
- mStyles.Add( styleName, style ); // shallow copy
+ RecordStyle(style, node, handle, constant);
+ mStyles.Add(styleName, style); // shallow copy
matchedStyle = &style;
}
}
}
- if( matchedStyle )
+ if(matchedStyle)
{
- StylePtr style( *matchedStyle );
+ StylePtr style(*matchedStyle);
Dictionary<Property::Map> instancedProperties;
- style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties );
+ style->ApplyVisualsAndPropertiesRecursively(handle, instancedProperties);
}
else // If there were no styles, instead set properties
{
- SetProperties( node, handle, constant );
+ SetProperties(node, handle, constant);
}
- ApplySignals( root, node, handle );
- ApplyStylesByActor( root, node, handle, constant );
+ ApplySignals(root, node, handle);
+ ApplyStylesByActor(root, node, handle, constant);
}
-void Builder::RecordStyle( StylePtr style,
- const TreeNode& node,
- Dali::Handle& handle,
- const Replacement& replacements )
+void Builder::RecordStyle(StylePtr style,
+ const TreeNode& node,
+ Dali::Handle& handle,
+ const Replacement& replacements)
{
// With repeated calls, accumulate inherited states, visuals and properties
// but override any with same name
- for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
+ for(TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter)
{
const TreeNode::KeyNodePair& keyValue = *iter;
- std::string key( keyValue.first );
- if( key == KEYNAME_STATES )
+ std::string key(keyValue.first);
+ if(key == KEYNAME_STATES)
{
const TreeNode& states = keyValue.second;
- if( states.GetType() != TreeNode::OBJECT )
+ if(states.GetType() != TreeNode::OBJECT)
{
- DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
+ DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str());
continue;
}
- for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
+ for(TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter)
{
const TreeNode& stateNode = (*iter).second;
- const char* stateName = stateNode.GetName();
- if( stateNode.GetType() != TreeNode::OBJECT )
+ const char* stateName = stateNode.GetName();
+ if(stateNode.GetType() != TreeNode::OBJECT)
{
- DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
+ DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON object\n", stateName);
continue;
}
- StylePtr* stylePtr = style->subStates.Find( stateName );
- if( stylePtr )
+ StylePtr* stylePtr = style->subStates.Find(stateName);
+ if(stylePtr)
{
StylePtr style(*stylePtr);
- RecordStyle( style, stateNode, handle, replacements );
+ RecordStyle(style, stateNode, handle, replacements);
}
else
{
StylePtr subState = Style::New();
- RecordStyle( subState, stateNode, handle, replacements );
- style->subStates.Add( stateName, subState );
+ RecordStyle(subState, stateNode, handle, replacements);
+ style->subStates.Add(stateName, subState);
}
}
}
- else if( key == KEYNAME_VISUALS )
+ else if(key == KEYNAME_VISUALS)
{
- for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
+ for(TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter)
{
// Each key in this table should be a property name matching a visual.
const TreeNode::KeyNodePair& visual = *iter;
- Dali::Property::Value property(Property::MAP);
- if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
+ Dali::Property::Value property(Property::MAP);
+ if(DeterminePropertyFromNode(visual.second, Property::MAP, property, replacements))
{
- Property::Map* mapPtr = style->visuals.Find( visual.first );
- if( mapPtr )
+ Property::Map* mapPtr = style->visuals.Find(visual.first);
+ if(mapPtr)
{
// Override existing visuals
mapPtr->Clear();
- mapPtr->Merge( *property.GetMap() );
+ mapPtr->Merge(*property.GetMap());
}
else
{
Property::Map* map = property.GetMap();
- if( map )
+ if(map)
{
- style->visuals.Add( visual.first, *map );
+ style->visuals.Add(visual.first, *map);
}
}
}
}
}
- else if( key == KEYNAME_ENTRY_TRANSITION )
+ else if(key == KEYNAME_ENTRY_TRANSITION)
{
- RecordTransitionData( keyValue, style->entryTransition, replacements );
+ RecordTransitionData(keyValue, style->entryTransition, replacements);
}
- else if( key == KEYNAME_EXIT_TRANSITION )
+ else if(key == KEYNAME_EXIT_TRANSITION)
{
- RecordTransitionData( keyValue, style->exitTransition, replacements );
+ RecordTransitionData(keyValue, style->exitTransition, replacements);
}
- else if( key == KEYNAME_TRANSITIONS )
+ else if(key == KEYNAME_TRANSITIONS)
{
- RecordTransitions( keyValue, style->transitions, replacements );
+ RecordTransitions(keyValue, style->transitions, replacements);
}
- else if( key == KEYNAME_TYPE ||
- key == KEYNAME_ACTORS ||
- key == KEYNAME_SIGNALS ||
- key == KEYNAME_STYLES ||
- key == KEYNAME_MAPPINGS ||
- key == KEYNAME_INHERIT )
+ else if(key == KEYNAME_TYPE ||
+ key == KEYNAME_ACTORS ||
+ key == KEYNAME_SIGNALS ||
+ key == KEYNAME_STYLES ||
+ key == KEYNAME_MAPPINGS ||
+ key == KEYNAME_INHERIT)
{
continue;
}
{
Property::Index index;
Property::Value value;
- if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
+ if(MapToTargetProperty(handle, key, keyValue.second, replacements, index, value))
{
- Property::Value* existingValuePtr = style->properties.Find( index );
- if( existingValuePtr != NULL )
+ Property::Value* existingValuePtr = style->properties.Find(index);
+ if(existingValuePtr != NULL)
{
*existingValuePtr = value; // Overwrite existing property.
}
else
{
- style->properties.Add( index, value );
+ style->properties.Add(index, value);
}
}
}
void Builder::RecordTransitions(
const TreeNode::KeyNodePair& keyValue,
- Property::Array& value,
- const Replacement& replacements )
+ Property::Array& value,
+ const Replacement& replacements)
{
//@todo add new transitions to style.transitions
// override existing transitions. A transition matches on target & property name
const TreeNode& node = keyValue.second;
- if( node.GetType() == TreeNode::ARRAY )
+ if(node.GetType() == TreeNode::ARRAY)
{
Dali::Property::Value property(Property::ARRAY);
- if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
+ if(DeterminePropertyFromNode(node, Property::ARRAY, property, replacements))
{
value = *property.GetArray();
}
}
- else if( node.GetType() == TreeNode::OBJECT )
+ else if(node.GetType() == TreeNode::OBJECT)
{
Dali::Property::Value property(Property::MAP);
- if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
+ if(DeterminePropertyFromNode(node, Property::MAP, property, replacements))
{
Property::Array propertyArray;
- propertyArray.Add( property );
+ propertyArray.Add(property);
value = propertyArray;
}
}
else
{
- DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first );
+ DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first);
}
}
void Builder::RecordTransitionData(
const TreeNode::KeyNodePair& keyValue,
- Toolkit::TransitionData& transitionData,
- const Replacement& replacements )
+ Toolkit::TransitionData& transitionData,
+ const Replacement& replacements)
{
const TreeNode& node = keyValue.second;
- if( node.GetType() == TreeNode::ARRAY )
+ if(node.GetType() == TreeNode::ARRAY)
{
Dali::Property::Value property(Property::ARRAY);
- if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) )
+ if(DeterminePropertyFromNode(keyValue.second, Property::ARRAY, property, replacements))
{
- transitionData = Toolkit::TransitionData::New( *property.GetArray() );
+ transitionData = Toolkit::TransitionData::New(*property.GetArray());
}
}
- else if( node.GetType() == TreeNode::OBJECT )
+ else if(node.GetType() == TreeNode::OBJECT)
{
Dali::Property::Value property(Property::MAP);
- if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
+ if(DeterminePropertyFromNode(keyValue.second, Property::MAP, property, replacements))
{
- transitionData = Toolkit::TransitionData::New( *property.GetMap() );
+ transitionData = Toolkit::TransitionData::New(*property.GetMap());
}
}
}
-
// Set properties from node on handle.
-void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
- Dali::Handle& handle, const Replacement& constant )
+void Builder::ApplyProperties(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant)
{
- SetProperties( node, handle, constant );
- ApplySignals( root, node, handle );
+ SetProperties(node, handle, constant);
+ ApplySignals(root, node, handle);
}
-void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
+void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle)
{
Actor actor = Actor::DownCast(handle);
- if( actor )
+ if(actor)
{
// add signals
- SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
- SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
+ SetupSignalAction(mSlotDelegate.GetConnectionTracker(), root, node, actor, this);
+ SetupPropertyNotification(mSlotDelegate.GetConnectionTracker(), root, node, actor, this);
}
}
-
// Appling by style helper
// use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
-void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node,
- Dali::Handle& handle, const Replacement& constant )
+void Builder::ApplyStylesByActor(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant)
{
- if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
+ if(Dali::Actor actor = Dali::Actor::DownCast(handle))
{
- if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
+ if(const TreeNode* actors = node.GetChild(KEYNAME_ACTORS))
{
// in a style the actor subtree properties referenced by actor name
- for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
+ for(TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter)
{
Dali::Actor foundActor;
- if( (*iter).first )
+ if((*iter).first)
{
- foundActor = actor.FindChildByName( (*iter).first );
+ foundActor = actor.FindChildByName((*iter).first);
}
- if( !foundActor )
+ if(!foundActor)
{
DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
}
else
{
DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
- ApplyProperties( root, (*iter).second, foundActor, constant );
+ ApplyProperties(root, (*iter).second, foundActor, constant);
}
}
}
/*
* Sets the handle properties found in the tree node
*/
-void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
+void Builder::SetProperties(const TreeNode& node, Handle& handle, const Replacement& constant)
{
- if( handle )
+ if(handle)
{
- for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
+ for(TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter)
{
const TreeNode::KeyNodePair& keyChild = *iter;
- std::string key( keyChild.first );
+ std::string key(keyChild.first);
// ignore special fields;
- if( key == KEYNAME_TYPE ||
- key == KEYNAME_ACTORS ||
- key == KEYNAME_SIGNALS ||
- key == KEYNAME_STYLES ||
- key == KEYNAME_MAPPINGS ||
- key == KEYNAME_INHERIT ||
- key == KEYNAME_STATES ||
- key == KEYNAME_VISUALS ||
- key == KEYNAME_ENTRY_TRANSITION ||
- key == KEYNAME_EXIT_TRANSITION ||
- key == KEYNAME_TRANSITIONS )
+ if(key == KEYNAME_TYPE ||
+ key == KEYNAME_ACTORS ||
+ key == KEYNAME_SIGNALS ||
+ key == KEYNAME_STYLES ||
+ key == KEYNAME_MAPPINGS ||
+ key == KEYNAME_INHERIT ||
+ key == KEYNAME_STATES ||
+ key == KEYNAME_VISUALS ||
+ key == KEYNAME_ENTRY_TRANSITION ||
+ key == KEYNAME_EXIT_TRANSITION ||
+ key == KEYNAME_TRANSITIONS)
{
continue;
}
Property::Index index;
Property::Value value;
- bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
- if( mapped )
+ bool mapped = MapToTargetProperty(handle, key, keyChild.second, constant, index, value);
+ if(mapped)
{
- DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
+ DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str());
- handle.SetProperty( index, value );
+ handle.SetProperty(index, value);
}
// Add custom properties
const TreeNode& node,
const Replacement& constant,
Property::Index& index,
- Property::Value& value )
+ Property::Value& value)
{
bool mapped = false;
- index = propertyObject.GetPropertyIndex( key );
- if( Property::INVALID_INDEX != index )
+ index = propertyObject.GetPropertyIndex(key);
+ if(Property::INVALID_INDEX != index)
{
Property::Type type = propertyObject.GetPropertyType(index);
// if node.value is a mapping, get the property value from the "mappings" table
- if( node.GetType() == TreeNode::STRING )
+ if(node.GetType() == TreeNode::STRING)
{
std::string mappingKey;
- if( GetMappingKey( node.GetString(), mappingKey) )
+ if(GetMappingKey(node.GetString(), mappingKey))
{
- OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
- mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
+ OptionalChild mappingRoot = IsChild(mParser.GetRoot(), KEYNAME_MAPPINGS);
+ mapped = GetPropertyMap(*mappingRoot, mappingKey.c_str(), type, value);
}
}
- if( ! mapped )
+ if(!mapped)
{
- mapped = DeterminePropertyFromNode( node, type, value, constant );
- if( ! mapped )
+ mapped = DeterminePropertyFromNode(node, type, value, constant);
+ if(!mapped)
{
// Just determine the property from the node and if it's valid, let the property object handle it
- DeterminePropertyFromNode( node, value, constant );
- mapped = ( value.GetType() != Property::NONE );
+ DeterminePropertyFromNode(node, value, constant);
+ mapped = (value.GetType() != Property::NONE);
}
}
}
return mapped;
}
-bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
+bool Builder::GetPropertyMap(const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value)
{
KeyStack keyStack;
- return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
+ return RecursePropertyMap(mappingRoot, keyStack, theKey, propertyType, value);
}
-bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
+bool Builder::RecursePropertyMap(const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value)
{
- Replacement replacer( mReplacementMap );
- bool result = false;
+ Replacement replacer(mReplacementMap);
+ bool result = false;
- keyStack.push_back( theKey );
+ keyStack.push_back(theKey);
- for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
+ for(TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter)
{
- std::string aKey( (*iter).first );
- if( aKey.compare( theKey ) == 0 )
+ std::string aKey((*iter).first);
+ if(aKey.compare(theKey) == 0)
{
- if( propertyType == Property::NONE )
+ if(propertyType == Property::NONE)
{
- DeterminePropertyFromNode( (*iter).second, value, replacer );
+ DeterminePropertyFromNode((*iter).second, value, replacer);
result = true;
}
else
{
- result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
+ result = DeterminePropertyFromNode((*iter).second, propertyType, value, replacer);
}
- if( result )
+ if(result)
{
ConvertChildValue(mappingRoot, keyStack, value);
}
return result;
}
-bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
+bool Builder::ConvertChildValue(const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child)
{
bool result = false;
- switch( child.GetType() )
+ switch(child.GetType())
{
case Property::STRING:
{
std::string value;
- if( child.Get( value ) )
+ if(child.Get(value))
{
std::string key;
- if( GetMappingKey( value, key ) )
+ if(GetMappingKey(value, key))
{
// Check key for cycles:
- result=true;
- for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
+ result = true;
+ for(KeyStack::iterator iter = keyStack.begin(); iter != keyStack.end(); ++iter)
{
- if( key.compare(*iter) == 0 )
+ if(key.compare(*iter) == 0)
{
// key is already in stack; stop.
DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
- child = Property::Value("");
- result=false;
+ child = Property::Value("");
+ result = false;
break;
}
}
- if( result )
+ if(result)
{
// The following call will overwrite the child with the value
// from the mapping.
- RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
+ RecursePropertyMap(mappingRoot, keyStack, key.c_str(), Property::NONE, child);
result = true;
}
}
case Property::MAP:
{
Property::Map* map = child.GetMap();
- if( map )
+ if(map)
{
- for( Property::Map::SizeType i=0; i < map->Count(); ++i )
+ for(Property::Map::SizeType i = 0; i < map->Count(); ++i)
{
Property::Value& child = map->GetValue(i);
ConvertChildValue(mappingRoot, keyStack, child);
case Property::ARRAY:
{
Property::Array* array = child.GetArray();
- if( array )
+ if(array)
{
- for( Property::Array::SizeType i=0; i < array->Count(); ++i )
+ for(Property::Array::SizeType i = 0; i < array->Count(); ++i)
{
Property::Value& child = array->GetElementAt(i);
ConvertChildValue(mappingRoot, keyStack, child);
return result;
}
-void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
- const std::string& childName, Property::AccessMode accessMode )
+void Builder::SetCustomProperties(const TreeNode& node, Handle& handle, const Replacement& constant, const std::string& childName, Property::AccessMode accessMode)
{
// Add custom properties
- if( OptionalChild customPropertiesChild = IsChild(node, childName) )
+ if(OptionalChild customPropertiesChild = IsChild(node, childName))
{
- const TreeNode& customPropertiesNode = *customPropertiesChild;
- const TreeConstIter endIter = customPropertiesNode.CEnd();
- for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
+ const TreeNode& customPropertiesNode = *customPropertiesChild;
+ const TreeConstIter endIter = customPropertiesNode.CEnd();
+ for(TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter)
{
const TreeNode::KeyNodePair& keyChild = *iter;
- std::string key( keyChild.first );
- Property::Value value;
- DeterminePropertyFromNode( keyChild.second, value, constant );
+ std::string key(keyChild.first);
+ Property::Value value;
+ DeterminePropertyFromNode(keyChild.second, value, constant);
// Register/Set property.
- handle.RegisterProperty( key, value, accessMode );
+ handle.RegisterProperty(key, value, accessMode);
}
}
}
-
} // namespace Internal
} // namespace Toolkit
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
// EXTERNAL INCLUDES
-#include <sstream>
#include <dali/public-api/object/property-array.h>
#include <dali/public-api/object/property-map.h>
+#include <sstream>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/builder/builder-impl.h>
#include <dali-toolkit/internal/builder/builder-get-is.inl.h>
-#include <dali-toolkit/internal/builder/replacement.h>
+#include <dali-toolkit/internal/builder/builder-impl.h>
#include <dali-toolkit/internal/builder/builder-set-property.h>
+#include <dali-toolkit/internal/builder/replacement.h>
#include <dali-toolkit/internal/helpers/color-conversion.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
/**
* A property value type can be forced when its unknown by a disambiguation convention in the json
* ie "myarray": [1,2,3,4] ; would be a vector but
* @param replacement The user overriding constant map
* @return True if child contained a disambiguated string that could be converted.
*/
-bool Disambiguated(const TreeNode& child,
+bool Disambiguated(const TreeNode& child,
Dali::Property::Value& value,
- const Replacement& replacement )
+ const Replacement& replacement)
{
- OptionalString childType = IsString( IsChild(child, "typeCast") );
- OptionalChild childValue = IsChild(child, "value");
+ OptionalString childType = IsString(IsChild(child, "typeCast"));
+ OptionalChild childValue = IsChild(child, "value");
- if( childType && childValue && (2 == child.Size()) )
+ if(childType && childValue && (2 == child.Size()))
{
// this case allows disambiguation but normally the type is guessed
// 2 == child.count() is an extra check as the user could have a user dictionary/map with
// type-cast and value keys. If they do then a work around is to add a bogus key to not run this case.
if(*childType == "boolean")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::BOOLEAN, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::BOOLEAN, value, replacement);
}
else if(*childType == "float")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::FLOAT, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::FLOAT, value, replacement);
}
else if(*childType == "vector2")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR2, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR2, value, replacement);
}
else if(*childType == "vector3")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR3, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR3, value, replacement);
}
else if(*childType == "vector4")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR4, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR4, value, replacement);
}
else if(*childType == "rotation")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::ROTATION, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::ROTATION, value, replacement);
}
else if(*childType == "rect")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::RECTANGLE, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::RECTANGLE, value, replacement);
}
else if(*childType == "string")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::STRING, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::STRING, value, replacement);
}
else if(*childType == "map")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::MAP, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::MAP, value, replacement);
}
else if(*childType == "array")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::ARRAY, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::ARRAY, value, replacement);
}
else if(*childType == "extents")
{
- return DeterminePropertyFromNode( *childValue, Dali::Property::EXTENTS, value, replacement);
+ return DeterminePropertyFromNode(*childValue, Dali::Property::EXTENTS, value, replacement);
}
}
return false;
}
-
-bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Property::Value& value)
+bool DeterminePropertyFromNode(const TreeNode& node, Property::Type type, Property::Value& value)
{
Replacement noReplacement;
- return DeterminePropertyFromNode( node, type, value, noReplacement );
+ return DeterminePropertyFromNode(node, type, value, noReplacement);
}
-bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Property::Value& value,
- const Replacement& replacer )
+bool DeterminePropertyFromNode(const TreeNode& node, Property::Type type, Property::Value& value, const Replacement& replacer)
{
bool done = false;
{
case Property::BOOLEAN:
{
- if( OptionalBoolean v = replacer.IsBoolean(node) )
+ if(OptionalBoolean v = replacer.IsBoolean(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
case Property::FLOAT:
{
- if( OptionalFloat v = replacer.IsFloat(node) )
+ if(OptionalFloat v = replacer.IsFloat(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
case Property::INTEGER:
{
- if( OptionalInteger v = replacer.IsInteger(node) )
+ if(OptionalInteger v = replacer.IsInteger(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
case Property::VECTOR2:
{
- if( OptionalVector2 v = replacer.IsVector2(node) )
+ if(OptionalVector2 v = replacer.IsVector2(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
case Property::VECTOR3:
{
- if( OptionalVector3 v = replacer.IsVector3(node) )
+ if(OptionalVector3 v = replacer.IsVector3(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
case Property::VECTOR4:
{
- if( OptionalVector4 v = replacer.IsVector4(node) )
+ if(OptionalVector4 v = replacer.IsVector4(node))
{
value = *v;
- done = true;
+ done = true;
}
- else if( OptionalString s = replacer.IsString(node) )
+ else if(OptionalString s = replacer.IsString(node))
{
Vector4 color;
- done = ConvertStringToColor( *s, color );
+ done = ConvertStringToColor(*s, color);
value = color;
}
- else if( TreeNode::OBJECT == node.GetType() )
+ else if(TreeNode::OBJECT == node.GetType())
{
// check for "r", "g" and "b" child color component nodes
- OptionalInteger r = replacer.IsInteger( IsChild(node, "r") );
- OptionalInteger g = replacer.IsInteger( IsChild(node, "g") );
- OptionalInteger b = replacer.IsInteger( IsChild(node, "b") );
- if( r && g && b )
+ OptionalInteger r = replacer.IsInteger(IsChild(node, "r"));
+ OptionalInteger g = replacer.IsInteger(IsChild(node, "g"));
+ OptionalInteger b = replacer.IsInteger(IsChild(node, "b"));
+ if(r && g && b)
{
- float red( (*r) * (1.0f/255.0f) );
- float green( (*g) * (1.0f/255.0f) );
- float blue( (*b) * (1.0f/255.0f) );
+ float red((*r) * (1.0f / 255.0f));
+ float green((*g) * (1.0f / 255.0f));
+ float blue((*b) * (1.0f / 255.0f));
// check for optional "a" (alpha) node, default to fully opaque if it is not found.
- float alpha( 1.0f );
- OptionalInteger a = replacer.IsInteger( IsChild(node, "a") );
- if( a )
+ float alpha(1.0f);
+ OptionalInteger a = replacer.IsInteger(IsChild(node, "a"));
+ if(a)
{
- alpha = (*a) * (1.0f/255.0f);
+ alpha = (*a) * (1.0f / 255.0f);
}
- value = Vector4( red, green, blue, alpha );
- done = true;
+ value = Vector4(red, green, blue, alpha);
+ done = true;
}
}
break;
}
case Property::MATRIX3:
{
- if( OptionalMatrix3 v = replacer.IsMatrix3(node) )
+ if(OptionalMatrix3 v = replacer.IsMatrix3(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
case Property::MATRIX:
{
- if( OptionalMatrix v = replacer.IsMatrix(node) )
+ if(OptionalMatrix v = replacer.IsMatrix(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
case Property::RECTANGLE:
{
- if( OptionalRect v = replacer.IsRect(node) )
+ if(OptionalRect v = replacer.IsRect(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
{
if(4 == node.Size())
{
- if( OptionalVector4 ov = replacer.IsVector4(node) )
+ if(OptionalVector4 ov = replacer.IsVector4(node))
{
const Vector4& v = *ov;
// angle, axis as per spec
value = Quaternion(Radian(Degree(v[3])),
- Vector3(v[0],v[1],v[2]));
- done = true;
+ Vector3(v[0], v[1], v[2]));
+ done = true;
}
}
else
{
// degrees Euler as per spec
- if( OptionalVector3 v = replacer.IsVector3(node) )
+ if(OptionalVector3 v = replacer.IsVector3(node))
{
value = Quaternion(Radian(Degree((*v).x)),
Radian(Degree((*v).y)),
Radian(Degree((*v).z)));
- done = true;
+ done = true;
}
}
break;
}
case Property::STRING:
{
- if( OptionalString v = replacer.IsString(node) )
+ if(OptionalString v = replacer.IsString(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
case Property::ARRAY:
{
- if( replacer.IsArray( node, value ) )
+ if(replacer.IsArray(node, value))
{
done = true;
}
else if(node.Size())
{
- value = Property::Value(Property::ARRAY);
+ value = Property::Value(Property::ARRAY);
Property::Array* array = value.GetArray();
- unsigned int i = 0;
+ unsigned int i = 0;
TreeNode::ConstIterator iter(node.CBegin());
- if( array )
+ if(array)
{
- for( ; i < node.Size(); ++i, ++iter)
+ for(; i < node.Size(); ++i, ++iter)
{
Property::Value childValue;
- DeterminePropertyFromNode( (*iter).second, childValue, replacer );
- array->PushBack( childValue );
+ DeterminePropertyFromNode((*iter).second, childValue, replacer);
+ array->PushBack(childValue);
}
- done = ( array->Count() == node.Size() );
+ done = (array->Count() == node.Size());
}
}
break;
}
case Property::MAP:
{
- if( replacer.IsMap( node, value ) )
+ if(replacer.IsMap(node, value))
{
done = true;
}
else if(node.Size())
{
- value = Property::Value(Property::MAP);
+ value = Property::Value(Property::MAP);
Property::Map* map = value.GetMap();
- unsigned int i = 0;
+ unsigned int i = 0;
TreeNode::ConstIterator iter(node.CBegin());
- if( map )
+ if(map)
{
- for( ; i < node.Size(); ++i, ++iter)
+ for(; i < node.Size(); ++i, ++iter)
{
Property::Value childValue;
- DeterminePropertyFromNode( (*iter).second, childValue, replacer );
- map->Insert( (*iter).first, childValue );
+ DeterminePropertyFromNode((*iter).second, childValue, replacer);
+ map->Insert((*iter).first, childValue);
}
- done = ( map->Count() == node.Size() );
+ done = (map->Count() == node.Size());
}
}
break;
}
case Property::EXTENTS:
{
- if( OptionalExtents v = replacer.IsExtents(node) )
+ if(OptionalExtents v = replacer.IsExtents(node))
{
value = *v;
- done = true;
+ done = true;
}
break;
}
return done;
}
-void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value )
+void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value)
{
Replacement replacer;
- DeterminePropertyFromNode( node, value, replacer );
+ DeterminePropertyFromNode(node, value, replacer);
}
-void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value,
- const Replacement& replacer )
+void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value, const Replacement& replacer)
{
-
TreeNode::NodeType nodeType = node.GetType();
// Some values are ambiguous as we have no Property::Type but can be disambiguated in the JSON.
// Currently Rotations and Rectangle must always be disambiguated when a type isn't available
- if( !Disambiguated( node, value, replacer ) )
+ if(!Disambiguated(node, value, replacer))
{
bool done = false;
// 4) If no match still; Create as array.
// First handle nodes with children.
- if( node.Size() )
+ if(node.Size())
{
// Handle array types.
- if( nodeType == TreeNode::ARRAY )
+ if(nodeType == TreeNode::ARRAY)
{
// our current heuristic for deciding an array is actually a vector and not say a map
// is to check if the values are all floats
bool allNumbers = true;
- for( TreeConstIter iter = node.CBegin(); iter != node.CEnd(); ++iter )
+ for(TreeConstIter iter = node.CBegin(); iter != node.CEnd(); ++iter)
{
- OptionalFloat checkFloat = IsFloat( ( *iter ).second );
- if( !checkFloat )
+ OptionalFloat checkFloat = IsFloat((*iter).second);
+ if(!checkFloat)
{
allNumbers = false;
break;
}
}
- if( allNumbers )
+ if(allNumbers)
{
// prefer finding vectors over presuming composite Property::Array...
- if( OptionalMatrix v = IsMatrix( node ) )
+ if(OptionalMatrix v = IsMatrix(node))
{
value = *v;
- done = true;
+ done = true;
}
- else if( OptionalMatrix3 v = IsMatrix3( node ) )
+ else if(OptionalMatrix3 v = IsMatrix3(node))
{
value = *v;
- done = true;
+ done = true;
}
- else if( OptionalVector4 v = IsVector4( node ) )
+ else if(OptionalVector4 v = IsVector4(node))
{
value = *v;
- done = true;
+ done = true;
}
- else if( OptionalVector3 v = IsVector3( node ) )
+ else if(OptionalVector3 v = IsVector3(node))
{
value = *v;
- done = true;
+ done = true;
}
- else if( OptionalVector2 v = IsVector2( node ) )
+ else if(OptionalVector2 v = IsVector2(node))
{
value = *v;
- done = true;
+ done = true;
}
- else if( 4 == node.Size() )
+ else if(4 == node.Size())
{
- if( OptionalVector4 v = IsVector4( node ) )
+ if(OptionalVector4 v = IsVector4(node))
{
value = *v;
- done = true;
+ done = true;
}
}
}
}
} // if node.size()
- else if( ( nodeType != TreeNode::OBJECT ) && ( nodeType != TreeNode::ARRAY ) )
+ else if((nodeType != TreeNode::OBJECT) && (nodeType != TreeNode::ARRAY))
{
// no children so either one of bool, float, integer, string
- OptionalBoolean aBool = replacer.IsBoolean( node );
- OptionalInteger anInt = replacer.IsInteger( node );
- OptionalFloat aFloat = replacer.IsFloat( node );
- OptionalString aString = replacer.IsString( node );
+ OptionalBoolean aBool = replacer.IsBoolean(node);
+ OptionalInteger anInt = replacer.IsInteger(node);
+ OptionalFloat aFloat = replacer.IsFloat(node);
+ OptionalString aString = replacer.IsString(node);
- if( aBool )
+ if(aBool)
{
// a bool is also an int but here we presume int
- if( anInt )
+ if(anInt)
{
value = *anInt;
}
// {"value":"123"}
// {"value":123}
// This means we can't have a string with purely numeric content without disambiguation.
- if( aFloat )
+ if(aFloat)
{
value = *aFloat;
}
- else if( anInt )
+ else if(anInt)
{
value = *anInt;
}
} // if( node.size() )
// If we have not created a value so far, attempt to create a Map or Array.
- if( !done )
+ if(!done)
{
// We are guaranteed to have at least one entry as this has been checked already.
TreeConstIter containerIterator = node.CBegin();
- TreeConstIter containerEnd = node.CEnd();
+ TreeConstIter containerEnd = node.CEnd();
// The TreeNode::OBJECT type implies a Property::Map.
- if( nodeType == TreeNode::OBJECT )
+ if(nodeType == TreeNode::OBJECT)
{
// We have a key, treat container as a Map.
- value = Property::Value( Property::MAP );
+ value = Property::Value(Property::MAP);
Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
// Iterate through container to add all entries.
- for( ; containerIterator != containerEnd; ++containerIterator )
+ for(; containerIterator != containerEnd; ++containerIterator)
{
Property::Value childValue;
- DeterminePropertyFromNode( ( *containerIterator ).second, childValue, replacer );
- map->Insert( ( *containerIterator ).first, childValue );
+ DeterminePropertyFromNode((*containerIterator).second, childValue, replacer);
+ map->Insert((*containerIterator).first, childValue);
}
}
}
// We don't have a key, treat container as an array.
// Note: We don't check if the node type is array here, as we want to cope with unknowns by creating an array also.
// This is the fall-back if no other types could be created.
- value = Property::Value( Property::ARRAY );
+ value = Property::Value(Property::ARRAY);
Property::Array* array = value.GetArray();
- if( array )
+ if(array)
{
// Iterate through container to add all entries.
- for( ; containerIterator != containerEnd; ++containerIterator )
+ for(; containerIterator != containerEnd; ++containerIterator)
{
Property::Value childValue;
- DeterminePropertyFromNode( ( *containerIterator ).second, childValue, replacer );
- array->PushBack( childValue );
+ DeterminePropertyFromNode((*containerIterator).second, childValue, replacer);
+ array->PushBack(childValue);
}
}
}
} // if !done
- } // if !Disambiguated()
+ } // if !Disambiguated()
}
-
} // namespace Internal
} // namespace Toolkit
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
// EXTERNAL INCLUDES
+#include <dali/devel-api/common/stage.h>
#include <dali/public-api/actors/layer.h>
#include <dali/public-api/common/vector-wrapper.h>
-#include <dali/public-api/object/type-info.h>
#include <dali/public-api/object/property-notification.h>
-#include <dali/devel-api/common/stage.h>
+#include <dali/public-api/object/type-info.h>
#include <dali/integration-api/debug.h>
#include <limits>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/builder/builder-impl.h>
#include <dali-toolkit/internal/builder/builder-get-is.inl.h>
+#include <dali-toolkit/internal/builder/builder-impl.h>
namespace Dali
{
{
namespace Internal
{
-extern Animation CreateAnimation( const TreeNode& child, Dali::Toolkit::Internal::Builder* const builder );
-extern void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value );
-}
-}
-}
+extern Animation CreateAnimation(const TreeNode& child, Dali::Toolkit::Internal::Builder* const builder);
+extern void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value);
+} // namespace Internal
+} // namespace Toolkit
+} // namespace Dali
namespace
{
// Action on child actor. The child is found by name
struct ChildActorAction
{
- std::string actorName;
- std::string actionName;
- std::string childName;
+ std::string actorName;
+ std::string actionName;
+ std::string childName;
Property::Map parameters;
void operator()(void)
// Action to set a property
struct PropertySetAction
{
- std::string actorName;
- std::string propertyName;
+ std::string actorName;
+ std::string propertyName;
Property::Value value;
void operator()(void)
{
Property::Index idx = actor.GetPropertyIndex(propertyName);
- if( idx != Property::INVALID_INDEX )
+ if(idx != Property::INVALID_INDEX)
{
- if( actor.GetPropertyType(idx) != value.GetType() )
+ if(actor.GetPropertyType(idx) != value.GetType())
{
DALI_SCRIPT_WARNING("Set property action has different type for property '%s'\n", propertyName.c_str());
}
else
{
- actor.SetProperty( idx, value );
+ actor.SetProperty(idx, value);
}
}
else
// Generic action on a handle (Animation & Actor)
struct GenericAction
{
- std::string actorName;
- std::string actionName;
+ std::string actorName;
+ std::string actionName;
Property::Map parameters;
void operator()(void)
{
actor.DoAction(actionName, parameters);
}
-
};
};
// Delay an animation play; ie wait as its not on stage yet
struct DelayedAnimationPlay
{
- OptionalChild animNode;
- Dali::IntrusivePtr<Dali::Toolkit::Internal::Builder> builder;
+ OptionalChild animNode;
+ Dali::IntrusivePtr<Dali::Toolkit::Internal::Builder> builder;
void operator()(void)
{
- Animation anim = Toolkit::Internal::CreateAnimation(*animNode, builder.Get() );
+ Animation anim = Toolkit::Internal::CreateAnimation(*animNode, builder.Get());
if(anim)
{
anim.Play();
// Delay a pathConstrainer apply
struct DelayedConstrainerApply
{
- std::string constrainerName;
+ std::string constrainerName;
std::vector<std::string> targetActorNames;
std::vector<std::string> sourceActorNames;
std::vector<std::string> targetPropertyNames;
std::vector<std::string> sourcePropertyNames;
- std::vector<Vector2> ranges;
- std::vector<Vector2> wrapRanges;
+ std::vector<Vector2> ranges;
+ std::vector<Vector2> wrapRanges;
- Dali::IntrusivePtr<Dali::Toolkit::Internal::Builder> builder;
+ Dali::IntrusivePtr<Dali::Toolkit::Internal::Builder> builder;
/*
* Helper function to get the parameters to apply each constraint
* @param[out] sourceActor Source actor for the constraint
* @param[out] sourcePropertyIndex Source property index for the constraint
*/
- bool GetApplyParameters( size_t i,
- Actor& targetActor, Property::Index& targetPropertyIndex,
- Actor& sourceActor, Property::Index& sourcePropertyIndex)
+ bool GetApplyParameters(size_t i,
+ Actor& targetActor,
+ Property::Index& targetPropertyIndex,
+ Actor& sourceActor,
+ Property::Index& sourcePropertyIndex)
{
-
- targetActor = Stage::GetCurrent().GetRootLayer().FindChildByName(targetActorNames[i]);
+ targetActor = Stage::GetCurrent().GetRootLayer().FindChildByName(targetActorNames[i]);
targetPropertyIndex = Property::INVALID_INDEX;
if(targetActor)
{
targetPropertyIndex = targetActor.GetPropertyIndex(targetPropertyNames[i]);
- if( targetPropertyIndex == Property::INVALID_INDEX )
+ if(targetPropertyIndex == Property::INVALID_INDEX)
{
- DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", targetPropertyNames[i].c_str(), targetActorNames[i].c_str() );
+ DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", targetPropertyNames[i].c_str(), targetActorNames[i].c_str());
return false;
}
}
else
{
- DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str() );
+ DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str());
return false;
}
-
- sourceActor = Stage::GetCurrent().GetRootLayer().FindChildByName(sourceActorNames[i]);
+ sourceActor = Stage::GetCurrent().GetRootLayer().FindChildByName(sourceActorNames[i]);
sourcePropertyIndex = Property::INVALID_INDEX;
if(sourceActor)
{
sourcePropertyIndex = sourceActor.GetPropertyIndex(sourcePropertyNames[i]);
- if( sourcePropertyIndex == Property::INVALID_INDEX )
+ if(sourcePropertyIndex == Property::INVALID_INDEX)
{
- DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", sourcePropertyNames[i].c_str(), sourceActorNames[i].c_str() );
+ DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", sourcePropertyNames[i].c_str(), sourceActorNames[i].c_str());
return false;
}
}
else
{
- DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str() );
+ DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str());
return false;
}
return true;
void operator()(void)
{
- Actor sourceActor, targetActor;
+ Actor sourceActor, targetActor;
Property::Index targetPropertyIndex(Property::INVALID_INDEX);
Property::Index sourcePropertyIndex(Property::INVALID_INDEX);
- size_t actorCount( targetActorNames.size() );
- if( builder.Get()->IsPathConstrainer( constrainerName ))
+ size_t actorCount(targetActorNames.size());
+ if(builder.Get()->IsPathConstrainer(constrainerName))
{
PathConstrainer constrainer = builder.Get()->GetPathConstrainer(constrainerName);
- if( constrainer )
+ if(constrainer)
{
- for(size_t i(0); i<actorCount; ++i )
+ for(size_t i(0); i < actorCount; ++i)
{
-
- if( GetApplyParameters( i, targetActor, targetPropertyIndex, sourceActor, sourcePropertyIndex ) )
+ if(GetApplyParameters(i, targetActor, targetPropertyIndex, sourceActor, sourcePropertyIndex))
{
- constrainer.Apply( Property(targetActor,targetPropertyIndex),
- Property(sourceActor,sourcePropertyIndex),
- ranges[i],
- wrapRanges[i]);
+ constrainer.Apply(Property(targetActor, targetPropertyIndex),
+ Property(sourceActor, sourcePropertyIndex),
+ ranges[i],
+ wrapRanges[i]);
}
}
}
DALI_SCRIPT_WARNING("Constrainer %s not found\n", constrainerName.c_str());
}
}
- else if( builder.Get()->IsLinearConstrainer( constrainerName ) )
+ else if(builder.Get()->IsLinearConstrainer(constrainerName))
{
- Dali::LinearConstrainer constrainer( builder.Get()->GetLinearConstrainer(constrainerName));
- if( constrainer )
+ Dali::LinearConstrainer constrainer(builder.Get()->GetLinearConstrainer(constrainerName));
+ if(constrainer)
{
- for(size_t i(0); i<actorCount; ++i )
+ for(size_t i(0); i < actorCount; ++i)
{
-
- if( GetApplyParameters( i, targetActor, targetPropertyIndex, sourceActor, sourcePropertyIndex ) )
+ if(GetApplyParameters(i, targetActor, targetPropertyIndex, sourceActor, sourcePropertyIndex))
{
- constrainer.Apply( Property(targetActor,targetPropertyIndex),
- Property(sourceActor,sourcePropertyIndex),
- ranges[i],
- wrapRanges[i]);
+ constrainer.Apply(Property(targetActor, targetPropertyIndex),
+ Property(sourceActor, sourcePropertyIndex),
+ ranges[i],
+ wrapRanges[i]);
}
}
}
// Delay a pathConstrainer remove
struct DelayedConstrainerRemove
{
- std::string constrainerName;
- std::vector<std::string> targetActorNames;
- Dali::IntrusivePtr<Dali::Toolkit::Internal::Builder> builder;
+ std::string constrainerName;
+ std::vector<std::string> targetActorNames;
+ Dali::IntrusivePtr<Dali::Toolkit::Internal::Builder> builder;
void operator()(void)
{
- size_t actorCount( targetActorNames.size() );
- if( builder.Get()->IsPathConstrainer( constrainerName ))
+ size_t actorCount(targetActorNames.size());
+ if(builder.Get()->IsPathConstrainer(constrainerName))
{
PathConstrainer constrainer = builder.Get()->GetPathConstrainer(constrainerName);
- if( constrainer )
+ if(constrainer)
{
- for(size_t i(0); i<actorCount; ++i )
+ for(size_t i(0); i < actorCount; ++i)
{
Actor targetActor = Stage::GetCurrent().GetRootLayer().FindChildByName(targetActorNames[i]);
if(targetActor)
{
- constrainer.Remove( targetActor );
+ constrainer.Remove(targetActor);
}
}
}
DALI_SCRIPT_WARNING("Constrainer %s not found\n", constrainerName.c_str());
}
}
- else if(builder.Get()->IsLinearConstrainer( constrainerName ))
+ else if(builder.Get()->IsLinearConstrainer(constrainerName))
{
LinearConstrainer constrainer = builder.Get()->GetLinearConstrainer(constrainerName);
- if( constrainer )
+ if(constrainer)
{
- for(size_t i(0); i<actorCount; ++i )
+ for(size_t i(0); i < actorCount; ++i)
{
Actor targetActor = Stage::GetCurrent().GetRootLayer().FindChildByName(targetActorNames[i]);
if(targetActor)
{
- constrainer.Remove( targetActor );
+ constrainer.Remove(targetActor);
}
}
}
/*
* Gets Property::Value from child
*/
-Property::Value GetPropertyValue(const TreeNode &child)
+Property::Value GetPropertyValue(const TreeNode& child)
{
size_t nChildren = child.Size();
if(0 == nChildren)
{
// cast away unused return for static analyzers
- static_cast<void>( Dali::Toolkit::Internal::DeterminePropertyFromNode( child, ret ) );
+ static_cast<void>(Dali::Toolkit::Internal::DeterminePropertyFromNode(child, ret));
}
else if(1 == nChildren)
{
// {"property": {"quaternion":[1,2,3,4]} }
// {"property": {"angle":22, "axis": [1,2,3]} }
- OptionalChild quaternion = IsChild(&child, "quaternion");
- OptionalChild axis = IsChild(&child, "axis");
- OptionalChild angle = IsChild(&child, "angle");
+ OptionalChild quaternion = IsChild(&child, "quaternion");
+ OptionalChild axis = IsChild(&child, "axis");
+ OptionalChild angle = IsChild(&child, "angle");
if(quaternion)
{
return ret;
}
-
/*
* Gets Parmeter list from child
* params is be cleared before insertion
*/
void GetParameters(const TreeNode& child, Property::Map& params)
{
- if( OptionalChild c = IsChild(child, "parameters") )
+ if(OptionalChild c = IsChild(child, "parameters"))
{
const TreeNode& node = *c;
for(TreeNode::ConstIterator iter(node.CBegin()); iter != node.CEnd(); ++iter)
{
- params[ (*iter).first ] = GetPropertyValue( (*iter).second );
+ params[(*iter).first] = GetPropertyValue((*iter).second);
}
}
}
// Shim for the property notifcation signal
-template <typename T>
+template<typename T>
struct PropertyNotifcationSignalShim
{
T mFunctor;
- PropertyNotifcationSignalShim(T& functor) : mFunctor(functor) {}
+ PropertyNotifcationSignalShim(T& functor)
+ : mFunctor(functor)
+ {
+ }
void operator()(PropertyNotification& /* source */)
{
};
// Specializations for the different signal connection calls between actor & PropertyNotification
-template <typename T>
-struct SignalConnector {};
+template<typename T>
+struct SignalConnector
+{
+};
// Actor specialization
-template <>
-struct SignalConnector<Actor> {
- Actor& mActor;
+template<>
+struct SignalConnector<Actor>
+{
+ Actor& mActor;
ConnectionTracker* mTracker;
const std::string& mName;
SignalConnector<Actor>(ConnectionTracker* tracker, Actor& actor, const std::string& name)
- : mActor(actor), mTracker(tracker), mName(name) {}
+ : mActor(actor),
+ mTracker(tracker),
+ mName(name)
+ {
+ }
- template <typename T>
+ template<typename T>
void Connect(T& functor)
{
- mActor.ConnectSignal( mTracker, mName, functor);
+ mActor.ConnectSignal(mTracker, mName, functor);
}
};
// PropertyNotification specialization
-template <>
+template<>
struct SignalConnector<PropertyNotification>
{
PropertyNotification& mNotification;
- ConnectionTracker* mTracker;
+ ConnectionTracker* mTracker;
- SignalConnector<PropertyNotification>(ConnectionTracker* tracker, PropertyNotification ¬ification)
- : mNotification(notification), mTracker(tracker) {}
+ SignalConnector<PropertyNotification>(ConnectionTracker* tracker, PropertyNotification& notification)
+ : mNotification(notification),
+ mTracker(tracker)
+ {
+ }
- template <typename T>
+ template<typename T>
void Connect(T& functor)
{
- mNotification.NotifySignal().Connect( mTracker, PropertyNotifcationSignalShim<T>(functor) );
+ mNotification.NotifySignal().Connect(mTracker, PropertyNotifcationSignalShim<T>(functor));
}
};
/**
* Set an action functor on a signal
*/
-template <typename T>
-void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder, SignalConnector<T>& connector)
+template<typename T>
+void SetActionOnSignal(const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder, SignalConnector<T>& connector)
{
- OptionalString childActorName(IsString( IsChild(&child, "childActor")) );
- OptionalString actorName(IsString( IsChild(&child, "actor")) );
- OptionalString propertyName(IsString( IsChild(&child, "property")) );
- OptionalChild valueChild( IsChild(&child, "value") );
+ OptionalString childActorName(IsString(IsChild(&child, "childActor")));
+ OptionalString actorName(IsString(IsChild(&child, "actor")));
+ OptionalString propertyName(IsString(IsChild(&child, "property")));
+ OptionalChild valueChild(IsChild(&child, "value"));
- OptionalString actionName = IsString( IsChild(&child, "action") );
+ OptionalString actionName = IsString(IsChild(&child, "action"));
DALI_ASSERT_ALWAYS(actionName && "Signal must have an action");
if(childActorName)
{
ChildActorAction action;
- action.actorName = *actorName;
- action.childName = *childActorName;
- action.actionName = *actionName;
+ action.actorName = *actorName;
+ action.childName = *childActorName;
+ action.actionName = *actionName;
GetParameters(child, action.parameters);
- connector.Connect( action );
+ connector.Connect(action);
}
else if(actorName)
{
- if(propertyName && valueChild && ("set" == *actionName) )
+ if(propertyName && valueChild && ("set" == *actionName))
{
PropertySetAction action;
- action.actorName = *actorName;
- action.propertyName = *propertyName;
+ action.actorName = *actorName;
+ action.propertyName = *propertyName;
// actor may not exist yet so we can't check the property type
- Dali::Toolkit::Internal::DeterminePropertyFromNode( *valueChild, action.value );
- connector.Connect( action );
+ Dali::Toolkit::Internal::DeterminePropertyFromNode(*valueChild, action.value);
+ connector.Connect(action);
}
else
{
GenericAction action;
- action.actorName = *actorName;
- action.actionName = *actionName;
+ action.actorName = *actorName;
+ action.actionName = *actionName;
GetParameters(child, action.parameters);
- connector.Connect( action );
+ connector.Connect(action);
}
}
else if("quit" == *actionName)
{
QuitAction action;
action.builder = builder;
- connector.Connect( action );
+ connector.Connect(action);
}
else if("play" == *actionName)
{
- OptionalChild animations = IsChild( root, "animations" );
- OptionalString animationName = IsString( IsChild(child, "animation") );
- if( animations && animationName )
+ OptionalChild animations = IsChild(root, "animations");
+ OptionalString animationName = IsString(IsChild(child, "animation"));
+ if(animations && animationName)
{
- if( OptionalChild animNode = IsChild(*animations, *animationName) )
+ if(OptionalChild animNode = IsChild(*animations, *animationName))
{
DelayedAnimationPlay action;
action.animNode = animNode;
- action.builder = builder;
+ action.builder = builder;
// @todo; put constants into the map
- connector.Connect( action );
+ connector.Connect(action);
}
else
{
DALI_SCRIPT_WARNING("Cannot find animations section\n");
}
}
- else if("applyConstraint" == *actionName )
+ else if("applyConstraint" == *actionName)
{
- OptionalString constrainerName = IsString( IsChild(child, "constrainer") );
- if( !constrainerName )
+ OptionalString constrainerName = IsString(IsChild(child, "constrainer"));
+ if(!constrainerName)
{
DALI_SCRIPT_WARNING("Need to specify a constrainer\n");
}
else
{
DelayedConstrainerApply action;
- action.constrainerName = *constrainerName;
- action.builder = builder;
+ action.constrainerName = *constrainerName;
+ action.builder = builder;
OptionalChild propertiesNode = IsChild(child, "properties");
if(propertiesNode)
{
const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd();
- for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter )
+ for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter)
{
const TreeNode::KeyNodePair& pKeyChild = *iter;
- OptionalString sourceActorName(IsString(IsChild(pKeyChild.second, "source")));
+ OptionalString sourceActorName(IsString(IsChild(pKeyChild.second, "source")));
if(!sourceActorName)
{
DALI_SCRIPT_WARNING("Need to specify source actor to apply the constraint\n");
continue;
}
- OptionalString sourcePropertyName( IsString( IsChild(pKeyChild.second, "sourceProperty" ) ) );
+ OptionalString sourcePropertyName(IsString(IsChild(pKeyChild.second, "sourceProperty")));
if(!sourcePropertyName)
{
DALI_SCRIPT_WARNING("Need to specify source property to apply the constraint\n");
continue;
}
- OptionalString targetPropertyName( IsString( IsChild(pKeyChild.second, "targetProperty" ) ) );
+ OptionalString targetPropertyName(IsString(IsChild(pKeyChild.second, "targetProperty")));
if(!targetPropertyName)
{
DALI_SCRIPT_WARNING("Need to specify target property name to apply the constraint\n");
continue;
}
- Vector2 wrap(-std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
+ Vector2 wrap(-std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
OptionalVector2 wrapRange(IsVector2(IsChild(pKeyChild.second, "wrap")));
if(wrapRange)
{
}
}
}
- else if("removeConstraints" == *actionName )
+ else if("removeConstraints" == *actionName)
{
- OptionalString constrainerName = IsString( IsChild(child, "constrainer") );
- if( !constrainerName )
+ OptionalString constrainerName = IsString(IsChild(child, "constrainer"));
+ if(!constrainerName)
{
DALI_SCRIPT_WARNING("Need to specify a constrainer\n");
}
else
{
-
DelayedConstrainerRemove action;
- action.constrainerName = *constrainerName;
- action.builder = builder;
+ action.constrainerName = *constrainerName;
+ action.builder = builder;
OptionalChild propertiesNode = IsChild(child, "properties");
if(propertiesNode)
{
const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd();
- for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter )
+ for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter)
{
const TreeNode::KeyNodePair& pKeyChild = *iter;
- OptionalString targetActorName(IsString(IsChild(pKeyChild.second, "target")));
+ OptionalString targetActorName(IsString(IsChild(pKeyChild.second, "target")));
if(targetActorName)
{
action.targetActorNames.push_back(*targetActorName);
{
// no named actor; presume self
GenericAction action;
- action.actorName = actor.GetProperty< std::string >( Dali::Actor::Property::NAME );
- action.actionName = *actionName;
+ action.actorName = actor.GetProperty<std::string>(Dali::Actor::Property::NAME);
+ action.actionName = *actionName;
GetParameters(child, action.parameters);
- connector.Connect( action );
+ connector.Connect(action);
}
}
-
/**
* Get a notification condition argument0 as 'arg0' 'value' or 'min'
*/
-float GetConditionArg0(const TreeNode &child)
+float GetConditionArg0(const TreeNode& child)
{
- OptionalFloat f = IsFloat( IsChild(child, "arg0") );
+ OptionalFloat f = IsFloat(IsChild(child, "arg0"));
// allowing some human preferable alternatives
if(!f)
{
- f = IsFloat( IsChild(child, "value") );
+ f = IsFloat(IsChild(child, "value"));
}
if(!f)
{
- f = IsFloat( IsChild(child, "min") );
+ f = IsFloat(IsChild(child, "min"));
}
DALI_ASSERT_ALWAYS(f && "Notification condition for arg0 not specified");
/**
* Get a notification condition argument1 as 'arg1' or 'max'
*/
-float GetConditionArg1(const TreeNode &child)
+float GetConditionArg1(const TreeNode& child)
{
- OptionalFloat f = IsFloat( IsChild(child, "arg1") );
+ OptionalFloat f = IsFloat(IsChild(child, "arg1"));
// allowing some human preferable alternatives
if(!f)
{
- f = IsFloat( IsChild(child, "max") );
+ f = IsFloat(IsChild(child, "max"));
}
DALI_ASSERT_ALWAYS(f && "Notification condition for arg1 not specified");
return *f;
}
-
-
-}; // anon namespace
+}; // namespace
namespace Dali
{
{
namespace Internal
{
-
-Actor SetupSignalAction(const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder );
-Actor SetupPropertyNotification(const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder );
+Actor SetupSignalAction(const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
+Actor SetupPropertyNotification(const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
/**
* Setup signals and actions on an actor
*/
-Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder )
+Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder)
{
DALI_ASSERT_ALWAYS(actor);
if(OptionalChild signalsChild = IsChild(child, "signals"))
{
- const TreeNode& signalsNode = *signalsChild;
- const TreeConstIter endIter = signalsNode.CEnd();
- for( TreeConstIter iter = signalsNode.CBegin(); endIter != iter; ++iter )
+ const TreeNode& signalsNode = *signalsChild;
+ const TreeConstIter endIter = signalsNode.CEnd();
+ for(TreeConstIter iter = signalsNode.CBegin(); endIter != iter; ++iter)
{
const TreeNode::KeyNodePair& key_child = *iter;
- DALI_SCRIPT_INFO(" Creating Signal for: %s\n", actor.GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str());
+ DALI_SCRIPT_INFO(" Creating Signal for: %s\n", actor.GetProperty<std::string>(Dali::Actor::Property::NAME).c_str());
- OptionalString name( IsString( IsChild( key_child.second, "name")) );
+ OptionalString name(IsString(IsChild(key_child.second, "name")));
DALI_ASSERT_ALWAYS(name && "Signal must have a name");
SignalConnector<Actor> connector(tracker, actor, *name);
/**
* Setup Property notifications for an actor
*/
-Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder )
+Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder)
{
DALI_ASSERT_ALWAYS(actor);
- if(OptionalChild notificationsChild = IsChild(child,"notifications"))
+ if(OptionalChild notificationsChild = IsChild(child, "notifications"))
{
- const TreeNode& notificationsNode = *notificationsChild;
- const TreeNode::ConstIterator endIter = notificationsNode.CEnd();
- for( TreeNode::ConstIterator iter = notificationsNode.CBegin(); endIter != iter; ++iter )
+ const TreeNode& notificationsNode = *notificationsChild;
+ const TreeNode::ConstIterator endIter = notificationsNode.CEnd();
+ for(TreeNode::ConstIterator iter = notificationsNode.CBegin(); endIter != iter; ++iter)
{
const TreeNode::KeyNodePair& key_child = *iter;
- OptionalString prop(IsString( IsChild(key_child.second, "property")) );
+ OptionalString prop(IsString(IsChild(key_child.second, "property")));
DALI_ASSERT_ALWAYS(prop && "Notification signal must specify a property");
Property::Index prop_index = actor.GetPropertyIndex(*prop);
DALI_ASSERT_ALWAYS(prop_index != Property::INVALID_INDEX && "Notification signal specifies an unknown property");
- OptionalString cond(IsString( IsChild(key_child.second, "condition")));
+ OptionalString cond(IsString(IsChild(key_child.second, "condition")));
DALI_ASSERT_ALWAYS(cond && "Notification signal must specify a condition");
if("False" == *cond)
{
- PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop),
- LessThanCondition(1.f) );
+ PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop),
+ LessThanCondition(1.f));
+
SignalConnector<PropertyNotification> connector(tracker, notification);
SetActionOnSignal(root, key_child.second, actor, builder, connector);
}
else if("LessThan" == *cond)
{
- PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop),
- LessThanCondition(GetConditionArg0(key_child.second)) );
+ PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop),
+ LessThanCondition(GetConditionArg0(key_child.second)));
+
SignalConnector<PropertyNotification> connector(tracker, notification);
SetActionOnSignal(root, key_child.second, actor, builder, connector);
}
else if("GreaterThan" == *cond)
{
- PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop),
- GreaterThanCondition(GetConditionArg0(key_child.second)) );
+ PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop),
+ GreaterThanCondition(GetConditionArg0(key_child.second)));
+
SignalConnector<PropertyNotification> connector(tracker, notification);
SetActionOnSignal(root, key_child.second, actor, builder, connector);
}
else if("Inside" == *cond)
{
- PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop),
- InsideCondition(GetConditionArg0(key_child.second),
- GetConditionArg1(key_child.second)) );
+ PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop),
+ InsideCondition(GetConditionArg0(key_child.second),
+ GetConditionArg1(key_child.second)));
+
SignalConnector<PropertyNotification> connector(tracker, notification);
SetActionOnSignal(root, key_child.second, actor, builder, connector);
}
else if("Outside" == *cond)
{
- PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop),
- OutsideCondition(GetConditionArg0(key_child.second),
- GetConditionArg1(key_child.second)) );
+ PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop),
+ OutsideCondition(GetConditionArg0(key_child.second),
+ GetConditionArg1(key_child.second)));
+
SignalConnector<PropertyNotification> connector(tracker, notification);
SetActionOnSignal(root, key_child.second, actor, builder, connector);
}
} // AddPropertyNotification
-
} // namespace Internal
} // namespace Toolkit
} // namespace Dali
#include <cstring>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/builder/tree-node-manipulator.h>
#include <dali-toolkit/internal/builder/json-parser-state.h>
+#include <dali-toolkit/internal/builder/tree-node-manipulator.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
const char ERROR_DESCRIPTION_NONE[] = "No Error";
-template <typename IteratorType,typename EndIteratorType>
+template<typename IteratorType, typename EndIteratorType>
inline IteratorType Advance(IteratorType& iter, EndIteratorType& end, int n)
{
- for(int i =0; i < n; ++i)
+ for(int i = 0; i < n; ++i)
{
++iter;
}
return iter;
}
-} // anon namespace
-
+} // namespace
JsonParser::JsonParser()
- : mRoot(NULL),
- mErrorDescription(ERROR_DESCRIPTION_NONE),
- mErrorPosition(0),
- mErrorLine(0),
- mErrorColumn(0),
- mNumberOfChars(0),
- mNumberOfNodes(0)
+: mRoot(NULL),
+ mErrorDescription(ERROR_DESCRIPTION_NONE),
+ mErrorPosition(0),
+ mErrorLine(0),
+ mErrorColumn(0),
+ mNumberOfChars(0),
+ mNumberOfNodes(0)
{
}
JsonParser::JsonParser(const TreeNode& tree)
- : mRoot(NULL),
- mErrorDescription(ERROR_DESCRIPTION_NONE),
- mErrorPosition(0),
- mErrorLine(0),
- mErrorColumn(0),
- mNumberOfChars(0),
- mNumberOfNodes(0)
+: mRoot(NULL),
+ mErrorDescription(ERROR_DESCRIPTION_NONE),
+ mErrorPosition(0),
+ mErrorLine(0),
+ mErrorColumn(0),
+ mNumberOfChars(0),
+ mNumberOfNodes(0)
{
- mRoot = TreeNodeManipulator::Copy( tree, mNumberOfNodes, mNumberOfChars );
+ mRoot = TreeNodeManipulator::Copy(tree, mNumberOfNodes, mNumberOfChars);
- mSources.push_back( VectorChar( (sizeof(char) * mNumberOfChars) ) );
+ mSources.push_back(VectorChar((sizeof(char) * mNumberOfChars)));
VectorChar& buffer = mSources.back();
bool JsonParser::Parse(const std::string& source)
{
- mSources.push_back( VectorChar(source.begin(), source.end()) );
+ mSources.push_back(VectorChar(source.begin(), source.end()));
JsonParserState parserState(mRoot);
- if( parserState.ParseJson(mSources.back()) )
+ if(parserState.ParseJson(mSources.back()))
{
mRoot = parserState.GetRoot();
mNumberOfChars += parserState.GetParsedStringSize();
mNumberOfNodes += parserState.GetCreatedNodeCount();
- mErrorDescription = ERROR_DESCRIPTION_NONE;
- mErrorPosition = 0;
- mErrorLine = 0;
- mErrorColumn = 0;
+ mErrorDescription = ERROR_DESCRIPTION_NONE;
+ mErrorPosition = 0;
+ mErrorLine = 0;
+ mErrorColumn = 0;
}
else
{
mRoot = NULL;
- mErrorDescription = parserState.GetErrorDescription();
+ mErrorDescription = parserState.GetErrorDescription();
if(NULL == mErrorDescription)
{
mErrorDescription = ERROR_DESCRIPTION_NONE;
}
- mErrorPosition = parserState.GetErrorPosition();
- mErrorLine = parserState.GetErrorLineNumber();
- mErrorColumn = parserState.GetErrorColumn();
+ mErrorPosition = parserState.GetErrorPosition();
+ mErrorLine = parserState.GetErrorLineNumber();
+ mErrorColumn = parserState.GetErrorColumn();
}
return mRoot != NULL;
}
-
const TreeNode* JsonParser::GetRoot() const
{
return mRoot;
void JsonParser::Pack(void)
{
- mSources.push_back( VectorChar( (sizeof(char) * mNumberOfChars) ) );
+ mSources.push_back(VectorChar((sizeof(char) * mNumberOfChars)));
VectorChar& buffer = mSources.back();
modify.MoveStrings(start, buffer.end());
- mSources.erase( mSources.begin(), --mSources.end() );
+ mSources.erase(mSources.begin(), --mSources.end());
}
void JsonParser::Write(std::ostream& output, int indent) const
modify.Write(output, indent);
}
-
} // namespace Internal
} // namespace Toolkit
#include <dali-toolkit/internal/builder/json-parser-state.h>
// EXTERNAL INCLUDES
-#include <string>
#include <algorithm>
+#include <string>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// true if character represent a digit
inline bool IsDigit(char c)
{
}
// convert string to integer
-bool StringToInteger(const char *first, const char *last, int& out)
+bool StringToInteger(const char* first, const char* last, int& out)
{
int sign = 1;
- if (first != last)
+ if(first != last)
{
- if (*first == '-')
+ if(*first == '-')
{
sign = -1;
++first;
}
- else if (*first == '+')
+ else if(*first == '+')
{
++first;
}
}
// json error for int starting with zero
- if( 0 == (*first - '0') && (first+1 != last))
+ if(0 == (*first - '0') && (first + 1 != last))
{
return false;
}
int result = 0;
- for (; first != last && IsDigit(*first); ++first)
+ for(; first != last && IsDigit(*first); ++first)
{
result = 10 * result + (*first - '0');
}
}
// convert hexadecimal string to unsigned integer
-bool HexStringToUnsignedInteger(const char *first, const char *last, unsigned int& out)
+bool HexStringToUnsignedInteger(const char* first, const char* last, unsigned int& out)
{
unsigned int result = 0;
- for (; first != last; ++first)
+ for(; first != last; ++first)
{
int digit;
- if (IsDigit(*first))
+ if(IsDigit(*first))
{
digit = *first - '0';
}
- else if (*first >= 'a' && *first <= 'f')
+ else if(*first >= 'a' && *first <= 'f')
{
digit = *first - 'a' + 10;
}
- else if (*first >= 'A' && *first <= 'F')
+ else if(*first >= 'A' && *first <= 'F')
{
digit = *first - 'A' + 10;
}
{
// sign
float sign = 1;
- if (first != last)
+ if(first != last)
{
- if (*first == '-')
+ if(*first == '-')
{
sign = -1;
++first;
}
- else if (*first == '+')
+ else if(*first == '+')
{
++first;
}
// integer part
float result = 0;
- for (; first != last && IsDigit(*first); ++first)
+ for(; first != last && IsDigit(*first); ++first)
{
result = 10 * result + (*first - '0');
}
// fraction part
- if (first != last && *first == '.')
+ if(first != last && *first == '.')
{
++first;
float inv_base = 0.1f;
- for (; first != last && IsDigit(*first); ++first)
+ for(; first != last && IsDigit(*first); ++first)
{
result += (*first - '0') * inv_base;
inv_base *= 0.1f;
// exponent
bool exponent_negative = false;
- int exponent = 0;
- if (first != last && (*first == 'e' || *first == 'E'))
+ int exponent = 0;
+ if(first != last && (*first == 'e' || *first == 'E'))
{
++first;
- if (*first == '-')
+ if(*first == '-')
{
exponent_negative = true;
++first;
}
- else if (*first == '+')
+ else if(*first == '+')
{
++first;
}
return false;
}
- for (; first != last && IsDigit(*first); ++first)
+ for(; first != last && IsDigit(*first); ++first)
{
exponent = 10 * exponent + (*first - '0');
}
}
- if (exponent)
+ if(exponent)
{
float power_of_ten = 10;
- for (; exponent > 1; exponent--)
+ for(; exponent > 1; exponent--)
{
power_of_ten *= 10;
}
- if (exponent_negative)
+ if(exponent_negative)
{
result /= power_of_ten;
}
}
}
-
bool IsNumber(char c)
{
bool ret = false;
- switch( c )
+ switch(c)
{
case '0':
case '1':
return ret;
}
-} // anon namespace
-
+} // namespace
JsonParserState::JsonParserState(TreeNode* _root)
- : mRoot(_root), mCurrent(_root),
- mErrorDescription(nullptr), mErrorNewLine(0), mErrorColumn(0), mErrorPosition(0),
- mNumberOfParsedChars(0), mNumberOfCreatedNodes(0), mFirstParse(false),
- mState(STATE_START)
+: mRoot(_root),
+ mCurrent(_root),
+ mErrorDescription(nullptr),
+ mErrorNewLine(0),
+ mErrorColumn(0),
+ mErrorPosition(0),
+ mNumberOfParsedChars(0),
+ mNumberOfCreatedNodes(0),
+ mFirstParse(false),
+ mState(STATE_START)
{
if(_root == nullptr)
{
++mNumberOfCreatedNodes;
return node;
-
}
TreeNode* JsonParserState::NewNode(const char* name, TreeNode::NodeType type)
if(name)
{
const TreeNode* found = mCurrent.GetChild(name);
- if( nullptr != found )
+ if(nullptr != found)
{
node = const_cast<TreeNode*>(found);
}
else
{
// if root node
- if( mCurrent.GetParent() == nullptr )
+ if(mCurrent.GetParent() == nullptr)
{
node = mRoot;
}
bool c_comment = false;
bool cpp_comment = false;
- if( mIter == mEnd )
+ if(mIter == mEnd)
{
return true;
}
NewLine();
}
- if( AtLeast(2) )
+ if(AtLeast(2))
{
nextChar = mIter[1];
}
nextChar = 0;
}
- if( cpp_comment )
+ if(cpp_comment)
{
- if( '\n' == c )
+ if('\n' == c)
{
cpp_comment = false;
Advance(1);
continue; // rather than carry on as comments may be back to back
}
}
- else if( !c_comment && (c == '/' && nextChar == '/') )
+ else if(!c_comment && (c == '/' && nextChar == '/'))
{
cpp_comment = true;
}
- if( c_comment )
+ if(c_comment)
{
- if( c == '*' && nextChar == '/' )
+ if(c == '*' && nextChar == '/')
{
c_comment = false;
Advance(2);
continue;
}
}
- else if( !cpp_comment && (c == '/' && nextChar == '*') )
+ else if(!cpp_comment && (c == '/' && nextChar == '*'))
{
c_comment = true;
}
- if( ! (c_comment || cpp_comment) )
+ if(!(c_comment || cpp_comment))
{
- if( ! (c == '\x20' || c == '\x9' || c == '\xD' || c == '\xA' ) )
+ if(!(c == '\x20' || c == '\x9' || c == '\xD' || c == '\xA'))
{
break;
}
}
- if( AdvanceEnded(1) )
+ if(AdvanceEnded(1))
{
break;
}
bool JsonParserState::ParseSymbol(const std::string& symbol)
{
- if( AtLeast( symbol.size() ) )
+ if(AtLeast(symbol.size()))
{
- for(int i = 0; i < static_cast<int>( symbol.size() ); ++i)
+ for(int i = 0; i < static_cast<int>(symbol.size()); ++i)
{
if(*mIter != symbol[i])
{
bool JsonParserState::ParseTrue()
{
- if( ParseSymbol("true") )
+ if(ParseSymbol("true"))
{
mCurrent.SetInteger(1);
mCurrent.SetType(TreeNode::BOOLEAN);
bool JsonParserState::ParseFalse()
{
- if( ParseSymbol("false") )
+ if(ParseSymbol("false"))
{
mCurrent.SetInteger(0);
mCurrent.SetType(TreeNode::BOOLEAN);
bool JsonParserState::ParseNULL()
{
- if( ParseSymbol("null") )
+ if(ParseSymbol("null"))
{
mCurrent.SetType(TreeNode::IS_NULL);
return true;
bool JsonParserState::ParseNumber()
{
- mCurrent.SetType( TreeNode::INTEGER );
+ mCurrent.SetType(TreeNode::INTEGER);
VectorCharIter first = mIter;
- char c = Char();
+ char c = Char();
- if( !(c == '-' || IsNumber(c) ) )
+ if(!(c == '-' || IsNumber(c)))
{
return Error("Number must start with '-' or 0-9");
}
- while ( IsNumber(c) || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-' )
+ while(IsNumber(c) || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-')
{
- if (c == '.' || c == 'e' || c == 'E')
+ if(c == '.' || c == 'e' || c == 'E')
{
- mCurrent.SetType( TreeNode::FLOAT );
+ mCurrent.SetType(TreeNode::FLOAT);
}
Advance(1);
c = Char();
}
- if( mCurrent.GetType() == TreeNode::INTEGER )
+ if(mCurrent.GetType() == TreeNode::INTEGER)
{
int i = 0;
- if( StringToInteger(&(*first), &(*mIter), i ) )
+ if(StringToInteger(&(*first), &(*mIter), i))
{
mCurrent.SetInteger(i);
}
if(mCurrent.GetType() == TreeNode::FLOAT)
{
float f = 0.f;
- if( StringToFloat(&(*first), &(*mIter), f) )
+ if(StringToFloat(&(*first), &(*mIter), f))
{
mCurrent.SetFloat(f);
}
}
}
- return (mCurrent.GetType() == TreeNode::INTEGER) || (mCurrent.GetType() == TreeNode::FLOAT);
+ return (mCurrent.GetType() == TreeNode::INTEGER) || (mCurrent.GetType() == TreeNode::FLOAT);
}
char* JsonParserState::EncodeString()
{
- int substitution = 0;
- VectorCharIter first = mIter;
- VectorCharIter last = mIter;
+ int substitution = 0;
+ VectorCharIter first = mIter;
+ VectorCharIter last = mIter;
- while (*mIter)
+ while(*mIter)
{
- if (static_cast<unsigned char>(*mIter) < '\x20')
+ if(static_cast<unsigned char>(*mIter) < '\x20')
{
- static_cast<void>( Error("Control characters not allowed in strings") );
+ static_cast<void>(Error("Control characters not allowed in strings"));
return nullptr;
}
- else if (*mIter == '\\' && AtLeast(2))
+ else if(*mIter == '\\' && AtLeast(2))
{
- switch (*(mIter+1))
+ switch(*(mIter + 1))
{
case '"':
{
case 'u':
{
unsigned int codepoint;
- if( !AtLeast(6) )
+ if(!AtLeast(6))
{
- static_cast<void>( Error("Bad unicode codepoint; not enough characters") );
+ static_cast<void>(Error("Bad unicode codepoint; not enough characters"));
return nullptr;
}
- if ( !HexStringToUnsignedInteger(&(*(mIter + 2)), &(*(mIter + 6)), codepoint) )
+ if(!HexStringToUnsignedInteger(&(*(mIter + 2)), &(*(mIter + 6)), codepoint))
{
- static_cast<void>( Error("Bad unicode codepoint") );
+ static_cast<void>(Error("Bad unicode codepoint"));
return nullptr;
}
- if (codepoint <= 0x7F)
+ if(codepoint <= 0x7F)
{
*last = (char)codepoint;
}
- else if (codepoint <= 0x7FF)
+ else if(codepoint <= 0x7FF)
{
*last++ = (char)(0xC0 | (codepoint >> 6));
- *last = (char)(0x80 | (codepoint & 0x3F));
+ *last = (char)(0x80 | (codepoint & 0x3F));
}
- else if (codepoint <= 0xFFFF)
+ else if(codepoint <= 0xFFFF)
{
*last++ = (char)(0xE0 | (codepoint >> 12));
*last++ = (char)(0x80 | ((codepoint >> 6) & 0x3F));
- *last = (char)(0x80 | (codepoint & 0x3F));
+ *last = (char)(0x80 | (codepoint & 0x3F));
}
Advance(4);
default:
{
- static_cast<void>( Error("Unrecognized escape sequence") );
+ static_cast<void>(Error("Unrecognized escape sequence"));
return nullptr;
}
}
++last;
Advance(2);
}
- else if (*mIter == '{')
+ else if(*mIter == '{')
{
if((0 == substitution) && (*last != '\\'))
{
*last++ = *mIter;
Advance(1);
}
- else if (*mIter == '}')
+ else if(*mIter == '}')
{
if(substitution)
{
*last++ = *mIter;
Advance(1);
}
- else if (*mIter == '"')
+ else if(*mIter == '"')
{
*last = 0;
Advance(1);
} // while(*mIter)
mNumberOfParsedChars += last - first;
- mNumberOfParsedChars += 1 ; // null terminator
+ mNumberOfParsedChars += 1; // null terminator
- mCurrent.SetSubstitution( substitution > 1 );
+ mCurrent.SetSubstitution(substitution > 1);
// return true;
return &(*first);
bool JsonParserState::HandleStartState(const char* name, const char currentChar)
{
- if( '{' == currentChar )
+ if('{' == currentChar)
{
NewNode(name, TreeNode::OBJECT);
mState = STATE_OBJECT;
}
- else if( '[' == currentChar )
+ else if('[' == currentChar)
{
NewNode(name, TreeNode::ARRAY);
mState = STATE_VALUE;
bool JsonParserState::HandleObjectState(const char currentChar, const char lastCharacter)
{
- if( '}' == currentChar )
+ if('}' == currentChar)
{
if(',' == lastCharacter)
{
return Error("Unexpected comma");
}
- if( !UpToParent() )
+ if(!UpToParent())
{
return false;
}
mState = STATE_VALUE;
}
- else if ( '"' == currentChar )
+ else if('"' == currentChar)
{
mState = STATE_KEY;
}
bool JsonParserState::HandleKeyState(char*& name)
{
name = EncodeString();
- if( nullptr == name )
+ if(nullptr == name)
{
return false;
}
- if( !ParseWhiteSpace() )
+ if(!ParseWhiteSpace())
{
return false;
}
- if( ':' != Char())
+ if(':' != Char())
{
return Error("Expected ':'");
}
- if( !ParseWhiteSpace() )
+ if(!ParseWhiteSpace())
{
return false;
}
{
Advance(1);
NewNode(name, TreeNode::STRING);
- if( char* value = EncodeString() )
+ if(char* value = EncodeString())
{
mCurrent.SetString(value);
}
{
return false;
}
- if( !UpToParent() )
+ if(!UpToParent())
{
return false;
}
bool JsonParserState::HandleCharacterNumberOrHyphen(const char* name)
{
NewNode(name, TreeNode::IS_NULL);
- if( !ParseNumber() )
+ if(!ParseNumber())
{
return false;
}
- if( !UpToParent() )
+ if(!UpToParent())
{
return false;
}
{
bool handled = true;
- if( '"' == currentChar )
+ if('"' == currentChar)
{
handled = HandleCharacterQuote(name);
}
- else if( IsNumber(currentChar) || currentChar == '-' )
+ else if(IsNumber(currentChar) || currentChar == '-')
{
handled = HandleCharacterNumberOrHyphen(name);
}
- else if( '{' == currentChar )
+ else if('{' == currentChar)
{
handled = HandleCharacterBracesStart(name, lastCharacter);
}
- else if( '}' == currentChar )
+ else if('}' == currentChar)
{
handled = HandleCharacterBracesEnd(lastCharacter);
}
- else if( '[' == currentChar )
+ else if('[' == currentChar)
{
handled = HandleCharacterSquareBracketStart(name);
}
- else if( ']' == currentChar )
+ else if(']' == currentChar)
{
handled = HandleCharacterSquareBracketEnd(lastCharacter);
}
- else if( 't' == currentChar )
+ else if('t' == currentChar)
{
handled = HandleCharacterLowercaseT(name);
}
- else if( 'n' == currentChar )
+ else if('n' == currentChar)
{
handled = HandleCharacterLowercaseN(name);
}
- else if( 'f' == currentChar)
+ else if('f' == currentChar)
{
handled = HandleCharacterLowercaseF(name);
}
- else if( ',' == currentChar )
+ else if(',' == currentChar)
{
handled = HandleCharacterComma(name);
}
{
Reset();
- if( 0 == source.size() )
+ if(0 == source.size())
{
return Error("Empty source buffer to parse");
}
mIter = source.begin();
mEnd = source.end();
- char* name = nullptr;
- char currentChar = 0;
- char lastCharacter = 0;
+ char* name = nullptr;
+ char currentChar = 0;
+ char lastCharacter = 0;
- if( !ParseWhiteSpace() )
+ if(!ParseWhiteSpace())
{
return false;
}
while(mIter != mEnd)
{
lastCharacter = currentChar;
- currentChar = Char();
+ currentChar = Char();
- switch( mState )
+ switch(mState)
{
case STATE_START:
{
} // while(1)
//
- if( mState != STATE_END )
+ if(mState != STATE_END)
{
return Error("Unexpected termination character");
}
{
mCurrent = TreeNodeManipulator(mRoot);
- mErrorDescription = nullptr;
- mErrorNewLine = 0;
- mErrorColumn = 0;
- mErrorPosition = 0;
+ mErrorDescription = nullptr;
+ mErrorNewLine = 0;
+ mErrorColumn = 0;
+ mErrorPosition = 0;
}
bool JsonParserState::HandleCharacterBracesStart(const char* name, const char lastCharacter)
{
- if( '}' == lastCharacter )
+ if('}' == lastCharacter)
{
return Error("Expected a comma");
}
}
else
{
- if( !UpToParent() )
+ if(!UpToParent())
{
return false;
}
}
else
{
- if( !UpToParent() )
+ if(!UpToParent())
{
return false;
}
bool JsonParserState::HandleCharacterLowercaseT(const char* name)
{
NewNode(name, TreeNode::BOOLEAN);
- if( !ParseTrue() )
+ if(!ParseTrue())
{
return false;
}
- if( !UpToParent() )
+ if(!UpToParent())
{
return false;
}
bool JsonParserState::HandleCharacterLowercaseN(const char* name)
{
NewNode(name, TreeNode::IS_NULL);
- if( !ParseNULL() )
+ if(!ParseNULL())
{
return false;
}
- if( !UpToParent() )
+ if(!UpToParent())
{
return false;
}
bool JsonParserState::HandleCharacterLowercaseF(const char* name)
{
NewNode(name, TreeNode::BOOLEAN);
- if( !ParseFalse() )
+ if(!ParseFalse())
{
return false;
}
- if( !UpToParent() )
+ if(!UpToParent())
{
return false;
}
bool JsonParserState::HandleCharacterComma(const char* name)
{
- if( 0 == mCurrent.Size() )
+ if(0 == mCurrent.Size())
{
return Error("Missing Value");
}
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/builder/replacement.h>
-#include <dali-toolkit/internal/builder/builder-impl.h>
#include <dali-toolkit/internal/builder/builder-get-is.inl.h>
+#include <dali-toolkit/internal/builder/builder-impl.h>
+#include <dali-toolkit/internal/builder/replacement.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-namespace // anon
+namespace // anon
{
-
-Property::Value* FindReplacement( const std::string &str, const Property::Map& overrideMap, const Property::Map& defaultMap )
+Property::Value* FindReplacement(const std::string& str, const Property::Map& overrideMap, const Property::Map& defaultMap)
{
- Property::Value* ret = overrideMap.Find( str );
+ Property::Value* ret = overrideMap.Find(str);
- if ( !ret )
+ if(!ret)
{
- ret = defaultMap.Find( str );
+ ret = defaultMap.Find(str);
// @ todo
// try localized text ie dgettext. Look for colon {DOMAIN:TEXT} {LC_MESSAGE:ID_XXXX}
return ret;
}
-std::size_t FirstUnescapedChar(const std::string &initialValue, const std::size_t& startPos, const char c)
+std::size_t FirstUnescapedChar(const std::string& initialValue, const std::size_t& startPos, const char c)
{
- std::size_t pos = initialValue.find( c, startPos );
+ std::size_t pos = initialValue.find(c, startPos);
if(pos > 0)
{
- while( pos != std::string::npos )
+ while(pos != std::string::npos)
{
- if( '\\' == initialValue.at( pos-1 ) )
+ if('\\' == initialValue.at(pos - 1))
{
- pos = initialValue.find( c, pos );
+ pos = initialValue.find(c, pos);
}
else
{
return pos;
}
-bool GetSubstitutionPosition( const std::string &initialValue, std::size_t &startPos, std::size_t &size )
+bool GetSubstitutionPosition(const std::string& initialValue, std::size_t& startPos, std::size_t& size)
{
std::size_t pos = FirstUnescapedChar(initialValue, 0, '{');
- if( std::string::npos == pos )
+ if(std::string::npos == pos)
{
startPos = std::string::npos;
return false;
pos = FirstUnescapedChar(initialValue, startPos, '}');
- if( std::string::npos == pos )
+ if(std::string::npos == pos)
{
size = std::string::npos;
return false;
return true;
}
-bool ResolvePartialReplacement( const std::string &initialValue, Property::Value &out,
- const Property::Map& overrideMap, const Property::Map& defaultMap )
+bool ResolvePartialReplacement(const std::string& initialValue, Property::Value& out, const Property::Map& overrideMap, const Property::Map& defaultMap)
{
-
- if( initialValue.size() >= 2 )
+ if(initialValue.size() >= 2)
{
// eg '{"constants": { "IMAGE_DIR": "/share/images" },
// ...
std::size_t startPos = 0;
std::size_t size = std::string::npos;
- if( !GetSubstitutionPosition( initialValue, startPos, size ) )
+ if(!GetSubstitutionPosition(initialValue, startPos, size))
{
out = initialValue;
return true;
}
else
{
- const std::string str( initialValue.substr( startPos, size ) );
+ const std::string str(initialValue.substr(startPos, size));
- Property::Value* value = FindReplacement( str, overrideMap, defaultMap );
+ Property::Value* value = FindReplacement(str, overrideMap, defaultMap);
- if( !value )
+ if(!value)
{
- DALI_SCRIPT_WARNING( "Cannot find replacement for '%s'\n", str.c_str() );
+ DALI_SCRIPT_WARNING("Cannot find replacement for '%s'\n", str.c_str());
}
else
{
- if( Property::STRING != value->GetType() )
+ if(Property::STRING != value->GetType())
{
- DALI_SCRIPT_WARNING( "Cannot replace substring in non string property type='%s'. Initial value '%s'\n",
- PropertyTypes::GetName( out.GetType() ), initialValue.c_str() );
+ DALI_SCRIPT_WARNING("Cannot replace substring in non string property type='%s'. Initial value '%s'\n",
+ PropertyTypes::GetName(out.GetType()),
+ initialValue.c_str());
}
else
{
- std::string newString = \
+ std::string newString =
initialValue.substr(0, startPos - 1) +
- value->Get< std::string >() +
- initialValue.substr( startPos + size + 1 );
+ value->Get<std::string>() +
+ initialValue.substr(startPos + size + 1);
- return ResolvePartialReplacement( newString, out, overrideMap, defaultMap );
+ return ResolvePartialReplacement(newString, out, overrideMap, defaultMap);
}
}
}
return false;
}
-} // namespace anon
+} // namespace
-
-Replacement::Replacement( const Property::Map& overrideMap, const Property::Map& defaultMap )
- : mOverrideMap( &overrideMap ), mDefaultMap( &defaultMap )
+Replacement::Replacement(const Property::Map& overrideMap, const Property::Map& defaultMap)
+: mOverrideMap(&overrideMap),
+ mDefaultMap(&defaultMap)
{
-
}
namespace
Property::Map noMap;
}
-Replacement::Replacement( const Property::Map& defaultMap )
- : mOverrideMap( &noMap ), mDefaultMap( &defaultMap )
+Replacement::Replacement(const Property::Map& defaultMap)
+: mOverrideMap(&noMap),
+ mDefaultMap(&defaultMap)
{
-
}
-Replacement::Replacement( )
- : mOverrideMap( &noMap ), mDefaultMap( &noMap )
+Replacement::Replacement()
+: mOverrideMap(&noMap),
+ mDefaultMap(&noMap)
{
-
}
-OptionalString Replacement::HasFullReplacement( const TreeNode & node ) const
+OptionalString Replacement::HasFullReplacement(const TreeNode& node) const
{
OptionalString ret;
- if( node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count()) )
+ if(node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count()))
{
- OptionalString v = ::IsString( node );
- if( v )
+ OptionalString v = ::IsString(node);
+ if(v)
{
const std::string& initialValue = *v;
- if( (initialValue[ 0 ] == '{') && (initialValue[ initialValue.size() -1 ] == '}') )
+ if((initialValue[0] == '{') && (initialValue[initialValue.size() - 1] == '}'))
{
- ret = initialValue.substr( 1, initialValue.size() - 2 );
+ ret = initialValue.substr(1, initialValue.size() - 2);
}
}
}
return ret;
}
-Property::Value Replacement::GetFullReplacement( const std::string& replacementString ) const
+Property::Value Replacement::GetFullReplacement(const std::string& replacementString) const
{
Property::Value out;
- DALI_ASSERT_DEBUG( mOverrideMap && "missing map");
- DALI_ASSERT_DEBUG( mDefaultMap && "missing map");
+ DALI_ASSERT_DEBUG(mOverrideMap && "missing map");
+ DALI_ASSERT_DEBUG(mDefaultMap && "missing map");
- Property::Value* value = FindReplacement( replacementString, *mOverrideMap, *mDefaultMap );
+ Property::Value* value = FindReplacement(replacementString, *mOverrideMap, *mDefaultMap);
- if( !value )
+ if(!value)
{
DALI_SCRIPT_WARNING("Cannot find replacement for '%s'\n", replacementString.c_str());
}
#if defined(DEBUG_ENABLED)
DALI_SCRIPT_VERBOSE(" Full replacement for '%s' => to Type '%s'\n",
replacementString.c_str(),
- PropertyTypes::GetName( out.GetType()) );
+ PropertyTypes::GetName(out.GetType()));
#endif
}
return out;
}
-OptionalBoolean Replacement::IsBoolean( const TreeNode & node ) const
+OptionalBoolean Replacement::IsBoolean(const TreeNode& node) const
{
OptionalBoolean ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::BOOLEAN == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::BOOLEAN == value.GetType())
{
ret = value.Get<bool>();
}
}
else
{
- ret = ::IsBoolean( node );
+ ret = ::IsBoolean(node);
}
return ret;
}
-OptionalBoolean Replacement::IsBoolean( OptionalChild child ) const
+OptionalBoolean Replacement::IsBoolean(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsBoolean( *child );
+ return IsBoolean(*child);
}
else
{
}
}
-OptionalFloat Replacement::IsFloat( const TreeNode & node ) const
+OptionalFloat Replacement::IsFloat(const TreeNode& node) const
{
OptionalFloat ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::FLOAT == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::FLOAT == value.GetType())
{
ret = value.Get<float>();
}
}
else
{
- ret = ::IsFloat( node );
+ ret = ::IsFloat(node);
}
return ret;
}
-OptionalString Replacement::IsString( const TreeNode& node ) const
+OptionalString Replacement::IsString(const TreeNode& node) const
{
OptionalString ret;
- DALI_ASSERT_DEBUG( mOverrideMap && "missing map");
- DALI_ASSERT_DEBUG( mDefaultMap && "missing map");
+ DALI_ASSERT_DEBUG(mOverrideMap && "missing map");
+ DALI_ASSERT_DEBUG(mDefaultMap && "missing map");
- if( node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count()) )
+ if(node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count()))
{
- if( OptionalString v = ::IsString( node ) )
+ if(OptionalString v = ::IsString(node))
{
Property::Value value;
- if( ResolvePartialReplacement( *v, value, *mOverrideMap, *mDefaultMap ) )
+ if(ResolvePartialReplacement(*v, value, *mOverrideMap, *mDefaultMap))
{
- if( Property::STRING == value.GetType() )
+ if(Property::STRING == value.GetType())
{
ret = value.Get<std::string>();
#if defined(DEBUG_ENABLED)
}
else
{
- ret = ::IsString( node );
+ ret = ::IsString(node);
}
return ret;
}
-OptionalInteger Replacement::IsInteger( const TreeNode & node ) const
+OptionalInteger Replacement::IsInteger(const TreeNode& node) const
{
OptionalInteger ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::INTEGER == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::INTEGER == value.GetType())
{
ret = value.Get<int>();
}
}
else
{
- ret = ::IsInteger( node );
+ ret = ::IsInteger(node);
}
return ret;
}
-OptionalVector2 Replacement::IsVector2( const TreeNode & node ) const
+OptionalVector2 Replacement::IsVector2(const TreeNode& node) const
{
OptionalVector2 ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::VECTOR2 == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::VECTOR2 == value.GetType())
{
ret = value.Get<Vector2>();
}
}
else
{
- ret = ::IsVector2( node );
+ ret = ::IsVector2(node);
}
return ret;
}
-OptionalVector3 Replacement::IsVector3( const TreeNode & node ) const
+OptionalVector3 Replacement::IsVector3(const TreeNode& node) const
{
OptionalVector3 ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::VECTOR3 == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::VECTOR3 == value.GetType())
{
ret = value.Get<Vector3>();
}
}
else
{
- ret = ::IsVector3( node );
+ ret = ::IsVector3(node);
}
return ret;
}
-OptionalVector4 Replacement::IsVector4( const TreeNode & node ) const
+OptionalVector4 Replacement::IsVector4(const TreeNode& node) const
{
OptionalVector4 ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::VECTOR4 == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::VECTOR4 == value.GetType())
{
ret = value.Get<Vector4>();
}
}
else
{
- ret = ::IsVector4( node );
+ ret = ::IsVector4(node);
}
return ret;
}
-OptionalMatrix Replacement::IsMatrix( const TreeNode & node ) const
+OptionalMatrix Replacement::IsMatrix(const TreeNode& node) const
{
OptionalMatrix ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::MATRIX == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::MATRIX == value.GetType())
{
ret = value.Get<Matrix>();
}
}
else
{
- ret = ::IsMatrix( node );
+ ret = ::IsMatrix(node);
}
return ret;
}
-OptionalMatrix3 Replacement::IsMatrix3( const TreeNode & node ) const
+OptionalMatrix3 Replacement::IsMatrix3(const TreeNode& node) const
{
OptionalMatrix3 ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::MATRIX3 == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::MATRIX3 == value.GetType())
{
ret = value.Get<Matrix3>();
}
}
else
{
- ret = ::IsMatrix3( node );
+ ret = ::IsMatrix3(node);
}
return ret;
}
-OptionalRect Replacement::IsRect( const TreeNode & node ) const
+OptionalRect Replacement::IsRect(const TreeNode& node) const
{
OptionalRect ret;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::RECTANGLE == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::RECTANGLE == value.GetType())
{
ret = value.Get<Rect<int> >();
}
}
else
{
- ret = ::IsRect( node );
+ ret = ::IsRect(node);
}
return ret;
}
-OptionalExtents Replacement::IsExtents( const TreeNode & node ) const
+OptionalExtents Replacement::IsExtents(const TreeNode& node) const
{
OptionalExtents extents;
- if( OptionalString replace = HasFullReplacement( node ) )
+ if(OptionalString replace = HasFullReplacement(node))
{
- Property::Value value = GetFullReplacement( *replace );
- if( Property::EXTENTS == value.GetType() )
+ Property::Value value = GetFullReplacement(*replace);
+ if(Property::EXTENTS == value.GetType())
{
extents = value.Get<Extents>();
}
}
else
{
- extents = ::IsExtents( node );
+ extents = ::IsExtents(node);
}
return extents;
}
-OptionalFloat Replacement::IsFloat( OptionalChild child ) const
+OptionalFloat Replacement::IsFloat(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsFloat( *child );
+ return IsFloat(*child);
}
else
{
}
}
-
-OptionalString Replacement::IsString( OptionalChild child ) const
+OptionalString Replacement::IsString(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsString( *child );
+ return IsString(*child);
}
else
{
}
}
-OptionalInteger Replacement::IsInteger( OptionalChild child ) const
+OptionalInteger Replacement::IsInteger(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsInteger( *child );
+ return IsInteger(*child);
}
else
{
}
}
-OptionalVector2 Replacement::IsVector2( OptionalChild child ) const
+OptionalVector2 Replacement::IsVector2(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsVector2( *child );
+ return IsVector2(*child);
}
else
{
}
}
-OptionalVector3 Replacement::IsVector3( OptionalChild child ) const
+OptionalVector3 Replacement::IsVector3(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsVector3( *child );
+ return IsVector3(*child);
}
else
{
}
}
-OptionalVector4 Replacement::IsVector4( OptionalChild child ) const
+OptionalVector4 Replacement::IsVector4(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsVector4( *child );
+ return IsVector4(*child);
}
else
{
}
}
-OptionalMatrix Replacement::IsMatrix( OptionalChild child ) const
+OptionalMatrix Replacement::IsMatrix(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsMatrix( *child );
+ return IsMatrix(*child);
}
else
{
}
}
-OptionalMatrix3 Replacement::IsMatrix3( OptionalChild child ) const
+OptionalMatrix3 Replacement::IsMatrix3(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsMatrix3( *child );
+ return IsMatrix3(*child);
}
else
{
}
}
-OptionalRect Replacement::IsRect( OptionalChild child ) const
+OptionalRect Replacement::IsRect(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsRect( *child );
+ return IsRect(*child);
}
else
{
}
}
-bool Replacement::IsMap( OptionalChild child, Property::Value& out ) const
+bool Replacement::IsMap(OptionalChild child, Property::Value& out) const
{
bool ret = false;
- if( child )
+ if(child)
{
- if( OptionalString replace = HasFullReplacement( *child ) )
+ if(OptionalString replace = HasFullReplacement(*child))
{
- out = GetFullReplacement( *replace );
- if( Property::MAP == out.GetType() )
+ out = GetFullReplacement(*replace);
+ if(Property::MAP == out.GetType())
{
ret = true;
}
return ret;
}
-bool Replacement::IsArray( OptionalChild child, Property::Value& out ) const
+bool Replacement::IsArray(OptionalChild child, Property::Value& out) const
{
bool ret = false;
- if( child )
+ if(child)
{
- if( OptionalString replace = HasFullReplacement( *child ) )
+ if(OptionalString replace = HasFullReplacement(*child))
{
- out = GetFullReplacement( *replace );
- if( Property::ARRAY == out.GetType() )
+ out = GetFullReplacement(*replace);
+ if(Property::ARRAY == out.GetType())
{
ret = true;
}
return ret;
}
-OptionalExtents Replacement::IsExtents( OptionalChild child ) const
+OptionalExtents Replacement::IsExtents(OptionalChild child) const
{
- if( child )
+ if(child)
{
- return IsExtents( *child );
+ return IsExtents(*child);
}
else
{
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-#include <dali/public-api/object/handle.h>
-#include <dali/devel-api/scripting/scripting.h>
-#include <dali-toolkit/public-api/controls/control.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/builder/style.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
+#include <dali-toolkit/public-api/controls/control.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
+#include <dali/devel-api/scripting/scripting.h>
+#include <dali/public-api/object/handle.h>
namespace Dali
{
namespace Toolkit
{
-
namespace Internal
{
-
extern const Dali::Scripting::StringEnum ControlStateTable[];
-extern const unsigned int ControlStateTableCount;
+extern const unsigned int ControlStateTableCount;
StylePtr Style::New()
{
- StylePtr stylePtr( new Style() );
+ StylePtr stylePtr(new Style());
return stylePtr;
}
void Style::ApplyVisualsAndPropertiesRecursively(
- Handle handle,
- const Dictionary<Property::Map>& instancedProperties ) const
+ Handle handle,
+ const Dictionary<Property::Map>& instancedProperties) const
{
- ApplyVisuals( handle, instancedProperties );
- ApplyProperties( handle );
+ ApplyVisuals(handle, instancedProperties);
+ ApplyProperties(handle);
Toolkit::Control control = Toolkit::Control::DownCast(handle);
- if( control )
+ if(control)
{
- std::string stateName;
- Property::Value value = control.GetProperty(DevelControl::Property::STATE);
+ std::string stateName;
+ Property::Value value = control.GetProperty(DevelControl::Property::STATE);
Dali::Toolkit::DevelControl::State state = static_cast<Dali::Toolkit::DevelControl::State>(value.Get<int>());
- stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( state, ControlStateTable, ControlStateTableCount );
+ stateName = Scripting::GetEnumerationName<Toolkit::DevelControl::State>(state, ControlStateTable, ControlStateTableCount);
- if( ! stateName.empty() )
+ if(!stateName.empty())
{
// Look up state in states table:
- const StylePtr* stylePtr = subStates.FindConst( stateName );
- if( stylePtr )
+ const StylePtr* stylePtr = subStates.FindConst(stateName);
+ if(stylePtr)
{
const StylePtr statePtr(*stylePtr);
// We have a state match.
- statePtr->ApplyVisuals( handle, instancedProperties );
- statePtr->ApplyProperties( handle );
+ statePtr->ApplyVisuals(handle, instancedProperties);
+ statePtr->ApplyProperties(handle);
// Apply substate visuals
Property::Value value = control.GetProperty(DevelControl::Property::SUB_STATE);
- std::string subStateName;
- if( value.Get( subStateName ) && ! subStateName.empty() )
+ std::string subStateName;
+ if(value.Get(subStateName) && !subStateName.empty())
{
- const StylePtr* stylePtr = statePtr->subStates.FindConst( subStateName );
- if( stylePtr )
+ const StylePtr* stylePtr = statePtr->subStates.FindConst(subStateName);
+ if(stylePtr)
{
const StylePtr subStatePtr(*stylePtr);
// We have a sub-state match.
- subStatePtr->ApplyVisuals( handle, instancedProperties );
- subStatePtr->ApplyProperties( handle );
+ subStatePtr->ApplyVisuals(handle, instancedProperties);
+ subStatePtr->ApplyProperties(handle);
}
}
}
}
void Style::ApplyVisuals(
- Handle handle,
- const Dictionary<Property::Map>& instancedProperties ) const
+ Handle handle,
+ const Dictionary<Property::Map>& instancedProperties) const
{
- ApplyVisuals( handle, visuals, instancedProperties );
+ ApplyVisuals(handle, visuals, instancedProperties);
}
void Style::ApplyVisuals(
- Handle handle,
+ Handle handle,
const Dictionary<Property::Map>& visualMaps,
- const Dictionary<Property::Map>& instancedProperties )
+ const Dictionary<Property::Map>& instancedProperties)
{
- for( Dictionary<Property::Map>::iterator iter = visualMaps.Begin(); iter != visualMaps.End() ; ++iter )
+ for(Dictionary<Property::Map>::iterator iter = visualMaps.Begin(); iter != visualMaps.End(); ++iter)
{
- const std::string& visualName = (*iter).key;
- Property::Map map = (*iter).entry;
- Property::Map* instancedMap = instancedProperties.Find( visualName );
- ApplyVisual( handle, visualName, map, instancedMap );
+ const std::string& visualName = (*iter).key;
+ Property::Map map = (*iter).entry;
+ Property::Map* instancedMap = instancedProperties.Find(visualName);
+ ApplyVisual(handle, visualName, map, instancedMap);
}
}
void Style::ApplyVisual(
- Handle handle,
- const std::string& visualName,
+ Handle handle,
+ const std::string& visualName,
const Property::Map& visualMap,
- const Property::Map* instancedProperties )
+ const Property::Map* instancedProperties)
{
// Check if this visual name is a valid property of handle
- Dali::Property::Index index = handle.GetPropertyIndex( visualName );
- if( index != Property::INVALID_INDEX )
+ Dali::Property::Index index = handle.GetPropertyIndex(visualName);
+ if(index != Property::INVALID_INDEX)
{
const Property::Map* applyMap = &visualMap;
- Property::Map mergedMap;
+ Property::Map mergedMap;
// If there are instanced properties, and the visual types match,
// merge them into the visual map
- if( instancedProperties )
+ if(instancedProperties)
{
- Property::Value* instanceTypeValue = instancedProperties->Find( Toolkit::Visual::Property::TYPE);
- Property::Value* newTypeValue = visualMap.Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE );
- if( instanceTypeValue && newTypeValue )
+ Property::Value* instanceTypeValue = instancedProperties->Find(Toolkit::Visual::Property::TYPE);
+ Property::Value* newTypeValue = visualMap.Find(Toolkit::Visual::Property::TYPE, VISUAL_TYPE);
+ if(instanceTypeValue && newTypeValue)
{
- int instanceVisualType=-1;
- int newVisualType=-1;
- Scripting::GetEnumerationProperty( *instanceTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, instanceVisualType );
- Scripting::GetEnumerationProperty( *newTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, newVisualType );
+ int instanceVisualType = -1;
+ int newVisualType = -1;
+ Scripting::GetEnumerationProperty(*instanceTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, instanceVisualType);
+ Scripting::GetEnumerationProperty(*newTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, newVisualType);
- if( instanceVisualType == newVisualType )
+ if(instanceVisualType == newVisualType)
{
// Same type - merge remaining instance data
- mergedMap.Merge( visualMap );
- mergedMap.Merge( *instancedProperties );
+ mergedMap.Merge(visualMap);
+ mergedMap.Merge(*instancedProperties);
applyMap = &mergedMap;
}
}
// Apply the visual property map to the handle
const Property::Value value(const_cast<Property::Map&>(*applyMap));
- handle.SetProperty( index, value );
+ handle.SetProperty(index, value);
}
}
-void Style::ApplyProperties( Handle handle ) const
+void Style::ApplyProperties(Handle handle) const
{
- for( Property::Map::SizeType i=0; i<properties.Count(); ++i )
+ for(Property::Map::SizeType i = 0; i < properties.Count(); ++i)
{
- KeyValuePair keyValue = properties.GetKeyValue( i );
- if( keyValue.first.type == Property::Key::INDEX )
+ KeyValuePair keyValue = properties.GetKeyValue(i);
+ if(keyValue.first.type == Property::Key::INDEX)
{
- handle.SetProperty( keyValue.first.indexKey, keyValue.second );
+ handle.SetProperty(keyValue.first.indexKey, keyValue.second);
}
}
}
{
}
-
-} // Internal
-} // Toolkit
-} // Dali
+} // namespace Internal
+} // namespace Toolkit
+} // namespace Dali
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
void Indent(std::ostream& o, int level, int indentWidth)
{
- for (int i = 0; i < level*indentWidth; ++i)
+ for(int i = 0; i < level * indentWidth; ++i)
{
o << " ";
}
}
-std::string EscapeQuotes( const char* aString)
+std::string EscapeQuotes(const char* aString)
{
std::string escapedString;
- int length = strlen(aString);
+ int length = strlen(aString);
escapedString.reserve(length);
- const char* end = aString+length;
- for( const char* iter = aString; iter != end ; ++iter)
+ const char* end = aString + length;
+ for(const char* iter = aString; iter != end; ++iter)
{
if(*iter != '\"')
{
} // anonymous namespace
TreeNodeManipulator::TreeNodeManipulator(TreeNode* node)
- : mNode(node)
+: mNode(node)
{
}
DALI_ASSERT_DEBUG(from);
DALI_ASSERT_DEBUG(to);
- if( from )
+ if(from)
{
- to->mName = from->mName;
- to->mType = from->mType;
- to->mSubstituion = from->mSubstituion;
+ to->mName = from->mName;
+ to->mType = from->mType;
+ to->mSubstituion = from->mSubstituion;
switch(from->mType)
{
case TreeNode::INTEGER:
}
}
}
-
}
void TreeNodeManipulator::MoveNodeStrings(VectorCharIter& start, const VectorCharIter& sentinel)
CollectNodes collector;
- DepthFirst( mNode, collector );
+ DepthFirst(mNode, collector);
for(CollectNodes::iterator iter = collector.nodes.begin(); iter != collector.nodes.end(); ++iter)
{
- if( *iter != mNode)
+ if(*iter != mNode)
{
delete *iter;
}
DALI_ASSERT_DEBUG(from && "Operation on NULL JSON node");
DALI_ASSERT_DEBUG(to);
- for( TreeNode::ConstIterator iter = from->CBegin(); iter != from->CEnd(); ++iter)
+ for(TreeNode::ConstIterator iter = from->CBegin(); iter != from->CEnd(); ++iter)
{
const TreeNode* child = &((*iter).second);
if(child->mName)
}
}
-TreeNode *TreeNodeManipulator::AddChild(TreeNode *rhs)
+TreeNode* TreeNodeManipulator::AddChild(TreeNode* rhs)
{
DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node");
rhs->mParent = mNode;
- if (mNode->mLastChild)
+ if(mNode->mLastChild)
{
mNode->mLastChild = mNode->mLastChild->mNextSibling = rhs;
}
return mNode->Size();
}
-void TreeNodeManipulator::SetType( TreeNode::NodeType type)
+void TreeNodeManipulator::SetType(TreeNode::NodeType type)
{
DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node");
- if( mNode->mType != type )
+ if(mNode->mType != type)
{
mNode->mType = type;
- if( NULL != mNode->mFirstChild )
+ if(NULL != mNode->mFirstChild)
{
// value types have no children
- bool removeChildren = ! (TreeNode::OBJECT == type || TreeNode::ARRAY == type);
+ bool removeChildren = !(TreeNode::OBJECT == type || TreeNode::ARRAY == type);
// ie if swapping array for object
removeChildren = (removeChildren == true) ? true : type != mNode->mType;
// so remove any children
- if( removeChildren && NULL != mNode->mFirstChild)
+ if(removeChildren && NULL != mNode->mFirstChild)
{
RemoveChildren();
}
}
}
- else if( TreeNode::ARRAY == mNode->mType )
+ else if(TreeNode::ARRAY == mNode->mType)
{
- if( mNode->mFirstChild != NULL )
+ if(mNode->mFirstChild != NULL)
{
TreeNode::NodeType type = mNode->mFirstChild->GetType();
- if( TreeNode::FLOAT == type || TreeNode::INTEGER == type )
+ if(TreeNode::FLOAT == type || TreeNode::INTEGER == type)
{
// Arrays of numbers should be replaced, not appended to.
RemoveChildren();
}
}
-void TreeNodeManipulator::SetName( const char* name )
+void TreeNodeManipulator::SetName(const char* name)
{
DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node");
mNode->mName = name;
}
-void TreeNodeManipulator::SetSubstitution( bool b )
+void TreeNodeManipulator::SetSubstitution(bool b)
{
DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node");
mNode->mSubstituion = b;
return NULL == mNode ? NULL : mNode->GetChild(name);
}
-void TreeNodeManipulator::SetString( const char* string )
+void TreeNodeManipulator::SetString(const char* string)
{
DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node");
SetType(TreeNode::STRING);
mNode->mStringValue = string;
}
-void TreeNodeManipulator::SetInteger( int i )
+void TreeNodeManipulator::SetInteger(int i)
{
DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node");
SetType(TreeNode::INTEGER);
mNode->mIntValue = i;
}
-void TreeNodeManipulator::SetFloat( float f )
+void TreeNodeManipulator::SetFloat(float f)
{
DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node");
SetType(TreeNode::FLOAT);
mNode->mFloatValue = f;
}
-void TreeNodeManipulator::SetBoolean( bool b )
+void TreeNodeManipulator::SetBoolean(bool b)
{
DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node");
SetType(TreeNode::BOOLEAN);
DoWrite(mNode, output, 0, indent, false);
}
-void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, int level, int indentWidth, bool groupChildren) const
+void TreeNodeManipulator::DoWrite(const TreeNode* value, std::ostream& output, int level, int indentWidth, bool groupChildren) const
{
DALI_ASSERT_DEBUG(value && "Operation on NULL JSON node");
Indent(output, level, indentWidth);
}
- if (value->GetName())
+ if(value->GetName())
{
output << "\"" << value->GetName() << "\":";
}
{
output << ", ";
}
- if( !groupChildren )
+ if(!groupChildren)
{
output << std::endl;
}
{
bool groupMyChildren = false;
- if( TreeNode::ARRAY == value->GetType() && value->mFirstChild &&
- ( TreeNode::INTEGER == value->mFirstChild->GetType() ||
- TreeNode::FLOAT == value->mFirstChild->GetType() ) )
+ if(TreeNode::ARRAY == value->GetType() && value->mFirstChild &&
+ (TreeNode::INTEGER == value->mFirstChild->GetType() ||
+ TreeNode::FLOAT == value->mFirstChild->GetType()))
{
groupMyChildren = true;
}
- if( value->GetType() == TreeNode::OBJECT)
+ if(value->GetType() == TreeNode::OBJECT)
{
output << std::endl;
Indent(output, level, indentWidth);
}
else
{
- if( !groupMyChildren )
+ if(!groupMyChildren)
{
output << std::endl;
Indent(output, level, indentWidth);
output << "[";
}
- if( groupMyChildren )
+ if(groupMyChildren)
{
output << " ";
}
output << std::endl;
}
- for (TreeNode::ConstIterator it = value->CBegin(); it != value->CEnd(); ++it)
+ for(TreeNode::ConstIterator it = value->CBegin(); it != value->CEnd(); ++it)
{
- DoWrite( &((*it).second), output, level+1, indentWidth, groupMyChildren );
+ DoWrite(&((*it).second), output, level + 1, indentWidth, groupMyChildren);
}
- if( !groupMyChildren )
+ if(!groupMyChildren)
{
Indent(output, level, indentWidth);
}
- if( value->GetType() == TreeNode::OBJECT )
+ if(value->GetType() == TreeNode::OBJECT)
{
output << "}";
}
output << "]";
}
- if( NULL != value->mNextSibling )
+ if(NULL != value->mNextSibling)
{
output << ",";
}
- if( !groupChildren )
+ if(!groupChildren)
{
output << std::endl;
}
output << ",";
}
- if( groupChildren )
+ if(groupChildren)
{
output << " ";
}
output << ",";
}
- if( groupChildren )
+ if(groupChildren)
{
output << " ";
}
}
case TreeNode::FLOAT:
{
- output.setf( std::ios::floatfield );
+ output.setf(std::ios::floatfield);
output << value->GetFloat();
- output.unsetf( std::ios::floatfield );
+ output.unsetf(std::ios::floatfield);
if(NULL != value->mNextSibling)
{
output << ",";
}
- if( groupChildren )
+ if(groupChildren)
{
output << " ";
}
}
case TreeNode::BOOLEAN:
{
- if( value->GetInteger() )
+ if(value->GetInteger())
{
output << "true";
}
output << ",";
}
- if( groupChildren )
+ if(groupChildren)
{
output << " ";
}
const TreeNode* found = NULL;
- if( node )
+ if(node)
{
- if( NULL != (found = node->GetChild(childName)) )
+ if(NULL != (found = node->GetChild(childName)))
{
return found;
}
{
for(TreeNode::ConstIterator iter = node->CBegin(); iter != node->CEnd(); ++iter)
{
- if( NULL != (found = FindIt(childName, &((*iter).second)) ) )
+ if(NULL != (found = FindIt(childName, &((*iter).second))))
{
return found;
}
return found;
}
-char *CopyString( const char *fromString, VectorCharIter& iter, const VectorCharIter& sentinel)
+char* CopyString(const char* fromString, VectorCharIter& iter, const VectorCharIter& sentinel)
{
DALI_ASSERT_DEBUG(fromString);
DALI_ASSERT_DEBUG(iter != sentinel);
- char *start= &(*iter);
- const char *ptr = fromString;
+ char* start = &(*iter);
+ const char* ptr = fromString;
if(ptr)
{
return start;
}
-
-} // namespace internal
+} // namespace Internal
} // namespace Toolkit
// EXTERNAL INCLUDES
#include <dali/public-api/object/property-input.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/size-negotiation/relayout-container.h>
// INTERNAL INCLUDES
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
//Type Registration
BaseHandle Create()
{
return Toolkit::Alignment::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Alignment, Toolkit::Control, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Alignment, Toolkit::Control, Create)
DALI_TYPE_REGISTRATION_END()
/**
* @param currentSize of the object
* @param parentSize
*/
-inline Vector3 GetPosition( const Toolkit::Alignment::Padding& padding, Toolkit::Alignment::Type horizontalAlignment, Toolkit::Alignment::Type verticalAlignment,
- const Vector2& currentSize, const Vector2& parentSize )
+inline Vector3 GetPosition(const Toolkit::Alignment::Padding& padding, Toolkit::Alignment::Type horizontalAlignment, Toolkit::Alignment::Type verticalAlignment, const Vector2& currentSize, const Vector2& parentSize)
{
- Vector3 position( 0.f, 0.f, 0.f );
+ Vector3 position(0.f, 0.f, 0.f);
- switch( horizontalAlignment )
+ switch(horizontalAlignment)
{
case Dali::Toolkit::Alignment::HORIZONTAL_LEFT:
{
break;
}
case Dali::Toolkit::Alignment::HORIZONTAL_CENTER: // FALLTHROUGH
- default: // use center as default
+ default: // use center as default
{
- if( currentSize.width + padding.left + padding.right >= parentSize.width )
+ if(currentSize.width + padding.left + padding.right >= parentSize.width)
{
- position.x += 0.5f * ( padding.left - padding.right );
+ position.x += 0.5f * (padding.left - padding.right);
}
break;
}
}
- switch( verticalAlignment )
+ switch(verticalAlignment)
{
case Dali::Toolkit::Alignment::VERTICAL_TOP:
{
break;
}
case Dali::Toolkit::Alignment::VERTICAL_CENTER: // FALLTHROUGH
- default: // use center as default
+ default: // use center as default
{
- if( currentSize.height + padding.top + padding.bottom >= parentSize.height )
+ if(currentSize.height + padding.top + padding.bottom >= parentSize.height)
{
- position.y += 0.5f * ( padding.top - padding.bottom );
+ position.y += 0.5f * (padding.top - padding.bottom);
}
break;
}
} // namespace
-Toolkit::Alignment Alignment::New( Toolkit::Alignment::Type horizontal, Toolkit::Alignment::Type vertical )
+Toolkit::Alignment Alignment::New(Toolkit::Alignment::Type horizontal, Toolkit::Alignment::Type vertical)
{
// Create the implementation, temporarily owned on stack
- IntrusivePtr< Alignment > internalAlignment = new Alignment( horizontal, vertical );
+ IntrusivePtr<Alignment> internalAlignment = new Alignment(horizontal, vertical);
// Pass ownership to Toolkit::Alignment
- Toolkit::Alignment alignment( *internalAlignment );
+ Toolkit::Alignment alignment(*internalAlignment);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return alignment;
}
-void Alignment::SetAlignmentType( Toolkit::Alignment::Type type )
+void Alignment::SetAlignmentType(Toolkit::Alignment::Type type)
{
// Horizontal Alignment
- if( type & Toolkit::Alignment::HORIZONTAL_RIGHT )
+ if(type & Toolkit::Alignment::HORIZONTAL_RIGHT)
{
mHorizontal = Toolkit::Alignment::HORIZONTAL_RIGHT;
}
- if( type & Toolkit::Alignment::HORIZONTAL_LEFT )
+ if(type & Toolkit::Alignment::HORIZONTAL_LEFT)
{
mHorizontal = Toolkit::Alignment::HORIZONTAL_LEFT;
}
- if( type & Toolkit::Alignment::HORIZONTAL_CENTER )
+ if(type & Toolkit::Alignment::HORIZONTAL_CENTER)
{
mHorizontal = Toolkit::Alignment::HORIZONTAL_CENTER;
}
// Vertical Alignment
- if( type & Toolkit::Alignment::VERTICAL_BOTTOM )
+ if(type & Toolkit::Alignment::VERTICAL_BOTTOM)
{
mVertical = Toolkit::Alignment::VERTICAL_BOTTOM;
}
- if( type & Toolkit::Alignment::VERTICAL_TOP )
+ if(type & Toolkit::Alignment::VERTICAL_TOP)
{
mVertical = Toolkit::Alignment::VERTICAL_TOP;
}
- if( type & Toolkit::Alignment::VERTICAL_CENTER )
+ if(type & Toolkit::Alignment::VERTICAL_CENTER)
{
mVertical = Toolkit::Alignment::VERTICAL_CENTER;
}
Toolkit::Alignment::Type Alignment::GetAlignmentType() const
{
- return Toolkit::Alignment::Type( mHorizontal | mVertical );
+ return Toolkit::Alignment::Type(mHorizontal | mVertical);
}
-void Alignment::SetScaling( Toolkit::Alignment::Scaling scaling )
+void Alignment::SetScaling(Toolkit::Alignment::Scaling scaling)
{
mScaling = scaling;
return mScaling;
}
-void Alignment::SetPadding( const Toolkit::Alignment::Padding& padding )
+void Alignment::SetPadding(const Toolkit::Alignment::Padding& padding)
{
- DALI_ASSERT_ALWAYS( ( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f ) );
+ DALI_ASSERT_ALWAYS((padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f));
mPadding = padding;
void Alignment::OnInitialize()
{
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER));
+ });
}
-void Alignment::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void Alignment::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
// lay out the actors
- Vector3 anchorPointAndParentOrigin = Vector3::ZERO;
- anchorPointAndParentOrigin.z = 0.5f;
+ Vector3 anchorPointAndParentOrigin = Vector3::ZERO;
+ anchorPointAndParentOrigin.z = 0.5f;
// anchorPoint.x is initialized to 0.0, which is HORIZONTAL_LEFT
- if( Toolkit::Alignment::HORIZONTAL_CENTER == mHorizontal )
+ if(Toolkit::Alignment::HORIZONTAL_CENTER == mHorizontal)
{
anchorPointAndParentOrigin.x = 0.5f;
}
- else if( Toolkit::Alignment::HORIZONTAL_RIGHT == mHorizontal )
+ else if(Toolkit::Alignment::HORIZONTAL_RIGHT == mHorizontal)
{
anchorPointAndParentOrigin.x = 1.0f;
}
// anchorPoint.y is initialized to 0.0, which is VERTICAL_TOP
- if( Toolkit::Alignment::VERTICAL_CENTER == mVertical )
+ if(Toolkit::Alignment::VERTICAL_CENTER == mVertical)
{
anchorPointAndParentOrigin.y = 0.5f;
}
- else if( Toolkit::Alignment::VERTICAL_BOTTOM == mVertical )
+ else if(Toolkit::Alignment::VERTICAL_BOTTOM == mVertical)
{
anchorPointAndParentOrigin.y = 1.0f;
}
- for( unsigned int i = 0, childCount = Self().GetChildCount(); i < childCount; ++i )
+ for(unsigned int i = 0, childCount = Self().GetChildCount(); i < childCount; ++i)
{
Actor child = Self().GetChildAt(i);
- child.SetProperty( Actor::Property::ANCHOR_POINT, anchorPointAndParentOrigin );
- child.SetProperty( Actor::Property::PARENT_ORIGIN, anchorPointAndParentOrigin );
+ child.SetProperty(Actor::Property::ANCHOR_POINT, anchorPointAndParentOrigin);
+ child.SetProperty(Actor::Property::PARENT_ORIGIN, anchorPointAndParentOrigin);
- Vector2 currentChildSize( child.GetTargetSize().GetVectorXY() );
- if( currentChildSize == Vector2::ZERO )
+ Vector2 currentChildSize(child.GetTargetSize().GetVectorXY());
+ if(currentChildSize == Vector2::ZERO)
{
currentChildSize = child.GetNaturalSize();
}
- bool renegotiate = true;
+ bool renegotiate = true;
Vector2 newChildSize;
- newChildSize.width = size.width - ( mPadding.left + mPadding.right );
- newChildSize.height = size.height- ( mPadding.top + mPadding.bottom );
+ newChildSize.width = size.width - (mPadding.left + mPadding.right);
+ newChildSize.height = size.height - (mPadding.top + mPadding.bottom);
// prevent ridiculous sizes if parent is really small or if we don't have a proper size for the actor
- if( ( newChildSize.width > Math::MACHINE_EPSILON_1000 ) && ( newChildSize.height > Math::MACHINE_EPSILON_1000 ) &&
- ( currentChildSize.width > Math::MACHINE_EPSILON_1000 ) && ( currentChildSize.height > Math::MACHINE_EPSILON_1000 ) )
+ if((newChildSize.width > Math::MACHINE_EPSILON_1000) && (newChildSize.height > Math::MACHINE_EPSILON_1000) &&
+ (currentChildSize.width > Math::MACHINE_EPSILON_1000) && (currentChildSize.height > Math::MACHINE_EPSILON_1000))
{
// no point trying to squeeze actors into too small size
- switch( mScaling )
+ switch(mScaling)
{
case Toolkit::Alignment::SCALE_NONE:
{
}
case Toolkit::Alignment::SCALE_TO_FIT_KEEP_ASPECT:
{
- newChildSize = currentChildSize * std::min( ( newChildSize.width / currentChildSize.width ), ( newChildSize.height / currentChildSize.height ) );
+ newChildSize = currentChildSize * std::min((newChildSize.width / currentChildSize.width), (newChildSize.height / currentChildSize.height));
break;
}
case Toolkit::Alignment::SCALE_TO_FILL_KEEP_ASPECT:
{
- newChildSize = currentChildSize * std::max( ( newChildSize.width / currentChildSize.width ), ( newChildSize.height / currentChildSize.height ) );
+ newChildSize = currentChildSize * std::max((newChildSize.width / currentChildSize.width), (newChildSize.height / currentChildSize.height));
break;
}
case Toolkit::Alignment::SHRINK_TO_FIT:
{
- newChildSize = Vector2( std::min( newChildSize.width, currentChildSize.width ), std::min( newChildSize.height, currentChildSize.height ) );
+ newChildSize = Vector2(std::min(newChildSize.width, currentChildSize.width), std::min(newChildSize.height, currentChildSize.height));
break;
}
case Toolkit::Alignment::SHRINK_TO_FIT_KEEP_ASPECT:
{
// check source size vs target size to see if we need to shrink
- float widthScale = ( newChildSize.width < currentChildSize.width ) ? (newChildSize.width / currentChildSize.width) : 1.f;
- float heightScale = ( newChildSize.height < currentChildSize.height ) ? (newChildSize.height / currentChildSize.height) : 1.0f;
+ float widthScale = (newChildSize.width < currentChildSize.width) ? (newChildSize.width / currentChildSize.width) : 1.f;
+ float heightScale = (newChildSize.height < currentChildSize.height) ? (newChildSize.height / currentChildSize.height) : 1.0f;
// use smaller of the scales
- float scale = std::min( widthScale, heightScale );
+ float scale = std::min(widthScale, heightScale);
// check if we need to scale
- if( scale < 1.0f )
+ if(scale < 1.0f)
{
// scale natural size to fit inside
newChildSize *= scale;
}
}
- child.SetProperty( Actor::Property::POSITION, GetPosition( mPadding, mHorizontal, mVertical , newChildSize, currentChildSize ) );
+ child.SetProperty(Actor::Property::POSITION, GetPosition(mPadding, mHorizontal, mVertical, newChildSize, currentChildSize));
- if( renegotiate )
+ if(renegotiate)
{
- container.Add( child, newChildSize );
+ container.Add(child, newChildSize);
}
}
}
-Alignment::Alignment( Toolkit::Alignment::Type horizontal, Toolkit::Alignment::Type vertical )
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mHorizontal( horizontal ),
- mVertical( vertical ),
- mScaling( Toolkit::Alignment::SCALE_NONE ),
- mPadding( 0.f, 0.f, 0.f, 0.f )
+Alignment::Alignment(Toolkit::Alignment::Type horizontal, Toolkit::Alignment::Type vertical)
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mHorizontal(horizontal),
+ mVertical(vertical),
+ mScaling(Toolkit::Alignment::SCALE_NONE),
+ mPadding(0.f, 0.f, 0.f, 0.f)
{
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "bloom-view-impl.h"
// EXTERNAL INCLUDES
-#include <sstream>
-#include <iomanip>
+#include <dali/devel-api/common/stage.h>
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/animation/constraints.h>
-#include <dali/devel-api/common/stage.h>
#include <dali/public-api/object/property-map.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/render-tasks/render-task-list.h>
#include <dali/public-api/rendering/renderer.h>
+#include <iomanip>
+#include <sstream>
// INTERNAL INCLUDES
-#include <dali-toolkit/devel-api/controls/gaussian-blur-view/gaussian-blur-view.h>
#include <dali-toolkit/devel-api/controls/bloom-view/bloom-view.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
-#include <dali-toolkit/internal/controls/gaussian-blur-view/gaussian-blur-view-impl.h>
-#include <dali-toolkit/internal/controls/control/control-renderers.h>
+#include <dali-toolkit/devel-api/controls/gaussian-blur-view/gaussian-blur-view.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/controls/control/control-renderers.h>
+#include <dali-toolkit/internal/controls/gaussian-blur-view/gaussian-blur-view-impl.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
using namespace Dali;
BaseHandle Create()
return Toolkit::BloomView::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::BloomView, Toolkit::Control, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::BloomView, Toolkit::Control, Create)
DALI_TYPE_REGISTRATION_END()
// default parameters
-const float BLOOM_THRESHOLD_DEFAULT = 0.25f;
+const float BLOOM_THRESHOLD_DEFAULT = 0.25f;
const float BLOOM_BLUR_STRENGTH_DEFAULT = 1.0f;
-const float BLOOM_INTENSITY_DEFAULT = 1.0f;
-const float IMAGE_INTENSITY_DEFAULT = 1.0f;
-const float BLOOM_SATURATION_DEFAULT = 1.0f;
-const float IMAGE_SATURATION_DEFAULT = 1.0f;
+const float BLOOM_INTENSITY_DEFAULT = 1.0f;
+const float IMAGE_INTENSITY_DEFAULT = 1.0f;
+const float BLOOM_SATURATION_DEFAULT = 1.0f;
+const float IMAGE_SATURATION_DEFAULT = 1.0f;
// gaussian blur
-const unsigned int BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5;
-const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f;
+const unsigned int BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5;
+const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f;
const Pixel::Format BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888;
-const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_FADE_IN = 1.0f; // default, fully blurred
-const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
-const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
+const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_FADE_IN = 1.0f; // default, fully blurred
+const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
+const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f;
-const char* const BLOOM_BLUR_STRENGTH_PROPERTY_NAME = "BlurStrengthProperty";
-const char* const BLOOM_THRESHOLD_PROPERTY_NAME = "uBloomThreshold";
+const char* const BLOOM_BLUR_STRENGTH_PROPERTY_NAME = "BlurStrengthProperty";
+const char* const BLOOM_THRESHOLD_PROPERTY_NAME = "uBloomThreshold";
const char* const RECIP_ONE_MINUS_BLOOM_THRESHOLD_PROPERTY_NAME = "uRecipOneMinusBloomThreshold";
-const char* const BLOOM_INTENSITY_PROPERTY_NAME = "uBloomIntensity";
-const char* const BLOOM_SATURATION_PROPERTY_NAME = "uBloomSaturation";
-const char* const IMAGE_INTENSITY_PROPERTY_NAME = "uImageIntensity";
-const char* const IMAGE_SATURATION_PROPERTY_NAME = "uImageSaturation";
+const char* const BLOOM_INTENSITY_PROPERTY_NAME = "uBloomIntensity";
+const char* const BLOOM_SATURATION_PROPERTY_NAME = "uBloomSaturation";
+const char* const IMAGE_INTENSITY_PROPERTY_NAME = "uImageIntensity";
+const char* const IMAGE_SATURATION_PROPERTY_NAME = "uImageSaturation";
} // namespace
-
-
BloomView::BloomView()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mBlurNumSamples(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES),
mBlurBellCurveWidth(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH),
mPixelFormat(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT),
mDownsampleWidthScale(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE),
mDownsampleHeightScale(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE),
- mDownsampledWidth( 0.0f ),
- mDownsampledHeight( 0.0f ),
+ mDownsampledWidth(0.0f),
+ mDownsampledHeight(0.0f),
mTargetSize(Vector2::ZERO),
mLastSize(Vector2::ZERO),
mChildrenRoot(Actor::New()),
- mInternalRoot(Actor::New() ),
+ mInternalRoot(Actor::New()),
mBloomThresholdPropertyIndex(Property::INVALID_INDEX),
mBlurStrengthPropertyIndex(Property::INVALID_INDEX),
mBloomIntensityPropertyIndex(Property::INVALID_INDEX),
mBloomSaturationPropertyIndex(Property::INVALID_INDEX),
mImageIntensityPropertyIndex(Property::INVALID_INDEX),
mImageSaturationPropertyIndex(Property::INVALID_INDEX),
- mActivated( false )
+ mActivated(false)
{
}
-BloomView::BloomView( const unsigned int blurNumSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat,
- const float downsampleWidthScale, const float downsampleHeightScale)
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+BloomView::BloomView(const unsigned int blurNumSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, const float downsampleWidthScale, const float downsampleHeightScale)
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mBlurNumSamples(blurNumSamples),
mBlurBellCurveWidth(blurBellCurveWidth),
mPixelFormat(renderTargetPixelFormat),
mDownsampleWidthScale(downsampleWidthScale),
mDownsampleHeightScale(downsampleHeightScale),
- mDownsampledWidth( 0.0f ),
- mDownsampledHeight( 0.0f ),
+ mDownsampledWidth(0.0f),
+ mDownsampledHeight(0.0f),
mTargetSize(Vector2::ZERO),
mLastSize(Vector2::ZERO),
mChildrenRoot(Actor::New()),
mBloomSaturationPropertyIndex(Property::INVALID_INDEX),
mImageIntensityPropertyIndex(Property::INVALID_INDEX),
mImageSaturationPropertyIndex(Property::INVALID_INDEX),
- mActivated( false )
+ mActivated(false)
{
}
{
BloomView* impl = new BloomView();
- Dali::Toolkit::BloomView handle = Dali::Toolkit::BloomView( *impl );
+ Dali::Toolkit::BloomView handle = Dali::Toolkit::BloomView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-Toolkit::BloomView BloomView::New(const unsigned int blurNumSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat,
- const float downsampleWidthScale, const float downsampleHeightScale)
+Toolkit::BloomView BloomView::New(const unsigned int blurNumSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, const float downsampleWidthScale, const float downsampleHeightScale)
{
- BloomView* impl = new BloomView( blurNumSamples, blurBellCurveWidth, renderTargetPixelFormat, downsampleWidthScale, downsampleHeightScale);
+ BloomView* impl = new BloomView(blurNumSamples, blurBellCurveWidth, renderTargetPixelFormat, downsampleWidthScale, downsampleHeightScale);
- Dali::Toolkit::BloomView handle = Dali::Toolkit::BloomView( *impl );
+ Dali::Toolkit::BloomView handle = Dali::Toolkit::BloomView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
void BloomView::OnInitialize()
{
// root actor to parent all user added actors, needed to allow us to set that subtree as exclusive for our child render task
- mChildrenRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mInternalRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mChildrenRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mInternalRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
//////////////////////////////////////////////////////
// Create actors
// Create an image view for rendering from the scene texture to the bloom texture
mBloomExtractActor = Actor::New();
- mBloomExtractActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mBloomExtractActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
// Create an image view for compositing the result (scene and bloom textures) to output
mCompositeActor = Actor::New();
- mCompositeActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mCompositeActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
// Create an image view for holding final result, i.e. the blurred image. This will get rendered to screen later, via default / user render task
mTargetActor = Actor::New();
- mTargetActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mTargetActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
// Create the Gaussian Blur object + render tasks
// Note that we use mBloomExtractTarget as the source image and also re-use this as the gaussian blur final render target. This saves the gaussian blur code from creating it
// render targets etc internally, so we make better use of resources
// Note, this also internally creates the render tasks used by the Gaussian blur, this must occur after the bloom extraction and before the compositing
mGaussianBlurView = Dali::Toolkit::GaussianBlurView::New(mBlurNumSamples, mBlurBellCurveWidth, mPixelFormat, mDownsampleWidthScale, mDownsampleHeightScale, true);
- mGaussianBlurView.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
-
+ mGaussianBlurView.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
//////////////////////////////////////////////////////
// Create cameras for the renders corresponding to the (potentially downsampled) render targets' size
mRenderDownsampledCamera = CameraActor::New();
- mRenderDownsampledCamera.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- mRenderDownsampledCamera.SetInvertYAxis( true );
+ mRenderDownsampledCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mRenderDownsampledCamera.SetInvertYAxis(true);
mRenderFullSizeCamera = CameraActor::New();
- mRenderFullSizeCamera.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- mRenderFullSizeCamera.SetInvertYAxis( true );
-
+ mRenderFullSizeCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mRenderFullSizeCamera.SetInvertYAxis(true);
////////////////////////////////
// Connect to actor tree
- Self().Add( mChildrenRoot );
- Self().Add( mInternalRoot );
- mInternalRoot.Add( mBloomExtractActor );
- mInternalRoot.Add( mGaussianBlurView );
- mInternalRoot.Add( mCompositeActor );
- mInternalRoot.Add( mTargetActor );
- mInternalRoot.Add( mRenderDownsampledCamera );
- mInternalRoot.Add( mRenderFullSizeCamera );
+ Self().Add(mChildrenRoot);
+ Self().Add(mInternalRoot);
+ mInternalRoot.Add(mBloomExtractActor);
+ mInternalRoot.Add(mGaussianBlurView);
+ mInternalRoot.Add(mCompositeActor);
+ mInternalRoot.Add(mTargetActor);
+ mInternalRoot.Add(mRenderDownsampledCamera);
+ mInternalRoot.Add(mRenderFullSizeCamera);
// bind properties for / set shader constants to defaults
SetupProperties();
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::ANIMATION ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::ANIMATION));
+ });
}
void BloomView::OnSizeSet(const Vector3& targetSize)
{
mTargetSize = Vector2(targetSize);
- mChildrenRoot.SetProperty( Actor::Property::SIZE, targetSize);
- mCompositeActor.SetProperty( Actor::Property::SIZE, targetSize);
- mTargetActor.SetProperty( Actor::Property::SIZE, targetSize);
+ mChildrenRoot.SetProperty(Actor::Property::SIZE, targetSize);
+ mCompositeActor.SetProperty(Actor::Property::SIZE, targetSize);
+ mTargetActor.SetProperty(Actor::Property::SIZE, targetSize);
// Children render camera must move when GaussianBlurView object is
// resized. This is since we cannot change render target size - so we need
// this is the trade off for not being able to modify render target size
// Change camera z position based on GaussianBlurView actor height
float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f);
- mRenderFullSizeCamera.SetProperty( Actor::Property::POSITION_Z, mTargetSize.height * cameraPosConstraintScale);
+ mRenderFullSizeCamera.SetProperty(Actor::Property::POSITION_Z, mTargetSize.height * cameraPosConstraintScale);
// if we have already activated the blur, need to update render target sizes now to reflect the new size of this actor
if(mActivated)
Activate();
}
- Control::OnSizeSet( targetSize );
+ Control::OnSizeSet(targetSize);
}
-void BloomView::OnChildAdd( Actor& child )
+void BloomView::OnChildAdd(Actor& child)
{
- if( child != mChildrenRoot && child != mInternalRoot)
+ if(child != mChildrenRoot && child != mInternalRoot)
{
- mChildrenRoot.Add( child );
+ mChildrenRoot.Add(child);
}
- Control::OnChildAdd( child );
+ Control::OnChildAdd(child);
}
-void BloomView::OnChildRemove( Actor& child )
+void BloomView::OnChildRemove(Actor& child)
{
- mChildrenRoot.Remove( child );
+ mChildrenRoot.Remove(child);
- Control::OnChildRemove( child );
+ Control::OnChildRemove(child);
}
void BloomView::AllocateResources()
mLastSize = mTargetSize;
// get size of downsampled render targets
- mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale;
+ mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale;
mDownsampledHeight = mTargetSize.height * mDownsampleHeightScale;
-
//////////////////////////////////////////////////////
// Create cameras
mRenderDownsampledCamera.SetAspectRatio(mDownsampledWidth / mDownsampledHeight);
mRenderDownsampledCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
- mRenderDownsampledCamera.SetProperty( Actor::Property::POSITION, Vector3( 0.0f, 0.0f, ( ( mDownsampledHeight * 0.5f ) / tanf( ARBITRARY_FIELD_OF_VIEW * 0.5f ) ) ) );
+ mRenderDownsampledCamera.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, ((mDownsampledHeight * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f))));
// Create and place a camera for the children render, corresponding to its render target size
mRenderFullSizeCamera.SetFieldOfView(ARBITRARY_FIELD_OF_VIEW);
mRenderFullSizeCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f);
- mRenderFullSizeCamera.SetProperty( Actor::Property::POSITION, Vector3( 0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale ) );
+ mRenderFullSizeCamera.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale));
//////////////////////////////////////////////////////
// Pass size change onto GaussianBlurView, so it matches
- mGaussianBlurView.SetProperty( Actor::Property::SIZE, mTargetSize );
+ mGaussianBlurView.SetProperty(Actor::Property::SIZE, mTargetSize);
GetImpl(mGaussianBlurView).AllocateResources();
- mGaussianBlurView.SetProperty( Actor::Property::VISIBLE, true );
+ mGaussianBlurView.SetProperty(Actor::Property::VISIBLE, true);
//////////////////////////////////////////////////////
// Create render targets
// create off screen buffer of new size to render our child actors to
- mRenderTargetForRenderingChildren = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture textureForChildren = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mRenderTargetForRenderingChildren.AttachColorTexture( textureForChildren );
+ mRenderTargetForRenderingChildren = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture textureForChildren = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mRenderTargetForRenderingChildren.AttachColorTexture(textureForChildren);
- mBloomExtractTarget = FrameBuffer::New( mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE );
- Texture texture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight) );
- mBloomExtractTarget.AttachColorTexture( texture );
+ mBloomExtractTarget = FrameBuffer::New(mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE);
+ Texture texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight));
+ mBloomExtractTarget.AttachColorTexture(texture);
- FrameBuffer blurExtractTarget = FrameBuffer::New( mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE );
- texture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight) );
- blurExtractTarget.AttachColorTexture( texture );
+ FrameBuffer blurExtractTarget = FrameBuffer::New(mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE);
+ texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight));
+ blurExtractTarget.AttachColorTexture(texture);
- mOutputRenderTarget = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture outputTexture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mOutputRenderTarget.AttachColorTexture( outputTexture );
+ mOutputRenderTarget = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture outputTexture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mOutputRenderTarget.AttachColorTexture(outputTexture);
//////////////////////////////////////////////////////
// Point actors and render tasks at new render targets
- Renderer bloomRenderer = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_BLOOM_VIEW_EXTRACT_SHADER_FRAG );
- SetRendererTexture( bloomRenderer, mRenderTargetForRenderingChildren );
- mBloomExtractActor.AddRenderer( bloomRenderer );
- mBloomExtractActor.SetProperty( Actor::Property::SIZE, Vector2( mDownsampledWidth, mDownsampledHeight ) ); // size needs to match render target
+ Renderer bloomRenderer = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_BLOOM_VIEW_EXTRACT_SHADER_FRAG);
+ SetRendererTexture(bloomRenderer, mRenderTargetForRenderingChildren);
+ mBloomExtractActor.AddRenderer(bloomRenderer);
+ mBloomExtractActor.SetProperty(Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight)); // size needs to match render target
// set GaussianBlurView to blur our extracted bloom
- mGaussianBlurView.SetUserImageAndOutputRenderTarget( mBloomExtractTarget.GetColorTexture(), blurExtractTarget );
+ mGaussianBlurView.SetUserImageAndOutputRenderTarget(mBloomExtractTarget.GetColorTexture(), blurExtractTarget);
// use the completed blur in the first buffer and composite with the original child actors render
- Renderer compositeRenderer = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_BLOOM_VIEW_COMPOSITE_SHADER_FRAG );
- SetRendererTexture( compositeRenderer, mRenderTargetForRenderingChildren );
+ Renderer compositeRenderer = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_BLOOM_VIEW_COMPOSITE_SHADER_FRAG);
+ SetRendererTexture(compositeRenderer, mRenderTargetForRenderingChildren);
TextureSet textureSet = compositeRenderer.GetTextures();
- textureSet.SetTexture( 0u, mRenderTargetForRenderingChildren.GetColorTexture() );
- textureSet.SetTexture( 1u, blurExtractTarget.GetColorTexture() );
- mCompositeActor.AddRenderer( compositeRenderer );
+ textureSet.SetTexture(0u, mRenderTargetForRenderingChildren.GetColorTexture());
+ textureSet.SetTexture(1u, blurExtractTarget.GetColorTexture());
+ mCompositeActor.AddRenderer(compositeRenderer);
// set up target actor for rendering result, i.e. the blurred image
- Renderer targetRenderer = CreateRenderer( BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE );
- SetRendererTexture( targetRenderer, mOutputRenderTarget );
- mTargetActor.AddRenderer( targetRenderer );
+ Renderer targetRenderer = CreateRenderer(BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE);
+ SetRendererTexture(targetRenderer, mOutputRenderTarget);
+ mTargetActor.AddRenderer(targetRenderer);
}
}
// create render task to render our child actors to offscreen buffer
mRenderChildrenTask = taskList.CreateTask();
- mRenderChildrenTask.SetSourceActor( mChildrenRoot );
+ mRenderChildrenTask.SetSourceActor(mChildrenRoot);
mRenderChildrenTask.SetExclusive(true);
- mRenderChildrenTask.SetInputEnabled( false );
- mRenderChildrenTask.SetClearEnabled( true );
+ mRenderChildrenTask.SetInputEnabled(false);
+ mRenderChildrenTask.SetClearEnabled(true);
mRenderChildrenTask.SetCameraActor(mRenderFullSizeCamera); // use camera that covers render target exactly
- mRenderChildrenTask.SetFrameBuffer( mRenderTargetForRenderingChildren );
+ mRenderChildrenTask.SetFrameBuffer(mRenderTargetForRenderingChildren);
// Extract the bright part of the image and render to a new buffer. Downsampling also occurs at this stage to save pixel fill, if it is set up.
mBloomExtractTask = taskList.CreateTask();
- mBloomExtractTask.SetSourceActor( mBloomExtractActor );
+ mBloomExtractTask.SetSourceActor(mBloomExtractActor);
mBloomExtractTask.SetExclusive(true);
- mBloomExtractTask.SetInputEnabled( false );
- mBloomExtractTask.SetClearEnabled( true );
+ mBloomExtractTask.SetInputEnabled(false);
+ mBloomExtractTask.SetClearEnabled(true);
mBloomExtractTask.SetCameraActor(mRenderDownsampledCamera);
- mBloomExtractTask.SetFrameBuffer( mBloomExtractTarget );
+ mBloomExtractTask.SetFrameBuffer(mBloomExtractTarget);
// GaussianBlurView tasks must be created here, so they are executed in the correct order with respect to BloomView tasks
GetImpl(mGaussianBlurView).CreateRenderTasks();
// Use an image view displaying the children render and composite it with the blurred bloom buffer, targeting the output
mCompositeTask = taskList.CreateTask();
- mCompositeTask.SetSourceActor( mCompositeActor );
+ mCompositeTask.SetSourceActor(mCompositeActor);
mCompositeTask.SetExclusive(true);
- mCompositeTask.SetInputEnabled( false );
- mCompositeTask.SetClearEnabled( true );
+ mCompositeTask.SetInputEnabled(false);
+ mCompositeTask.SetClearEnabled(true);
mCompositeTask.SetCameraActor(mRenderFullSizeCamera);
- mCompositeTask.SetFrameBuffer( mOutputRenderTarget );
+ mCompositeTask.SetFrameBuffer(mOutputRenderTarget);
}
void BloomView::RemoveRenderTasks()
mOutputRenderTarget.Reset();
// Reset children
- mBloomExtractActor.RemoveRenderer( 0u );
- mTargetActor.RemoveRenderer( 0u );
- mCompositeActor.RemoveRenderer( 0u );
+ mBloomExtractActor.RemoveRenderer(0u);
+ mTargetActor.RemoveRenderer(0u);
+ mCompositeActor.RemoveRenderer(0u);
- mGaussianBlurView.SetProperty( Actor::Property::VISIBLE, false );
+ mGaussianBlurView.SetProperty(Actor::Property::VISIBLE, false);
mActivated = false;
}
*/
struct RecipOneMinusConstraint
{
- RecipOneMinusConstraint(){}
+ RecipOneMinusConstraint()
+ {
+ }
- void operator()( float& current, const PropertyInputContainer& inputs )
+ void operator()(float& current, const PropertyInputContainer& inputs)
{
- current = 1.0f / ( 1.0f - inputs[0]->GetFloat() );
+ current = 1.0f / (1.0f - inputs[0]->GetFloat());
}
};
{
CustomActor self = Self();
-
///////////////////////////////////////////
// bloom threshold
// set defaults, makes sure properties are registered with shader
- mBloomExtractActor.RegisterProperty( BLOOM_THRESHOLD_PROPERTY_NAME, BLOOM_THRESHOLD_DEFAULT );
- mBloomExtractActor.RegisterProperty( RECIP_ONE_MINUS_BLOOM_THRESHOLD_PROPERTY_NAME, 1.0f / (1.0f - BLOOM_THRESHOLD_DEFAULT) );
+ mBloomExtractActor.RegisterProperty(BLOOM_THRESHOLD_PROPERTY_NAME, BLOOM_THRESHOLD_DEFAULT);
+ mBloomExtractActor.RegisterProperty(RECIP_ONE_MINUS_BLOOM_THRESHOLD_PROPERTY_NAME, 1.0f / (1.0f - BLOOM_THRESHOLD_DEFAULT));
// Register a property that the user can control to change the bloom threshold
- mBloomThresholdPropertyIndex = self.RegisterProperty(BLOOM_THRESHOLD_PROPERTY_NAME, BLOOM_THRESHOLD_DEFAULT);
+ mBloomThresholdPropertyIndex = self.RegisterProperty(BLOOM_THRESHOLD_PROPERTY_NAME, BLOOM_THRESHOLD_DEFAULT);
Property::Index shaderBloomThresholdPropertyIndex = mBloomExtractActor.GetPropertyIndex(BLOOM_THRESHOLD_PROPERTY_NAME);
- Constraint bloomThresholdConstraint = Constraint::New<float>( mBloomExtractActor, shaderBloomThresholdPropertyIndex, EqualToConstraint());
- bloomThresholdConstraint.AddSource( Source(self, mBloomThresholdPropertyIndex) );
+ Constraint bloomThresholdConstraint = Constraint::New<float>(mBloomExtractActor, shaderBloomThresholdPropertyIndex, EqualToConstraint());
+ bloomThresholdConstraint.AddSource(Source(self, mBloomThresholdPropertyIndex));
bloomThresholdConstraint.Apply();
// precalc 1.0 / (1.0 - threshold) on CPU to save shader insns, using constraint to tie to the normal threshold property
Property::Index shaderRecipOneMinusBloomThresholdPropertyIndex = mBloomExtractActor.GetPropertyIndex(RECIP_ONE_MINUS_BLOOM_THRESHOLD_PROPERTY_NAME);
- Constraint thresholdConstraint = Constraint::New<float>( mBloomExtractActor, shaderRecipOneMinusBloomThresholdPropertyIndex, RecipOneMinusConstraint());
- thresholdConstraint.AddSource( LocalSource(shaderBloomThresholdPropertyIndex) );
+ Constraint thresholdConstraint = Constraint::New<float>(mBloomExtractActor, shaderRecipOneMinusBloomThresholdPropertyIndex, RecipOneMinusConstraint());
+ thresholdConstraint.AddSource(LocalSource(shaderBloomThresholdPropertyIndex));
thresholdConstraint.Apply();
-
////////////////////////////////////////////
// bloom strength
// Register a property that the user can control to fade the blur in / out via internal GaussianBlurView object
- mBlurStrengthPropertyIndex = self.RegisterProperty(BLOOM_BLUR_STRENGTH_PROPERTY_NAME, BLOOM_BLUR_STRENGTH_DEFAULT);
- Constraint blurStrengthConstraint = Constraint::New<float>( mGaussianBlurView, mGaussianBlurView.GetBlurStrengthPropertyIndex(), EqualToConstraint());
- blurStrengthConstraint.AddSource( Source(self, mBlurStrengthPropertyIndex) );
+ mBlurStrengthPropertyIndex = self.RegisterProperty(BLOOM_BLUR_STRENGTH_PROPERTY_NAME, BLOOM_BLUR_STRENGTH_DEFAULT);
+ Constraint blurStrengthConstraint = Constraint::New<float>(mGaussianBlurView, mGaussianBlurView.GetBlurStrengthPropertyIndex(), EqualToConstraint());
+ blurStrengthConstraint.AddSource(Source(self, mBlurStrengthPropertyIndex));
blurStrengthConstraint.Apply();
-
////////////////////////////////////////////
// bloom intensity
// Register a property that the user can control to fade the bloom intensity via internally hidden shader
mBloomIntensityPropertyIndex = self.RegisterProperty(BLOOM_INTENSITY_PROPERTY_NAME, BLOOM_INTENSITY_DEFAULT);
- mCompositeActor.RegisterProperty( BLOOM_INTENSITY_PROPERTY_NAME, BLOOM_INTENSITY_DEFAULT );
+ mCompositeActor.RegisterProperty(BLOOM_INTENSITY_PROPERTY_NAME, BLOOM_INTENSITY_DEFAULT);
Property::Index shaderBloomIntensityPropertyIndex = mCompositeActor.GetPropertyIndex(BLOOM_INTENSITY_PROPERTY_NAME);
- Constraint bloomIntensityConstraint = Constraint::New<float>( mCompositeActor, shaderBloomIntensityPropertyIndex, EqualToConstraint());
- bloomIntensityConstraint.AddSource( Source(self, mBloomIntensityPropertyIndex) );
+ Constraint bloomIntensityConstraint = Constraint::New<float>(mCompositeActor, shaderBloomIntensityPropertyIndex, EqualToConstraint());
+ bloomIntensityConstraint.AddSource(Source(self, mBloomIntensityPropertyIndex));
bloomIntensityConstraint.Apply();
-
////////////////////////////////////////////
// bloom saturation
// Register a property that the user can control to fade the bloom saturation via internally hidden shader
mBloomSaturationPropertyIndex = self.RegisterProperty(BLOOM_SATURATION_PROPERTY_NAME, BLOOM_SATURATION_DEFAULT);
- mCompositeActor.RegisterProperty( BLOOM_SATURATION_PROPERTY_NAME, BLOOM_SATURATION_DEFAULT );
+ mCompositeActor.RegisterProperty(BLOOM_SATURATION_PROPERTY_NAME, BLOOM_SATURATION_DEFAULT);
Property::Index shaderBloomSaturationPropertyIndex = mCompositeActor.GetPropertyIndex(BLOOM_SATURATION_PROPERTY_NAME);
- Constraint bloomSaturationConstraint = Constraint::New<float>( mCompositeActor, shaderBloomSaturationPropertyIndex, EqualToConstraint());
- bloomSaturationConstraint.AddSource( Source(self, mBloomSaturationPropertyIndex) );
+ Constraint bloomSaturationConstraint = Constraint::New<float>(mCompositeActor, shaderBloomSaturationPropertyIndex, EqualToConstraint());
+ bloomSaturationConstraint.AddSource(Source(self, mBloomSaturationPropertyIndex));
bloomSaturationConstraint.Apply();
-
////////////////////////////////////////////
// image intensity
// Register a property that the user can control to fade the image intensity via internally hidden shader
mImageIntensityPropertyIndex = self.RegisterProperty(IMAGE_INTENSITY_PROPERTY_NAME, IMAGE_INTENSITY_DEFAULT);
- mCompositeActor.RegisterProperty( IMAGE_INTENSITY_PROPERTY_NAME, IMAGE_INTENSITY_DEFAULT );
+ mCompositeActor.RegisterProperty(IMAGE_INTENSITY_PROPERTY_NAME, IMAGE_INTENSITY_DEFAULT);
Property::Index shaderImageIntensityPropertyIndex = mCompositeActor.GetPropertyIndex(IMAGE_INTENSITY_PROPERTY_NAME);
- Constraint imageIntensityConstraint = Constraint::New<float>( mCompositeActor, shaderImageIntensityPropertyIndex, EqualToConstraint());
- imageIntensityConstraint.AddSource( Source(self, mImageIntensityPropertyIndex) );
+ Constraint imageIntensityConstraint = Constraint::New<float>(mCompositeActor, shaderImageIntensityPropertyIndex, EqualToConstraint());
+ imageIntensityConstraint.AddSource(Source(self, mImageIntensityPropertyIndex));
imageIntensityConstraint.Apply();
-
////////////////////////////////////////////
// image saturation
// Register a property that the user can control to fade the image saturation via internally hidden shader
mImageSaturationPropertyIndex = self.RegisterProperty(IMAGE_SATURATION_PROPERTY_NAME, IMAGE_SATURATION_DEFAULT);
- mCompositeActor.RegisterProperty( IMAGE_SATURATION_PROPERTY_NAME, IMAGE_SATURATION_DEFAULT );
+ mCompositeActor.RegisterProperty(IMAGE_SATURATION_PROPERTY_NAME, IMAGE_SATURATION_DEFAULT);
Property::Index shaderImageSaturationPropertyIndex = mCompositeActor.GetPropertyIndex(IMAGE_SATURATION_PROPERTY_NAME);
- Constraint imageSaturationConstraint = Constraint::New<float>( mCompositeActor, shaderImageSaturationPropertyIndex, EqualToConstraint());
- imageSaturationConstraint.AddSource( Source(self, mImageSaturationPropertyIndex) );
+ Constraint imageSaturationConstraint = Constraint::New<float>(mCompositeActor, shaderImageSaturationPropertyIndex, EqualToConstraint());
+ imageSaturationConstraint.AddSource(Source(self, mImageSaturationPropertyIndex));
imageSaturationConstraint.Apply();
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
#include <dali/public-api/animation/animation.h>
#include <dali/public-api/render-tasks/render-task-list.h>
-#include <dali/public-api/rendering/texture.h>
#include <dali/public-api/rendering/shader.h>
+#include <dali/public-api/rendering/texture.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/controls/bubble-effect/bubble-effect.h>
struct Vertex
{
Vertex()
- : index( 0.0f ), position(), textureCoord()
+ : index(0.0f),
+ position(),
+ textureCoord()
{
}
- Vertex( float index, const Dali::Vector2& position, const Dali::Vector2& textureCoord )
- : index( index ), position( position ), textureCoord( textureCoord )
+ Vertex(float index, const Dali::Vector2& position, const Dali::Vector2& textureCoord)
+ : index(index),
+ position(position),
+ textureCoord(textureCoord)
{
}
- float index;
+ float index;
Dali::Vector2 position;
Dali::Vector2 textureCoord;
};
*/
float RandomRange(float f0, float f1, unsigned int& seed)
{
- return f0 + (rand_r( &seed ) & 0xfff) * (f1-f0) * (1.0f/4095.0f);
+ return f0 + (rand_r(&seed) & 0xfff) * (f1 - f0) * (1.0f / 4095.0f);
}
Dali::Geometry CreateTexturedQuad()
Dali::Vector2 texCoord;
};
- static const Vertex data[] = {{ Dali::Vector2( -0.5f, -0.5f ), Dali::Vector2( 0.0f, 0.0f ) },
- { Dali::Vector2( 0.5f, -0.5f ), Dali::Vector2( 1.0f, 0.0f ) },
- { Dali::Vector2( -0.5f, 0.5f ), Dali::Vector2( 0.0f, 1.0f ) },
- { Dali::Vector2( 0.5f, 0.5f ), Dali::Vector2( 1.0f, 1.0f ) }};
+ static const Vertex data[] = {{Dali::Vector2(-0.5f, -0.5f), Dali::Vector2(0.0f, 0.0f)},
+ {Dali::Vector2(0.5f, -0.5f), Dali::Vector2(1.0f, 0.0f)},
+ {Dali::Vector2(-0.5f, 0.5f), Dali::Vector2(0.0f, 1.0f)},
+ {Dali::Vector2(0.5f, 0.5f), Dali::Vector2(1.0f, 1.0f)}};
// Create a vertex buffer for vertex positions and texture coordinates
- Dali::VertexBuffer vertexBuffer = Dali::VertexBuffer::New( Dali::Property::Map()
- .Add( "aPosition", Dali::Property::VECTOR2 )
- .Add( "aTexCoord", Dali::Property::VECTOR2 ) );
- vertexBuffer.SetData( data, 4u );
+ Dali::VertexBuffer vertexBuffer = Dali::VertexBuffer::New(Dali::Property::Map()
+ .Add("aPosition", Dali::Property::VECTOR2)
+ .Add("aTexCoord", Dali::Property::VECTOR2));
+ vertexBuffer.SetData(data, 4u);
//Create the geometry
Dali::Geometry geometry = Dali::Geometry::New();
- geometry.AddVertexBuffer( vertexBuffer );
- geometry.SetType(Dali::Geometry::TRIANGLE_STRIP );
+ geometry.AddVertexBuffer(vertexBuffer);
+ geometry.SetType(Dali::Geometry::TRIANGLE_STRIP);
return geometry;
}
-}
+} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-BubbleEmitter::BubbleEmitter( const Vector2& movementArea,
- Texture shapeTexture,
- unsigned int maximumNumberOfBubble,
- const Vector2& bubbleSizeRange )
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mShapeTexture( shapeTexture ),
- mMovementArea( movementArea ),
- mBubbleSizeRange( bubbleSizeRange ),
- mDensity( 5 ),
- mTotalNumOfBubble( maximumNumberOfBubble ),
- mCurrentBubble( 0 ),
- mRandomSeed( 0 ),
+BubbleEmitter::BubbleEmitter(const Vector2& movementArea,
+ Texture shapeTexture,
+ unsigned int maximumNumberOfBubble,
+ const Vector2& bubbleSizeRange)
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mShapeTexture(shapeTexture),
+ mMovementArea(movementArea),
+ mBubbleSizeRange(bubbleSizeRange),
+ mDensity(5),
+ mTotalNumOfBubble(maximumNumberOfBubble),
+ mCurrentBubble(0),
+ mRandomSeed(0),
mRenderTaskRunning(false)
{
// Calculate how many shaders are required
- if( mTotalNumOfBubble>100 )
+ if(mTotalNumOfBubble > 100)
{
mNumBubblePerRenderer = 100;
- mNumRenderer = mTotalNumOfBubble / 100;
- if( mNumRenderer*mNumBubblePerRenderer < mTotalNumOfBubble )
+ mNumRenderer = mTotalNumOfBubble / 100;
+ if(mNumRenderer * mNumBubblePerRenderer < mTotalNumOfBubble)
{
mNumRenderer++;
- mNumBubblePerRenderer = mTotalNumOfBubble / mNumRenderer+1;
- mTotalNumOfBubble = mNumRenderer * mNumBubblePerRenderer;
+ mNumBubblePerRenderer = mTotalNumOfBubble / mNumRenderer + 1;
+ mTotalNumOfBubble = mNumRenderer * mNumBubblePerRenderer;
}
}
else
{
mNumBubblePerRenderer = mTotalNumOfBubble;
- mNumRenderer = 1;
+ mNumRenderer = 1;
}
- mRandomSeed = time( NULL );
+ mRandomSeed = time(NULL);
}
BubbleEmitter::~BubbleEmitter()
{
}
-Toolkit::BubbleEmitter BubbleEmitter::New( const Vector2& winSize,
- Texture shapeTexture,
- unsigned int maximumNumberOfBubble,
- const Vector2& bubbleSizeRange )
+Toolkit::BubbleEmitter BubbleEmitter::New(const Vector2& winSize,
+ Texture shapeTexture,
+ unsigned int maximumNumberOfBubble,
+ const Vector2& bubbleSizeRange)
{
// Create the implementation
- IntrusivePtr<BubbleEmitter> internalBubbleEmitter ( new BubbleEmitter( winSize, shapeTexture,
- maximumNumberOfBubble,bubbleSizeRange ) );
+ IntrusivePtr<BubbleEmitter> internalBubbleEmitter(new BubbleEmitter(winSize, shapeTexture, maximumNumberOfBubble, bubbleSizeRange));
// Pass ownership to Toolkit::BubbleEmitter handle
- Toolkit::BubbleEmitter bubbleEmitter( *internalBubbleEmitter );
+ Toolkit::BubbleEmitter bubbleEmitter(*internalBubbleEmitter);
//Second phase of implementeation : Initialization
internalBubbleEmitter->OnInitialize();
{
// Create the root actor, all the meshActor should be its children
mBubbleRoot = Actor::New();
- mBubbleRoot.SetProperty( Actor::Property::SIZE, mMovementArea );
+ mBubbleRoot.SetProperty(Actor::Property::SIZE, mMovementArea);
// Prepare the frame buffer to store the color adjusted background texture
- Vector2 imageSize = Vector2( mMovementArea.width/4.f, mMovementArea.height/4.f );
- mFrameBuffer = FrameBuffer::New( imageSize.x, imageSize.y, FrameBuffer::Attachment::NONE );
- mEffectTexture = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, imageSize.x, imageSize.y );
- mFrameBuffer.AttachColorTexture( mEffectTexture );
+ Vector2 imageSize = Vector2(mMovementArea.width / 4.f, mMovementArea.height / 4.f);
+ mFrameBuffer = FrameBuffer::New(imageSize.x, imageSize.y, FrameBuffer::Attachment::NONE);
+ mEffectTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, imageSize.x, imageSize.y);
+ mFrameBuffer.AttachColorTexture(mEffectTexture);
// Generate the geometry, which is used by all bubbleActors
- mMeshGeometry = CreateGeometry( mNumBubblePerRenderer*mDensity );
+ mMeshGeometry = CreateGeometry(mNumBubblePerRenderer * mDensity);
- Shader bubbleShader = CreateBubbleShader( mNumBubblePerRenderer );
+ Shader bubbleShader = CreateBubbleShader(mNumBubblePerRenderer);
mTextureSet = TextureSet::New();
- mTextureSet.SetTexture( 0u, mEffectTexture );
- mTextureSet.SetTexture( 1u, mShapeTexture );
+ mTextureSet.SetTexture(0u, mEffectTexture);
+ mTextureSet.SetTexture(1u, mShapeTexture);
// Create the renderers to render the bubbles
- mBubbleRenderers.resize( mNumRenderer );
- for(unsigned int i=0; i < mNumRenderer; i++ )
+ mBubbleRenderers.resize(mNumRenderer);
+ for(unsigned int i = 0; i < mNumRenderer; i++)
{
- mBubbleRenderers[i].Initialize( mNumBubblePerRenderer, mMovementArea, mMeshGeometry, mTextureSet, bubbleShader );
- mBubbleRoot.AddRenderer( mBubbleRenderers[i].GetRenderer() );
+ mBubbleRenderers[i].Initialize(mNumBubblePerRenderer, mMovementArea, mMeshGeometry, mTextureSet, bubbleShader);
+ mBubbleRoot.AddRenderer(mBubbleRenderers[i].GetRenderer());
}
// Create a cameraActor for the off screen render task.
mCameraActor = CameraActor::New(mMovementArea);
- mCameraActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
Stage stage = Stage::GetCurrent();
return mBubbleRoot;
}
-void BubbleEmitter::SetBackground( Texture bgTexture, const Vector3& hsvDelta )
+void BubbleEmitter::SetBackground(Texture bgTexture, const Vector3& hsvDelta)
{
mBackgroundTexture = bgTexture;
- mHSVDelta = hsvDelta;
+ mHSVDelta = hsvDelta;
//Create RenderTask source actor
Actor sourceActor = Actor::New();
- sourceActor.SetProperty( Actor::Property::SIZE, mMovementArea );
- sourceActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- sourceActor.RegisterProperty( "uHSVDelta", hsvDelta );
- Stage::GetCurrent().Add( sourceActor );
+ sourceActor.SetProperty(Actor::Property::SIZE, mMovementArea);
+ sourceActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ sourceActor.RegisterProperty("uHSVDelta", hsvDelta);
+ Stage::GetCurrent().Add(sourceActor);
//Create renderer
- Dali::Geometry geometry = CreateTexturedQuad();
- Shader shader = Shader::New( SHADER_BUBBLE_EMITTER_VERT, SHADER_BUBBLE_EMITTER_FRAG );
- Renderer renderer = Renderer::New( geometry, shader );
- TextureSet textureSet = TextureSet::New();
- textureSet.SetTexture(0u, bgTexture );
- renderer.SetTextures( textureSet );
- sourceActor.AddRenderer( renderer );
+ Dali::Geometry geometry = CreateTexturedQuad();
+ Shader shader = Shader::New(SHADER_BUBBLE_EMITTER_VERT, SHADER_BUBBLE_EMITTER_FRAG);
+ Renderer renderer = Renderer::New(geometry, shader);
+ TextureSet textureSet = TextureSet::New();
+ textureSet.SetTexture(0u, bgTexture);
+ renderer.SetTextures(textureSet);
+ sourceActor.AddRenderer(renderer);
RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
- RenderTask task = taskList.CreateTask();
- task.SetRefreshRate( RenderTask::REFRESH_ONCE );
- task.SetSourceActor( sourceActor );
+ RenderTask task = taskList.CreateTask();
+ task.SetRefreshRate(RenderTask::REFRESH_ONCE);
+ task.SetSourceActor(sourceActor);
task.SetExclusive(true);
task.SetCameraActor(mCameraActor);
task.GetCameraActor().SetInvertYAxis(true);
- task.SetFrameBuffer( mFrameBuffer );
+ task.SetFrameBuffer(mFrameBuffer);
task.FinishedSignal().Connect(this, &BubbleEmitter::OnRenderFinished);
mRenderTaskRunning = true;
}
-void BubbleEmitter::SetBubbleShape( Texture shapeTexture )
+void BubbleEmitter::SetBubbleShape(Texture shapeTexture)
{
- mTextureSet.SetTexture( 1, shapeTexture );
+ mTextureSet.SetTexture(1, shapeTexture);
}
-void BubbleEmitter::SetBubbleScale( float scale )
+void BubbleEmitter::SetBubbleScale(float scale)
{
- for(unsigned int i=0; i < mNumRenderer; i++ )
+ for(unsigned int i = 0; i < mNumRenderer; i++)
{
- mBubbleRenderers[i].SetDynamicScale( scale );
+ mBubbleRenderers[i].SetDynamicScale(scale);
}
}
-void BubbleEmitter::SetBubbleDensity( unsigned int density )
+void BubbleEmitter::SetBubbleDensity(unsigned int density)
{
- DALI_ASSERT_ALWAYS( density>0 && density<=9 && " Only densities between 1 to 9 are valid " );
+ DALI_ASSERT_ALWAYS(density > 0 && density <= 9 && " Only densities between 1 to 9 are valid ");
- if( density == mDensity )
+ if(density == mDensity)
{
return;
}
else
{
- mDensity = density;
- mMeshGeometry = CreateGeometry( mNumBubblePerRenderer*mDensity );
- for(unsigned int i=0; i < mNumRenderer; i++ )
+ mDensity = density;
+ mMeshGeometry = CreateGeometry(mNumBubblePerRenderer * mDensity);
+ for(unsigned int i = 0; i < mNumRenderer; i++)
{
- mBubbleRenderers[i].SetGeometry( mMeshGeometry );
+ mBubbleRenderers[i].SetGeometry(mMeshGeometry);
}
}
}
void BubbleEmitter::OnRenderFinished(RenderTask& source)
{
mRenderTaskRunning = false;
- Actor sourceActor = source.GetSourceActor();
- Stage stage = Stage::GetCurrent();
+ Actor sourceActor = source.GetSourceActor();
+ Stage stage = Stage::GetCurrent();
stage.Remove(sourceActor);
stage.GetRenderTaskList().RemoveTask(source);
}
{
// Context was lost, so the framebuffer has been destroyed. Re-create render task
// and trigger re-draw if not already running
- if( ! mRenderTaskRunning )
+ if(!mRenderTaskRunning)
{
- SetBackground( mBackgroundTexture, mHSVDelta );
+ SetBackground(mBackgroundTexture, mHSVDelta);
}
}
-void BubbleEmitter::EmitBubble( Animation& animation, const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement )
+void BubbleEmitter::EmitBubble(Animation& animation, const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement)
{
- unsigned int curUniform = mCurrentBubble % mNumBubblePerRenderer;
- unsigned int groupIdx = mCurrentBubble / mNumBubblePerRenderer;
- SetBubbleParameter( mBubbleRenderers[groupIdx], curUniform, emitPosition - Vector2(mMovementArea.x*0.5f,mMovementArea.y*0.5f), direction, displacement);
- animation.AnimateTo( mBubbleRenderers[groupIdx].GetPercentageProperty(curUniform),
- 1.f, AlphaFunction::LINEAR );
+ unsigned int curUniform = mCurrentBubble % mNumBubblePerRenderer;
+ unsigned int groupIdx = mCurrentBubble / mNumBubblePerRenderer;
+ SetBubbleParameter(mBubbleRenderers[groupIdx], curUniform, emitPosition - Vector2(mMovementArea.x * 0.5f, mMovementArea.y * 0.5f), direction, displacement);
+ animation.AnimateTo(mBubbleRenderers[groupIdx].GetPercentageProperty(curUniform),
+ 1.f,
+ AlphaFunction::LINEAR);
mCurrentBubble = (mCurrentBubble + 1) % mTotalNumOfBubble;
}
void BubbleEmitter::Restore()
{
- for(unsigned int i=0; i < mNumRenderer; i++ )
+ for(unsigned int i = 0; i < mNumRenderer; i++)
{
mBubbleRenderers[i].ResetProperties();
}
}
-Geometry BubbleEmitter::CreateGeometry( unsigned int numOfPatch )
+Geometry BubbleEmitter::CreateGeometry(unsigned int numOfPatch)
{
- unsigned int numVertex = numOfPatch*4u;
+ unsigned int numVertex = numOfPatch * 4u;
Vector<Vertex> vertexData;
- vertexData.Reserve( numVertex );
+ vertexData.Reserve(numVertex);
- unsigned int numIndex = numOfPatch*6u;
+ unsigned int numIndex = numOfPatch * 6u;
Vector<unsigned short> indexData;
- indexData.Reserve( numIndex );
+ indexData.Reserve(numIndex);
for(unsigned int i = 0; i < numOfPatch; i++)
{
float halfSize = RandomRange(mBubbleSizeRange.x, mBubbleSizeRange.y, mRandomSeed) * 0.5f;
- float index = static_cast<float>( i );
- vertexData.PushBack( Vertex( index, Vector2(-halfSize,-halfSize),Vector2(0.f,0.f) ) );
- vertexData.PushBack( Vertex( index, Vector2(-halfSize, halfSize), Vector2(0.f,1.f) ) );
- vertexData.PushBack( Vertex( index, Vector2( halfSize, halfSize), Vector2(1.f,1.f) ) );
- vertexData.PushBack( Vertex( index, Vector2( halfSize,-halfSize), Vector2(1.f,0.f) ) );
+ float index = static_cast<float>(i);
+ vertexData.PushBack(Vertex(index, Vector2(-halfSize, -halfSize), Vector2(0.f, 0.f)));
+ vertexData.PushBack(Vertex(index, Vector2(-halfSize, halfSize), Vector2(0.f, 1.f)));
+ vertexData.PushBack(Vertex(index, Vector2(halfSize, halfSize), Vector2(1.f, 1.f)));
+ vertexData.PushBack(Vertex(index, Vector2(halfSize, -halfSize), Vector2(1.f, 0.f)));
unsigned short idx = index * 4;
- indexData.PushBack( idx );
- indexData.PushBack( idx+1 );
- indexData.PushBack( idx+2 );
- indexData.PushBack( idx );
- indexData.PushBack( idx+2 );
- indexData.PushBack( idx+3 );
+ indexData.PushBack(idx);
+ indexData.PushBack(idx + 1);
+ indexData.PushBack(idx + 2);
+ indexData.PushBack(idx);
+ indexData.PushBack(idx + 2);
+ indexData.PushBack(idx + 3);
}
Property::Map vertexFormat;
- vertexFormat["aIndex"] = Property::FLOAT;
+ vertexFormat["aIndex"] = Property::FLOAT;
vertexFormat["aPosition"] = Property::VECTOR2;
vertexFormat["aTexCoord"] = Property::VECTOR2;
- VertexBuffer vertices = VertexBuffer::New( vertexFormat );
- vertices.SetData( &vertexData[0], numVertex );
+ VertexBuffer vertices = VertexBuffer::New(vertexFormat);
+ vertices.SetData(&vertexData[0], numVertex);
Geometry geometry = Geometry::New();
- geometry.AddVertexBuffer( vertices );
- geometry.SetIndexBuffer( &indexData[0], numIndex );
+ geometry.AddVertexBuffer(vertices);
+ geometry.SetIndexBuffer(&indexData[0], numIndex);
return geometry;
}
-void BubbleEmitter::SetBubbleParameter( BubbleRenderer& bubbleRenderer, unsigned int curUniform,
- const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement )
+void BubbleEmitter::SetBubbleParameter(BubbleRenderer& bubbleRenderer, unsigned int curUniform, const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement)
{
Vector2 dir(direction);
int halfRange = displacement.x / 2;
// for the y coordinate, always negative, so bubbles always go upwards
- Vector2 randomVec( rand_r( &mRandomSeed ) % static_cast<int>(displacement.x) - halfRange, -rand_r( &mRandomSeed ) % static_cast<int>(displacement.y) );
+ Vector2 randomVec(rand_r(&mRandomSeed) % static_cast<int>(displacement.x) - halfRange, -rand_r(&mRandomSeed) % static_cast<int>(displacement.y));
dir.Normalize();
- randomVec.x -= dir.x*halfRange;
- randomVec.y *= 1.0f - fabsf(dir.x)*0.33f;
+ randomVec.x -= dir.x * halfRange;
+ randomVec.y *= 1.0f - fabsf(dir.x) * 0.33f;
if(randomVec.y > 0.0f)
{
randomVec.y *= 0.33f;
}
- Vector4 startAndEndPos( emitPosition.x, emitPosition.y, emitPosition.x+randomVec.x, emitPosition.y+randomVec.y );
- bubbleRenderer.SetStartAndEndPosition( curUniform, startAndEndPos );
+ Vector4 startAndEndPos(emitPosition.x, emitPosition.y, emitPosition.x + randomVec.x, emitPosition.y + randomVec.y);
+ bubbleRenderer.SetStartAndEndPosition(curUniform, startAndEndPos);
- bubbleRenderer.SetPercentage( curUniform, 0.f);
+ bubbleRenderer.SetPercentage(curUniform, 0.f);
}
} // namespace Internal
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
BubbleRenderer::BubbleRenderer()
: mRenderer(),
mIndicesOffset(),
mIndiceStartEndPos(),
mIndicesPercentage(),
- mIndexGravity( Property::INVALID_INDEX ),
- mIndexDynamicScale( Property::INVALID_INDEX ),
- mIndexInvertedMovementArea( Property::INVALID_INDEX )
+ mIndexGravity(Property::INVALID_INDEX),
+ mIndexDynamicScale(Property::INVALID_INDEX),
+ mIndexInvertedMovementArea(Property::INVALID_INDEX)
{
}
-void BubbleRenderer::Initialize( unsigned int numberOfBubble, const Vector2& movementArea, Geometry geometry, TextureSet textureSet, Shader shader )
+void BubbleRenderer::Initialize(unsigned int numberOfBubble, const Vector2& movementArea, Geometry geometry, TextureSet textureSet, Shader shader)
{
- if( mRenderer )
+ if(mRenderer)
{
// This function is supposed to be called once
return;
}
- mRenderer = Renderer::New( geometry, shader );
- mRenderer.SetTextures( textureSet );
+ mRenderer = Renderer::New(geometry, shader);
+ mRenderer.SetTextures(textureSet);
// register uniforms
- mIndexGravity = mRenderer.RegisterProperty( "uGravity", 50.f );
- mIndexDynamicScale = mRenderer.RegisterProperty( "uDynamicScale", 1.f );
+ mIndexGravity = mRenderer.RegisterProperty("uGravity", 50.f);
+ mIndexDynamicScale = mRenderer.RegisterProperty("uDynamicScale", 1.f);
- mIndexInvertedMovementArea = mRenderer.RegisterProperty( "uInvertedMovementArea", Vector2(1.f,1.f) / movementArea );
+ mIndexInvertedMovementArea = mRenderer.RegisterProperty("uInvertedMovementArea", Vector2(1.f, 1.f) / movementArea);
mIndicesOffset.resize(9);
int offset = movementArea.Length() / 10.f;
- unsigned int seed = time( NULL );
+ unsigned int seed = time(NULL);
- mIndicesOffset[0] = mRenderer.RegisterProperty( "uOffset[0]", Vector2( 0.f,0.f ) );
- mIndicesOffset[1] = mRenderer.RegisterProperty( "uOffset[1]", Vector2( rand_r( &seed ) % offset, rand_r( &seed ) % offset ) );
- mIndicesOffset[2] = mRenderer.RegisterProperty( "uOffset[2]", Vector2( rand_r( &seed ) % offset, -rand_r( &seed ) % offset ) );
- mIndicesOffset[3] = mRenderer.RegisterProperty( "uOffset[3]", Vector2(-rand_r( &seed ) % offset, rand_r( &seed ) % offset ) );
- mIndicesOffset[4] = mRenderer.RegisterProperty( "uOffset[4]", Vector2(-rand_r( &seed ) % offset, -rand_r( &seed ) % offset ) );
- mIndicesOffset[5] = mRenderer.RegisterProperty( "uOffset[5]", Vector2( rand_r( &seed ) % offset, 0.f ) );
- mIndicesOffset[6] = mRenderer.RegisterProperty( "uOffset[6]", Vector2(-rand_r( &seed ) % offset, 0.f ) );
- mIndicesOffset[7] = mRenderer.RegisterProperty( "uOffset[7]", Vector2( 0.f, rand_r( &seed ) % offset ) );
- mIndicesOffset[8] = mRenderer.RegisterProperty( "uOffset[8]", Vector2( 0.f, -rand_r( &seed ) % offset ) );
+ mIndicesOffset[0] = mRenderer.RegisterProperty("uOffset[0]", Vector2(0.f, 0.f));
+ mIndicesOffset[1] = mRenderer.RegisterProperty("uOffset[1]", Vector2(rand_r(&seed) % offset, rand_r(&seed) % offset));
+ mIndicesOffset[2] = mRenderer.RegisterProperty("uOffset[2]", Vector2(rand_r(&seed) % offset, -rand_r(&seed) % offset));
+ mIndicesOffset[3] = mRenderer.RegisterProperty("uOffset[3]", Vector2(-rand_r(&seed) % offset, rand_r(&seed) % offset));
+ mIndicesOffset[4] = mRenderer.RegisterProperty("uOffset[4]", Vector2(-rand_r(&seed) % offset, -rand_r(&seed) % offset));
+ mIndicesOffset[5] = mRenderer.RegisterProperty("uOffset[5]", Vector2(rand_r(&seed) % offset, 0.f));
+ mIndicesOffset[6] = mRenderer.RegisterProperty("uOffset[6]", Vector2(-rand_r(&seed) % offset, 0.f));
+ mIndicesOffset[7] = mRenderer.RegisterProperty("uOffset[7]", Vector2(0.f, rand_r(&seed) % offset));
+ mIndicesOffset[8] = mRenderer.RegisterProperty("uOffset[8]", Vector2(0.f, -rand_r(&seed) % offset));
Vector4 zeroVector;
- mIndiceStartEndPos.resize( numberOfBubble );
- mIndicesPercentage.resize( numberOfBubble );
- for( unsigned int i=0; i<numberOfBubble; i++ )
+ mIndiceStartEndPos.resize(numberOfBubble);
+ mIndicesPercentage.resize(numberOfBubble);
+ for(unsigned int i = 0; i < numberOfBubble; i++)
{
std::ostringstream ossProperty;
- ossProperty<< "uStartEndPosition["<< i << "]";
- mIndiceStartEndPos[i] = mRenderer.RegisterProperty( ossProperty.str(), zeroVector );
+ ossProperty << "uStartEndPosition[" << i << "]";
+ mIndiceStartEndPos[i] = mRenderer.RegisterProperty(ossProperty.str(), zeroVector);
ossProperty.str("");
- ossProperty<< "uPercentage["<< i << "]";
- mIndicesPercentage[i] = mRenderer.RegisterProperty( ossProperty.str(), 0.f );
+ ossProperty << "uPercentage[" << i << "]";
+ mIndicesPercentage[i] = mRenderer.RegisterProperty(ossProperty.str(), 0.f);
}
}
return mRenderer;
}
-void BubbleRenderer::SetGeometry( Geometry geometry )
+void BubbleRenderer::SetGeometry(Geometry geometry)
{
- mRenderer.SetGeometry( geometry );
+ mRenderer.SetGeometry(geometry);
}
-void BubbleRenderer::SetStartAndEndPosition( unsigned int index, const Vector4& startAndEndPosition )
+void BubbleRenderer::SetStartAndEndPosition(unsigned int index, const Vector4& startAndEndPosition)
{
- mRenderer.SetProperty( mIndiceStartEndPos[index], startAndEndPosition );
+ mRenderer.SetProperty(mIndiceStartEndPos[index], startAndEndPosition);
}
-void BubbleRenderer::SetPercentage( unsigned int index, float percentage )
+void BubbleRenderer::SetPercentage(unsigned int index, float percentage)
{
- mRenderer.SetProperty( mIndicesPercentage[index], percentage );
+ mRenderer.SetProperty(mIndicesPercentage[index], percentage);
}
-void BubbleRenderer::SetGravity( float gravity )
+void BubbleRenderer::SetGravity(float gravity)
{
- mRenderer.SetProperty( mIndexGravity, gravity );
+ mRenderer.SetProperty(mIndexGravity, gravity);
}
-void BubbleRenderer::SetDynamicScale( float scale )
+void BubbleRenderer::SetDynamicScale(float scale)
{
- mRenderer.SetProperty( mIndexDynamicScale, scale );
+ mRenderer.SetProperty(mIndexDynamicScale, scale);
}
-Property BubbleRenderer::GetPercentageProperty( unsigned int index )
+Property BubbleRenderer::GetPercentageProperty(unsigned int index)
{
- return Property( mRenderer, mIndicesPercentage[index] );
+ return Property(mRenderer, mIndicesPercentage[index]);
}
void BubbleRenderer::ResetProperties()
{
Vector4 zeroVector;
- for( unsigned int i=0; i<mIndicesPercentage.size(); i++ )
+ for(unsigned int i = 0; i < mIndicesPercentage.size(); i++)
{
- SetPercentage( i, 0.f);
- SetStartAndEndPosition( i, zeroVector );
+ SetPercentage(i, 0.f);
+ SetStartAndEndPosition(i, zeroVector);
}
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "button-impl.h"
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
+#include <dali/devel-api/object/property-helper-devel.h>
#include <dali/devel-api/scripting/enum-helper.h>
+#include <dali/devel-api/scripting/scripting.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/events/touch-event.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/size-negotiation/relayout-container.h>
-#include <dali/devel-api/object/property-helper-devel.h>
-#include <dali/devel-api/scripting/scripting.h>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/text-controls/text-label.h>
-#include <dali-toolkit/public-api/controls/image-view/image-view.h>
-#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
-#include <dali-toolkit/public-api/align-enumerations.h>
+#include <dali-toolkit/devel-api/controls/buttons/button-devel.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
-#include <dali-toolkit/devel-api/controls/buttons/button-devel.h>
#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
#include <dali-toolkit/internal/visuals/text/text-visual.h>
+#include <dali-toolkit/public-api/align-enumerations.h>
+#include <dali-toolkit/public-api/controls/image-view/image-view.h>
+#include <dali-toolkit/public-api/controls/text-controls/text-label.h>
+#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
#include <dali-toolkit/public-api/visuals/visual-properties.h>
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogButtonFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_BUTTON_CONTROL");
+Debug::Filter* gLogButtonFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_BUTTON_CONTROL");
#endif
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
// empty handle as we cannot create button (but type registered for clicked signal)
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Button, Toolkit::Control, Create )
-
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabled", BOOLEAN, DISABLED )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "autoRepeating", BOOLEAN, AUTO_REPEATING )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "initialAutoRepeatingDelay", FLOAT, INITIAL_AUTO_REPEATING_DELAY )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "nextAutoRepeatingDelay", FLOAT, NEXT_AUTO_REPEATING_DELAY )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "togglable", BOOLEAN, TOGGLABLE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selected", BOOLEAN, SELECTED )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "unselectedVisual", MAP, UNSELECTED_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selectedVisual", MAP, SELECTED_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledSelectedVisual", MAP, DISABLED_SELECTED_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledUnselectedVisual", MAP, DISABLED_UNSELECTED_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "unselectedBackgroundVisual", MAP, UNSELECTED_BACKGROUND_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "label", MAP, LABEL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selectedBackgroundVisual", MAP, SELECTED_BACKGROUND_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledUnselectedBackgroundVisual", MAP, DISABLED_UNSELECTED_BACKGROUND_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledSelectedBackgroundVisual", MAP, DISABLED_SELECTED_BACKGROUND_VISUAL )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "labelRelativeAlignment", STRING, LABEL_RELATIVE_ALIGNMENT )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "labelPadding", VECTOR4, LABEL_PADDING )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "visualPadding", VECTOR4, VISUAL_PADDING )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Button, Toolkit::Control, Create)
+
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabled", BOOLEAN, DISABLED)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "autoRepeating", BOOLEAN, AUTO_REPEATING)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "initialAutoRepeatingDelay", FLOAT, INITIAL_AUTO_REPEATING_DELAY)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "nextAutoRepeatingDelay", FLOAT, NEXT_AUTO_REPEATING_DELAY)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "togglable", BOOLEAN, TOGGLABLE)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "selected", BOOLEAN, SELECTED)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "unselectedVisual", MAP, UNSELECTED_VISUAL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "selectedVisual", MAP, SELECTED_VISUAL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabledSelectedVisual", MAP, DISABLED_SELECTED_VISUAL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabledUnselectedVisual", MAP, DISABLED_UNSELECTED_VISUAL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "unselectedBackgroundVisual", MAP, UNSELECTED_BACKGROUND_VISUAL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "label", MAP, LABEL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "selectedBackgroundVisual", MAP, SELECTED_BACKGROUND_VISUAL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabledUnselectedBackgroundVisual", MAP, DISABLED_UNSELECTED_BACKGROUND_VISUAL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabledSelectedBackgroundVisual", MAP, DISABLED_SELECTED_BACKGROUND_VISUAL)
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, Button, "labelRelativeAlignment", STRING, LABEL_RELATIVE_ALIGNMENT)
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, Button, "labelPadding", VECTOR4, LABEL_PADDING)
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, Button, "visualPadding", VECTOR4, VISUAL_PADDING)
// Signals:
-DALI_SIGNAL_REGISTRATION( Toolkit, Button, "pressed", SIGNAL_PRESSED )
-DALI_SIGNAL_REGISTRATION( Toolkit, Button, "released", SIGNAL_RELEASED )
-DALI_SIGNAL_REGISTRATION( Toolkit, Button, "clicked", SIGNAL_CLICKED )
-DALI_SIGNAL_REGISTRATION( Toolkit, Button, "stateChanged", SIGNAL_STATE_CHANGED )
+DALI_SIGNAL_REGISTRATION(Toolkit, Button, "pressed", SIGNAL_PRESSED)
+DALI_SIGNAL_REGISTRATION(Toolkit, Button, "released", SIGNAL_RELEASED)
+DALI_SIGNAL_REGISTRATION(Toolkit, Button, "clicked", SIGNAL_CLICKED)
+DALI_SIGNAL_REGISTRATION(Toolkit, Button, "stateChanged", SIGNAL_STATE_CHANGED)
// Actions:
-DALI_ACTION_REGISTRATION( Toolkit, Button, "buttonClick", ACTION_BUTTON_CLICK )
+DALI_ACTION_REGISTRATION(Toolkit, Button, "buttonClick", ACTION_BUTTON_CLICK)
DALI_TYPE_REGISTRATION_END()
-DALI_ENUM_TO_STRING_TABLE_BEGIN( ALIGNMENT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, BEGIN )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, END )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, TOP )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, BOTTOM )
-DALI_ENUM_TO_STRING_TABLE_END( ALIGNMENT )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(ALIGNMENT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Internal::Button, BEGIN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Internal::Button, END)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Internal::Button, TOP)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Internal::Button, BOTTOM)
+DALI_ENUM_TO_STRING_TABLE_END(ALIGNMENT)
const Scripting::StringEnum ALIGNMENT_STRING_TABLE[] =
-{
- { "BEGIN", Button::BEGIN },
- { "END", Button::END },
- { "TOP", Button::TOP },
- { "BOTTOM", Button::BOTTOM },
+ {
+ {"BEGIN", Button::BEGIN},
+ {"END", Button::END},
+ {"TOP", Button::TOP},
+ {"BOTTOM", Button::BOTTOM},
};
-const unsigned int ALIGNMENT_STRING_TABLE_COUNT = sizeof( ALIGNMENT_STRING_TABLE ) / sizeof( ALIGNMENT_STRING_TABLE[0] );
+const unsigned int ALIGNMENT_STRING_TABLE_COUNT = sizeof(ALIGNMENT_STRING_TABLE) / sizeof(ALIGNMENT_STRING_TABLE[0]);
const Property::Index VISUAL_INDEX_FOR_STATE[][Button::STATE_COUNT] =
-{
- { Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::UNSELECTED_VISUAL },
- { Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::SELECTED_VISUAL },
- { Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL },
- { Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_SELECTED_VISUAL }
-};
+ {
+ {Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::UNSELECTED_VISUAL},
+ {Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::SELECTED_VISUAL},
+ {Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL},
+ {Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_SELECTED_VISUAL}};
/**
* Checks if given map contains a text string
*/
-bool MapContainsTextString( Property::Map& map )
+bool MapContainsTextString(Property::Map& map)
{
- bool result = false;
- Property::Value* value = map.Find( Toolkit::TextVisual::Property::TEXT );
- if ( value )
+ bool result = false;
+ Property::Value* value = map.Find(Toolkit::TextVisual::Property::TEXT);
+ if(value)
{
std::string textString;
- value->Get( textString );
- if ( !textString.empty() )
+ value->Get(textString);
+ if(!textString.empty())
{
result = true;
}
} // unnamed namespace
Button::Button()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mAutoRepeatingTimer(),
- mTextLabelAlignment( END ),
- mAutoRepeating( false ),
- mTogglableButton( false ),
- mTextStringSetFlag( false ),
- mInitialAutoRepeatingDelay( 0.0f ),
- mNextAutoRepeatingDelay( 0.0f ),
- mAnimationTime( 0.0f ),
- mButtonPressedState( UNPRESSED ),
- mButtonState( UNSELECTED_STATE ),
- mPreviousButtonState( mButtonState ),
- mClickActionPerforming( false )
+ mTextLabelAlignment(END),
+ mAutoRepeating(false),
+ mTogglableButton(false),
+ mTextStringSetFlag(false),
+ mInitialAutoRepeatingDelay(0.0f),
+ mNextAutoRepeatingDelay(0.0f),
+ mAnimationTime(0.0f),
+ mButtonPressedState(UNPRESSED),
+ mButtonState(UNSELECTED_STATE),
+ mPreviousButtonState(mButtonState),
+ mClickActionPerforming(false)
{
}
{
}
-void Button::SetAutoRepeating( bool autoRepeating )
+void Button::SetAutoRepeating(bool autoRepeating)
{
mAutoRepeating = autoRepeating;
// An autorepeating button can't be a toggle button.
- if( autoRepeating )
+ if(autoRepeating)
{
- if( IsSelected() )
+ if(IsSelected())
{
- SetSelected( false ); // UnSelect before switching off Toggle feature.
+ SetSelected(false); // UnSelect before switching off Toggle feature.
}
mTogglableButton = false;
}
}
-void Button::SetInitialAutoRepeatingDelay( float initialAutoRepeatingDelay )
+void Button::SetInitialAutoRepeatingDelay(float initialAutoRepeatingDelay)
{
- DALI_ASSERT_DEBUG( initialAutoRepeatingDelay > 0.f );
+ DALI_ASSERT_DEBUG(initialAutoRepeatingDelay > 0.f);
mInitialAutoRepeatingDelay = initialAutoRepeatingDelay;
}
-void Button::SetNextAutoRepeatingDelay( float nextAutoRepeatingDelay )
+void Button::SetNextAutoRepeatingDelay(float nextAutoRepeatingDelay)
{
- DALI_ASSERT_DEBUG( nextAutoRepeatingDelay > 0.f );
+ DALI_ASSERT_DEBUG(nextAutoRepeatingDelay > 0.f);
mNextAutoRepeatingDelay = nextAutoRepeatingDelay;
}
-void Button::SetTogglableButton( bool togglable )
+void Button::SetTogglableButton(bool togglable)
{
mTogglableButton = togglable;
// A toggle button can't be an autorepeating button.
- if( togglable )
+ if(togglable)
{
mAutoRepeating = false;
}
}
-void Button::SetSelected( bool selected )
+void Button::SetSelected(bool selected)
{
- if( mTogglableButton )
+ if(mTogglableButton)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetSelected (%s)\n", (selected?"true":"false") );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetSelected (%s)\n", (selected ? "true" : "false"));
- if ( selected && ( mButtonState != SELECTED_STATE ) )
+ if(selected && (mButtonState != SELECTED_STATE))
{
- ChangeState( SELECTED_STATE );
+ ChangeState(SELECTED_STATE);
}
- else if ( !selected && ( mButtonState != UNSELECTED_STATE ) )
+ else if(!selected && (mButtonState != UNSELECTED_STATE))
{
- ChangeState( UNSELECTED_STATE );
+ ChangeState(UNSELECTED_STATE);
}
}
}
-void Button::SetDisabled( bool disabled )
+void Button::SetDisabled(bool disabled)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetDisabled(%s) state(%d)\n", (disabled)?"disabled":"active", mButtonState );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetDisabled(%s) state(%d)\n", (disabled) ? "disabled" : "active", mButtonState);
- if ( disabled )
+ if(disabled)
{
- if ( mButtonState == SELECTED_STATE )
+ if(mButtonState == SELECTED_STATE)
{
- ChangeState( DISABLED_SELECTED_STATE );
+ ChangeState(DISABLED_SELECTED_STATE);
}
- else if ( mButtonState == UNSELECTED_STATE )
+ else if(mButtonState == UNSELECTED_STATE)
{
- ChangeState( DISABLED_UNSELECTED_STATE );
+ ChangeState(DISABLED_UNSELECTED_STATE);
}
}
else
{
- if ( mButtonState == DISABLED_SELECTED_STATE )
+ if(mButtonState == DISABLED_SELECTED_STATE)
{
- ChangeState( SELECTED_STATE );
+ ChangeState(SELECTED_STATE);
}
- else if ( mButtonState == DISABLED_UNSELECTED_STATE )
+ else if(mButtonState == DISABLED_UNSELECTED_STATE)
{
- ChangeState( UNSELECTED_STATE );
+ ChangeState(UNSELECTED_STATE);
}
}
}
bool Button::IsDisabled() const
{
- return ( mButtonState == DISABLED_SELECTED_STATE || mButtonState == DISABLED_UNSELECTED_STATE ) ;
+ return (mButtonState == DISABLED_SELECTED_STATE || mButtonState == DISABLED_UNSELECTED_STATE);
}
-bool Button::ValidateState( State requestedState )
+bool Button::ValidateState(State requestedState)
{
/* Below tables shows allowed state transitions
* Match rows in first column to following columns, if true then transition allowed.
* eg UNSELECTED_STATE to DISABLED_UNSELECTED_STATE is true so state transition allowed.
*
to| UNSELECTED_STATE | SELECTED_STATE | DISABLED_UNSELECTED_STATE | DISABLED_SELECTED_STATE |*/
- /* from*/
- bool transitionTable[4][4] = { /* UNSELECTED_STATE*/ { false, true, true, false },
- /* SELECTED_STATE*/ { true, false, false, true },
- /* DISABLED_UNSELECTED_STATE*/{ true, true, false, false },
- /* DISABLED_SELECTED_STATE*/ { false, true, false, false }
- };
+ /* from*/
+ bool transitionTable[4][4] = {/* UNSELECTED_STATE*/ {false, true, true, false},
+ /* SELECTED_STATE*/ {true, false, false, true},
+ /* DISABLED_UNSELECTED_STATE*/ {true, true, false, false},
+ /* DISABLED_SELECTED_STATE*/ {false, true, false, false}};
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ValidateState ReuestedState:%d, CurrentState:%d, result:%s\n",
- requestedState, mButtonState, (transitionTable[mButtonState][requestedState])?"change-accepted":"change-denied");
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::ValidateState ReuestedState:%d, CurrentState:%d, result:%s\n", requestedState, mButtonState, (transitionTable[mButtonState][requestedState]) ? "change-accepted" : "change-denied");
return transitionTable[mButtonState][requestedState];
}
-void Button::ChangeState( State requestedState )
+void Button::ChangeState(State requestedState)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d)\n", requestedState );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d)\n", requestedState);
// Validate State before changing
- if ( !ValidateState( requestedState ))
+ if(!ValidateState(requestedState))
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d) not validated\n", requestedState );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d) not validated\n", requestedState);
return;
}
// If not on stage the button could have still been set to selected so update state
- mPreviousButtonState = mButtonState; // Store previous state for visual removal (used when animations ended)
- mButtonState = requestedState; // Update current state
+ mPreviousButtonState = mButtonState; // Store previous state for visual removal (used when animations ended)
+ mButtonState = requestedState; // Update current state
- if ( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if(Self().GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
- OnStateChange( mButtonState ); // Notify derived buttons
- SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] );
- SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] );
+ OnStateChange(mButtonState); // Notify derived buttons
+ SelectRequiredVisual(VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND]);
+ SelectRequiredVisual(VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND]);
// If animation supported then visual removal should be performed after any transition animation has completed.
// If Required Visual is not loaded before current visual is removed then a flickering will be evident.
// Derived button can override OnButtonVisualRemoval
- OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ BACKGROUND ] );
- OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ FOREGROUND ] );
+ OnButtonVisualRemoval(VISUAL_INDEX_FOR_STATE[mPreviousButtonState][BACKGROUND]);
+ OnButtonVisualRemoval(VISUAL_INDEX_FOR_STATE[mPreviousButtonState][FOREGROUND]);
RelayoutRequest();
}
- Toolkit::Button handle( GetOwner() );
+ Toolkit::Button handle(GetOwner());
// Emit signal.
- mStateChangedSignal.Emit( handle );
+ mStateChangedSignal.Emit(handle);
}
bool Button::IsSelected() const
{
- bool selected = ( mButtonState == SELECTED_STATE ) || ( mButtonState == DISABLED_SELECTED_STATE );
+ bool selected = (mButtonState == SELECTED_STATE) || (mButtonState == DISABLED_SELECTED_STATE);
return mTogglableButton && selected;
}
-void Button::MergeWithExistingLabelProperties( const Property::Map& inMap, Property::Map& outMap )
+void Button::MergeWithExistingLabelProperties(const Property::Map& inMap, Property::Map& outMap)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties with %d properties\n", inMap.Count() );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "MergeLabelProperties with %d properties\n", inMap.Count());
/**
* Properties for the Label visual could be from a style sheet but after being set the "TEXT" property could be set.
* 3) Merge with new properties ( settings )
* 4) Return new merged map
*/
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL );
- if ( visual )
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, Toolkit::Button::Property::LABEL);
+ if(visual)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties Visual already exists, retrieving existing map\n");
- visual.CreatePropertyMap( outMap );
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties retrieved %d properties\n", outMap.Count() );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "MergeLabelProperties Visual already exists, retrieving existing map\n");
+ visual.CreatePropertyMap(outMap);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "MergeLabelProperties retrieved %d properties\n", outMap.Count());
}
- outMap.Merge( inMap );
+ outMap.Merge(inMap);
// Store if a text string has been supplied.
- mTextStringSetFlag = MapContainsTextString( outMap );
+ mTextStringSetFlag = MapContainsTextString(outMap);
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties now has %d properties\n", outMap.Count() );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "MergeLabelProperties now has %d properties\n", outMap.Count());
}
-void Button::SetLabelAlignment( Button::Align labelAlignment)
+void Button::SetLabelAlignment(Button::Align labelAlignment)
{
mTextLabelAlignment = labelAlignment;
RelayoutRequest();
* 3) Register visual with control with false for enable flag. Button will later enable visual when needed ( Button::SelectRequiredVisual )
* 4) Unregister visual if empty map was provided. This is the method to remove a visual
*/
-void Button::CreateVisualsForComponent( Property::Index index, const Property::Value& value, const int visualDepth )
+void Button::CreateVisualsForComponent(Property::Index index, const Property::Value& value, const int visualDepth)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent index(%d)\n", index );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent index(%d)\n", index);
Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get();
- Toolkit::Visual::Base buttonVisual;
+ Toolkit::Visual::Base buttonVisual;
std::string imageUrl;
- if( value.Get( imageUrl ) )
+ if(value.Get(imageUrl))
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using image URL(%d)\n", index );
- if ( !imageUrl.empty() )
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using image URL(%d)\n", index);
+ if(!imageUrl.empty())
{
- DALI_ASSERT_DEBUG( index != Toolkit::Button::Property::LABEL && "Creating a Image Visual instead of Text Visual " );
- buttonVisual = visualFactory.CreateVisual( imageUrl, ImageDimensions() );
+ DALI_ASSERT_DEBUG(index != Toolkit::Button::Property::LABEL && "Creating a Image Visual instead of Text Visual ");
+ buttonVisual = visualFactory.CreateVisual(imageUrl, ImageDimensions());
}
}
else
{
// if its not a string then get a Property::Map from the property if possible.
- const Property::Map *map = value.GetMap();
- if( map && !map->Empty() ) // Empty map results in current visual removal.
+ const Property::Map* map = value.GetMap();
+ if(map && !map->Empty()) // Empty map results in current visual removal.
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using Map(%d)\n", index );
- buttonVisual = visualFactory.CreateVisual( *map );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using Map(%d)\n", index);
+ buttonVisual = visualFactory.CreateVisual(*map);
}
}
- if ( buttonVisual )
+ if(buttonVisual)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent RegisterVisual index(%d) enabled(%s)\n",
- index, DevelControl::IsVisualEnabled( *this, index )?"true":"false" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent RegisterVisual index(%d) enabled(%s)\n", index, DevelControl::IsVisualEnabled(*this, index) ? "true" : "false");
// enable the visual if needed for current state
- const bool enabled = ( ( index == VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] )||
- ( index == VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] )||
- ( index == Toolkit::Button::Property::LABEL ) );
- DevelControl::RegisterVisual( *this, index, buttonVisual, enabled, visualDepth );
+ const bool enabled = ((index == VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND]) ||
+ (index == VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND]) ||
+ (index == Toolkit::Button::Property::LABEL));
+ DevelControl::RegisterVisual(*this, index, buttonVisual, enabled, visualDepth);
}
else
{
- DevelControl::UnregisterVisual( *this, index );
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "CreateVisualsForComponent Visual not created or empty map (clearing visual).(%d)\n", index);
+ DevelControl::UnregisterVisual(*this, index);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "CreateVisualsForComponent Visual not created or empty map (clearing visual).(%d)\n", index);
}
RelayoutRequest();
}
-bool Button::GetPropertyMapForVisual( Property::Index visualIndex, Property::Map& retreivedMap ) const
+bool Button::GetPropertyMapForVisual(Property::Index visualIndex, Property::Map& retreivedMap) const
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetPropertyMapForVisual visual(%d)\n", visualIndex);
- bool success = false;
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, visualIndex );
- if ( visual )
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetPropertyMapForVisual visual(%d)\n", visualIndex);
+ bool success = false;
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, visualIndex);
+ if(visual)
{
- visual.CreatePropertyMap( retreivedMap );
+ visual.CreatePropertyMap(retreivedMap);
success = true;
}
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetPropertyMapForVisual %s\n", success?"Success":"Failure");
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetPropertyMapForVisual %s\n", success ? "Success" : "Failure");
return success;
}
-bool Button::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
+bool Button::DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes)
{
bool ret = false;
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- Toolkit::Button button = Toolkit::Button::DownCast( handle );
+ Toolkit::Button button = Toolkit::Button::DownCast(handle);
- DALI_ASSERT_DEBUG( button );
+ DALI_ASSERT_DEBUG(button);
- if( 0 == strcmp( actionName.c_str(), ACTION_BUTTON_CLICK ) )
+ if(0 == strcmp(actionName.c_str(), ACTION_BUTTON_CLICK))
{
- ret = GetImplementation( button ).DoClickAction( attributes );
+ ret = GetImplementation(button).DoClickAction(attributes);
}
return ret;
}
-bool Button::DoClickAction( const Property::Map& attributes )
+bool Button::DoClickAction(const Property::Map& attributes)
{
// Prevents the button signals from doing a recursive loop by sending an action
// and re-emitting the signals.
- if( !mClickActionPerforming )
+ if(!mClickActionPerforming)
{
mClickActionPerforming = true;
ButtonDown();
- if ( !mTogglableButton )
+ if(!mTogglableButton)
{
mButtonPressedState = DEPRESSED;
}
void Button::ButtonDown()
{
- if( mTogglableButton )
+ if(mTogglableButton)
{
- if ( mButtonState != SELECTED_STATE )
+ if(mButtonState != SELECTED_STATE)
{
- SetSelected( true );
+ SetSelected(true);
mButtonPressedState = TOGGLE_DEPRESSED;
}
else
{
Pressed();
mButtonPressedState = DEPRESSED;
- if( mAutoRepeating )
+ if(mAutoRepeating)
{
- SetUpTimer( mInitialAutoRepeatingDelay );
+ SetUpTimer(mInitialAutoRepeatingDelay);
}
}
// The pressed signal should be emitted regardless of toggle mode.
- Toolkit::Button handle( GetOwner() );
- mPressedSignal.Emit( handle );
+ Toolkit::Button handle(GetOwner());
+ mPressedSignal.Emit(handle);
}
void Button::ButtonUp()
{
bool emitSignalsForPressAndReleaseAction = false;
- if( DEPRESSED == mButtonPressedState )
+ if(DEPRESSED == mButtonPressedState)
{
- if( mTogglableButton ) // Button up will change state
+ if(mTogglableButton) // Button up will change state
{
emitSignalsForPressAndReleaseAction = OnToggleReleased(); // Derived toggle buttons can override this to provide custom behaviour
}
else
{
Released(); // Button up will result in unselected state
- if( mAutoRepeating )
+ if(mAutoRepeating)
{
mAutoRepeatingTimer.Reset();
}
emitSignalsForPressAndReleaseAction = true;
}
}
- else if ( TOGGLE_DEPRESSED == mButtonPressedState )
+ else if(TOGGLE_DEPRESSED == mButtonPressedState)
{
emitSignalsForPressAndReleaseAction = true; // toggle released after being pressed, a click
}
- if ( emitSignalsForPressAndReleaseAction )
+ if(emitSignalsForPressAndReleaseAction)
{
// The clicked and released signals should be emitted regardless of toggle mode.
- Toolkit::Button handle( GetOwner() );
- mReleasedSignal.Emit( handle );
- mClickedSignal.Emit( handle );
+ Toolkit::Button handle(GetOwner());
+ mReleasedSignal.Emit(handle);
+ mClickedSignal.Emit(handle);
}
}
bool Button::OnToggleReleased()
{
- SetSelected( !IsSelected() );
+ SetSelected(!IsSelected());
mButtonPressedState = UNPRESSED;
return true;
}
-
void Button::OnTouchPointLeave()
{
- if( DEPRESSED == mButtonPressedState )
+ if(DEPRESSED == mButtonPressedState)
{
- if( !mTogglableButton )
+ if(!mTogglableButton)
{
Released();
- if( mAutoRepeating )
+ if(mAutoRepeating)
{
mAutoRepeatingTimer.Reset();
}
mButtonPressedState = UNPRESSED;
// The released signal should be emitted regardless of toggle mode.
- Toolkit::Button handle( GetOwner() );
- mReleasedSignal.Emit( handle );
+ Toolkit::Button handle(GetOwner());
+ mReleasedSignal.Emit(handle);
}
}
return mStateChangedSignal;
}
-bool Button::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool Button::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::Button button = Toolkit::Button::DownCast( handle );
+ bool connected(true);
+ Toolkit::Button button = Toolkit::Button::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_PRESSED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_PRESSED))
{
- button.PressedSignal().Connect( tracker, functor );
+ button.PressedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_RELEASED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_RELEASED))
{
- button.ReleasedSignal().Connect( tracker, functor );
+ button.ReleasedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_CLICKED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_CLICKED))
{
- button.ClickedSignal().Connect( tracker, functor );
+ button.ClickedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_STATE_CHANGED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_STATE_CHANGED))
{
- button.StateChangedSignal().Connect( tracker, functor );
+ button.StateChangedSignal().Connect(tracker, functor);
}
else
{
void Button::OnInitialize()
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnInitialize\n" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::OnInitialize\n");
Actor self = Self();
mTapDetector = TapGestureDetector::New();
- mTapDetector.Attach( self );
+ mTapDetector.Attach(self);
mTapDetector.DetectedSignal().Connect(this, &Button::OnTap);
- self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true );
- self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true );
+ self.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true);
+ self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
- self.TouchedSignal().Connect( this, &Button::OnTouch );
+ self.TouchedSignal().Connect(this, &Button::OnTouch);
}
bool Button::OnAccessibilityActivated()
return OnKeyboardEnter();
}
-bool Button::OnTouch( Actor actor, const TouchEvent& touch )
+bool Button::OnTouch(Actor actor, const TouchEvent& touch)
{
- if( !IsDisabled() && (actor == touch.GetHitActor(0)) )
+ if(!IsDisabled() && (actor == touch.GetHitActor(0)))
{
- if ( 1 == touch.GetPointCount() )
+ if(1 == touch.GetPointCount())
{
- switch( touch.GetState( 0 ) )
+ switch(touch.GetState(0))
{
case PointState::DOWN:
{
}
}
}
- else if( 1 < touch.GetPointCount() )
+ else if(1 < touch.GetPointCount())
{
OnTouchPointLeave(); // Notification for derived classes.
{
// When the enter key is pressed, or button is activated, the click action is performed.
Property::Map attributes;
- bool ret = DoClickAction( attributes );
+ bool ret = DoClickAction(attributes);
return ret;
}
void Button::OnSceneDisconnection()
{
- if( DEPRESSED == mButtonPressedState )
+ if(DEPRESSED == mButtonPressedState)
{
- if( !mTogglableButton )
+ if(!mTogglableButton)
{
Released();
- if( mAutoRepeating )
+ if(mAutoRepeating)
{
mAutoRepeatingTimer.Reset();
}
Control::OnSceneDisconnection(); // Visuals will be set off stage
}
-void Button::OnSceneConnection( int depth )
+void Button::OnSceneConnection(int depth)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnSceneConnection ptr(%p) \n", this );
- OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ BACKGROUND ] );
- OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ FOREGROUND ] );
- SelectRequiredVisual( Toolkit::Button::Property::LABEL );
- SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] );
- SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] );
- Control::OnSceneConnection( depth ); // Enabled visuals will be put on stage
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::OnSceneConnection ptr(%p) \n", this);
+ OnButtonVisualRemoval(VISUAL_INDEX_FOR_STATE[mPreviousButtonState][BACKGROUND]);
+ OnButtonVisualRemoval(VISUAL_INDEX_FOR_STATE[mPreviousButtonState][FOREGROUND]);
+ SelectRequiredVisual(Toolkit::Button::Property::LABEL);
+ SelectRequiredVisual(VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND]);
+ SelectRequiredVisual(VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND]);
+ Control::OnSceneConnection(depth); // Enabled visuals will be put on stage
RelayoutRequest();
}
bool foreGroundVisualUsed = false;
- for ( int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++ )
+ for(int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++)
{
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[state][FOREGROUND] );
- Size visualSize;
- if ( visual )
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, VISUAL_INDEX_FOR_STATE[state][FOREGROUND]);
+ Size visualSize;
+ if(visual)
{
- visual.GetNaturalSize( visualSize );
- largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width );
- largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height );
- foreGroundVisualUsed = true;
+ visual.GetNaturalSize(visualSize);
+ largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width);
+ largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height);
+ foreGroundVisualUsed = true;
}
}
- if ( !foreGroundVisualUsed ) // If foreground visual not supplied then use the background visual to calculate Natural size
+ if(!foreGroundVisualUsed) // If foreground visual not supplied then use the background visual to calculate Natural size
{
- for ( int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++ )
+ for(int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++)
{
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[state][BACKGROUND] );
- Size visualSize;
- if ( visual )
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, VISUAL_INDEX_FOR_STATE[state][BACKGROUND]);
+ Size visualSize;
+ if(visual)
{
- visual.GetNaturalSize( visualSize );
- largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width );
- largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height );
+ visual.GetNaturalSize(visualSize);
+ largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width);
+ largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height);
}
}
}
// Get horizontal padding total
- if ( largestProvidedVisual.width > 0 ) // if visual exists
+ if(largestProvidedVisual.width > 0) // if visual exists
{
size.width += largestProvidedVisual.width + mForegroundPadding.left + mForegroundPadding.right;
}
// Get vertical padding total
- if ( largestProvidedVisual.height > 0 )
+ if(largestProvidedVisual.height > 0)
{
size.height += largestProvidedVisual.height + mForegroundPadding.top + mForegroundPadding.bottom;
}
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize visual Size(%f,%f)\n",
- largestProvidedVisual.width, largestProvidedVisual.height );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetNaturalSize visual Size(%f,%f)\n", largestProvidedVisual.width, largestProvidedVisual.height);
// Get natural size of label if text has been set
- if ( mTextStringSetFlag )
+ if(mTextStringSetFlag)
{
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL );
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, Toolkit::Button::Property::LABEL);
- if ( visual )
+ if(visual)
{
- visual.GetNaturalSize( labelSize );
+ visual.GetNaturalSize(labelSize);
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize labelSize(%f,%f) padding(%f,%f)\n",
- labelSize.width, labelSize.height, mLabelPadding.left + mLabelPadding.right, mLabelPadding.top + mLabelPadding.bottom);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetNaturalSize labelSize(%f,%f) padding(%f,%f)\n", labelSize.width, labelSize.height, mLabelPadding.left + mLabelPadding.right, mLabelPadding.top + mLabelPadding.bottom);
labelSize.width += mLabelPadding.left + mLabelPadding.right;
labelSize.height += mLabelPadding.top + mLabelPadding.bottom;
// Add label size to height or width depending on alignment position
- if ( horizontalAlignment )
+ if(horizontalAlignment)
{
size.width += labelSize.width;
- size.height = std::max(size.height, labelSize.height );
+ size.height = std::max(size.height, labelSize.height);
}
else
{
size.height += labelSize.height;
- size.width = std::max(size.width, labelSize.width );
+ size.width = std::max(size.width, labelSize.width);
}
}
}
- if( size.width < 1 && size.height < 1 )
+ if(size.width < 1 && size.height < 1)
{
// if no image or label then use Control's natural size
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize Using control natural size\n");
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetNaturalSize Using control natural size\n");
size = Control::GetNaturalSize();
}
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "Button GetNaturalSize (%f,%f)\n", size.width, size.height );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "Button GetNaturalSize (%f,%f)\n", size.width, size.height);
return size;
}
-void Button::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
+void Button::OnSetResizePolicy(ResizePolicy::Type policy, Dimension::Type dimension)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnSetResizePolicy\n");
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnSetResizePolicy\n");
RelayoutRequest();
}
* Whilst the control has it's size negotiated it has to size it's visuals explicitly here.
*/
-void Button::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void Button::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout targetSize(%f,%f) ptr(%p) state[%d]\n", size.width, size.height, this, mButtonState );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout targetSize(%f,%f) ptr(%p) state[%d]\n", size.width, size.height, this, mButtonState);
- Toolkit::Visual::Base currentVisual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND] );
- Toolkit::Visual::Base currentBackGroundVisual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND] );
+ Toolkit::Visual::Base currentVisual = DevelControl::GetVisual(*this, VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND]);
+ Toolkit::Visual::Base currentBackGroundVisual = DevelControl::GetVisual(*this, VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND]);
// Sizes and padding set to zero, if not present then values will no effect calculations.
- Vector2 visualPosition = Vector2::ZERO;
- Vector2 labelPosition = Vector2::ZERO;
- Size visualSize = Size::ZERO;
- Padding foregroundVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f );
- Padding labelVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f );
+ Vector2 visualPosition = Vector2::ZERO;
+ Vector2 labelPosition = Vector2::ZERO;
+ Size visualSize = Size::ZERO;
+ Padding foregroundVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f);
+ Padding labelVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f);
- if ( mTextStringSetFlag )
+ if(mTextStringSetFlag)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Label padding setting padding:%f,%f,%f,%f\n", mLabelPadding.y, mLabelPadding.x, mLabelPadding.width,mLabelPadding.height );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Label padding setting padding:%f,%f,%f,%f\n", mLabelPadding.y, mLabelPadding.x, mLabelPadding.width, mLabelPadding.height);
labelVisualPadding = mLabelPadding;
}
- if ( currentVisual )
+ if(currentVisual)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Foreground Visual setting padding:%f,%f,%f,%f\n", mForegroundPadding.y, mForegroundPadding.x, mForegroundPadding.width,mForegroundPadding.height );
- currentVisual.GetNaturalSize( visualSize );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Foreground Visual setting padding:%f,%f,%f,%f\n", mForegroundPadding.y, mForegroundPadding.x, mForegroundPadding.width, mForegroundPadding.height);
+ currentVisual.GetNaturalSize(visualSize);
foregroundVisualPadding = mForegroundPadding;
}
Toolkit::Align::Type visualAnchorPoint = Toolkit::Align::TOP_BEGIN;
- Vector2 visualAndPaddingSize = Vector2( ( foregroundVisualPadding.x + visualSize.width + foregroundVisualPadding.y ),
- ( foregroundVisualPadding.width + visualSize.height + foregroundVisualPadding.height ));
+ Vector2 visualAndPaddingSize = Vector2((foregroundVisualPadding.x + visualSize.width + foregroundVisualPadding.y),
+ (foregroundVisualPadding.width + visualSize.height + foregroundVisualPadding.height));
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout visualAndPaddingSize(%f,%f)\n", visualAndPaddingSize.width, visualAndPaddingSize.height);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout visualAndPaddingSize(%f,%f)\n", visualAndPaddingSize.width, visualAndPaddingSize.height);
// Text Visual should take all space available after foreground visual size and all padding is considered.
// Remaining Space priority, Foreground padding, foreground visual, Text padding then Text visual.
Size remainingSpaceForText = Size::ZERO;
- switch ( mTextLabelAlignment )
+ switch(mTextLabelAlignment)
{
- case BEGIN :
+ case BEGIN:
{
visualAnchorPoint = Toolkit::Align::TOP_END;
- visualPosition.x = foregroundVisualPadding.right;
- visualPosition.y = foregroundVisualPadding.top;
+ visualPosition.x = foregroundVisualPadding.right;
+ visualPosition.y = foregroundVisualPadding.top;
labelPosition.x = labelVisualPadding.x;
labelPosition.y = labelVisualPadding.top;
- remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y;
+ remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y;
remainingSpaceForText.height = size.height - labelVisualPadding.top - labelVisualPadding.bottom;
break;
}
- case END :
+ case END:
{
visualAnchorPoint = Toolkit::Align::TOP_BEGIN;
- visualPosition.x = foregroundVisualPadding.left;
- visualPosition.y = foregroundVisualPadding.top;
+ visualPosition.x = foregroundVisualPadding.left;
+ visualPosition.y = foregroundVisualPadding.top;
labelPosition.x = visualAndPaddingSize.width + labelVisualPadding.x;
labelPosition.y = labelVisualPadding.top;
- remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y;
+ remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y;
remainingSpaceForText.height = size.height - labelVisualPadding.top - labelVisualPadding.bottom;
break;
}
- case TOP :
+ case TOP:
{
visualAnchorPoint = Toolkit::Align::BOTTOM_END;
- visualPosition.x = foregroundVisualPadding.left;
- visualPosition.y = foregroundVisualPadding.bottom;
+ visualPosition.x = foregroundVisualPadding.left;
+ visualPosition.y = foregroundVisualPadding.bottom;
labelPosition.x = labelVisualPadding.left;
labelPosition.y = labelVisualPadding.top;
- remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y;
+ remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y;
remainingSpaceForText.height = size.height - visualAndPaddingSize.height - labelVisualPadding.top - labelVisualPadding.bottom;
break;
}
- case BOTTOM :
+ case BOTTOM:
{
visualAnchorPoint = Toolkit::Align::TOP_END;
- visualPosition.x = foregroundVisualPadding.left;
- visualPosition.y = foregroundVisualPadding.top;
+ visualPosition.x = foregroundVisualPadding.left;
+ visualPosition.y = foregroundVisualPadding.top;
labelPosition.x = labelVisualPadding.left;
labelPosition.y = visualAndPaddingSize.height + labelVisualPadding.top;
- remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y;
+ remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y;
remainingSpaceForText.height = size.height - visualAndPaddingSize.height - labelVisualPadding.top - labelVisualPadding.bottom;
break;
}
}
- if ( currentBackGroundVisual )
+ if(currentBackGroundVisual)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Setting visual background size to(%f,%f)\n", size.width, size.height);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Setting visual background size to(%f,%f)\n", size.width, size.height);
Property::Map visualTransform;
- visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, size )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) );
+ visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, size)
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE));
- currentBackGroundVisual.SetTransformAndSize( visualTransform, size );
+ currentBackGroundVisual.SetTransformAndSize(visualTransform, size);
}
- if ( currentVisual )
+ if(currentVisual)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height);
Property::Map visualTransform;
- visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, visualSize )
- .Add( Toolkit::Visual::Transform::Property::OFFSET, visualPosition )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN )
- .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint );
+ visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, visualSize)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET, visualPosition)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN)
+ .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint);
- currentVisual.SetTransformAndSize( visualTransform, size );
+ currentVisual.SetTransformAndSize(visualTransform, size);
}
- if ( mTextStringSetFlag )
+ if(mTextStringSetFlag)
{
- Toolkit::Visual::Base textVisual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL ); // No need to search for Label visual if no text set.
+ Toolkit::Visual::Base textVisual = DevelControl::GetVisual(*this, Toolkit::Button::Property::LABEL); // No need to search for Label visual if no text set.
- if ( textVisual )
+ if(textVisual)
{
- if ( !currentVisual )
+ if(!currentVisual)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Only Text\n");
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Only Text\n");
labelPosition.x = labelVisualPadding.left;
labelPosition.y = labelVisualPadding.height;
}
- Vector2 preSize = Vector2( static_cast< int >( remainingSpaceForText.x ), static_cast< int >( remainingSpaceForText.y ));
-
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout text Size(%f,%f) text Position(%f,%f) \n", remainingSpaceForText.width, remainingSpaceForText.height, labelPosition.x, labelPosition.y);
+ Vector2 preSize = Vector2(static_cast<int>(remainingSpaceForText.x), static_cast<int>(remainingSpaceForText.y));
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout text Size -- (%f,%f) text Position(%f,%f) \n", preSize.width, preSize.height, labelPosition.x, labelPosition.y);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout text Size(%f,%f) text Position(%f,%f) \n", remainingSpaceForText.width, remainingSpaceForText.height, labelPosition.x, labelPosition.y);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout text Size -- (%f,%f) text Position(%f,%f) \n", preSize.width, preSize.height, labelPosition.x, labelPosition.y);
Property::Map textVisualTransform;
- textVisualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, preSize )
- .Add( Toolkit::Visual::Transform::Property::OFFSET, labelPosition )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN )
- .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint );
-
- textVisual.SetTransformAndSize( textVisualTransform, size );
+ textVisualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, preSize)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET, labelPosition)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN)
+ .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint);
+
+ textVisual.SetTransformAndSize(textVisualTransform, size);
}
}
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout selected (%s) \n", IsSelected()?"yes":"no" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout selected (%s) \n", IsSelected() ? "yes" : "no");
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout << \n");
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout << \n");
}
void Button::OnTap(Actor actor, const TapGesture& tap)
// Prevents Parent getting a tap event
}
-void Button::SetUpTimer( float delay )
+void Button::SetUpTimer(float delay)
{
- mAutoRepeatingTimer = Dali::Timer::New( static_cast<unsigned int>( 1000.f * delay ) );
- mAutoRepeatingTimer.TickSignal().Connect( this, &Button::AutoRepeatingSlot );
+ mAutoRepeatingTimer = Dali::Timer::New(static_cast<unsigned int>(1000.f * delay));
+ mAutoRepeatingTimer.TickSignal().Connect(this, &Button::AutoRepeatingSlot);
mAutoRepeatingTimer.Start();
}
bool Button::AutoRepeatingSlot()
{
bool consumed = false;
- if( !IsDisabled() )
+ if(!IsDisabled())
{
// Restart the autorepeat timer.
- SetUpTimer( mNextAutoRepeatingDelay );
+ SetUpTimer(mNextAutoRepeatingDelay);
Pressed();
- Toolkit::Button handle( GetOwner() );
+ Toolkit::Button handle(GetOwner());
//Emit signal.
- consumed = mReleasedSignal.Emit( handle );
- consumed = mClickedSignal.Emit( handle );
- consumed |= mPressedSignal.Emit( handle );
- }
+ consumed = mReleasedSignal.Emit(handle);
+ consumed = mClickedSignal.Emit(handle);
+ consumed |= mPressedSignal.Emit(handle);
+ }
return consumed;
}
void Button::Pressed()
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::Pressed\n" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::Pressed\n");
- if( mButtonState == UNSELECTED_STATE )
+ if(mButtonState == UNSELECTED_STATE)
{
- ChangeState( SELECTED_STATE );
- OnPressed(); // Notifies the derived class the button has been pressed.
+ ChangeState(SELECTED_STATE);
+ OnPressed(); // Notifies the derived class the button has been pressed.
}
}
void Button::Released()
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::Released\n" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::Released\n");
- if( mButtonState == SELECTED_STATE && !mTogglableButton )
+ if(mButtonState == SELECTED_STATE && !mTogglableButton)
{
- ChangeState( UNSELECTED_STATE );
+ ChangeState(UNSELECTED_STATE);
OnReleased(); // // Notifies the derived class the button has been released.
}
mButtonPressedState = UNPRESSED;
}
-void Button::SelectRequiredVisual( Property::Index visualIndex )
+void Button::SelectRequiredVisual(Property::Index visualIndex)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SelectRequiredVisual index(%d) state(%d)\n", visualIndex, mButtonState );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SelectRequiredVisual index(%d) state(%d)\n", visualIndex, mButtonState);
// only enable visuals that exist
- if( DevelControl::GetVisual( *this, visualIndex ) )
+ if(DevelControl::GetVisual(*this, visualIndex))
{
- DevelControl::EnableVisual( *this, visualIndex, true );
+ DevelControl::EnableVisual(*this, visualIndex, true);
}
}
-void Button::RemoveVisual( Property::Index visualIndex )
+void Button::RemoveVisual(Property::Index visualIndex)
{
// Use OnButtonVisualRemoval if want button developer to have the option to override removal.
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::RemoveVisual index(%d) state(%d)\n", visualIndex, mButtonState );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::RemoveVisual index(%d) state(%d)\n", visualIndex, mButtonState);
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, visualIndex );
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, visualIndex);
- if( visual )
+ if(visual)
{
- DevelControl::EnableVisual( *this, visualIndex, false );
+ DevelControl::EnableVisual(*this, visualIndex, false);
}
}
-void Button::OnButtonVisualRemoval( Property::Index visualIndex )
+void Button::OnButtonVisualRemoval(Property::Index visualIndex)
{
// Derived Buttons can over ride this to prevent default removal.
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnButtonVisualRemoval index(%d)\n", visualIndex );
- RemoveVisual( visualIndex );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::OnButtonVisualRemoval index(%d)\n", visualIndex);
+ RemoveVisual(visualIndex);
}
-void Button::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void Button::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::Button button = Toolkit::Button::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Button button = Toolkit::Button::DownCast(Dali::BaseHandle(object));
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetProperty index[%d]\n", index );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetProperty index[%d]\n", index);
- if ( button )
+ if(button)
{
- switch ( index )
+ switch(index)
{
case Toolkit::Button::Property::DISABLED:
{
- GetImplementation( button ).SetDisabled( value.Get< bool >() );
+ GetImplementation(button).SetDisabled(value.Get<bool>());
break;
}
case Toolkit::Button::Property::AUTO_REPEATING:
{
- GetImplementation( button ).SetAutoRepeating( value.Get< bool >() );
+ GetImplementation(button).SetAutoRepeating(value.Get<bool>());
break;
}
case Toolkit::Button::Property::INITIAL_AUTO_REPEATING_DELAY:
{
- GetImplementation( button ).SetInitialAutoRepeatingDelay( value.Get< float >() );
+ GetImplementation(button).SetInitialAutoRepeatingDelay(value.Get<float>());
break;
}
case Toolkit::Button::Property::NEXT_AUTO_REPEATING_DELAY:
{
- GetImplementation( button ).SetNextAutoRepeatingDelay( value.Get< float >() );
+ GetImplementation(button).SetNextAutoRepeatingDelay(value.Get<float>());
break;
}
case Toolkit::Button::Property::TOGGLABLE:
{
- GetImplementation( button ).SetTogglableButton( value.Get< bool >() );
+ GetImplementation(button).SetTogglableButton(value.Get<bool>());
break;
}
case Toolkit::Button::Property::SELECTED:
{
- GetImplementation( button ).SetSelected( value.Get< bool >() );
+ GetImplementation(button).SetSelected(value.Get<bool>());
break;
}
case Toolkit::Button::Property::DISABLED_SELECTED_VISUAL:
case Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL:
{
- GetImplementation( button ).CreateVisualsForComponent( index, value, DepthIndex::CONTENT );
+ GetImplementation(button).CreateVisualsForComponent(index, value, DepthIndex::CONTENT);
break;
}
case Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL:
case Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL:
{
- GetImplementation( button ).CreateVisualsForComponent( index , value, DepthIndex::BACKGROUND);
+ GetImplementation(button).CreateVisualsForComponent(index, value, DepthIndex::BACKGROUND);
break;
}
case Toolkit::Button::Property::LABEL:
{
Property::Map outTextVisualProperties;
- std::string textString;
+ std::string textString;
- if ( value.Get( textString ) )
+ if(value.Get(textString))
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetProperty Setting TextVisual with string[%s]\n", textString.c_str() );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetProperty Setting TextVisual with string[%s]\n", textString.c_str());
Property::Map setPropertyMap;
- setPropertyMap.Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT )
- .Add( Toolkit::TextVisual::Property::TEXT, textString );
+ setPropertyMap.Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT)
+ .Add(Toolkit::TextVisual::Property::TEXT, textString);
- GetImplementation( button ).MergeWithExistingLabelProperties( setPropertyMap, outTextVisualProperties );
+ GetImplementation(button).MergeWithExistingLabelProperties(setPropertyMap, outTextVisualProperties);
}
else
{
// Get a Property::Map from the property if possible.
const Property::Map* setPropertyMap = value.GetMap();
- if( setPropertyMap )
+ if(setPropertyMap)
{
- Property::Map indexKeys = TextVisual::ConvertStringKeysToIndexKeys( *setPropertyMap );
- GetImplementation( button ).MergeWithExistingLabelProperties( indexKeys, outTextVisualProperties );
+ Property::Map indexKeys = TextVisual::ConvertStringKeysToIndexKeys(*setPropertyMap);
+ GetImplementation(button).MergeWithExistingLabelProperties(indexKeys, outTextVisualProperties);
}
}
- if( !outTextVisualProperties.Empty() )
+ if(!outTextVisualProperties.Empty())
{
- GetImplementation( button ).CreateVisualsForComponent( index, outTextVisualProperties, DepthIndex::CONTENT );
+ GetImplementation(button).CreateVisualsForComponent(index, outTextVisualProperties, DepthIndex::CONTENT);
}
break;
}
case Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT:
{
Button::Align labelAlignment(END);
- Scripting::GetEnumeration< Button::Align> ( value.Get< std::string >().c_str(),
- ALIGNMENT_TABLE, ALIGNMENT_TABLE_COUNT,
- labelAlignment );
+ Scripting::GetEnumeration<Button::Align>(value.Get<std::string>().c_str(),
+ ALIGNMENT_TABLE,
+ ALIGNMENT_TABLE_COUNT,
+ labelAlignment);
- GetImplementation( button ).SetLabelAlignment( labelAlignment );
+ GetImplementation(button).SetLabelAlignment(labelAlignment);
break;
}
case Toolkit::DevelButton::Property::LABEL_PADDING:
{
- Vector4 padding ( value.Get< Vector4 >() );
- GetImplementation( button ).SetLabelPadding( Padding( padding.x, padding.y, padding.z, padding.w ) );
+ Vector4 padding(value.Get<Vector4>());
+ GetImplementation(button).SetLabelPadding(Padding(padding.x, padding.y, padding.z, padding.w));
break;
}
case Toolkit::DevelButton::Property::VISUAL_PADDING:
{
- Vector4 padding ( value.Get< Vector4 >() );
- GetImplementation( button ).SetForegroundPadding( Padding( padding.x, padding.y, padding.z, padding.w ) );
+ Vector4 padding(value.Get<Vector4>());
+ GetImplementation(button).SetForegroundPadding(Padding(padding.x, padding.y, padding.z, padding.w));
break;
}
}
}
}
-Property::Value Button::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value Button::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::Button button = Toolkit::Button::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Button button = Toolkit::Button::DownCast(Dali::BaseHandle(object));
- if ( button )
+ if(button)
{
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::Button::Property::DISABLED:
{
- value = GetImplementation( button ).IsDisabled();
+ value = GetImplementation(button).IsDisabled();
break;
}
case Toolkit::Button::Property::AUTO_REPEATING:
{
- value = GetImplementation( button ).mAutoRepeating;
+ value = GetImplementation(button).mAutoRepeating;
break;
}
case Toolkit::Button::Property::INITIAL_AUTO_REPEATING_DELAY:
{
- value = GetImplementation( button ).mInitialAutoRepeatingDelay;
+ value = GetImplementation(button).mInitialAutoRepeatingDelay;
break;
}
case Toolkit::Button::Property::NEXT_AUTO_REPEATING_DELAY:
{
- value = GetImplementation( button ).mNextAutoRepeatingDelay;
+ value = GetImplementation(button).mNextAutoRepeatingDelay;
break;
}
case Toolkit::Button::Property::TOGGLABLE:
{
- value = GetImplementation( button ).mTogglableButton;
+ value = GetImplementation(button).mTogglableButton;
break;
}
case Toolkit::Button::Property::SELECTED:
{
- value = GetImplementation( button ).IsSelected();
+ value = GetImplementation(button).IsSelected();
break;
}
case Toolkit::Button::Property::LABEL:
{
Property::Map visualProperty;
- if ( GetImplementation( button ).GetPropertyMapForVisual( propertyIndex, visualProperty ) )
+ if(GetImplementation(button).GetPropertyMapForVisual(propertyIndex, visualProperty))
{
value = visualProperty;
}
case Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT:
{
- const char* alignment = Scripting::GetEnumerationName< Button::Align >( GetImplementation( button ).GetLabelAlignment(),
- ALIGNMENT_STRING_TABLE,
- ALIGNMENT_STRING_TABLE_COUNT );
- if( alignment )
+ const char* alignment = Scripting::GetEnumerationName<Button::Align>(GetImplementation(button).GetLabelAlignment(),
+ ALIGNMENT_STRING_TABLE,
+ ALIGNMENT_STRING_TABLE_COUNT);
+ if(alignment)
{
- value = std::string( alignment );
+ value = std::string(alignment);
}
break;
case Toolkit::DevelButton::Property::LABEL_PADDING:
{
- Padding padding = GetImplementation( button ).GetLabelPadding();
- value = Vector4( padding.x, padding.y, padding.top, padding.bottom);
+ Padding padding = GetImplementation(button).GetLabelPadding();
+ value = Vector4(padding.x, padding.y, padding.top, padding.bottom);
break;
}
case Toolkit::DevelButton::Property::VISUAL_PADDING:
{
- Padding padding = GetImplementation( button ).GetForegroundPadding();
- value = Vector4( padding.x, padding.y, padding.top, padding.bottom);
+ Padding padding = GetImplementation(button).GetForegroundPadding();
+ value = Vector4(padding.x, padding.y, padding.top, padding.bottom);
}
}
}
return value;
}
-void Button::SetLabelPadding( const Padding& padding)
+void Button::SetLabelPadding(const Padding& padding)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetLabelPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top );
- mLabelPadding = Padding( padding.left, padding.right, padding.bottom, padding.top );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetLabelPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top);
+ mLabelPadding = Padding(padding.left, padding.right, padding.bottom, padding.top);
RelayoutRequest();
}
return mLabelPadding;
}
-void Button::SetForegroundPadding( const Padding& padding)
+void Button::SetForegroundPadding(const Padding& padding)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetForegroundPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top );
- mForegroundPadding = Padding( padding.left, padding.right, padding.bottom, padding.top );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetForegroundPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top);
+ mForegroundPadding = Padding(padding.left, padding.right, padding.bottom, padding.top);
RelayoutRequest();
}
std::string Button::AccessibleImpl::GetNameRaw()
{
- std::string labelText;
- auto slf = Toolkit::Button::DownCast( self );
- Property::Map labelMap = slf.GetProperty<Property::Map>( Toolkit::Button::Property::LABEL );
+ std::string labelText;
+ auto slf = Toolkit::Button::DownCast(self);
+ Property::Map labelMap = slf.GetProperty<Property::Map>(Toolkit::Button::Property::LABEL);
- Property::Value* textPropertyPtr = labelMap.Find( Toolkit::TextVisual::Property::TEXT );
- if ( textPropertyPtr )
+ Property::Value* textPropertyPtr = labelMap.Find(Toolkit::TextVisual::Property::TEXT);
+ if(textPropertyPtr)
{
- textPropertyPtr->Get( labelText );
+ textPropertyPtr->Get(labelText);
}
return labelText;
}
-
Property::Index Button::AccessibleImpl::GetNamePropertyIndex()
{
- Property::Index label = Toolkit::Button::Property::LABEL;
- Property::Map labelMap = self.GetProperty<Property::Map>(label);
+ Property::Index label = Toolkit::Button::Property::LABEL;
+ Property::Map labelMap = self.GetProperty<Property::Map>(label);
- if (MapContainsTextString(labelMap))
+ if(MapContainsTextString(labelMap))
return label;
else
return Property::INVALID_INDEX;
Dali::Accessibility::States Button::AccessibleImpl::CalculateStates()
{
- auto tmp = Control::Impl::AccessibleImpl::CalculateStates();
+ auto tmp = Control::Impl::AccessibleImpl::CalculateStates();
tmp[Dali::Accessibility::State::SELECTABLE] = true;
- auto slf = Toolkit::Button::DownCast( self );
- tmp[Dali::Accessibility::State::ENABLED] = !slf.GetProperty<bool>( Toolkit::Button::Property::DISABLED );
- tmp[Dali::Accessibility::State::CHECKED] = slf.GetProperty<bool>( Toolkit::Button::Property::SELECTED );
+ auto slf = Toolkit::Button::DownCast(self);
+ tmp[Dali::Accessibility::State::ENABLED] = !slf.GetProperty<bool>(Toolkit::Button::Property::DISABLED);
+ tmp[Dali::Accessibility::State::CHECKED] = slf.GetProperty<bool>(Toolkit::Button::Property::SELECTED);
return tmp;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali/public-api/object/type-registry.h>
//INTERNAL INCLUDES
-#include <dali-toolkit/internal/controls/image-view/image-view-impl.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/shader-effects/image-region-effect.h>
-#include <dali-toolkit/devel-api/shader-effects/image-region-effect.h>
+#include <dali-toolkit/internal/controls/image-view/image-view-impl.h>
#if defined(DEBUG_ENABLED)
- extern Debug::Filter* gLogButtonFilter;
+extern Debug::Filter* gLogButtonFilter;
#endif
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
return Toolkit::CheckBoxButton::New();
}
-TypeRegistration mType( typeid(Toolkit::CheckBoxButton), typeid(Toolkit::Button), Create );
-
+TypeRegistration mType(typeid(Toolkit::CheckBoxButton), typeid(Toolkit::Button), Create);
-
-}
+} // namespace
Dali::Toolkit::CheckBoxButton CheckBoxButton::New()
{
// Create the implementation, temporarily owned on stack
- IntrusivePtr< CheckBoxButton > internalCheckBoxButton = new CheckBoxButton();
+ IntrusivePtr<CheckBoxButton> internalCheckBoxButton = new CheckBoxButton();
// Pass ownership to CustomActor
- Dali::Toolkit::CheckBoxButton checkBoxButton( *internalCheckBoxButton );
+ Dali::Toolkit::CheckBoxButton checkBoxButton(*internalCheckBoxButton);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
CheckBoxButton::CheckBoxButton()
: Button()
{
- SetTogglableButton( true );
+ SetTogglableButton(true);
}
CheckBoxButton::~CheckBoxButton()
{
Button::OnInitialize();
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::CHECK_BOX ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::CHECK_BOX));
+ });
}
Dali::Accessibility::States CheckBoxButton::AccessibleImpl::CalculateStates()
{
auto tmp = Button::AccessibleImpl::CalculateStates();
- auto slf = Toolkit::Button::DownCast( self );
- if( slf.GetProperty<bool>( Toolkit::Button::Property::SELECTED ) )
+ auto slf = Toolkit::Button::DownCast(self);
+ if(slf.GetProperty<bool>(Toolkit::Button::Property::SELECTED))
tmp[Dali::Accessibility::State::CHECKED] = true;
return tmp;
}
-void CheckBoxButton::OnStateChange( State newState )
+void CheckBoxButton::OnStateChange(State newState)
{
// TODO: replace it with OnPropertySet hook once Button::Property::SELECTED will be consistently used
- if (Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE))
+ if(Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE))
{
Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged(
- Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0
- );
+ Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0);
}
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "push-button-impl.h"
// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/devel-api/scripting/scripting.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/image-view/image-view.h>
-#include <dali-toolkit/public-api/controls/text-controls/text-label.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
+#include <dali-toolkit/public-api/controls/image-view/image-view.h>
+#include <dali-toolkit/public-api/controls/text-controls/text-label.h>
#if defined(DEBUG_ENABLED)
- extern Debug::Filter* gLogButtonFilter;
+extern Debug::Filter* gLogButtonFilter;
#endif
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
return Toolkit::PushButton::New();
// Properties
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PushButton, Toolkit::Button, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::PushButton, Toolkit::Button, Create)
-DALI_PROPERTY_REGISTRATION( Toolkit, PushButton, "labelPadding", STRING, LABEL_PADDING )
-DALI_PROPERTY_REGISTRATION( Toolkit, PushButton, "iconPadding", STRING, ICON_PADDING )
+DALI_PROPERTY_REGISTRATION(Toolkit, PushButton, "labelPadding", STRING, LABEL_PADDING)
+DALI_PROPERTY_REGISTRATION(Toolkit, PushButton, "iconPadding", STRING, ICON_PADDING)
DALI_TYPE_REGISTRATION_END()
namespace
{
-
} // unnamed namespace
Dali::Toolkit::PushButton PushButton::New()
{
// Create the implementation, temporarily owned on stack
- IntrusivePtr< PushButton > internalPushButton = new PushButton();
+ IntrusivePtr<PushButton> internalPushButton = new PushButton();
// Pass ownership to CustomActor
- Dali::Toolkit::PushButton pushButton( *internalPushButton );
+ Dali::Toolkit::PushButton pushButton(*internalPushButton);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
PushButton::PushButton()
: Button(),
- mIconAlignment( RIGHT )
+ mIconAlignment(RIGHT)
{
}
// Push button requires the Leave event.
Actor self = Self();
- self.SetProperty( Actor::Property::LEAVE_REQUIRED, true );
+ self.SetProperty(Actor::Property::LEAVE_REQUIRED, true);
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::PUSH_BUTTON ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::PUSH_BUTTON));
+ });
}
-void PushButton::SetIconAlignment( const PushButton::IconAlignment iconAlignment )
+void PushButton::SetIconAlignment(const PushButton::IconAlignment iconAlignment)
{
mIconAlignment = iconAlignment;
Button::Align labelAlignment;
- switch ( iconAlignment )
+ switch(iconAlignment)
{
- case RIGHT:
- {
- labelAlignment = Button::BEGIN;
- break;
- }
- case TOP:
- {
- labelAlignment = Button::BOTTOM;
- break;
- }
- case BOTTOM:
- {
- labelAlignment = Button::TOP;
- break;
- }
- case LEFT:
- default:
- labelAlignment = Button::END;
- break;
+ case RIGHT:
+ {
+ labelAlignment = Button::BEGIN;
+ break;
+ }
+ case TOP:
+ {
+ labelAlignment = Button::BOTTOM;
+ break;
+ }
+ case BOTTOM:
+ {
+ labelAlignment = Button::TOP;
+ break;
+ }
+ case LEFT:
+ default:
+ labelAlignment = Button::END;
+ break;
}
- Button::SetLabelAlignment( labelAlignment );
+ Button::SetLabelAlignment(labelAlignment);
}
const PushButton::IconAlignment PushButton::GetIconAlignment() const
return mIconAlignment;
}
-void PushButton::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
+void PushButton::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value)
{
- Toolkit::PushButton pushButton = Toolkit::PushButton::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::PushButton pushButton = Toolkit::PushButton::DownCast(Dali::BaseHandle(object));
- if ( pushButton )
+ if(pushButton)
{
- PushButton& pushButtonImpl( GetImplementation( pushButton ) );
+ PushButton& pushButtonImpl(GetImplementation(pushButton));
// Properties remain here for Tizen 3.0 legacy requirements. Are now in Button base class
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::PushButton::Property::LABEL_PADDING:
{
- Vector4 padding ( value.Get< Vector4 >() );
- pushButtonImpl.Button::SetLabelPadding( Padding( padding.x, padding.y, padding.z, padding.w ) );
+ Vector4 padding(value.Get<Vector4>());
+ pushButtonImpl.Button::SetLabelPadding(Padding(padding.x, padding.y, padding.z, padding.w));
break;
}
case Toolkit::PushButton::Property::ICON_PADDING:
{
- Vector4 padding ( value.Get< Vector4 >() );
- pushButtonImpl.Button::SetForegroundPadding( Padding( padding.x, padding.y, padding.z, padding.w ) );
+ Vector4 padding(value.Get<Vector4>());
+ pushButtonImpl.Button::SetForegroundPadding(Padding(padding.x, padding.y, padding.z, padding.w));
break;
}
}
}
}
-Property::Value PushButton::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value PushButton::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::PushButton pushButton = Toolkit::PushButton::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::PushButton pushButton = Toolkit::PushButton::DownCast(Dali::BaseHandle(object));
- if ( pushButton )
+ if(pushButton)
{
- PushButton& pushButtonImpl( GetImplementation( pushButton ) );
+ PushButton& pushButtonImpl(GetImplementation(pushButton));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::PushButton::Property::LABEL_PADDING:
{
Padding padding = pushButtonImpl.Button::GetLabelPadding();
- value = Vector4( padding.x, padding.y, padding.top, padding.bottom);
+ value = Vector4(padding.x, padding.y, padding.top, padding.bottom);
break;
}
case Toolkit::PushButton::Property::ICON_PADDING:
{
Padding padding = pushButtonImpl.Button::GetForegroundPadding();
- value = Vector4( padding.x, padding.y, padding.top, padding.bottom);
+ value = Vector4(padding.x, padding.y, padding.top, padding.bottom);
break;
}
}
Dali::Accessibility::States PushButton::AccessibleImpl::CalculateStates()
{
- auto tmp = Button::AccessibleImpl::CalculateStates();
- auto slf = Toolkit::Button::DownCast( self );
- tmp[Dali::Accessibility::State::PRESSED] = slf.GetProperty<bool>( Toolkit::Button::Property::SELECTED );
+ auto tmp = Button::AccessibleImpl::CalculateStates();
+ auto slf = Toolkit::Button::DownCast(self);
+ tmp[Dali::Accessibility::State::PRESSED] = slf.GetProperty<bool>(Toolkit::Button::Property::SELECTED);
return tmp;
}
-void PushButton::OnStateChange( State newState )
+void PushButton::OnStateChange(State newState)
{
// TODO: replace it with OnPropertySet hook once Button::Property::SELECTED will be consistently used
- if (Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE))
+ if(Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE))
{
Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged(
- Dali::Accessibility::State::PRESSED, newState == SELECTED_STATE ? 1 : 0, 0
- );
+ Dali::Accessibility::State::PRESSED, newState == SELECTED_STATE ? 1 : 0, 0);
- if (Self().GetProperty<bool>(Toolkit::Button::Property::TOGGLABLE))
+ if(Self().GetProperty<bool>(Toolkit::Button::Property::TOGGLABLE))
{
Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged(
- Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0
- );
+ Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0);
}
}
}
*
*/
-
// CLASS HEADER
#include "radio-button-impl.h"
#include <dali/public-api/object/type-registry.h>
#if defined(DEBUG_ENABLED)
- extern Debug::Filter* gLogButtonFilter;
+extern Debug::Filter* gLogButtonFilter;
#endif
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
return Toolkit::RadioButton::New();
}
-TypeRegistration typeRegistration( typeid( Toolkit::RadioButton ), typeid( Toolkit::Button ), Create);
+TypeRegistration typeRegistration(typeid(Toolkit::RadioButton), typeid(Toolkit::Button), Create);
-}
+} // namespace
Dali::Toolkit::RadioButton RadioButton::New()
{
// Create the implementation, temporarily owned on stack
- IntrusivePtr< RadioButton > internalRadioButton = new RadioButton();
+ IntrusivePtr<RadioButton> internalRadioButton = new RadioButton();
// Pass ownership to CustomActor
Dali::Toolkit::RadioButton radioButton(*internalRadioButton);
{
Button::OnInitialize();
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::RADIO_BUTTON ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::RADIO_BUTTON));
+ });
}
bool RadioButton::OnToggleReleased()
return false;
}
-void RadioButton::OnStateChange( State newState )
+void RadioButton::OnStateChange(State newState)
{
// Radio button can be part of a group, if a button in the group is selected then all others should be unselected
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "RadioButton::OnStateChange state(%d)\n", newState );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "RadioButton::OnStateChange state(%d)\n", newState);
- if ( SELECTED_STATE == newState )
+ if(SELECTED_STATE == newState)
{
Actor parent = Self().GetParent();
- if( parent )
+ if(parent)
{
- for( unsigned int i = 0; i < parent.GetChildCount(); ++i )
+ for(unsigned int i = 0; i < parent.GetChildCount(); ++i)
{
- Dali::Toolkit::RadioButton radioButtonChild = Dali::Toolkit::RadioButton::DownCast( parent.GetChildAt( i ) );
- if( radioButtonChild && radioButtonChild != Self() )
+ Dali::Toolkit::RadioButton radioButtonChild = Dali::Toolkit::RadioButton::DownCast(parent.GetChildAt(i));
+ if(radioButtonChild && radioButtonChild != Self())
{
- radioButtonChild.SetProperty( Toolkit::Button::Property::SELECTED, false );
+ radioButtonChild.SetProperty(Toolkit::Button::Property::SELECTED, false);
}
}
}
}
// TODO: replace it with OnPropertySet hook once Button::Property::SELECTED will be consistently used
- if (Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE))
+ if(Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE))
{
Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged(
- Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0
- );
+ Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0);
}
}
Dali::Accessibility::States RadioButton::AccessibleImpl::CalculateStates()
{
auto tmp = Button::AccessibleImpl::CalculateStates();
- auto slf = Toolkit::Button::DownCast( self );
- if( slf.GetProperty<bool>( Toolkit::Button::Property::SELECTED ) )
+ auto slf = Toolkit::Button::DownCast(self);
+ if(slf.GetProperty<bool>(Toolkit::Button::Property::SELECTED))
tmp[Dali::Accessibility::State::CHECKED] = true;
tmp[Dali::Accessibility::State::SELECTABLE] = true;
return tmp;
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "toggle-button-impl.h"
// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/devel-api/scripting/scripting.h>
-#include <dali/public-api/object/property-array.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/property-array.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
+#include <dali-toolkit/devel-api/controls/tooltip/tooltip-properties.h>
#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/public-api/align-enumerations.h>
-#include <dali-toolkit/devel-api/controls/tooltip/tooltip-properties.h>
+#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
-#include <dali-toolkit/devel-api/controls/control-devel.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
#if defined(DEBUG_ENABLED)
- extern Debug::Filter* gLogButtonFilter;
+extern Debug::Filter* gLogButtonFilter;
#endif
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
return Toolkit::ToggleButton::New();
}
// Properties
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ToggleButton, Toolkit::Button, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ToggleButton, Toolkit::Button, Create)
-DALI_PROPERTY_REGISTRATION( Toolkit, ToggleButton, "stateVisuals", ARRAY, STATE_VISUALS )
-DALI_PROPERTY_REGISTRATION( Toolkit, ToggleButton, "tooltips", ARRAY, TOOLTIPS )
-DALI_PROPERTY_REGISTRATION( Toolkit, ToggleButton, "currentStateIndex", INTEGER, CURRENT_STATE_INDEX )
+DALI_PROPERTY_REGISTRATION(Toolkit, ToggleButton, "stateVisuals", ARRAY, STATE_VISUALS)
+DALI_PROPERTY_REGISTRATION(Toolkit, ToggleButton, "tooltips", ARRAY, TOOLTIPS)
+DALI_PROPERTY_REGISTRATION(Toolkit, ToggleButton, "currentStateIndex", INTEGER, CURRENT_STATE_INDEX)
DALI_TYPE_REGISTRATION_END()
Dali::Toolkit::ToggleButton ToggleButton::New()
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::New\n" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::New\n");
// Create the implementation, temporarily owned on stack
- IntrusivePtr< ToggleButton > internalToggleButton = new ToggleButton();
+ IntrusivePtr<ToggleButton> internalToggleButton = new ToggleButton();
// Pass ownership to CustomActor
- Dali::Toolkit::ToggleButton toggleButton( *internalToggleButton );
+ Dali::Toolkit::ToggleButton toggleButton(*internalToggleButton);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
mToggleTooltips(),
mCurrentToggleIndex(0)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::Constructor\n" );
- SetTogglableButton( false );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::Constructor\n");
+ SetTogglableButton(false);
}
ToggleButton::~ToggleButton()
void ToggleButton::OnInitialize()
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnInitialize\n" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnInitialize\n");
Button::OnInitialize();
// Toggle button requires the Leave event.
Actor self = Self();
- self.SetProperty( Actor::Property::LEAVE_REQUIRED, true );
+ self.SetProperty(Actor::Property::LEAVE_REQUIRED, true);
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::TOGGLE_BUTTON ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::TOGGLE_BUTTON));
+ });
}
-void ToggleButton::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
+void ToggleButton::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value)
{
- Toolkit::ToggleButton toggleButton = Toolkit::ToggleButton::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ToggleButton toggleButton = Toolkit::ToggleButton::DownCast(Dali::BaseHandle(object));
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::SetProperty index[%d]\n", propertyIndex );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::SetProperty index[%d]\n", propertyIndex);
- if ( toggleButton )
+ if(toggleButton)
{
- ToggleButton& toggleButtonImpl( GetImplementation( toggleButton ) );
+ ToggleButton& toggleButtonImpl(GetImplementation(toggleButton));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::ToggleButton::Property::STATE_VISUALS:
{
Property::Array stateArray;
- if( value.Get( stateArray ) )
+ if(value.Get(stateArray))
{
- toggleButtonImpl.SetToggleStates( stateArray );
+ toggleButtonImpl.SetToggleStates(stateArray);
}
break;
case Toolkit::ToggleButton::Property::TOOLTIPS:
{
const Property::Array* tipArray = value.GetArray();
- if( tipArray )
+ if(tipArray)
{
std::vector<std::string> tips;
- size_t tipsCount = tipArray->Count();
- tips.resize( tipsCount );
- for( size_t i = 0; i != tipsCount; ++i )
+ size_t tipsCount = tipArray->Count();
+ tips.resize(tipsCount);
+ for(size_t i = 0; i != tipsCount; ++i)
{
- tipArray->GetElementAt( i ).Get( tips[i] );
+ tipArray->GetElementAt(i).Get(tips[i]);
}
toggleButtonImpl.SetToggleTooltips(tips);
}
break;
}
- default :
+ default:
{
break;
}
}
}
-Property::Value ToggleButton::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value ToggleButton::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::ToggleButton toggleButton = Toolkit::ToggleButton::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ToggleButton toggleButton = Toolkit::ToggleButton::DownCast(Dali::BaseHandle(object));
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::GetProperty index[%d]\n", propertyIndex );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::GetProperty index[%d]\n", propertyIndex);
- if ( toggleButton )
+ if(toggleButton)
{
- ToggleButton& toggleButtonImpl( GetImplementation( toggleButton ) );
+ ToggleButton& toggleButtonImpl(GetImplementation(toggleButton));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::ToggleButton::Property::STATE_VISUALS:
{
Property::Array array = toggleButtonImpl.GetToggleStates();
- value = Property::Value( array );
+ value = Property::Value(array);
break;
}
case Toolkit::ToggleButton::Property::TOOLTIPS:
{
- Property::Value value1( Property::ARRAY );
+ Property::Value value1(Property::ARRAY);
Property::Array* tipArray = value1.GetArray();
- if( tipArray )
+ if(tipArray)
{
std::vector<std::string> tips = toggleButtonImpl.GetToggleTooltips();
- size_t tipsCount( tips.size() );
- for( size_t i( 0 ); i != tipsCount; ++i )
+ size_t tipsCount(tips.size());
+ for(size_t i(0); i != tipsCount; ++i)
{
- tipArray->PushBack( tips[i] );
+ tipArray->PushBack(tips[i]);
}
}
value = value1;
return value;
}
-void ToggleButton::CreateVisualsForAllStates( const Property::Array& states, std::vector<Toolkit::Visual::Base>& visuals )
+void ToggleButton::CreateVisualsForAllStates(const Property::Array& states, std::vector<Toolkit::Visual::Base>& visuals)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::CreateVisualsForAllStates\n" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::CreateVisualsForAllStates\n");
visuals.clear();
- for ( unsigned int i = 0; i < states.Count(); i++ )
+ for(unsigned int i = 0; i < states.Count(); i++)
{
- Property::Value value( states[i] );
+ Property::Value value(states[i]);
Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get();
- Toolkit::Visual::Base stateVisual;
+ Toolkit::Visual::Base stateVisual;
- if ( value.GetType() == Property::MAP )
+ if(value.GetType() == Property::MAP)
{
- Property::Map *map = value.GetMap();
- if( map && !map->Empty() ) // Empty map results in current visual removal.
+ Property::Map* map = value.GetMap();
+ if(map && !map->Empty()) // Empty map results in current visual removal.
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals Using Map\n" );
- stateVisual = visualFactory.CreateVisual( *map );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals Using Map\n");
+ stateVisual = visualFactory.CreateVisual(*map);
}
}
- else if ( value.GetType() == Property::STRING )
+ else if(value.GetType() == Property::STRING)
{
std::string imageUrl = value.Get<std::string>();
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals Using image URL\n" );
- if ( !imageUrl.empty() )
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals Using image URL\n");
+ if(!imageUrl.empty())
{
- stateVisual = visualFactory.CreateVisual( imageUrl, ImageDimensions() );
+ stateVisual = visualFactory.CreateVisual(imageUrl, ImageDimensions());
}
}
- if ( stateVisual )
+ if(stateVisual)
{
- stateVisual.SetDepthIndex( DepthIndex::CONTENT );
- visuals.push_back( stateVisual );
+ stateVisual.SetDepthIndex(DepthIndex::CONTENT);
+ visuals.push_back(stateVisual);
}
} // end of for
- DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals mToggleVisuals:%d\n", mToggleVisuals.size() );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals mToggleVisuals:%d\n", mToggleVisuals.size());
}
-void ToggleButton::SetToggleStates( const Property::Array& states )
+void ToggleButton::SetToggleStates(const Property::Array& states)
{ //this should really be generalized to be either string or maps so that any visual can be created.
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::SetToggleStates\n" );
- if ( !states.Empty() )
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::SetToggleStates\n");
+ if(!states.Empty())
{
mToggleStates.Clear();
mToggleStates = states;
mCurrentToggleIndex = 0;
// Create all visuals, save to mToggleVisuals.
- CreateVisualsForAllStates( states, mToggleVisuals );
- CreateVisualsForAllStates( states, mToggleSelectedVisuals );
- CreateVisualsForAllStates( states, mToggleDisabledVisuals );
- CreateVisualsForAllStates( states, mToggleDisabledSelectedVisuals );
+ CreateVisualsForAllStates(states, mToggleVisuals);
+ CreateVisualsForAllStates(states, mToggleSelectedVisuals);
+ CreateVisualsForAllStates(states, mToggleDisabledVisuals);
+ CreateVisualsForAllStates(states, mToggleDisabledSelectedVisuals);
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::Began to register visual.\n" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::Began to register visual.\n");
- PrepareVisual( Toolkit::Button::Property::UNSELECTED_VISUAL, mToggleVisuals[mCurrentToggleIndex] );
- PrepareVisual( Toolkit::Button::Property::SELECTED_VISUAL, mToggleSelectedVisuals[mCurrentToggleIndex] );
- PrepareVisual( Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, mToggleDisabledVisuals[mCurrentToggleIndex] );
- PrepareVisual( Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, mToggleDisabledSelectedVisuals[mCurrentToggleIndex] );
+ PrepareVisual(Toolkit::Button::Property::UNSELECTED_VISUAL, mToggleVisuals[mCurrentToggleIndex]);
+ PrepareVisual(Toolkit::Button::Property::SELECTED_VISUAL, mToggleSelectedVisuals[mCurrentToggleIndex]);
+ PrepareVisual(Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, mToggleDisabledVisuals[mCurrentToggleIndex]);
+ PrepareVisual(Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, mToggleDisabledSelectedVisuals[mCurrentToggleIndex]);
RelayoutRequest();
}
return mToggleStates;
}
-void ToggleButton::SetToggleTooltips( std::vector<std::string>& tips )
+void ToggleButton::SetToggleTooltips(std::vector<std::string>& tips)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::SetToggleTooltips\n" );
- if ( !tips.empty() )
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::SetToggleTooltips\n");
+ if(!tips.empty())
{
mToggleTooltips.clear();
- mToggleTooltips.swap( tips );
+ mToggleTooltips.swap(tips);
}
- if ( !mToggleTooltips.empty() && ( mCurrentToggleIndex < mToggleTooltips.size() ) )
+ if(!mToggleTooltips.empty() && (mCurrentToggleIndex < mToggleTooltips.size()))
{
- Self().SetProperty( Toolkit::DevelControl::Property::TOOLTIP, mToggleTooltips[mCurrentToggleIndex] );
+ Self().SetProperty(Toolkit::DevelControl::Property::TOOLTIP, mToggleTooltips[mCurrentToggleIndex]);
}
RelayoutRequest();
bool enabled = false; // Disabled by default
// Unregister the visual with the given index if registered previously
- if( DevelControl::GetVisual( *this, index ) )
+ if(DevelControl::GetVisual(*this, index))
{
// Check whether it was enabled to ensure we do the same with the new visual we're registering
- enabled = DevelControl::IsVisualEnabled( *this, index );
- DevelControl::UnregisterVisual( *this, index );
+ enabled = DevelControl::IsVisualEnabled(*this, index);
+ DevelControl::UnregisterVisual(*this, index);
}
- DevelControl::RegisterVisual( *this, index, visual, enabled );
+ DevelControl::RegisterVisual(*this, index, visual, enabled);
}
-void ToggleButton::RelayoutVisual( Property::Index index, const Vector2& size )
+void ToggleButton::RelayoutVisual(Property::Index index, const Vector2& size)
{
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, index );
- if ( visual )
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, index);
+ if(visual)
{
- Size visualSize = Size::ZERO;
+ Size visualSize = Size::ZERO;
Vector2 visualPosition = Vector2::ZERO;
- visual.GetNaturalSize( visualSize );
+ visual.GetNaturalSize(visualSize);
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height );
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout Setting visual position to(%f,%f)\n", visualPosition.x, visualPosition.y );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height);
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout Setting visual position to(%f,%f)\n", visualPosition.x, visualPosition.y);
Property::Map visualTransform;
- visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, visualSize )
- .Add( Toolkit::Visual::Transform::Property::OFFSET, visualPosition )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::CENTER )
- .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::CENTER );
-
- visual.SetTransformAndSize( visualTransform, size );
+ visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, visualSize)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET, visualPosition)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::CENTER)
+ .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::CENTER);
+
+ visual.SetTransformAndSize(visualTransform, size);
}
}
-void ToggleButton::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void ToggleButton::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout targetSize(%f,%f) ptr(%p)\n", size.width, size.height, this );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout targetSize(%f,%f) ptr(%p)\n", size.width, size.height, this);
- RelayoutVisual( Toolkit::Button::Property::UNSELECTED_VISUAL, size );
- RelayoutVisual( Toolkit::Button::Property::SELECTED_VISUAL, size );
- RelayoutVisual( Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, size );
- RelayoutVisual( Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, size );
+ RelayoutVisual(Toolkit::Button::Property::UNSELECTED_VISUAL, size);
+ RelayoutVisual(Toolkit::Button::Property::SELECTED_VISUAL, size);
+ RelayoutVisual(Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, size);
+ RelayoutVisual(Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, size);
}
void ToggleButton::OnPressed()
{
- DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnPressed\n" );
+ DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnPressed\n");
// State index will add 1 only when button is pressed.
- mCurrentToggleIndex = ( mCurrentToggleIndex + 1 ) % mToggleVisuals.size();
+ mCurrentToggleIndex = (mCurrentToggleIndex + 1) % mToggleVisuals.size();
// Both create SelectedVisual and UnselectedVisual
- PrepareVisual( Toolkit::Button::Property::UNSELECTED_VISUAL, mToggleVisuals[mCurrentToggleIndex] );
- PrepareVisual( Toolkit::Button::Property::SELECTED_VISUAL, mToggleSelectedVisuals[mCurrentToggleIndex] );
- PrepareVisual( Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, mToggleDisabledVisuals[mCurrentToggleIndex] );
- PrepareVisual( Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, mToggleDisabledSelectedVisuals[mCurrentToggleIndex] );
+ PrepareVisual(Toolkit::Button::Property::UNSELECTED_VISUAL, mToggleVisuals[mCurrentToggleIndex]);
+ PrepareVisual(Toolkit::Button::Property::SELECTED_VISUAL, mToggleSelectedVisuals[mCurrentToggleIndex]);
+ PrepareVisual(Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, mToggleDisabledVisuals[mCurrentToggleIndex]);
+ PrepareVisual(Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, mToggleDisabledSelectedVisuals[mCurrentToggleIndex]);
//Need to check mCurrentToggleIndex, it must less than the size of mToggleTooltips.
- if ( !mToggleTooltips.empty() && ( mCurrentToggleIndex < mToggleTooltips.size() ) )
+ if(!mToggleTooltips.empty() && (mCurrentToggleIndex < mToggleTooltips.size()))
{
- Self().SetProperty( Toolkit::DevelControl::Property::TOOLTIP, mToggleTooltips[mCurrentToggleIndex] );
+ Self().SetProperty(Toolkit::DevelControl::Property::TOOLTIP, mToggleTooltips[mCurrentToggleIndex]);
}
RelayoutRequest();
Dali::Accessibility::States ToggleButton::AccessibleImpl::CalculateStates()
{
auto states = Button::AccessibleImpl::CalculateStates();
- auto button = Toolkit::ToggleButton::DownCast( self );
- if( button.GetProperty<int>( Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX ) )
+ auto button = Toolkit::ToggleButton::DownCast(self);
+ if(button.GetProperty<int>(Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX))
states[Dali::Accessibility::State::CHECKED] = true;
return states;
}
std::string ToggleButton::AccessibleImpl::GetDescriptionRaw()
{
- auto button = Toolkit::ToggleButton::DownCast( self );
- auto index = button.GetProperty<int>( Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX );
- auto tooltips = button.GetProperty<Property::Array>( Toolkit::ToggleButton::Property::TOOLTIPS );
+ auto button = Toolkit::ToggleButton::DownCast(self);
+ auto index = button.GetProperty<int>(Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX);
+ auto tooltips = button.GetProperty<Property::Array>(Toolkit::ToggleButton::Property::TOOLTIPS);
return tooltips[index].Get<std::string>();
}
return Toolkit::ToggleButton::Property::TOOLTIPS;
}
-void ToggleButton::OnStateChange( State newState )
+void ToggleButton::OnStateChange(State newState)
{
// TODO: replace it with OnPropertySet hook once Button::Property::SELECTED will be consistently used
- if (Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE))
+ if(Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE))
{
Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged(
- Dali::Accessibility::State::CHECKED, mCurrentToggleIndex ? 1 : 0, 0
- );
+ Dali::Accessibility::State::CHECKED, mCurrentToggleIndex ? 1 : 0, 0);
if(Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
{
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "control-data-impl.h"
// EXTERNAL INCLUDES
+#include <dali-toolkit/public-api/controls/control-impl.h>
+#include <dali-toolkit/public-api/controls/control.h>
#include <dali-toolkit/public-api/dali-toolkit-common.h>
-#include <dali/integration-api/debug.h>
+#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/devel-api/adaptor-framework/accessibility.h>
+#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/object/handle-devel.h>
#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/devel-api/scripting/scripting.h>
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/integration-api/adaptor-framework/adaptor.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali-toolkit/public-api/controls/control.h>
+#include <dali/integration-api/debug.h>
#include <dali/public-api/object/object-registry.h>
-#include <dali/devel-api/adaptor-framework/accessibility.h>
-#include <dali-toolkit/public-api/controls/control-impl.h>
-#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/public-api/object/type-registry-helper.h>
#include <cstring>
#include <limits>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/visuals/visual-base-impl.h>
-#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
+#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
#include <dali-toolkit/devel-api/controls/control-wrapper-impl.h>
#include <dali-toolkit/internal/styling/style-manager-impl.h>
+#include <dali-toolkit/internal/visuals/visual-base-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/public-api/focus-manager/keyboard-focus-manager.h>
#include <dali-toolkit/public-api/controls/image-view/image-view.h>
-#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
+#include <dali-toolkit/public-api/focus-manager/keyboard-focus-manager.h>
+#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace
{
- const std::string READING_INFO_TYPE_NAME = "name";
- const std::string READING_INFO_TYPE_ROLE = "role";
- const std::string READING_INFO_TYPE_DESCRIPTION = "description";
- const std::string READING_INFO_TYPE_STATE = "state";
- const std::string READING_INFO_TYPE_ATTRIBUTE_NAME = "reading_info_type";
- const std::string READING_INFO_TYPE_SEPARATOR = "|";
-}
+const std::string READING_INFO_TYPE_NAME = "name";
+const std::string READING_INFO_TYPE_ROLE = "role";
+const std::string READING_INFO_TYPE_DESCRIPTION = "description";
+const std::string READING_INFO_TYPE_STATE = "state";
+const std::string READING_INFO_TYPE_ATTRIBUTE_NAME = "reading_info_type";
+const std::string READING_INFO_TYPE_SEPARATOR = "|";
+} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
extern const Dali::Scripting::StringEnum ControlStateTable[];
-extern const unsigned int ControlStateTableCount;
-
+extern const unsigned int ControlStateTableCount;
// Not static or anonymous - shared with other translation units
const Scripting::StringEnum ControlStateTable[] = {
- { "NORMAL", Toolkit::DevelControl::NORMAL },
- { "FOCUSED", Toolkit::DevelControl::FOCUSED },
- { "DISABLED", Toolkit::DevelControl::DISABLED },
+ {"NORMAL", Toolkit::DevelControl::NORMAL},
+ {"FOCUSED", Toolkit::DevelControl::FOCUSED},
+ {"DISABLED", Toolkit::DevelControl::DISABLED},
};
-const unsigned int ControlStateTableCount = sizeof( ControlStateTable ) / sizeof( ControlStateTable[0] );
-
-
+const unsigned int ControlStateTableCount = sizeof(ControlStateTable) / sizeof(ControlStateTable[0]);
namespace
{
-
#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_CONTROL_VISUALS");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_CONTROL_VISUALS");
#endif
-
template<typename T>
-void Remove( Dictionary<T>& keyValues, const std::string& name )
+void Remove(Dictionary<T>& keyValues, const std::string& name)
{
keyValues.Remove(name);
}
-void Remove( DictionaryKeys& keys, const std::string& name )
+void Remove(DictionaryKeys& keys, const std::string& name)
{
- DictionaryKeys::iterator iter = std::find( keys.begin(), keys.end(), name );
- if( iter != keys.end())
+ DictionaryKeys::iterator iter = std::find(keys.begin(), keys.end(), name);
+ if(iter != keys.end())
{
keys.erase(iter);
}
/**
* Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter
*/
-bool FindVisual( Property::Index targetIndex, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter )
+bool FindVisual(Property::Index targetIndex, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter)
{
- for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
+ for(iter = visuals.Begin(); iter != visuals.End(); iter++)
{
- if ( (*iter)->index == targetIndex )
+ if((*iter)->index == targetIndex)
{
return true;
}
/**
* Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter
*/
-bool FindVisual( std::string visualName, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter )
+bool FindVisual(std::string visualName, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter)
{
- for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
+ for(iter = visuals.Begin(); iter != visuals.End(); iter++)
{
Toolkit::Visual::Base visual = (*iter)->visual;
- if( visual && visual.GetName() == visualName )
+ if(visual && visual.GetName() == visualName)
{
return true;
}
return false;
}
-void FindChangableVisuals( Dictionary<Property::Map>& stateVisualsToAdd,
- Dictionary<Property::Map>& stateVisualsToChange,
- DictionaryKeys& stateVisualsToRemove)
+void FindChangableVisuals(Dictionary<Property::Map>& stateVisualsToAdd,
+ Dictionary<Property::Map>& stateVisualsToChange,
+ DictionaryKeys& stateVisualsToRemove)
{
DictionaryKeys copyOfStateVisualsToRemove = stateVisualsToRemove;
- for( DictionaryKeys::iterator iter = copyOfStateVisualsToRemove.begin();
- iter != copyOfStateVisualsToRemove.end(); ++iter )
+ for(DictionaryKeys::iterator iter = copyOfStateVisualsToRemove.begin();
+ iter != copyOfStateVisualsToRemove.end();
+ ++iter)
{
const std::string& visualName = (*iter);
- Property::Map* toMap = stateVisualsToAdd.Find( visualName );
- if( toMap )
+ Property::Map* toMap = stateVisualsToAdd.Find(visualName);
+ if(toMap)
{
- stateVisualsToChange.Add( visualName, *toMap );
- stateVisualsToAdd.Remove( visualName );
- Remove( stateVisualsToRemove, visualName );
+ stateVisualsToChange.Add(visualName, *toMap);
+ stateVisualsToAdd.Remove(visualName);
+ Remove(stateVisualsToRemove, visualName);
}
}
}
Toolkit::Visual::Base GetVisualByName(
const RegisteredVisualContainer& visuals,
- const std::string& visualName )
+ const std::string& visualName)
{
Toolkit::Visual::Base visualHandle;
RegisteredVisualContainer::Iterator iter;
- for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
+ for(iter = visuals.Begin(); iter != visuals.End(); iter++)
{
Toolkit::Visual::Base visual = (*iter)->visual;
- if( visual && visual.GetName() == visualName )
+ if(visual && visual.GetName() == visualName)
{
visualHandle = visual;
break;
/**
* Move visual from source to destination container
*/
-void MoveVisual( RegisteredVisualContainer::Iterator sourceIter, RegisteredVisualContainer& source, RegisteredVisualContainer& destination )
+void MoveVisual(RegisteredVisualContainer::Iterator sourceIter, RegisteredVisualContainer& source, RegisteredVisualContainer& destination)
{
- Toolkit::Visual::Base visual = (*sourceIter)->visual;
- if( visual )
- {
- RegisteredVisual* rv = source.Release( sourceIter );
- destination.PushBack( rv );
- }
+ Toolkit::Visual::Base visual = (*sourceIter)->visual;
+ if(visual)
+ {
+ RegisteredVisual* rv = source.Release(sourceIter);
+ destination.PushBack(rv);
+ }
}
/**
const char* ACTION_ACCESSIBILITY_READING_SKIPPED = "ReadingSkipped";
const char* ACTION_ACCESSIBILITY_READING_STOPPED = "ReadingStopped";
-static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
+static bool DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes)
{
bool ret = true;
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- Toolkit::Control control = Toolkit::Control::DownCast( handle );
+ Toolkit::Control control = Toolkit::Control::DownCast(handle);
- DALI_ASSERT_ALWAYS( control );
+ DALI_ASSERT_ALWAYS(control);
- if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED ) ||
- actionName == "activate" )
+ if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED) ||
+ actionName == "activate")
{
// if cast succeeds there is an implementation so no need to check
- if( !DevelControl::AccessibilityActivateSignal( control ).Empty() )
- DevelControl::AccessibilityActivateSignal( control ).Emit();
- else ret = Internal::GetImplementation( control ).OnAccessibilityActivated();
+ if(!DevelControl::AccessibilityActivateSignal(control).Empty())
+ DevelControl::AccessibilityActivateSignal(control).Emit();
+ else
+ ret = Internal::GetImplementation(control).OnAccessibilityActivated();
}
- else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_SKIPPED ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_SKIPPED))
{
// if cast succeeds there is an implementation so no need to check
- if( !DevelControl::AccessibilityReadingSkippedSignal( control ).Empty() )
- DevelControl::AccessibilityReadingSkippedSignal( control ).Emit();
+ if(!DevelControl::AccessibilityReadingSkippedSignal(control).Empty())
+ DevelControl::AccessibilityReadingSkippedSignal(control).Emit();
}
- else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_PAUSED ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_PAUSED))
{
// if cast succeeds there is an implementation so no need to check
- if( !DevelControl::AccessibilityReadingPausedSignal( control ).Empty() )
- DevelControl::AccessibilityReadingPausedSignal( control ).Emit();
+ if(!DevelControl::AccessibilityReadingPausedSignal(control).Empty())
+ DevelControl::AccessibilityReadingPausedSignal(control).Emit();
}
- else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_RESUMED ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_RESUMED))
{
// if cast succeeds there is an implementation so no need to check
- if( !DevelControl::AccessibilityReadingResumedSignal( control ).Empty() )
- DevelControl::AccessibilityReadingResumedSignal( control ).Emit();
+ if(!DevelControl::AccessibilityReadingResumedSignal(control).Empty())
+ DevelControl::AccessibilityReadingResumedSignal(control).Emit();
}
- else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_CANCELLED ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_CANCELLED))
{
// if cast succeeds there is an implementation so no need to check
- if( !DevelControl::AccessibilityReadingCancelledSignal( control ).Empty() )
- DevelControl::AccessibilityReadingCancelledSignal( control ).Emit();
+ if(!DevelControl::AccessibilityReadingCancelledSignal(control).Empty())
+ DevelControl::AccessibilityReadingCancelledSignal(control).Emit();
}
- else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_STOPPED ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_STOPPED))
{
// if cast succeeds there is an implementation so no need to check
- if(!DevelControl::AccessibilityReadingStoppedSignal( control ).Empty())
- DevelControl::AccessibilityReadingStoppedSignal( control ).Emit();
- } else
+ if(!DevelControl::AccessibilityReadingStoppedSignal(control).Empty())
+ DevelControl::AccessibilityReadingStoppedSignal(control).Emit();
+ }
+ else
{
ret = false;
}
* @return True if the signal was connected.
* @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
*/
-const char* SIGNAL_KEY_EVENT = "keyEvent";
+const char* SIGNAL_KEY_EVENT = "keyEvent";
const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "keyInputFocusGained";
-const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost";
-const char* SIGNAL_TAPPED = "tapped";
-const char* SIGNAL_PANNED = "panned";
-const char* SIGNAL_PINCHED = "pinched";
-const char* SIGNAL_LONG_PRESSED = "longPressed";
-const char* SIGNAL_GET_NAME = "getName";
-const char* SIGNAL_GET_DESCRIPTION = "getDescription";
-const char* SIGNAL_DO_GESTURE = "doGesture";
-static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
-{
- Dali::BaseHandle handle( object );
-
- bool connected( false );
- Toolkit::Control control = Toolkit::Control::DownCast( handle );
- if ( control )
- {
- Internal::Control& controlImpl( Internal::GetImplementation( control ) );
+const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost";
+const char* SIGNAL_TAPPED = "tapped";
+const char* SIGNAL_PANNED = "panned";
+const char* SIGNAL_PINCHED = "pinched";
+const char* SIGNAL_LONG_PRESSED = "longPressed";
+const char* SIGNAL_GET_NAME = "getName";
+const char* SIGNAL_GET_DESCRIPTION = "getDescription";
+const char* SIGNAL_DO_GESTURE = "doGesture";
+static bool DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
+{
+ Dali::BaseHandle handle(object);
+
+ bool connected(false);
+ Toolkit::Control control = Toolkit::Control::DownCast(handle);
+ if(control)
+ {
+ Internal::Control& controlImpl(Internal::GetImplementation(control));
connected = true;
- if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_KEY_EVENT))
{
- controlImpl.KeyEventSignal().Connect( tracker, functor );
+ controlImpl.KeyEventSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED))
{
- controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor );
+ controlImpl.KeyInputFocusGainedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST))
{
- controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor );
+ controlImpl.KeyInputFocusLostSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_TAPPED))
{
- controlImpl.EnableGestureDetection( GestureType::TAP );
- controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor );
+ controlImpl.EnableGestureDetection(GestureType::TAP);
+ controlImpl.GetTapGestureDetector().DetectedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_PANNED))
{
- controlImpl.EnableGestureDetection( GestureType::PAN );
- controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor );
+ controlImpl.EnableGestureDetection(GestureType::PAN);
+ controlImpl.GetPanGestureDetector().DetectedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_PINCHED))
{
- controlImpl.EnableGestureDetection( GestureType::PINCH );
- controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor );
+ controlImpl.EnableGestureDetection(GestureType::PINCH);
+ controlImpl.GetPinchGestureDetector().DetectedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_LONG_PRESSED))
{
- controlImpl.EnableGestureDetection( GestureType::LONG_PRESS );
- controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor );
+ controlImpl.EnableGestureDetection(GestureType::LONG_PRESS);
+ controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_GET_NAME ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_GET_NAME))
{
- DevelControl::AccessibilityGetNameSignal( control ).Connect( tracker, functor );
+ DevelControl::AccessibilityGetNameSignal(control).Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_GET_DESCRIPTION ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_GET_DESCRIPTION))
{
- DevelControl::AccessibilityGetDescriptionSignal( control ).Connect( tracker, functor );
+ DevelControl::AccessibilityGetDescriptionSignal(control).Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_DO_GESTURE ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_DO_GESTURE))
{
- DevelControl::AccessibilityDoGestureSignal( control ).Connect( tracker, functor );
+ DevelControl::AccessibilityDoGestureSignal(control).Connect(tracker, functor);
}
-
}
return connected;
}
return Internal::Control::New();
}
// Setup signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Control, CustomActor, Create );
+DALI_TYPE_REGISTRATION_BEGIN(Control, CustomActor, Create);
// Note: Properties are registered separately below.
-SignalConnectorType registerSignal1( typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal );
-SignalConnectorType registerSignal2( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal );
-SignalConnectorType registerSignal3( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal );
-SignalConnectorType registerSignal4( typeRegistration, SIGNAL_TAPPED, &DoConnectSignal );
-SignalConnectorType registerSignal5( typeRegistration, SIGNAL_PANNED, &DoConnectSignal );
-SignalConnectorType registerSignal6( typeRegistration, SIGNAL_PINCHED, &DoConnectSignal );
-SignalConnectorType registerSignal7( typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal );
-SignalConnectorType registerSignal8( typeRegistration, SIGNAL_GET_NAME, &DoConnectSignal );
-SignalConnectorType registerSignal9( typeRegistration, SIGNAL_GET_DESCRIPTION, &DoConnectSignal );
-SignalConnectorType registerSignal10( typeRegistration, SIGNAL_DO_GESTURE, &DoConnectSignal );
-
-TypeAction registerAction1( typeRegistration, "activate", &DoAction );
-TypeAction registerAction2( typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction );
-TypeAction registerAction3( typeRegistration, ACTION_ACCESSIBILITY_READING_SKIPPED, &DoAction );
-TypeAction registerAction4( typeRegistration, ACTION_ACCESSIBILITY_READING_CANCELLED, &DoAction );
-TypeAction registerAction5( typeRegistration, ACTION_ACCESSIBILITY_READING_STOPPED, &DoAction );
-TypeAction registerAction6( typeRegistration, ACTION_ACCESSIBILITY_READING_PAUSED, &DoAction );
-TypeAction registerAction7( typeRegistration, ACTION_ACCESSIBILITY_READING_RESUMED, &DoAction );
+SignalConnectorType registerSignal1(typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal);
+SignalConnectorType registerSignal2(typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal);
+SignalConnectorType registerSignal3(typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal);
+SignalConnectorType registerSignal4(typeRegistration, SIGNAL_TAPPED, &DoConnectSignal);
+SignalConnectorType registerSignal5(typeRegistration, SIGNAL_PANNED, &DoConnectSignal);
+SignalConnectorType registerSignal6(typeRegistration, SIGNAL_PINCHED, &DoConnectSignal);
+SignalConnectorType registerSignal7(typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal);
+SignalConnectorType registerSignal8(typeRegistration, SIGNAL_GET_NAME, &DoConnectSignal);
+SignalConnectorType registerSignal9(typeRegistration, SIGNAL_GET_DESCRIPTION, &DoConnectSignal);
+SignalConnectorType registerSignal10(typeRegistration, SIGNAL_DO_GESTURE, &DoConnectSignal);
+
+TypeAction registerAction1(typeRegistration, "activate", &DoAction);
+TypeAction registerAction2(typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction);
+TypeAction registerAction3(typeRegistration, ACTION_ACCESSIBILITY_READING_SKIPPED, &DoAction);
+TypeAction registerAction4(typeRegistration, ACTION_ACCESSIBILITY_READING_CANCELLED, &DoAction);
+TypeAction registerAction5(typeRegistration, ACTION_ACCESSIBILITY_READING_STOPPED, &DoAction);
+TypeAction registerAction6(typeRegistration, ACTION_ACCESSIBILITY_READING_PAUSED, &DoAction);
+TypeAction registerAction7(typeRegistration, ACTION_ACCESSIBILITY_READING_RESUMED, &DoAction);
DALI_TYPE_REGISTRATION_END()
* @param[in] container Container of visuals
* @param[in] parent Parent actor to remove visuals from
*/
-void SetVisualsOffScene( const RegisteredVisualContainer& container, Actor parent )
+void SetVisualsOffScene(const RegisteredVisualContainer& container, Actor parent)
{
- for( auto iter = container.Begin(), end = container.End() ; iter!= end; iter++)
+ for(auto iter = container.Begin(), end = container.End(); iter != end; iter++)
{
- if( (*iter)->visual )
+ if((*iter)->visual)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::SetOffScene Setting visual(%d) off stage\n", (*iter)->index );
- Toolkit::GetImplementation((*iter)->visual).SetOffScene( parent );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::SetOffScene Setting visual(%d) off stage\n", (*iter)->index);
+ Toolkit::GetImplementation((*iter)->visual).SetOffScene(parent);
}
}
}
} // unnamed namespace
-
+// clang-format off
// Properties registered without macro to use specific member variables.
-const PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "styleName", Toolkit::Control::Property::STYLE_NAME, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "keyInputFocus", Toolkit::Control::Property::KEY_INPUT_FOCUS, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_5( typeRegistration, "background", Toolkit::Control::Property::BACKGROUND, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_6( typeRegistration, "margin", Toolkit::Control::Property::MARGIN, Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_7( typeRegistration, "padding", Toolkit::Control::Property::PADDING, Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_8( typeRegistration, "tooltip", Toolkit::DevelControl::Property::TOOLTIP, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_9( typeRegistration, "state", Toolkit::DevelControl::Property::STATE, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_10( typeRegistration, "subState", Toolkit::DevelControl::Property::SUB_STATE, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_11( typeRegistration, "leftFocusableActorId", Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_12( typeRegistration, "rightFocusableActorId", Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID,Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_13( typeRegistration, "upFocusableActorId", Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_14( typeRegistration, "downFocusableActorId", Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_15( typeRegistration, "shadow", Toolkit::DevelControl::Property::SHADOW, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_16( typeRegistration, "accessibilityAttributes", Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_17( typeRegistration, "accessibilityName", Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_18( typeRegistration, "accessibilityDescription", Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_19( typeRegistration, "accessibilityTranslationDomain", Toolkit::DevelControl::Property::ACCESSIBILITY_TRANSLATION_DOMAIN, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_20( typeRegistration, "accessibilityRole", Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_21( typeRegistration, "accessibilityHighlightable", Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-const PropertyRegistration Control::Impl::PROPERTY_22( typeRegistration, "accessibilityAnimated", Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
-
-Control::Impl::Impl( Control& controlImpl )
-: mControlImpl( controlImpl ),
- mState( Toolkit::DevelControl::NORMAL ),
+const PropertyRegistration Control::Impl::PROPERTY_1(typeRegistration, "styleName", Toolkit::Control::Property::STYLE_NAME, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_4(typeRegistration, "keyInputFocus", Toolkit::Control::Property::KEY_INPUT_FOCUS, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_5(typeRegistration, "background", Toolkit::Control::Property::BACKGROUND, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_6(typeRegistration, "margin", Toolkit::Control::Property::MARGIN, Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_7(typeRegistration, "padding", Toolkit::Control::Property::PADDING, Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_8(typeRegistration, "tooltip", Toolkit::DevelControl::Property::TOOLTIP, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_9(typeRegistration, "state", Toolkit::DevelControl::Property::STATE, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_10(typeRegistration, "subState", Toolkit::DevelControl::Property::SUB_STATE, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_11(typeRegistration, "leftFocusableActorId", Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_12(typeRegistration, "rightFocusableActorId", Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_13(typeRegistration, "upFocusableActorId", Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_14(typeRegistration, "downFocusableActorId", Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_15(typeRegistration, "shadow", Toolkit::DevelControl::Property::SHADOW, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_16(typeRegistration, "accessibilityAttributes", Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_17(typeRegistration, "accessibilityName", Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_18(typeRegistration, "accessibilityDescription", Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_19(typeRegistration, "accessibilityTranslationDomain", Toolkit::DevelControl::Property::ACCESSIBILITY_TRANSLATION_DOMAIN, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_20(typeRegistration, "accessibilityRole", Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_21(typeRegistration, "accessibilityHighlightable", Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+const PropertyRegistration Control::Impl::PROPERTY_22(typeRegistration, "accessibilityAnimated", Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty);
+// clang-format on
+
+Control::Impl::Impl(Control& controlImpl)
+: mControlImpl(controlImpl),
+ mState(Toolkit::DevelControl::NORMAL),
mSubStateName(""),
- mLeftFocusableActorId( -1 ),
- mRightFocusableActorId( -1 ),
- mUpFocusableActorId( -1 ),
- mDownFocusableActorId( -1 ),
+ mLeftFocusableActorId(-1),
+ mRightFocusableActorId(-1),
+ mUpFocusableActorId(-1),
+ mDownFocusableActorId(-1),
mStyleName(""),
mBackgroundColor(Color::TRANSPARENT),
mStartingPinchScale(nullptr),
- mMargin( 0, 0, 0, 0 ),
- mPadding( 0, 0, 0, 0 ),
+ mMargin(0, 0, 0, 0),
+ mPadding(0, 0, 0, 0),
mKeyEventSignal(),
mKeyInputFocusGainedSignal(),
mKeyInputFocusLostSignal(),
mPanGestureDetector(),
mTapGestureDetector(),
mLongPressGestureDetector(),
- mTooltip( NULL ),
+ mTooltip(NULL),
mInputMethodContext(),
mIdleCallback(nullptr),
- mFlags( Control::ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mIsKeyboardNavigationSupported( false ),
- mIsKeyboardFocusGroup( false ),
+ mFlags(Control::ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mIsKeyboardNavigationSupported(false),
+ mIsKeyboardFocusGroup(false),
mIsEmittingResourceReadySignal(false),
mNeedToEmitResourceReady(false)
{
Dali::Accessibility::Accessible::RegisterControlAccessibilityGetter(
- []( Dali::Actor actor ) -> Dali::Accessibility::Accessible* {
- return Control::Impl::GetAccessibilityObject( actor );
- } );
+ [](Dali::Actor actor) -> Dali::Accessibility::Accessible* {
+ return Control::Impl::GetAccessibilityObject(actor);
+ });
- accessibilityConstructor = []( Dali::Actor actor ) -> std::unique_ptr< Dali::Accessibility::Accessible > {
- return std::unique_ptr< Dali::Accessibility::Accessible >( new AccessibleImpl( actor,
- Dali::Accessibility::Role::UNKNOWN ) );
- };
+ accessibilityConstructor = [](Dali::Actor actor) -> std::unique_ptr<Dali::Accessibility::Accessible> {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(new AccessibleImpl(actor,
+ Dali::Accessibility::Role::UNKNOWN));
+ };
size_t len = static_cast<size_t>(Dali::Accessibility::RelationType::MAX_COUNT);
mAccessibilityRelations.reserve(len);
- for (auto i = 0u; i < len; ++i)
+ for(auto i = 0u; i < len; ++i)
{
mAccessibilityRelations.push_back({});
}
Control::Impl::~Impl()
{
- for( auto&& iter : mVisuals )
+ for(auto&& iter : mVisuals)
{
- StopObservingVisual( iter->visual );
+ StopObservingVisual(iter->visual);
}
- for( auto&& iter : mRemoveVisuals )
+ for(auto&& iter : mRemoveVisuals)
{
- StopObservingVisual( iter->visual );
+ StopObservingVisual(iter->visual);
}
AccessibilityDeregister();
}
}
-Control::Impl& Control::Impl::Get( Internal::Control& internalControl )
+Control::Impl& Control::Impl::Get(Internal::Control& internalControl)
{
return *internalControl.mImpl;
}
-const Control::Impl& Control::Impl::Get( const Internal::Control& internalControl )
+const Control::Impl& Control::Impl::Get(const Internal::Control& internalControl)
{
return *internalControl.mImpl;
}
mControlImpl.OnLongPress(longPress);
}
-void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual )
+void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual)
{
- RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::NOT_SET );
+ RegisterVisual(index, visual, VisualState::ENABLED, DepthIndexValue::NOT_SET);
}
-void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, int depthIndex )
+void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual, int depthIndex)
{
- RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::SET, depthIndex );
+ RegisterVisual(index, visual, VisualState::ENABLED, DepthIndexValue::SET, depthIndex);
}
-void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled )
+void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual, bool enabled)
{
- RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::NOT_SET );
+ RegisterVisual(index, visual, (enabled ? VisualState::ENABLED : VisualState::DISABLED), DepthIndexValue::NOT_SET);
}
-void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled, int depthIndex )
+void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual, bool enabled, int depthIndex)
{
- RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::SET, depthIndex );
+ RegisterVisual(index, visual, (enabled ? VisualState::ENABLED : VisualState::DISABLED), DepthIndexValue::SET, depthIndex);
}
-void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, VisualState::Type enabled, DepthIndexValue::Type depthIndexValueSet, int depthIndex )
+void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual, VisualState::Type enabled, DepthIndexValue::Type depthIndexValueSet, int depthIndex)
{
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "RegisterVisual:%d \n", index );
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "RegisterVisual:%d \n", index);
- bool visualReplaced ( false );
+ bool visualReplaced(false);
Actor self = mControlImpl.Self();
// Set the depth index, if not set by caller this will be either the current visual depth, max depth of all visuals
// or zero.
int requiredDepthIndex = visual.GetDepthIndex();
- if( depthIndexValueSet == DepthIndexValue::SET )
+ if(depthIndexValueSet == DepthIndexValue::SET)
{
requiredDepthIndex = depthIndex;
}
// Visual replacement, existing visual should only be removed from stage when replacement ready.
- if( !mVisuals.Empty() )
+ if(!mVisuals.Empty())
{
RegisteredVisualContainer::Iterator registeredVisualsiter;
// Check if visual (index) is already registered, this is the current visual.
- if( FindVisual( index, mVisuals, registeredVisualsiter ) )
+ if(FindVisual(index, mVisuals, registeredVisualsiter))
{
Toolkit::Visual::Base& currentRegisteredVisual = (*registeredVisualsiter)->visual;
- if( currentRegisteredVisual )
+ if(currentRegisteredVisual)
{
// Store current visual depth index as may need to set the replacement visual to same depth
const int currentDepthIndex = (*registeredVisualsiter)->visual.GetDepthIndex();
// No longer required to know if the replaced visual's resources are ready
- StopObservingVisual( currentRegisteredVisual );
+ StopObservingVisual(currentRegisteredVisual);
// If control staged and visual enabled then visuals will be swapped once ready
- if( self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) && enabled )
+ if(self.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE) && enabled)
{
// Check if visual is currently in the process of being replaced ( is in removal container )
RegisteredVisualContainer::Iterator visualQueuedForRemoval;
- if ( FindVisual( index, mRemoveVisuals, visualQueuedForRemoval ) )
+ if(FindVisual(index, mRemoveVisuals, visualQueuedForRemoval))
{
// Visual with same index is already in removal container so current visual pending
// Only the the last requested visual will be displayed so remove current visual which is staged but not ready.
- Toolkit::GetImplementation( currentRegisteredVisual ).SetOffScene( self );
- mVisuals.Erase( registeredVisualsiter );
+ Toolkit::GetImplementation(currentRegisteredVisual).SetOffScene(self);
+ mVisuals.Erase(registeredVisualsiter);
}
else
{
// current visual not already in removal container so add now.
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "RegisterVisual Move current registered visual to removal Queue: %d \n", index );
- MoveVisual( registeredVisualsiter, mVisuals, mRemoveVisuals );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "RegisterVisual Move current registered visual to removal Queue: %d \n", index);
+ MoveVisual(registeredVisualsiter, mVisuals, mRemoveVisuals);
}
}
else
{
// Control not staged or visual disabled so can just erase from registered visuals and new visual will be added later.
- mVisuals.Erase( registeredVisualsiter );
+ mVisuals.Erase(registeredVisualsiter);
}
// If we've not set the depth-index value and the new visual does not have a depth index applied to it, then use the previously set depth-index for this index
- if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
- ( visual.GetDepthIndex() == 0 ) )
+ if((depthIndexValueSet == DepthIndexValue::NOT_SET) &&
+ (visual.GetDepthIndex() == 0))
{
requiredDepthIndex = currentDepthIndex;
}
// If not set, set the name of the visual to the same name as the control's property.
// ( If the control has been type registered )
- if( visual.GetName().empty() )
+ if(visual.GetName().empty())
{
// returns empty string if index is not found as long as index is not -1
- std::string visualName = self.GetPropertyName( index );
- if( !visualName.empty() )
+ std::string visualName = self.GetPropertyName(index);
+ if(!visualName.empty())
{
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n",
- index, visualName.c_str() );
- visual.SetName( visualName );
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n", index, visualName.c_str());
+ visual.SetName(visualName);
}
}
- if( !visualReplaced ) // New registration entry
+ if(!visualReplaced) // New registration entry
{
// If we've not set the depth-index value, we have more than one visual and the visual does not have a depth index, then set it to be the highest
- if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
- ( mVisuals.Size() > 0 ) &&
- ( visual.GetDepthIndex() == 0 ) )
+ if((depthIndexValueSet == DepthIndexValue::NOT_SET) &&
+ (mVisuals.Size() > 0) &&
+ (visual.GetDepthIndex() == 0))
{
- int maxDepthIndex = std::numeric_limits< int >::min();
+ int maxDepthIndex = std::numeric_limits<int>::min();
- RegisteredVisualContainer::ConstIterator iter;
+ RegisteredVisualContainer::ConstIterator iter;
const RegisteredVisualContainer::ConstIterator endIter = mVisuals.End();
- for ( iter = mVisuals.Begin(); iter != endIter; iter++ )
+ for(iter = mVisuals.Begin(); iter != endIter; iter++)
{
const int visualDepthIndex = (*iter)->visual.GetDepthIndex();
- if ( visualDepthIndex > maxDepthIndex )
+ if(visualDepthIndex > maxDepthIndex)
{
maxDepthIndex = visualDepthIndex;
}
}
- ++maxDepthIndex; // Add one to the current maximum depth index so that our added visual appears on top
- requiredDepthIndex = std::max( 0, maxDepthIndex ); // Start at zero if maxDepth index belongs to a background
+ ++maxDepthIndex; // Add one to the current maximum depth index so that our added visual appears on top
+ requiredDepthIndex = std::max(0, maxDepthIndex); // Start at zero if maxDepth index belongs to a background
}
}
- if( visual )
+ if(visual)
{
// Set determined depth index
- visual.SetDepthIndex( requiredDepthIndex );
+ visual.SetDepthIndex(requiredDepthIndex);
// Monitor when the visual resources are ready
- StartObservingVisual( visual );
+ StartObservingVisual(visual);
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "New Visual registration index[%d] depth[%d]\n", index, requiredDepthIndex );
- RegisteredVisual* newRegisteredVisual = new RegisteredVisual( index, visual,
- ( enabled == VisualState::ENABLED ? true : false ),
- ( visualReplaced && enabled ) ) ;
- mVisuals.PushBack( newRegisteredVisual );
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "New Visual registration index[%d] depth[%d]\n", index, requiredDepthIndex);
+ RegisteredVisual* newRegisteredVisual = new RegisteredVisual(index, visual, (enabled == VisualState::ENABLED ? true : false), (visualReplaced && enabled));
+ mVisuals.PushBack(newRegisteredVisual);
- Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
+ Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
// Put on stage if enabled and the control is already on the stage
- if( ( enabled == VisualState::ENABLED ) && self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if((enabled == VisualState::ENABLED) && self.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
- visualImpl.SetOnScene( self );
+ visualImpl.SetOnScene(self);
}
- else if( visualImpl.IsResourceReady() ) // When not being staged, check if visual already 'ResourceReady' before it was Registered. ( Resource may have been loaded already )
+ else if(visualImpl.IsResourceReady()) // When not being staged, check if visual already 'ResourceReady' before it was Registered. ( Resource may have been loaded already )
{
- ResourceReady( visualImpl );
+ ResourceReady(visualImpl);
}
-
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n", visual.GetName().c_str(), index, enabled?"true":"false" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n", visual.GetName().c_str(), index, enabled ? "true" : "false");
}
-void Control::Impl::UnregisterVisual( Property::Index index )
+void Control::Impl::UnregisterVisual(Property::Index index)
{
RegisteredVisualContainer::Iterator iter;
- if ( FindVisual( index, mVisuals, iter ) )
+ if(FindVisual(index, mVisuals, iter))
{
// stop observing visual
- StopObservingVisual( (*iter)->visual );
+ StopObservingVisual((*iter)->visual);
- Actor self( mControlImpl.Self() );
- Toolkit::GetImplementation((*iter)->visual).SetOffScene( self );
+ Actor self(mControlImpl.Self());
+ Toolkit::GetImplementation((*iter)->visual).SetOffScene(self);
(*iter)->visual.Reset();
- mVisuals.Erase( iter );
+ mVisuals.Erase(iter);
}
- if( FindVisual( index, mRemoveVisuals, iter ) )
+ if(FindVisual(index, mRemoveVisuals, iter))
{
- Actor self( mControlImpl.Self() );
- Toolkit::GetImplementation( (*iter)->visual ).SetOffScene( self );
+ Actor self(mControlImpl.Self());
+ Toolkit::GetImplementation((*iter)->visual).SetOffScene(self);
(*iter)->pending = false;
(*iter)->visual.Reset();
- mRemoveVisuals.Erase( iter );
+ mRemoveVisuals.Erase(iter);
}
}
-Toolkit::Visual::Base Control::Impl::GetVisual( Property::Index index ) const
+Toolkit::Visual::Base Control::Impl::GetVisual(Property::Index index) const
{
RegisteredVisualContainer::Iterator iter;
- if ( FindVisual( index, mVisuals, iter ) )
+ if(FindVisual(index, mVisuals, iter))
{
return (*iter)->visual;
}
return Toolkit::Visual::Base();
}
-void Control::Impl::EnableVisual( Property::Index index, bool enable )
+void Control::Impl::EnableVisual(Property::Index index, bool enable)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Control::EnableVisual(%d, %s)\n", index, enable?"T":"F");
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Control::EnableVisual(%d, %s)\n", index, enable ? "T" : "F");
RegisteredVisualContainer::Iterator iter;
- if ( FindVisual( index, mVisuals, iter ) )
+ if(FindVisual(index, mVisuals, iter))
{
- if ( (*iter)->enabled == enable )
+ if((*iter)->enabled == enable)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable?"enabled":"disabled");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable ? "enabled" : "disabled");
return;
}
- (*iter)->enabled = enable;
+ (*iter)->enabled = enable;
Actor parentActor = mControlImpl.Self();
- if ( mControlImpl.Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) // If control not on Scene then Visual will be added when SceneConnection is called.
+ if(mControlImpl.Self().GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE)) // If control not on Scene then Visual will be added when SceneConnection is called.
{
- if ( enable )
+ if(enable)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index );
- Toolkit::GetImplementation((*iter)->visual).SetOnScene( parentActor );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index);
+ Toolkit::GetImplementation((*iter)->visual).SetOnScene(parentActor);
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index );
- Toolkit::GetImplementation((*iter)->visual).SetOffScene( parentActor ); // No need to call if control not staged.
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index);
+ Toolkit::GetImplementation((*iter)->visual).SetOffScene(parentActor); // No need to call if control not staged.
}
}
}
else
{
- DALI_LOG_WARNING( "Control::EnableVisual(%d, %s) FAILED - NO SUCH VISUAL\n", index, enable?"T":"F" );
+ DALI_LOG_WARNING("Control::EnableVisual(%d, %s) FAILED - NO SUCH VISUAL\n", index, enable ? "T" : "F");
}
}
-bool Control::Impl::IsVisualEnabled( Property::Index index ) const
+bool Control::Impl::IsVisualEnabled(Property::Index index) const
{
RegisteredVisualContainer::Iterator iter;
- if ( FindVisual( index, mVisuals, iter ) )
+ if(FindVisual(index, mVisuals, iter))
{
return (*iter)->enabled;
}
return false;
}
-void Control::Impl::StopObservingVisual( Toolkit::Visual::Base& visual )
+void Control::Impl::StopObservingVisual(Toolkit::Visual::Base& visual)
{
- Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
+ Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
// Stop observing the visual
- visualImpl.RemoveEventObserver( *this );
+ visualImpl.RemoveEventObserver(*this);
}
-void Control::Impl::StartObservingVisual( Toolkit::Visual::Base& visual)
+void Control::Impl::StartObservingVisual(Toolkit::Visual::Base& visual)
{
- Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
+ Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
// start observing the visual for events
- visualImpl.AddEventObserver( *this );
+ visualImpl.AddEventObserver(*this);
}
// Called by a Visual when it's resource is ready
-void Control::Impl::ResourceReady( Visual::Base& object)
+void Control::Impl::ResourceReady(Visual::Base& object)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::Impl::ResourceReady() replacements pending[%d]\n", mRemoveVisuals.Count() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::Impl::ResourceReady() replacements pending[%d]\n", mRemoveVisuals.Count());
Actor self = mControlImpl.Self();
// A resource is ready, find resource in the registered visuals container and get its index
- for( auto registeredIter = mVisuals.Begin(), end = mVisuals.End(); registeredIter != end; ++registeredIter )
+ for(auto registeredIter = mVisuals.Begin(), end = mVisuals.End(); registeredIter != end; ++registeredIter)
{
- Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation( (*registeredIter)->visual );
+ Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation((*registeredIter)->visual);
- if( &object == ®isteredVisualImpl )
+ if(&object == ®isteredVisualImpl)
{
RegisteredVisualContainer::Iterator visualToRemoveIter;
// Find visual with the same index in the removal container
// Set if off stage as it's replacement is now ready.
// Remove if from removal list as now removed from stage.
// Set Pending flag on the ready visual to false as now ready.
- if( FindVisual( (*registeredIter)->index, mRemoveVisuals, visualToRemoveIter ) )
+ if(FindVisual((*registeredIter)->index, mRemoveVisuals, visualToRemoveIter))
{
(*registeredIter)->pending = false;
- Toolkit::GetImplementation( (*visualToRemoveIter)->visual ).SetOffScene( self );
- mRemoveVisuals.Erase( visualToRemoveIter );
+ Toolkit::GetImplementation((*visualToRemoveIter)->visual).SetOffScene(self);
+ mRemoveVisuals.Erase(visualToRemoveIter);
}
break;
}
}
// A visual is ready so control may need relayouting if staged
- if ( self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if(self.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
mControlImpl.RelayoutRequest();
}
// Emit signal if all enabled visuals registered by the control are ready.
- if( IsResourceReady() )
+ if(IsResourceReady())
{
// Reset the flag
mNeedToEmitResourceReady = false;
}
}
-void Control::Impl::NotifyVisualEvent( Visual::Base& object, Property::Index signalId )
+void Control::Impl::NotifyVisualEvent(Visual::Base& object, Property::Index signalId)
{
- for( auto registeredIter = mVisuals.Begin(), end = mVisuals.End(); registeredIter != end; ++registeredIter )
+ for(auto registeredIter = mVisuals.Begin(), end = mVisuals.End(); registeredIter != end; ++registeredIter)
{
- Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation( (*registeredIter)->visual );
- if( &object == ®isteredVisualImpl )
+ Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation((*registeredIter)->visual);
+ if(&object == ®isteredVisualImpl)
{
- Dali::Toolkit::Control handle( mControlImpl.GetOwner() );
- mVisualEventSignal.Emit( handle, (*registeredIter)->index, signalId );
+ Dali::Toolkit::Control handle(mControlImpl.GetOwner());
+ mVisualEventSignal.Emit(handle, (*registeredIter)->index, signalId);
break;
}
}
bool Control::Impl::IsResourceReady() const
{
// Iterate through and check all the enabled visuals are ready
- for( auto visualIter = mVisuals.Begin();
- visualIter != mVisuals.End(); ++visualIter )
+ for(auto visualIter = mVisuals.Begin();
+ visualIter != mVisuals.End();
+ ++visualIter)
{
- const Toolkit::Visual::Base visual = (*visualIter)->visual;
- const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
+ const Toolkit::Visual::Base visual = (*visualIter)->visual;
+ const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
// one of the enabled visuals is not ready
- if( !visualImpl.IsResourceReady() && (*visualIter)->enabled )
+ if(!visualImpl.IsResourceReady() && (*visualIter)->enabled)
{
return false;
}
return true;
}
-Toolkit::Visual::ResourceStatus Control::Impl::GetVisualResourceStatus( Property::Index index ) const
+Toolkit::Visual::ResourceStatus Control::Impl::GetVisualResourceStatus(Property::Index index) const
{
RegisteredVisualContainer::Iterator iter;
- if ( FindVisual( index, mVisuals, iter ) )
+ if(FindVisual(index, mVisuals, iter))
{
- const Toolkit::Visual::Base visual = (*iter)->visual;
- const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
- return visualImpl.GetResourceStatus( );
+ const Toolkit::Visual::Base visual = (*iter)->visual;
+ const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
+ return visualImpl.GetResourceStatus();
}
return Toolkit::Visual::ResourceStatus::PREPARING;
}
-
-
-void Control::Impl::AddTransitions( Dali::Animation& animation,
- const Toolkit::TransitionData& handle,
- bool createAnimation )
+void Control::Impl::AddTransitions(Dali::Animation& animation,
+ const Toolkit::TransitionData& handle,
+ bool createAnimation)
{
// Setup a Transition from TransitionData.
- const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle );
- TransitionData::Iterator end = transitionData.End();
- for( TransitionData::Iterator iter = transitionData.Begin() ;
- iter != end; ++iter )
+ const Internal::TransitionData& transitionData = Toolkit::GetImplementation(handle);
+ TransitionData::Iterator end = transitionData.End();
+ for(TransitionData::Iterator iter = transitionData.Begin();
+ iter != end;
+ ++iter)
{
TransitionData::Animator* animator = (*iter);
- Toolkit::Visual::Base visual = GetVisualByName( mVisuals, animator->objectName );
+ Toolkit::Visual::Base visual = GetVisualByName(mVisuals, animator->objectName);
- if( visual )
+ if(visual)
{
#if defined(DEBUG_ENABLED)
- Dali::TypeInfo typeInfo;
+ Dali::TypeInfo typeInfo;
ControlWrapper* controlWrapperImpl = dynamic_cast<ControlWrapper*>(&mControlImpl);
- if( controlWrapperImpl )
+ if(controlWrapperImpl)
{
typeInfo = controlWrapperImpl->GetTypeInfo();
}
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n",
- visual.GetName().c_str(), typeInfo?typeInfo.GetName().c_str():"Unknown" );
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n", visual.GetName().c_str(), typeInfo ? typeInfo.GetName().c_str() : "Unknown");
#endif
- Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
- visualImpl.AnimateProperty( animation, *animator );
+ Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
+ visualImpl.AnimateProperty(animation, *animator);
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors");
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors");
// Otherwise, try any actor children of control (Including the control)
- Actor child = mControlImpl.Self().FindChildByName( animator->objectName );
- if( child )
+ Actor child = mControlImpl.Self().FindChildByName(animator->objectName);
+ if(child)
{
- Property::Index propertyIndex = child.GetPropertyIndex( animator->propertyKey );
- if( propertyIndex != Property::INVALID_INDEX )
+ Property::Index propertyIndex = child.GetPropertyIndex(animator->propertyKey);
+ if(propertyIndex != Property::INVALID_INDEX)
{
- if( animator->animate == false )
+ if(animator->animate == false)
{
- if( animator->targetValue.GetType() != Property::NONE )
+ if(animator->targetValue.GetType() != Property::NONE)
{
- child.SetProperty( propertyIndex, animator->targetValue );
+ child.SetProperty(propertyIndex, animator->targetValue);
}
}
else // animate the property
{
- if( animator->initialValue.GetType() != Property::NONE )
+ if(animator->initialValue.GetType() != Property::NONE)
{
- child.SetProperty( propertyIndex, animator->initialValue );
+ child.SetProperty(propertyIndex, animator->initialValue);
}
- if( createAnimation && !animation )
+ if(createAnimation && !animation)
{
- animation = Dali::Animation::New( 0.1f );
+ animation = Dali::Animation::New(0.1f);
}
- animation.AnimateTo( Property( child, propertyIndex ),
- animator->targetValue,
- animator->alphaFunction,
- TimePeriod( animator->timePeriodDelay,
- animator->timePeriodDuration ) );
+ animation.AnimateTo(Property(child, propertyIndex),
+ animator->targetValue,
+ animator->alphaFunction,
+ TimePeriod(animator->timePeriodDelay,
+ animator->timePeriodDuration));
}
}
}
}
}
-Dali::Animation Control::Impl::CreateTransition( const Toolkit::TransitionData& transitionData )
+Dali::Animation Control::Impl::CreateTransition(const Toolkit::TransitionData& transitionData)
{
Dali::Animation transition;
- if( transitionData.Count() > 0 )
+ if(transitionData.Count() > 0)
{
- AddTransitions( transition, transitionData, true );
+ AddTransitions(transition, transitionData, true);
}
return transition;
}
-
-
-void Control::Impl::DoAction( Dali::Property::Index visualIndex, Dali::Property::Index actionId, const Dali::Property::Value attributes )
+void Control::Impl::DoAction(Dali::Property::Index visualIndex, Dali::Property::Index actionId, const Dali::Property::Value attributes)
{
RegisteredVisualContainer::Iterator iter;
- if ( FindVisual( visualIndex, mVisuals, iter ) )
+ if(FindVisual(visualIndex, mVisuals, iter))
{
- Toolkit::GetImplementation((*iter)->visual).DoAction( actionId, attributes );
+ Toolkit::GetImplementation((*iter)->visual).DoAction(actionId, attributes);
}
}
-void Control::Impl::AppendAccessibilityAttribute( const std::string& key,
- const std::string value )
+void Control::Impl::AppendAccessibilityAttribute(const std::string& key,
+ const std::string value)
{
- Property::Value* val = mAccessibilityAttributes.Find( key );
- if( val )
+ Property::Value* val = mAccessibilityAttributes.Find(key);
+ if(val)
{
- mAccessibilityAttributes[key] = Property::Value( value );
+ mAccessibilityAttributes[key] = Property::Value(value);
}
else
{
- mAccessibilityAttributes.Insert( key, value );
+ mAccessibilityAttributes.Insert(key, value);
}
}
-void Control::Impl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void Control::Impl::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
+ Toolkit::Control control = Toolkit::Control::DownCast(BaseHandle(object));
- if ( control )
+ if(control)
{
- Control& controlImpl( GetImplementation( control ) );
+ Control& controlImpl(GetImplementation(control));
- switch ( index )
+ switch(index)
{
case Toolkit::Control::Property::STYLE_NAME:
{
- controlImpl.SetStyleName( value.Get< std::string >() );
+ controlImpl.SetStyleName(value.Get<std::string>());
break;
}
case Toolkit::DevelControl::Property::STATE:
{
- bool withTransitions=true;
- const Property::Value* valuePtr=&value;
- const Property::Map* map = value.GetMap();
+ bool withTransitions = true;
+ const Property::Value* valuePtr = &value;
+ const Property::Map* map = value.GetMap();
if(map)
{
Property::Value* value2 = map->Find("withTransitions");
- if( value2 )
+ if(value2)
{
withTransitions = value2->Get<bool>();
}
valuePtr = map->Find("state");
}
- if( valuePtr )
+ if(valuePtr)
{
- Toolkit::DevelControl::State state( controlImpl.mImpl->mState );
- if( Scripting::GetEnumerationProperty< Toolkit::DevelControl::State >( *valuePtr, ControlStateTable, ControlStateTableCount, state ) )
+ Toolkit::DevelControl::State state(controlImpl.mImpl->mState);
+ if(Scripting::GetEnumerationProperty<Toolkit::DevelControl::State>(*valuePtr, ControlStateTable, ControlStateTableCount, state))
{
- controlImpl.mImpl->SetState( state, withTransitions );
+ controlImpl.mImpl->SetState(state, withTransitions);
}
}
}
case Toolkit::DevelControl::Property::SUB_STATE:
{
std::string subState;
- if( value.Get( subState ) )
+ if(value.Get(subState))
{
- controlImpl.mImpl->SetSubState( subState );
+ controlImpl.mImpl->SetSubState(subState);
}
}
break;
case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
{
int focusId;
- if( value.Get( focusId ) )
+ if(value.Get(focusId))
{
controlImpl.mImpl->mLeftFocusableActorId = focusId;
}
case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
{
int focusId;
- if( value.Get( focusId ) )
+ if(value.Get(focusId))
{
controlImpl.mImpl->mRightFocusableActorId = focusId;
}
case Toolkit::DevelControl::Property::ACCESSIBILITY_NAME:
{
std::string name;
- if( value.Get( name ) )
+ if(value.Get(name))
{
- controlImpl.mImpl->mAccessibilityName = name;
+ controlImpl.mImpl->mAccessibilityName = name;
controlImpl.mImpl->mAccessibilityNameSet = true;
}
else
case Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION:
{
std::string txt;
- if( value.Get( txt ) )
+ if(value.Get(txt))
{
- controlImpl.mImpl->mAccessibilityDescription = txt;
+ controlImpl.mImpl->mAccessibilityDescription = txt;
controlImpl.mImpl->mAccessibilityDescriptionSet = true;
}
else
case Toolkit::DevelControl::Property::ACCESSIBILITY_TRANSLATION_DOMAIN:
{
std::string txt;
- if( value.Get( txt ) )
+ if(value.Get(txt))
{
- controlImpl.mImpl->mAccessibilityTranslationDomain = txt;
+ controlImpl.mImpl->mAccessibilityTranslationDomain = txt;
controlImpl.mImpl->mAccessibilityTranslationDomainSet = true;
}
else
case Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE:
{
bool highlightable;
- if( value.Get( highlightable ) )
+ if(value.Get(highlightable))
{
- controlImpl.mImpl->mAccessibilityHighlightable = highlightable;
+ controlImpl.mImpl->mAccessibilityHighlightable = highlightable;
controlImpl.mImpl->mAccessibilityHighlightableSet = true;
}
else
case Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE:
{
Dali::Accessibility::Role val;
- if( value.Get( val ) )
+ if(value.Get(val))
{
controlImpl.mImpl->mAccessibilityRole = val;
}
case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
{
int focusId;
- if( value.Get( focusId ) )
+ if(value.Get(focusId))
{
controlImpl.mImpl->mUpFocusableActorId = focusId;
}
case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
{
int focusId;
- if( value.Get( focusId ) )
+ if(value.Get(focusId))
{
controlImpl.mImpl->mDownFocusableActorId = focusId;
}
case Toolkit::Control::Property::KEY_INPUT_FOCUS:
{
- if ( value.Get< bool >() )
+ if(value.Get<bool>())
{
controlImpl.SetKeyInputFocus();
}
case Toolkit::Control::Property::BACKGROUND:
{
- std::string url;
- Vector4 color;
+ std::string url;
+ Vector4 color;
const Property::Map* map = value.GetMap();
- if( map && !map->Empty() )
+ if(map && !map->Empty())
{
- controlImpl.SetBackground( *map );
+ controlImpl.SetBackground(*map);
}
- else if( value.Get( url ) )
+ else if(value.Get(url))
{
// don't know the size to load
- Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() );
- if( visual )
+ Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(url, ImageDimensions());
+ if(visual)
{
- controlImpl.mImpl->RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND );
+ controlImpl.mImpl->RegisterVisual(Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND);
}
}
- else if( value.Get( color ) )
+ else if(value.Get(color))
{
controlImpl.SetBackgroundColor(color);
}
case Toolkit::Control::Property::MARGIN:
{
Extents margin;
- if( value.Get( margin ) )
+ if(value.Get(margin))
{
- controlImpl.mImpl->SetMargin( margin );
+ controlImpl.mImpl->SetMargin(margin);
}
break;
}
case Toolkit::Control::Property::PADDING:
{
Extents padding;
- if( value.Get( padding ) )
+ if(value.Get(padding))
{
- controlImpl.mImpl->SetPadding( padding );
+ controlImpl.mImpl->SetPadding(padding);
}
break;
}
case Toolkit::DevelControl::Property::TOOLTIP:
{
TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip;
- if( ! tooltipPtr )
+ if(!tooltipPtr)
{
- tooltipPtr = Tooltip::New( control );
+ tooltipPtr = Tooltip::New(control);
}
- tooltipPtr->SetProperties( value );
+ tooltipPtr->SetProperties(value);
break;
}
case Toolkit::DevelControl::Property::SHADOW:
{
const Property::Map* map = value.GetMap();
- if( map && !map->Empty() )
+ if(map && !map->Empty())
{
- controlImpl.mImpl->SetShadow( *map );
+ controlImpl.mImpl->SetShadow(*map);
}
else
{
case Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES:
{
const Property::Map* map = value.GetMap();
- if( map && !map->Empty() )
+ if(map && !map->Empty())
{
controlImpl.mImpl->mAccessibilityAttributes = *map;
}
case Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED:
{
bool animated;
- if( value.Get( animated ) )
+ if(value.Get(animated))
{
controlImpl.mImpl->mAccessibilityAnimated = animated;
}
}
}
-Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index index )
+Property::Value Control::Impl::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
+ Toolkit::Control control = Toolkit::Control::DownCast(BaseHandle(object));
- if ( control )
+ if(control)
{
- Control& controlImpl( GetImplementation( control ) );
+ Control& controlImpl(GetImplementation(control));
- switch ( index )
+ switch(index)
{
case Toolkit::Control::Property::STYLE_NAME:
{
case Toolkit::DevelControl::Property::ACCESSIBILITY_NAME:
{
- if (controlImpl.mImpl->mAccessibilityNameSet)
+ if(controlImpl.mImpl->mAccessibilityNameSet)
{
value = controlImpl.mImpl->mAccessibilityName;
}
case Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION:
{
- if (controlImpl.mImpl->mAccessibilityDescriptionSet)
+ if(controlImpl.mImpl->mAccessibilityDescriptionSet)
{
value = controlImpl.mImpl->mAccessibilityDescription;
}
case Toolkit::DevelControl::Property::ACCESSIBILITY_TRANSLATION_DOMAIN:
{
- if (controlImpl.mImpl->mAccessibilityTranslationDomainSet)
+ if(controlImpl.mImpl->mAccessibilityTranslationDomainSet)
{
value = controlImpl.mImpl->mAccessibilityTranslationDomain;
}
case Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE:
{
- if (controlImpl.mImpl->mAccessibilityHighlightableSet)
+ if(controlImpl.mImpl->mAccessibilityHighlightableSet)
{
value = controlImpl.mImpl->mAccessibilityHighlightable;
}
case Toolkit::Control::Property::BACKGROUND:
{
- Property::Map map;
- Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
- if( visual )
+ Property::Map map;
+ Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual(Toolkit::Control::Property::BACKGROUND);
+ if(visual)
{
- visual.CreatePropertyMap( map );
+ visual.CreatePropertyMap(map);
}
value = map;
case Toolkit::DevelControl::Property::TOOLTIP:
{
Property::Map map;
- if( controlImpl.mImpl->mTooltip )
+ if(controlImpl.mImpl->mTooltip)
{
- controlImpl.mImpl->mTooltip->CreatePropertyMap( map );
+ controlImpl.mImpl->mTooltip->CreatePropertyMap(map);
}
value = map;
break;
case Toolkit::DevelControl::Property::SHADOW:
{
- Property::Map map;
- Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::DevelControl::Property::SHADOW );
- if( visual )
+ Property::Map map;
+ Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual(Toolkit::DevelControl::Property::SHADOW);
+ if(visual)
{
- visual.CreatePropertyMap( map );
+ visual.CreatePropertyMap(map);
}
value = map;
return value;
}
-void Control::Impl::RemoveAccessibilityAttribute( const std::string& key )
+void Control::Impl::RemoveAccessibilityAttribute(const std::string& key)
{
- Property::Value* val = mAccessibilityAttributes.Find( key );
- if( val )
+ Property::Value* val = mAccessibilityAttributes.Find(key);
+ if(val)
mAccessibilityAttributes[key] = Property::Value();
}
mAccessibilityAttributes.Clear();
}
-void Control::Impl::SetAccessibilityReadingInfoType( const Dali::Accessibility::ReadingInfoTypes types )
+void Control::Impl::SetAccessibilityReadingInfoType(const Dali::Accessibility::ReadingInfoTypes types)
{
std::string value;
- if ( types[ Dali::Accessibility::ReadingInfoType::NAME ] )
+ if(types[Dali::Accessibility::ReadingInfoType::NAME])
{
value += READING_INFO_TYPE_NAME;
}
- if ( types[ Dali::Accessibility::ReadingInfoType::ROLE ] )
+ if(types[Dali::Accessibility::ReadingInfoType::ROLE])
{
- if( !value.empty() )
+ if(!value.empty())
{
value += READING_INFO_TYPE_SEPARATOR;
}
value += READING_INFO_TYPE_ROLE;
}
- if ( types[ Dali::Accessibility::ReadingInfoType::DESCRIPTION ] )
+ if(types[Dali::Accessibility::ReadingInfoType::DESCRIPTION])
{
- if( !value.empty() )
+ if(!value.empty())
{
value += READING_INFO_TYPE_SEPARATOR;
}
value += READING_INFO_TYPE_DESCRIPTION;
}
- if ( types[ Dali::Accessibility::ReadingInfoType::STATE ] )
+ if(types[Dali::Accessibility::ReadingInfoType::STATE])
{
- if( !value.empty() )
+ if(!value.empty())
{
value += READING_INFO_TYPE_SEPARATOR;
}
value += READING_INFO_TYPE_STATE;
}
- AppendAccessibilityAttribute( READING_INFO_TYPE_ATTRIBUTE_NAME, value );
+ AppendAccessibilityAttribute(READING_INFO_TYPE_ATTRIBUTE_NAME, value);
}
Dali::Accessibility::ReadingInfoTypes Control::Impl::GetAccessibilityReadingInfoType() const
{
std::string value;
- auto place = mAccessibilityAttributes.Find( READING_INFO_TYPE_ATTRIBUTE_NAME );
- if( place )
+ auto place = mAccessibilityAttributes.Find(READING_INFO_TYPE_ATTRIBUTE_NAME);
+ if(place)
{
- place->Get( value );
+ place->Get(value);
}
- if ( value.empty() )
+ if(value.empty())
{
return {};
}
Dali::Accessibility::ReadingInfoTypes types;
- if ( value.find( READING_INFO_TYPE_NAME ) != std::string::npos )
+ if(value.find(READING_INFO_TYPE_NAME) != std::string::npos)
{
- types[ Dali::Accessibility::ReadingInfoType::NAME ] = true;
+ types[Dali::Accessibility::ReadingInfoType::NAME] = true;
}
- if ( value.find( READING_INFO_TYPE_ROLE ) != std::string::npos )
+ if(value.find(READING_INFO_TYPE_ROLE) != std::string::npos)
{
- types[ Dali::Accessibility::ReadingInfoType::ROLE ] = true;
+ types[Dali::Accessibility::ReadingInfoType::ROLE] = true;
}
- if ( value.find( READING_INFO_TYPE_DESCRIPTION ) != std::string::npos )
+ if(value.find(READING_INFO_TYPE_DESCRIPTION) != std::string::npos)
{
- types[ Dali::Accessibility::ReadingInfoType::DESCRIPTION ] = true;
+ types[Dali::Accessibility::ReadingInfoType::DESCRIPTION] = true;
}
- if ( value.find( READING_INFO_TYPE_STATE ) != std::string::npos )
+ if(value.find(READING_INFO_TYPE_STATE) != std::string::npos)
{
- types[ Dali::Accessibility::ReadingInfoType::STATE ] = true;
+ types[Dali::Accessibility::ReadingInfoType::STATE] = true;
}
return types;
}
-void Control::Impl::CopyInstancedProperties( RegisteredVisualContainer& visuals, Dictionary<Property::Map>& instancedProperties )
+void Control::Impl::CopyInstancedProperties(RegisteredVisualContainer& visuals, Dictionary<Property::Map>& instancedProperties)
{
- for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter!= visuals.End(); iter++)
+ for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter != visuals.End(); iter++)
{
- if( (*iter)->visual )
+ if((*iter)->visual)
{
Property::Map instanceMap;
Toolkit::GetImplementation((*iter)->visual).CreateInstancePropertyMap(instanceMap);
- instancedProperties.Add( (*iter)->visual.GetName(), instanceMap );
+ instancedProperties.Add((*iter)->visual.GetName(), instanceMap);
}
}
}
-
-void Control::Impl::RemoveVisual( RegisteredVisualContainer& visuals, const std::string& visualName )
+void Control::Impl::RemoveVisual(RegisteredVisualContainer& visuals, const std::string& visualName)
{
- Actor self( mControlImpl.Self() );
+ Actor self(mControlImpl.Self());
- for ( RegisteredVisualContainer::Iterator visualIter = visuals.Begin();
- visualIter != visuals.End(); ++visualIter )
+ for(RegisteredVisualContainer::Iterator visualIter = visuals.Begin();
+ visualIter != visuals.End();
+ ++visualIter)
{
Toolkit::Visual::Base visual = (*visualIter)->visual;
- if( visual && visual.GetName() == visualName )
+ if(visual && visual.GetName() == visualName)
{
- Toolkit::GetImplementation(visual).SetOffScene( self );
+ Toolkit::GetImplementation(visual).SetOffScene(self);
(*visualIter)->visual.Reset();
- visuals.Erase( visualIter );
+ visuals.Erase(visualIter);
break;
}
}
}
-void Control::Impl::RemoveVisuals( RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals )
+void Control::Impl::RemoveVisuals(RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals)
{
- Actor self( mControlImpl.Self() );
- for( DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter )
+ Actor self(mControlImpl.Self());
+ for(DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter)
{
const std::string visualName = *iter;
- RemoveVisual( visuals, visualName );
+ RemoveVisual(visuals, visualName);
}
}
-void Control::Impl::RecreateChangedVisuals( Dictionary<Property::Map>& stateVisualsToChange,
- Dictionary<Property::Map>& instancedProperties )
+void Control::Impl::RecreateChangedVisuals(Dictionary<Property::Map>& stateVisualsToChange,
+ Dictionary<Property::Map>& instancedProperties)
{
- Dali::CustomActor handle( mControlImpl.GetOwner() );
- for( Dictionary<Property::Map>::iterator iter = stateVisualsToChange.Begin();
- iter != stateVisualsToChange.End(); ++iter )
+ Dali::CustomActor handle(mControlImpl.GetOwner());
+ for(Dictionary<Property::Map>::iterator iter = stateVisualsToChange.Begin();
+ iter != stateVisualsToChange.End();
+ ++iter)
{
- const std::string& visualName = (*iter).key;
- const Property::Map& toMap = (*iter).entry;
+ const std::string& visualName = (*iter).key;
+ const Property::Map& toMap = (*iter).entry;
- Actor self = mControlImpl.Self();
+ Actor self = mControlImpl.Self();
RegisteredVisualContainer::Iterator registeredVisualsiter;
// Check if visual (visualName) is already registered, this is the current visual.
if(FindVisual(visualName, mVisuals, registeredVisualsiter))
}
}
-void Control::Impl::ReplaceStateVisualsAndProperties( const StylePtr oldState, const StylePtr newState, const std::string& subState )
+void Control::Impl::ReplaceStateVisualsAndProperties(const StylePtr oldState, const StylePtr newState, const std::string& subState)
{
// Collect all old visual names
DictionaryKeys stateVisualsToRemove;
- if( oldState )
+ if(oldState)
{
- oldState->visuals.GetKeys( stateVisualsToRemove );
- if( ! subState.empty() )
+ oldState->visuals.GetKeys(stateVisualsToRemove);
+ if(!subState.empty())
{
const StylePtr* oldSubState = oldState->subStates.FindConst(subState);
- if( oldSubState )
+ if(oldSubState)
{
DictionaryKeys subStateVisualsToRemove;
- (*oldSubState)->visuals.GetKeys( subStateVisualsToRemove );
- Merge( stateVisualsToRemove, subStateVisualsToRemove );
+ (*oldSubState)->visuals.GetKeys(subStateVisualsToRemove);
+ Merge(stateVisualsToRemove, subStateVisualsToRemove);
}
}
}
// Collect all new visual properties
Dictionary<Property::Map> stateVisualsToAdd;
- if( newState )
+ if(newState)
{
stateVisualsToAdd = newState->visuals;
- if( ! subState.empty() )
+ if(!subState.empty())
{
const StylePtr* newSubState = newState->subStates.FindConst(subState);
- if( newSubState )
+ if(newSubState)
{
- stateVisualsToAdd.Merge( (*newSubState)->visuals );
+ stateVisualsToAdd.Merge((*newSubState)->visuals);
}
}
}
// If a name is in both add/remove, move it to change list.
Dictionary<Property::Map> stateVisualsToChange;
- FindChangableVisuals( stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove);
+ FindChangableVisuals(stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove);
// Copy instanced properties (e.g. text label) of current visuals
Dictionary<Property::Map> instancedProperties;
- CopyInstancedProperties( mVisuals, instancedProperties );
+ CopyInstancedProperties(mVisuals, instancedProperties);
// For each visual in remove list, remove from mVisuals
- RemoveVisuals( mVisuals, stateVisualsToRemove );
+ RemoveVisuals(mVisuals, stateVisualsToRemove);
// For each visual in add list, create and add to mVisuals
- Dali::CustomActor handle( mControlImpl.GetOwner() );
- Style::ApplyVisuals( handle, stateVisualsToAdd, instancedProperties );
+ Dali::CustomActor handle(mControlImpl.GetOwner());
+ Style::ApplyVisuals(handle, stateVisualsToAdd, instancedProperties);
// For each visual in change list, if it requires a new visual,
// remove old visual, create and add to mVisuals
- RecreateChangedVisuals( stateVisualsToChange, instancedProperties );
+ RecreateChangedVisuals(stateVisualsToChange, instancedProperties);
}
-void Control::Impl::SetState( DevelControl::State newState, bool withTransitions )
+void Control::Impl::SetState(DevelControl::State newState, bool withTransitions)
{
DevelControl::State oldState = mState;
- Dali::CustomActor handle( mControlImpl.GetOwner() );
- DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n",
- (mState == DevelControl::NORMAL ? "NORMAL" :(
- mState == DevelControl::FOCUSED ?"FOCUSED" : (
- mState == DevelControl::DISABLED?"DISABLED":"NONE" ))));
+ Dali::CustomActor handle(mControlImpl.GetOwner());
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n", (mState == DevelControl::NORMAL ? "NORMAL" : (mState == DevelControl::FOCUSED ? "FOCUSED" : (mState == DevelControl::DISABLED ? "DISABLED" : "NONE"))));
- if( mState != newState )
+ if(mState != newState)
{
// If mState was Disabled, and new state is Focused, should probably
// store that fact, e.g. in another property that FocusManager can access.
// Trigger state change and transitions
// Apply new style, if stylemanager is available
Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
- if( styleManager )
+ if(styleManager)
{
- const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
+ const StylePtr stylePtr = GetImpl(styleManager).GetRecordedStyle(Toolkit::Control(mControlImpl.GetOwner()));
- if( stylePtr )
+ if(stylePtr)
{
- std::string oldStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( oldState, ControlStateTable, ControlStateTableCount );
- std::string newStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( newState, ControlStateTable, ControlStateTableCount );
+ std::string oldStateName = Scripting::GetEnumerationName<Toolkit::DevelControl::State>(oldState, ControlStateTable, ControlStateTableCount);
+ std::string newStateName = Scripting::GetEnumerationName<Toolkit::DevelControl::State>(newState, ControlStateTable, ControlStateTableCount);
- const StylePtr* newStateStyle = stylePtr->subStates.Find( newStateName );
- const StylePtr* oldStateStyle = stylePtr->subStates.Find( oldStateName );
- if( oldStateStyle && newStateStyle )
+ const StylePtr* newStateStyle = stylePtr->subStates.Find(newStateName);
+ const StylePtr* oldStateStyle = stylePtr->subStates.Find(oldStateName);
+ if(oldStateStyle && newStateStyle)
{
// Only change if both state styles exist
- ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, mSubStateName );
+ ReplaceStateVisualsAndProperties(*oldStateStyle, *newStateStyle, mSubStateName);
}
}
}
}
}
-void Control::Impl::SetSubState( const std::string& subStateName, bool withTransitions )
+void Control::Impl::SetSubState(const std::string& subStateName, bool withTransitions)
{
- if( mSubStateName != subStateName )
+ if(mSubStateName != subStateName)
{
// Get existing sub-state visuals, and unregister them
- Dali::CustomActor handle( mControlImpl.GetOwner() );
+ Dali::CustomActor handle(mControlImpl.GetOwner());
Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
- if( styleManager )
+ if(styleManager)
{
- const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
- if( stylePtr )
+ const StylePtr stylePtr = GetImpl(styleManager).GetRecordedStyle(Toolkit::Control(mControlImpl.GetOwner()));
+ if(stylePtr)
{
// Stringify state
- std::string stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( mState, ControlStateTable, ControlStateTableCount );
+ std::string stateName = Scripting::GetEnumerationName<Toolkit::DevelControl::State>(mState, ControlStateTable, ControlStateTableCount);
- const StylePtr* state = stylePtr->subStates.Find( stateName );
- if( state )
+ const StylePtr* state = stylePtr->subStates.Find(stateName);
+ if(state)
{
StylePtr stateStyle(*state);
- const StylePtr* newStateStyle = stateStyle->subStates.Find( subStateName );
- const StylePtr* oldStateStyle = stateStyle->subStates.Find( mSubStateName );
- if( oldStateStyle && newStateStyle )
+ const StylePtr* newStateStyle = stateStyle->subStates.Find(subStateName);
+ const StylePtr* oldStateStyle = stateStyle->subStates.Find(mSubStateName);
+ if(oldStateStyle && newStateStyle)
{
std::string empty;
- ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, empty );
+ ReplaceStateVisualsAndProperties(*oldStateStyle, *newStateStyle, empty);
}
}
}
// then when this control appears back on stage it should use that new visual.
// Iterate through all registered visuals and set off scene
- SetVisualsOffScene( mVisuals, self );
+ SetVisualsOffScene(mVisuals, self);
// Visuals pending replacement can now be taken out of the removal list and set off scene
// Iterate through all replacement visuals and add to a move queue then set off scene
- for( auto removalIter = mRemoveVisuals.Begin(), end = mRemoveVisuals.End(); removalIter != end; removalIter++ )
+ for(auto removalIter = mRemoveVisuals.Begin(), end = mRemoveVisuals.End(); removalIter != end; removalIter++)
{
- Toolkit::GetImplementation((*removalIter)->visual).SetOffScene( self );
+ Toolkit::GetImplementation((*removalIter)->visual).SetOffScene(self);
}
- for( auto replacedIter = mVisuals.Begin(), end = mVisuals.End(); replacedIter != end; replacedIter++ )
+ for(auto replacedIter = mVisuals.Begin(), end = mVisuals.End(); replacedIter != end; replacedIter++)
{
(*replacedIter)->pending = false;
}
mRemoveVisuals.Clear();
}
-void Control::Impl::SetMargin( Extents margin )
+void Control::Impl::SetMargin(Extents margin)
{
mControlImpl.mImpl->mMargin = margin;
return mControlImpl.mImpl->mMargin;
}
-void Control::Impl::SetPadding( Extents padding )
+void Control::Impl::SetPadding(Extents padding)
{
mControlImpl.mImpl->mPadding = padding;
return mControlImpl.mImpl->mPadding;
}
-void Control::Impl::SetInputMethodContext( InputMethodContext& inputMethodContext )
+void Control::Impl::SetInputMethodContext(InputMethodContext& inputMethodContext)
{
mInputMethodContext = inputMethodContext;
}
-bool Control::Impl::FilterKeyEvent( const KeyEvent& event )
+bool Control::Impl::FilterKeyEvent(const KeyEvent& event)
{
- bool consumed ( false );
+ bool consumed(false);
- if ( mInputMethodContext )
+ if(mInputMethodContext)
{
- consumed = mInputMethodContext.FilterEventKey( event );
+ consumed = mInputMethodContext.FilterEventKey(event);
}
return consumed;
}
return mVisualEventSignal;
}
-void Control::Impl::SetShadow( const Property::Map& map )
+void Control::Impl::SetShadow(const Property::Map& map)
{
- Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( map );
+ Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(map);
visual.SetName("shadow");
- if( visual )
+ if(visual)
{
- mControlImpl.mImpl->RegisterVisual( Toolkit::DevelControl::Property::SHADOW, visual, DepthIndex::BACKGROUND_EFFECT );
+ mControlImpl.mImpl->RegisterVisual(Toolkit::DevelControl::Property::SHADOW, visual, DepthIndex::BACKGROUND_EFFECT);
mControlImpl.RelayoutRequest();
}
void Control::Impl::ClearShadow()
{
- mControlImpl.mImpl->UnregisterVisual( Toolkit::DevelControl::Property::SHADOW );
+ mControlImpl.mImpl->UnregisterVisual(Toolkit::DevelControl::Property::SHADOW);
- // Trigger a size negotiation request that may be needed when unregistering a visual.
- mControlImpl.RelayoutRequest();
+ // Trigger a size negotiation request that may be needed when unregistering a visual.
+ mControlImpl.RelayoutRequest();
}
Dali::Property Control::Impl::GetVisualProperty(Dali::Property::Index index, Dali::Property::Key visualPropertyKey)
if(!mIdleCallback)
{
// The callback manager takes the ownership of the callback object.
- mIdleCallback = MakeCallback( this, &Control::Impl::OnIdleCallback);
+ mIdleCallback = MakeCallback(this, &Control::Impl::OnIdleCallback);
Adaptor::Get().AddIdle(mIdleCallback, false);
}
}
mIdleCallback = nullptr;
}
-Dali::Accessibility::Accessible *Control::Impl::GetAccessibilityObject()
+Dali::Accessibility::Accessible* Control::Impl::GetAccessibilityObject()
{
- if( !accessibilityObject )
- accessibilityObject = accessibilityConstructor( mControlImpl.Self() );
+ if(!accessibilityObject)
+ accessibilityObject = accessibilityConstructor(mControlImpl.Self());
return accessibilityObject.get();
}
-Dali::Accessibility::Accessible *Control::Impl::GetAccessibilityObject(Dali::Actor actor)
+Dali::Accessibility::Accessible* Control::Impl::GetAccessibilityObject(Dali::Actor actor)
{
- if( actor )
+ if(actor)
{
- auto q = Dali::Toolkit::Control::DownCast( actor );
- if( q )
+ auto q = Dali::Toolkit::Control::DownCast(actor);
+ if(q)
{
- auto q2 = static_cast< Internal::Control* >( &q.GetImplementation() );
+ auto q2 = static_cast<Internal::Control*>(&q.GetImplementation());
return q2->mImpl->GetAccessibilityObject();
}
}
}
Control::Impl::AccessibleImpl::AccessibleImpl(Dali::Actor self, Dali::Accessibility::Role role, bool modal)
- : self(self), modal(modal)
+: self(self),
+ modal(modal)
{
auto control = Dali::Toolkit::Control::DownCast(self);
- Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control );
- Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl );
- if( controlImpl.mAccessibilityRole == Dali::Accessibility::Role::UNKNOWN )
+ Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control);
+ Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl);
+ if(controlImpl.mAccessibilityRole == Dali::Accessibility::Role::UNKNOWN)
controlImpl.mAccessibilityRole = role;
- self.PropertySetSignal().Connect(&controlImpl, [this, &controlImpl](Dali::Handle &handle, Dali::Property::Index index, Dali::Property::Value value)
- {
- if (this->self != Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
+ self.PropertySetSignal().Connect(&controlImpl, [this, &controlImpl](Dali::Handle& handle, Dali::Property::Index index, Dali::Property::Value value) {
+ if(this->self != Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
{
return;
}
- if (index == DevelControl::Property::ACCESSIBILITY_NAME
- || (index == GetNamePropertyIndex() && !controlImpl.mAccessibilityNameSet))
+ if(index == DevelControl::Property::ACCESSIBILITY_NAME || (index == GetNamePropertyIndex() && !controlImpl.mAccessibilityNameSet))
{
- if (controlImpl.mAccessibilityGetNameSignal.Empty())
+ if(controlImpl.mAccessibilityGetNameSignal.Empty())
{
Emit(Dali::Accessibility::ObjectPropertyChangeEvent::NAME);
}
}
- if (index == DevelControl::Property::ACCESSIBILITY_DESCRIPTION
- || (index == GetDescriptionPropertyIndex() && !controlImpl.mAccessibilityDescriptionSet))
+ if(index == DevelControl::Property::ACCESSIBILITY_DESCRIPTION || (index == GetDescriptionPropertyIndex() && !controlImpl.mAccessibilityDescriptionSet))
{
- if (controlImpl.mAccessibilityGetDescriptionSignal.Empty())
+ if(controlImpl.mAccessibilityGetDescriptionSignal.Empty())
{
Emit(Dali::Accessibility::ObjectPropertyChangeEvent::DESCRIPTION);
}
{
auto control = Dali::Toolkit::Control::DownCast(self);
- Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control );
- Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl );
+ Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control);
+ Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl);
- if (!controlImpl.mAccessibilityGetNameSignal.Empty()) {
- std::string ret;
- controlImpl.mAccessibilityGetNameSignal.Emit(ret);
- return ret;
+ if(!controlImpl.mAccessibilityGetNameSignal.Empty())
+ {
+ std::string ret;
+ controlImpl.mAccessibilityGetNameSignal.Emit(ret);
+ return ret;
}
- if (controlImpl.mAccessibilityNameSet)
+ if(controlImpl.mAccessibilityNameSet)
return controlImpl.mAccessibilityName;
- if (auto raw = GetNameRaw(); !raw.empty())
+ if(auto raw = GetNameRaw(); !raw.empty())
return raw;
- return self.GetProperty< std::string >( Actor::Property::NAME );
+ return self.GetProperty<std::string>(Actor::Property::NAME);
}
std::string Control::Impl::AccessibleImpl::GetNameRaw()
{
auto control = Dali::Toolkit::Control::DownCast(self);
- Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control );
- Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl );
+ Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control);
+ Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl);
- if (!controlImpl.mAccessibilityGetDescriptionSignal.Empty()) {
- std::string ret;
- controlImpl.mAccessibilityGetDescriptionSignal.Emit(ret);
- return ret;
+ if(!controlImpl.mAccessibilityGetDescriptionSignal.Empty())
+ {
+ std::string ret;
+ controlImpl.mAccessibilityGetDescriptionSignal.Emit(ret);
+ return ret;
}
- if (controlImpl.mAccessibilityDescriptionSet)
+ if(controlImpl.mAccessibilityDescriptionSet)
return controlImpl.mAccessibilityDescription;
return GetDescriptionRaw();
Dali::Accessibility::Accessible* Control::Impl::AccessibleImpl::GetParent()
{
- return Dali::Accessibility::Accessible::Get( self.GetParent() );
+ return Dali::Accessibility::Accessible::Get(self.GetParent());
}
size_t Control::Impl::AccessibleImpl::GetChildCount()
return self.GetChildCount();
}
-Dali::Accessibility::Accessible* Control::Impl::AccessibleImpl::GetChildAtIndex( size_t index )
+Dali::Accessibility::Accessible* Control::Impl::AccessibleImpl::GetChildAtIndex(size_t index)
{
- return Dali::Accessibility::Accessible::Get( self.GetChildAt( static_cast< unsigned int >( index ) ) );
+ return Dali::Accessibility::Accessible::Get(self.GetChildAt(static_cast<unsigned int>(index)));
}
size_t Control::Impl::AccessibleImpl::GetIndexInParent()
{
- auto s = self;
+ auto s = self;
auto parent = s.GetParent();
- DALI_ASSERT_ALWAYS( parent && "can't call GetIndexInParent on object without parent" );
+ DALI_ASSERT_ALWAYS(parent && "can't call GetIndexInParent on object without parent");
auto count = parent.GetChildCount();
- for( auto i = 0u; i < count; ++i )
+ for(auto i = 0u; i < count; ++i)
{
- auto c = parent.GetChildAt( i );
- if( c == s )
+ auto c = parent.GetChildAt(i);
+ if(c == s)
return i;
}
- DALI_ASSERT_ALWAYS( false && "object isn't child of it's parent" );
+ DALI_ASSERT_ALWAYS(false && "object isn't child of it's parent");
return static_cast<size_t>(-1);
}
Dali::Accessibility::Role Control::Impl::AccessibleImpl::GetRole()
{
- return self.GetProperty<Dali::Accessibility::Role>( Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE );
+ return self.GetProperty<Dali::Accessibility::Role>(Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE);
}
Dali::Accessibility::States Control::Impl::AccessibleImpl::CalculateStates()
{
Dali::Accessibility::States s;
- s[Dali::Accessibility::State::FOCUSABLE] = self.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE );
- s[Dali::Accessibility::State::FOCUSED] = Toolkit::KeyboardFocusManager::Get().GetCurrentFocusActor() == self;
- if(self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE ).GetType() == Property::NONE )
+ s[Dali::Accessibility::State::FOCUSABLE] = self.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE);
+ s[Dali::Accessibility::State::FOCUSED] = Toolkit::KeyboardFocusManager::Get().GetCurrentFocusActor() == self;
+ if(self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).GetType() == Property::NONE)
s[Dali::Accessibility::State::HIGHLIGHTABLE] = false;
else
- s[Dali::Accessibility::State::HIGHLIGHTABLE] = self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE ).Get< bool >();
+ s[Dali::Accessibility::State::HIGHLIGHTABLE] = self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).Get<bool>();
s[Dali::Accessibility::State::HIGHLIGHTED] = GetCurrentlyHighlightedActor() == self;
- s[Dali::Accessibility::State::ENABLED] = true;
- s[Dali::Accessibility::State::SENSITIVE] = true;
- s[Dali::Accessibility::State::ANIMATED] = self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED ).Get< bool >();
- s[Dali::Accessibility::State::VISIBLE] = true;
- if( modal )
+ s[Dali::Accessibility::State::ENABLED] = true;
+ s[Dali::Accessibility::State::SENSITIVE] = true;
+ s[Dali::Accessibility::State::ANIMATED] = self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED).Get<bool>();
+ s[Dali::Accessibility::State::VISIBLE] = true;
+ if(modal)
{
s[Dali::Accessibility::State::MODAL] = true;
}
- s[Dali::Accessibility::State::SHOWING] = !self.GetProperty( Dali::DevelActor::Property::CULLED ).Get< bool >()
- && self.GetCurrentProperty< bool >( Actor::Property::VISIBLE );
+ s[Dali::Accessibility::State::SHOWING] = !self.GetProperty(Dali::DevelActor::Property::CULLED).Get<bool>() && self.GetCurrentProperty<bool>(Actor::Property::VISIBLE);
- s[Dali::Accessibility::State::DEFUNCT] = !self.GetProperty( Dali::DevelActor::Property::CONNECTED_TO_SCENE ).Get< bool >();
+ s[Dali::Accessibility::State::DEFUNCT] = !self.GetProperty(Dali::DevelActor::Property::CONNECTED_TO_SCENE).Get<bool>();
return s;
}
Dali::Accessibility::Attributes Control::Impl::AccessibleImpl::GetAttributes()
{
- std::unordered_map< std::string, std::string > attribute_map;
- auto q = Dali::Toolkit::Control::DownCast( self );
- auto w =
- q.GetProperty( Dali::Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES );
+ std::unordered_map<std::string, std::string> attribute_map;
+ auto q = Dali::Toolkit::Control::DownCast(self);
+ auto w =
+ q.GetProperty(Dali::Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES);
auto z = w.GetMap();
- if( z )
+ if(z)
{
auto map_size = z->Count();
- for( unsigned int i = 0; i < map_size; i++ )
+ for(unsigned int i = 0; i < map_size; i++)
{
- auto map_key = z->GetKeyAt( i );
- if( map_key.type == Property::Key::STRING )
+ auto map_key = z->GetKeyAt(i);
+ if(map_key.type == Property::Key::STRING)
{
std::string map_value;
- if( z->GetValue( i ).Get( map_value ) )
+ if(z->GetValue(i).Get(map_value))
{
- attribute_map.emplace( std::move( map_key.stringKey ),
- std::move( map_value ) );
+ attribute_map.emplace(std::move(map_key.stringKey),
+ std::move(map_value));
}
}
}
return Dali::Accessibility::ComponentLayer::WINDOW;
}
-Dali::Rect<> Control::Impl::AccessibleImpl::GetExtents( Dali::Accessibility::CoordType ctype )
+Dali::Rect<> Control::Impl::AccessibleImpl::GetExtents(Dali::Accessibility::CoordType ctype)
{
Vector2 screenPosition =
- self.GetProperty( Dali::DevelActor::Property::SCREEN_POSITION )
- .Get< Vector2 >();
- auto size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * self.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_SCALE );
+ self.GetProperty(Dali::DevelActor::Property::SCREEN_POSITION)
+ .Get<Vector2>();
+ auto size = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE) * self.GetCurrentProperty<Vector3>(Actor::Property::WORLD_SCALE);
bool positionUsesAnchorPoint =
- self.GetProperty( Dali::DevelActor::Property::POSITION_USES_ANCHOR_POINT )
- .Get< bool >();
+ self.GetProperty(Dali::DevelActor::Property::POSITION_USES_ANCHOR_POINT)
+ .Get<bool>();
Vector3 anchorPointOffSet =
- size * ( positionUsesAnchorPoint ? self.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT )
- : AnchorPoint::TOP_LEFT );
- Vector2 position = Vector2( screenPosition.x - anchorPointOffSet.x,
- screenPosition.y - anchorPointOffSet.y );
+ size * (positionUsesAnchorPoint ? self.GetCurrentProperty<Vector3>(Actor::Property::ANCHOR_POINT)
+ : AnchorPoint::TOP_LEFT);
+ Vector2 position = Vector2(screenPosition.x - anchorPointOffSet.x,
+ screenPosition.y - anchorPointOffSet.y);
- return { position.x, position.y, size.x, size.y };
+ return {position.x, position.y, size.x, size.y};
}
-int16_t Control::Impl::AccessibleImpl::GetMdiZOrder() { return 0; }
-double Control::Impl::AccessibleImpl::GetAlpha() { return 0; }
+int16_t Control::Impl::AccessibleImpl::GetMdiZOrder()
+{
+ return 0;
+}
+double Control::Impl::AccessibleImpl::GetAlpha()
+{
+ return 0;
+}
bool Control::Impl::AccessibleImpl::GrabFocus()
{
- return Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor( self );
+ return Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor(self);
}
static Dali::Actor CreateHighlightIndicatorActor()
focusBorderImagePath += "/keyboard_focus.9.png";
// Create the default if it hasn't been set and one that's shared by all the
// keyboard focusable actors
- auto actor = Toolkit::ImageView::New( focusBorderImagePath );
- actor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
- DevelControl::AppendAccessibilityAttribute( actor, "highlight", "" );
- actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, true);
- actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false );
+ auto actor = Toolkit::ImageView::New(focusBorderImagePath);
+ actor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
+ DevelControl::AppendAccessibilityAttribute(actor, "highlight", "");
+ actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, true);
+ actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false);
return actor;
}
{
auto old = GetCurrentlyHighlightedActor();
- if( !Dali::Accessibility::IsUp() )
- return false;
- if( self == old )
+ if(!Dali::Accessibility::IsUp())
+ return false;
+ if(self == old)
return true;
- if( old )
+ if(old)
{
- auto c = dynamic_cast< Dali::Accessibility::Component* >( GetAccessibilityObject( old ) );
- if( c )
+ auto c = dynamic_cast<Dali::Accessibility::Component*>(GetAccessibilityObject(old));
+ if(c)
c->ClearHighlight();
}
auto highlight = GetHighlightActor();
- if ( !highlight )
+ if(!highlight)
{
highlight = CreateHighlightIndicatorActor();
- SetHighlightActor( highlight );
+ SetHighlightActor(highlight);
}
- highlight.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- highlight.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- highlight.SetProperty( Actor::Property::POSITION_Z, 1.0f );
- highlight.SetProperty( Actor::Property::POSITION, Vector2( 0.0f, 0.0f ));
+ highlight.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ highlight.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ highlight.SetProperty(Actor::Property::POSITION_Z, 1.0f);
+ highlight.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f));
EnsureSelfVisible();
- self.Add( highlight );
- SetCurrentlyHighlightedActor( self );
- EmitHighlighted( true );
+ self.Add(highlight);
+ SetCurrentlyHighlightedActor(self);
+ EmitHighlighted(true);
return true;
}
-
-
bool Control::Impl::AccessibleImpl::ClearHighlight()
{
- if( !Dali::Accessibility::IsUp() )
+ if(!Dali::Accessibility::IsUp())
return false;
- if( GetCurrentlyHighlightedActor() == self )
+ if(GetCurrentlyHighlightedActor() == self)
{
- self.Remove( GetHighlightActor() );
- SetCurrentlyHighlightedActor( {} );
- EmitHighlighted( false );
+ self.Remove(GetHighlightActor());
+ SetCurrentlyHighlightedActor({});
+ EmitHighlighted(false);
return true;
}
return false;
}
-std::string Control::Impl::AccessibleImpl::GetActionName( size_t index )
+std::string Control::Impl::AccessibleImpl::GetActionName(size_t index)
{
- if ( index >= GetActionCount() ) return "";
+ if(index >= GetActionCount()) return "";
Dali::TypeInfo type;
- self.GetTypeInfo( type );
- DALI_ASSERT_ALWAYS( type && "no TypeInfo object" );
- return type.GetActionName( index );
+ self.GetTypeInfo(type);
+ DALI_ASSERT_ALWAYS(type && "no TypeInfo object");
+ return type.GetActionName(index);
}
-std::string Control::Impl::AccessibleImpl::GetLocalizedActionName( size_t index )
+std::string Control::Impl::AccessibleImpl::GetLocalizedActionName(size_t index)
{
// TODO: add localization
- return GetActionName( index );
+ return GetActionName(index);
}
-std::string Control::Impl::AccessibleImpl::GetActionDescription( size_t index )
+std::string Control::Impl::AccessibleImpl::GetActionDescription(size_t index)
{
return "";
}
size_t Control::Impl::AccessibleImpl::GetActionCount()
{
Dali::TypeInfo type;
- self.GetTypeInfo( type );
- DALI_ASSERT_ALWAYS( type && "no TypeInfo object" );
+ self.GetTypeInfo(type);
+ DALI_ASSERT_ALWAYS(type && "no TypeInfo object");
return type.GetActionCount();
}
-std::string Control::Impl::AccessibleImpl::GetActionKeyBinding( size_t index )
+std::string Control::Impl::AccessibleImpl::GetActionKeyBinding(size_t index)
{
return "";
}
-bool Control::Impl::AccessibleImpl::DoAction( size_t index )
+bool Control::Impl::AccessibleImpl::DoAction(size_t index)
{
- std::string actionName = GetActionName( index );
- return self.DoAction( actionName, {} );
+ std::string actionName = GetActionName(index);
+ return self.DoAction(actionName, {});
}
bool Control::Impl::AccessibleImpl::DoAction(const std::string& name)
{
- return self.DoAction( name, {} );
+ return self.DoAction(name, {});
}
-bool Control::Impl::AccessibleImpl::DoGesture(const Dali::Accessibility::GestureInfo &gestureInfo)
+bool Control::Impl::AccessibleImpl::DoGesture(const Dali::Accessibility::GestureInfo& gestureInfo)
{
auto control = Dali::Toolkit::Control::DownCast(self);
- Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control );
- Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl );
+ Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control);
+ Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl);
- if (!controlImpl.mAccessibilityDoGestureSignal.Empty()) {
- auto ret = std::make_pair(gestureInfo, false);
- controlImpl.mAccessibilityDoGestureSignal.Emit(ret);
- return ret.second;
+ if(!controlImpl.mAccessibilityDoGestureSignal.Empty())
+ {
+ auto ret = std::make_pair(gestureInfo, false);
+ controlImpl.mAccessibilityDoGestureSignal.Emit(ret);
+ return ret.second;
}
return false;
{
auto control = Dali::Toolkit::Control::DownCast(self);
- Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control );
- Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl );
+ Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control);
+ Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl);
std::vector<Dali::Accessibility::Relation> ret;
- auto &v = controlImpl.mAccessibilityRelations;
- for (auto i = 0u; i < v.size(); ++i)
+ auto& v = controlImpl.mAccessibilityRelations;
+ for(auto i = 0u; i < v.size(); ++i)
{
- if ( v[i].empty() )
+ if(v[i].empty())
continue;
- ret.emplace_back( Accessibility::Relation{ static_cast<Accessibility::RelationType>(i), v[i] } );
+ ret.emplace_back(Accessibility::Relation{static_cast<Accessibility::RelationType>(i), v[i]});
}
return ret;
void Control::Impl::AccessibleImpl::EnsureSelfVisible()
{
auto parent = dynamic_cast<Control::Impl::AccessibleImpl*>(GetParent());
- if (parent)
+ if(parent)
{
parent->EnsureChildVisible(self);
}
return Property::INVALID_INDEX;
}
-void Control::Impl::PositionOrSizeChangedCallback( PropertyNotification &p )
+void Control::Impl::PositionOrSizeChangedCallback(PropertyNotification& p)
{
auto self = Dali::Actor::DownCast(p.GetTarget());
- if (Dali::Accessibility::IsUp() && !self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED ).Get< bool >())
+ if(Dali::Accessibility::IsUp() && !self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED).Get<bool>())
{
- auto extents = DevelActor::CalculateScreenExtents( self );
- Dali::Accessibility::Accessible::Get( self )->EmitBoundsChanged( extents );
+ auto extents = DevelActor::CalculateScreenExtents(self);
+ Dali::Accessibility::Accessible::Get(self)->EmitBoundsChanged(extents);
}
}
-void Control::Impl::CulledChangedCallback( PropertyNotification &p)
+void Control::Impl::CulledChangedCallback(PropertyNotification& p)
{
- if (Dali::Accessibility::IsUp())
+ if(Dali::Accessibility::IsUp())
{
auto self = Dali::Actor::DownCast(p.GetTarget());
- Dali::Accessibility::Accessible::Get(self)->EmitShowing( !self.GetProperty( DevelActor::Property::CULLED ).Get<bool>() );
+ Dali::Accessibility::Accessible::Get(self)->EmitShowing(!self.GetProperty(DevelActor::Property::CULLED).Get<bool>());
}
}
void Control::Impl::AccessibilityRegister()
{
- if (!accessibilityNotificationSet)
+ if(!accessibilityNotificationSet)
{
- accessibilityNotificationPosition = mControlImpl.Self().AddPropertyNotification( Actor::Property::POSITION, StepCondition( 0.01f ) );
- accessibilityNotificationPosition.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
- accessibilityNotificationPosition.NotifySignal().Connect( &Control::Impl::PositionOrSizeChangedCallback );
+ accessibilityNotificationPosition = mControlImpl.Self().AddPropertyNotification(Actor::Property::POSITION, StepCondition(0.01f));
+ accessibilityNotificationPosition.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
+ accessibilityNotificationPosition.NotifySignal().Connect(&Control::Impl::PositionOrSizeChangedCallback);
- accessibilityNotificationSize = mControlImpl.Self().AddPropertyNotification( Actor::Property::SIZE, StepCondition( 0.01f ) );
- accessibilityNotificationSize.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
- accessibilityNotificationSize.NotifySignal().Connect( &Control::Impl::PositionOrSizeChangedCallback );
+ accessibilityNotificationSize = mControlImpl.Self().AddPropertyNotification(Actor::Property::SIZE, StepCondition(0.01f));
+ accessibilityNotificationSize.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
+ accessibilityNotificationSize.NotifySignal().Connect(&Control::Impl::PositionOrSizeChangedCallback);
- accessibilityNotificationCulled = mControlImpl.Self().AddPropertyNotification( DevelActor::Property::CULLED, LessThanCondition( 0.5f ) );
- accessibilityNotificationCulled.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
- accessibilityNotificationCulled.NotifySignal().Connect( &Control::Impl::CulledChangedCallback );
+ accessibilityNotificationCulled = mControlImpl.Self().AddPropertyNotification(DevelActor::Property::CULLED, LessThanCondition(0.5f));
+ accessibilityNotificationCulled.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
+ accessibilityNotificationCulled.NotifySignal().Connect(&Control::Impl::CulledChangedCallback);
accessibilityNotificationSet = true;
}
void Control::Impl::AccessibilityDeregister()
{
- if (accessibilityNotificationSet)
+ if(accessibilityNotificationSet)
{
accessibilityNotificationPosition = {};
- accessibilityNotificationSize = {};
- accessibilityNotificationCulled = {};
- accessibilityNotificationSet = false;
+ accessibilityNotificationSize = {};
+ accessibilityNotificationCulled = {};
+ accessibilityNotificationSet = false;
}
}
/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-#include <dali/integration-api/debug.h>
-#include <dali/public-api/object/property.h>
-#include <dali/public-api/object/property-index-ranges.h>
-#include <dali-toolkit/public-api/controls/control-impl.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
#include <dali-toolkit/internal/controls/control/control-debug.h>
#include <dali-toolkit/internal/visuals/visual-base-impl.h>
-#include <iostream>
+#include <dali-toolkit/public-api/controls/control-impl.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/property-index-ranges.h>
+#include <dali/public-api/object/property.h>
#include <algorithm>
#include <functional>
+#include <iostream>
#if defined(DEBUG_ENABLED)
{
namespace Internal
{
-
class JsonWriter
{
public:
- JsonWriter( Property::Value& value )
+ JsonWriter(Property::Value& value)
: mValue(value)
{
}
std::string ToString()
{
std::ostringstream stream;
- ToStream( stream );
+ ToStream(stream);
return stream.str();
}
- void ToStream( std::ostream& stream )
+ void ToStream(std::ostream& stream)
{
- switch( mValue.GetType() )
+ switch(mValue.GetType())
{
case Dali::Property::BOOLEAN:
{
auto value = mValue.Get<bool>();
- stream << ((value)?"true":"false");
+ stream << ((value) ? "true" : "false");
break;
}
case Dali::Property::FLOAT:
{
auto matrix = mValue.Get<Matrix3>();
stream << "[";
- for( int i=0; i<9; ++i )
+ for(int i = 0; i < 9; ++i)
{
- if( i>0)
+ if(i > 0)
stream << ",";
stream << matrix.AsFloat()[i];
}
{
auto matrix = mValue.Get<Matrix>();
stream << "[";
- for( int i=0; i<16; ++i )
+ for(int i = 0; i < 16; ++i)
{
- if( i>0)
+ if(i > 0)
stream << ",";
stream << matrix.AsFloat()[i];
}
{
auto array = mValue.GetArray();
stream << "[ ";
- if( array )
+ if(array)
{
- for( Property::Array::SizeType i=0; i<array->Size(); ++i)
+ for(Property::Array::SizeType i = 0; i < array->Size(); ++i)
{
- if( i>0)
+ if(i > 0)
stream << ", ";
- auto outValue = JsonWriter( array->GetElementAt(i) );
+ auto outValue = JsonWriter(array->GetElementAt(i));
stream << outValue.ToString();
}
}
{
auto map = mValue.GetMap();
stream << "{ ";
- if( map )
+ if(map)
{
- for( Property::Map::SizeType i=0; i<map->Count(); ++i)
+ for(Property::Map::SizeType i = 0; i < map->Count(); ++i)
{
- if( i>0)
+ if(i > 0)
stream << ", ";
- auto key = map->GetKeyAt( i );
- auto outValue = JsonWriter( map->GetValue(i) );
+ auto key = map->GetKeyAt(i);
+ auto outValue = JsonWriter(map->GetValue(i));
stream << '\"' << key << "\":";
stream << outValue.ToString();
}
Property::Value& mValue;
};
-static std::ostream& operator<<( std::ostream& o, JsonWriter& value )
+static std::ostream& operator<<(std::ostream& o, JsonWriter& value)
{
value.ToStream(o);
return o;
}
-
-std::ostream& operator<<( std::ostream& o, const RegisteredVisual& registeredVisual )
+std::ostream& operator<<(std::ostream& o, const RegisteredVisual& registeredVisual)
{
- o << "{\n" << "\"index\":" << registeredVisual.index << ",\n";
- o << "\"enabled\":" << (registeredVisual.enabled?"true":"false") << ",\n";
- o << "\"pending\":" << (registeredVisual.pending?"true":"false") << ",\n";
+ o << "{\n"
+ << "\"index\":" << registeredVisual.index << ",\n";
+ o << "\"enabled\":" << (registeredVisual.enabled ? "true" : "false") << ",\n";
+ o << "\"pending\":" << (registeredVisual.pending ? "true" : "false") << ",\n";
Property::Map map;
- registeredVisual.visual.CreatePropertyMap( map );
+ registeredVisual.visual.CreatePropertyMap(map);
o << "\"visual\": {\n\"name\":\"" << registeredVisual.visual.GetName() << "\",\n";
- o << map << "}\n" << "\n}\n";
+ o << map << "}\n"
+ << "\n}\n";
return o;
}
-std::ostream& operator<<( std::ostream& o, const RegisteredVisualContainer& visualContainer )
+std::ostream& operator<<(std::ostream& o, const RegisteredVisualContainer& visualContainer)
{
- o<<"[\n";
+ o << "[\n";
- bool first=true;
- for( auto&& elem : visualContainer )
+ bool first = true;
+ for(auto&& elem : visualContainer)
{
if(!first)
{
}
first = false;
- o<<*elem<<"\n";
+ o << *elem << "\n";
}
- o<<"]\n";
+ o << "]\n";
return o;
}
-std::ostream& DumpProperty( std::ostream& o, Property::Index index, Handle handle )
+std::ostream& DumpProperty(std::ostream& o, Property::Index index, Handle handle)
{
- auto propertyValue = handle.GetProperty( index );
+ auto propertyValue = handle.GetProperty(index);
auto jsonPropertyValue = JsonWriter(propertyValue);
o << "{\n";
o << "\"index\":" << index << ",\n";
- o << "\"name\":\"" << handle.GetPropertyName( index ) << "\",\n";
+ o << "\"name\":\"" << handle.GetPropertyName(index) << "\",\n";
o << "\"value\":" << jsonPropertyValue << "\n";
o << "}";
return o;
}
-
-std::ostream& DumpPropertiesWithPredicate( std::ostream& o, Dali::Handle handle,
- Property::IndexContainer& indices, std::function<bool(int)> predicate)
+std::ostream& DumpPropertiesWithPredicate(std::ostream& o, Dali::Handle handle, Property::IndexContainer& indices, std::function<bool(int)> predicate)
{
bool first = true;
- for( auto index : indices )
+ for(auto index : indices)
{
- if( predicate( index ) )
+ if(predicate(index))
{
- if( !first )
+ if(!first)
{
o << ",";
}
o << std::endl;
first = false;
- DumpProperty( o, index, handle );
+ DumpProperty(o, index, handle);
}
}
return o;
}
-std::ostream& DumpProperties( std::ostream& o, Handle handle )
+std::ostream& DumpProperties(std::ostream& o, Handle handle)
{
Property::IndexContainer indices;
- handle.GetPropertyIndices( indices );
+ handle.GetPropertyIndices(indices);
- auto childPropertiesP = [](int index) -> bool
- {
- return CHILD_PROPERTY_REGISTRATION_START_INDEX <= index && index <= CHILD_PROPERTY_REGISTRATION_MAX_INDEX;
- };
- auto propertiesP = [](int index) -> bool
- {
- return !(CHILD_PROPERTY_REGISTRATION_START_INDEX <= index && index <= CHILD_PROPERTY_REGISTRATION_MAX_INDEX);
- };
+ auto childPropertiesP = [](int index) -> bool {
+ return CHILD_PROPERTY_REGISTRATION_START_INDEX <= index && index <= CHILD_PROPERTY_REGISTRATION_MAX_INDEX;
+ };
+ auto propertiesP = [](int index) -> bool {
+ return !(CHILD_PROPERTY_REGISTRATION_START_INDEX <= index && index <= CHILD_PROPERTY_REGISTRATION_MAX_INDEX);
+ };
- o << "\"childProperties\":[\n" ;
- DumpPropertiesWithPredicate( o, handle, indices, childPropertiesP );
- o << std::endl << "]," << std::endl;
+ o << "\"childProperties\":[\n";
+ DumpPropertiesWithPredicate(o, handle, indices, childPropertiesP);
+ o << std::endl
+ << "]," << std::endl;
- o << "\"Properties\":[\n" ;
- DumpPropertiesWithPredicate( o, handle, indices, propertiesP );
- o << std::endl << "]" << std::endl;
+ o << "\"Properties\":[\n";
+ DumpPropertiesWithPredicate(o, handle, indices, propertiesP);
+ o << std::endl
+ << "]" << std::endl;
return o;
}
-std::string DumpControl( const Internal::Control& control )
+std::string DumpControl(const Internal::Control& control)
{
- auto& controlData = Internal::Control::Impl::Get( control );
+ auto& controlData = Internal::Control::Impl::Get(control);
std::ostringstream oss;
oss << "{\n ";
- const std::string& name = control.Self().GetProperty< std::string >( Dali::Actor::Property::NAME );
- if( ! name.empty() )
+ const std::string& name = control.Self().GetProperty<std::string>(Dali::Actor::Property::NAME);
+ if(!name.empty())
{
oss << "\"name\":\"" << name << "\",\n";
}
- oss << "\"id\":\"" << control.Self().GetProperty< int >( Actor::Property::ID ) << "\",\n";
- oss << "\"registeredVisuals\":\n" << controlData.mVisuals << ",\n";
- oss << "\"removeVisuals\":\n" << controlData.mRemoveVisuals << ",\n";
+ oss << "\"id\":\"" << control.Self().GetProperty<int>(Actor::Property::ID) << "\",\n";
+ oss << "\"registeredVisuals\":\n"
+ << controlData.mVisuals << ",\n";
+ oss << "\"removeVisuals\":\n"
+ << controlData.mRemoveVisuals << ",\n";
oss << "\"rendererCount\":" << control.Self().GetRendererCount() << ",\n";
oss << "\"properties\":\n{\n";
- DumpProperties( oss, control.Self() ) << "}\n";
+ DumpProperties(oss, control.Self()) << "}\n";
oss << "}\n";
return oss.str();
}
-std::string DumpActor( Actor actor )
+std::string DumpActor(Actor actor)
{
std::ostringstream oss;
oss << "{\n ";
- const std::string& name = actor.GetProperty< std::string >( Dali::Actor::Property::NAME );
- if( ! name.empty() )
+ const std::string& name = actor.GetProperty<std::string>(Dali::Actor::Property::NAME);
+ if(!name.empty())
{
oss << "\"name\":\"" << name << "\",\n";
}
- oss << "\"id\":\"" << actor.GetProperty< int >( Actor::Property::ID ) << "\",\n";
+ oss << "\"id\":\"" << actor.GetProperty<int>(Actor::Property::ID) << "\",\n";
oss << "\"rendererCount\":" << actor.GetRendererCount() << ",\n";
oss << "\"properties\":\n{\n";
- Toolkit::Internal::DumpProperties( oss, actor ) << "}\n";
+ Toolkit::Internal::DumpProperties(oss, actor) << "}\n";
oss << "}\n";
return oss.str();
}
-void DumpControlHierarchy( std::ostream& o, Actor actor )
+void DumpControlHierarchy(std::ostream& o, Actor actor)
{
- auto control = Toolkit::Control::DownCast( actor );
+ auto control = Toolkit::Control::DownCast(actor);
o << "{\n";
- if( control )
+ if(control)
{
- o << "\"Control\":" << DumpControl( Toolkit::Internal::GetImplementation( control ) );
+ o << "\"Control\":" << DumpControl(Toolkit::Internal::GetImplementation(control));
}
else
{
- o << "\"Actor\":" << DumpActor( actor );
+ o << "\"Actor\":" << DumpActor(actor);
}
o << ",\n\"children\":[\n";
- bool first=true;
- for( auto count=actor.GetChildCount(), i=0u; i<count; ++i )
+ bool first = true;
+ for(auto count = actor.GetChildCount(), i = 0u; i < count; ++i)
{
- if( !first )
+ if(!first)
{
o << ",";
}
first = false;
o << "\n";
- DumpControlHierarchy( o, actor.GetChildAt( i ) );
+ DumpControlHierarchy(o, actor.GetChildAt(i));
}
o << "]}\n";
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Internal
{
-
-Geometry CreateGridGeometry( Uint16Pair gridSize )
+Geometry CreateGridGeometry(Uint16Pair gridSize)
{
- uint16_t gridWidth = gridSize.GetWidth();
+ uint16_t gridWidth = gridSize.GetWidth();
uint16_t gridHeight = gridSize.GetHeight();
// Create vertices
- Vector< Vector2 > vertices;
- vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
+ Vector<Vector2> vertices;
+ vertices.Reserve((gridWidth + 1) * (gridHeight + 1));
- for( int y = 0; y < gridHeight + 1; ++y )
+ for(int y = 0; y < gridHeight + 1; ++y)
{
- for( int x = 0; x < gridWidth + 1; ++x )
+ for(int x = 0; x < gridWidth + 1; ++x)
{
- vertices.PushBack( Vector2( (float)x/gridWidth - 0.5f, (float)y/gridHeight - 0.5f) );
+ vertices.PushBack(Vector2((float)x / gridWidth - 0.5f, (float)y / gridHeight - 0.5f));
}
}
// Create indices
- Vector< unsigned short > indices;
- indices.Reserve( (gridWidth+2)*gridHeight*2 - 2);
+ Vector<unsigned short> indices;
+ indices.Reserve((gridWidth + 2) * gridHeight * 2 - 2);
- for( unsigned int row = 0u; row < gridHeight; ++row )
+ for(unsigned int row = 0u; row < gridHeight; ++row)
{
- unsigned int rowStartIndex = row*(gridWidth+1u);
- unsigned int nextRowStartIndex = rowStartIndex + gridWidth +1u;
+ unsigned int rowStartIndex = row * (gridWidth + 1u);
+ unsigned int nextRowStartIndex = rowStartIndex + gridWidth + 1u;
- if( row != 0u ) // degenerate index on non-first row
+ if(row != 0u) // degenerate index on non-first row
{
- indices.PushBack( rowStartIndex );
+ indices.PushBack(rowStartIndex);
}
- for( unsigned int column = 0u; column < gridWidth+1u; column++) // main strip
+ for(unsigned int column = 0u; column < gridWidth + 1u; column++) // main strip
{
- indices.PushBack( rowStartIndex + column);
- indices.PushBack( nextRowStartIndex + column);
+ indices.PushBack(rowStartIndex + column);
+ indices.PushBack(nextRowStartIndex + column);
}
- if( row != gridHeight-1u ) // degenerate index on non-last row
+ if(row != gridHeight - 1u) // degenerate index on non-last row
{
- indices.PushBack( nextRowStartIndex + gridWidth );
+ indices.PushBack(nextRowStartIndex + gridWidth);
}
}
Property::Map vertexFormat;
- vertexFormat[ "aPosition" ] = Property::VECTOR2;
- VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat );
- if( vertices.Size() > 0 )
+ vertexFormat["aPosition"] = Property::VECTOR2;
+ VertexBuffer vertexBuffer = VertexBuffer::New(vertexFormat);
+ if(vertices.Size() > 0)
{
- vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() );
+ vertexBuffer.SetData(&vertices[0], vertices.Size());
}
// Create the geometry object
Geometry geometry = Geometry::New();
- geometry.AddVertexBuffer( vertexBuffer );
- if( indices.Size() > 0 )
+ geometry.AddVertexBuffer(vertexBuffer);
+ if(indices.Size() > 0)
{
- geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
+ geometry.SetIndexBuffer(&indices[0], indices.Size());
}
- geometry.SetType( Geometry::TRIANGLE_STRIP );
+ geometry.SetType(Geometry::TRIANGLE_STRIP);
return geometry;
}
-Dali::Renderer CreateRenderer( std::string_view vertexSrc, std::string_view fragmentSrc )
+Dali::Renderer CreateRenderer(std::string_view vertexSrc, std::string_view fragmentSrc)
{
- Dali::Shader shader = Dali::Shader::New( vertexSrc, fragmentSrc );
+ Dali::Shader shader = Dali::Shader::New(vertexSrc, fragmentSrc);
Dali::Geometry texturedQuadGeometry = Dali::Geometry::New();
- struct VertexPosition { Dali::Vector2 position; };
- struct VertexTexture { Dali::Vector2 texture; };
-
- VertexPosition positionArray[] =
+ struct VertexPosition
+ {
+ Dali::Vector2 position;
+ };
+ struct VertexTexture
{
- { Dali::Vector2( -0.5f, -0.5f ) },
- { Dali::Vector2( 0.5f, -0.5f ) },
- { Dali::Vector2( -0.5f, 0.5f ) },
- { Dali::Vector2( 0.5f, 0.5f ) }
+ Dali::Vector2 texture;
};
- uint32_t numberOfVertices = sizeof(positionArray)/sizeof(VertexPosition);
+
+ VertexPosition positionArray[] =
+ {
+ {Dali::Vector2(-0.5f, -0.5f)},
+ {Dali::Vector2(0.5f, -0.5f)},
+ {Dali::Vector2(-0.5f, 0.5f)},
+ {Dali::Vector2(0.5f, 0.5f)}};
+ uint32_t numberOfVertices = sizeof(positionArray) / sizeof(VertexPosition);
Dali::Property::Map positionVertexFormat;
- positionVertexFormat["aPosition"] = Dali::Property::VECTOR2;
- Dali::VertexBuffer positionVertices = Dali::VertexBuffer::New( positionVertexFormat );
- positionVertices.SetData( positionArray, numberOfVertices );
- texturedQuadGeometry.AddVertexBuffer( positionVertices );
+ positionVertexFormat["aPosition"] = Dali::Property::VECTOR2;
+ Dali::VertexBuffer positionVertices = Dali::VertexBuffer::New(positionVertexFormat);
+ positionVertices.SetData(positionArray, numberOfVertices);
+ texturedQuadGeometry.AddVertexBuffer(positionVertices);
- const uint16_t indices[] = { 0, 3, 1, 0, 2, 3 };
- texturedQuadGeometry.SetIndexBuffer ( &indices[0], sizeof( indices )/ sizeof( indices[0] ) );
+ const uint16_t indices[] = {0, 3, 1, 0, 2, 3};
+ texturedQuadGeometry.SetIndexBuffer(&indices[0], sizeof(indices) / sizeof(indices[0]));
- Dali::Renderer renderer = Dali::Renderer::New( texturedQuadGeometry, shader );
+ Dali::Renderer renderer = Dali::Renderer::New(texturedQuadGeometry, shader);
Dali::TextureSet textureSet = Dali::TextureSet::New();
- renderer.SetTextures( textureSet );
+ renderer.SetTextures(textureSet);
return renderer;
}
-Dali::Renderer CreateRenderer( std::string_view vertexSrc, std::string_view fragmentSrc, Dali::Shader::Hint::Value hints, Uint16Pair gridSize )
+Dali::Renderer CreateRenderer(std::string_view vertexSrc, std::string_view fragmentSrc, Dali::Shader::Hint::Value hints, Uint16Pair gridSize)
{
- Dali::Shader shader = Dali::Shader::New( vertexSrc, fragmentSrc, hints );
+ Dali::Shader shader = Dali::Shader::New(vertexSrc, fragmentSrc, hints);
- Dali::Geometry gridGeometry = CreateGridGeometry( gridSize );
+ Dali::Geometry gridGeometry = CreateGridGeometry(gridSize);
- Dali::Renderer renderer = Dali::Renderer::New( gridGeometry, shader );
+ Dali::Renderer renderer = Dali::Renderer::New(gridGeometry, shader);
Dali::TextureSet textureSet = Dali::TextureSet::New();
- renderer.SetTextures( textureSet );
+ renderer.SetTextures(textureSet);
return renderer;
}
-void SetRendererTexture( Dali::Renderer renderer, Dali::Texture texture )
+void SetRendererTexture(Dali::Renderer renderer, Dali::Texture texture)
{
- if( renderer )
+ if(renderer)
{
Dali::TextureSet textureSet = renderer.GetTextures();
- textureSet.SetTexture( 0u, texture );
+ textureSet.SetTexture(0u, texture);
}
}
-void SetRendererTexture( Dali::Renderer renderer, Dali::FrameBuffer frameBuffer )
+void SetRendererTexture(Dali::Renderer renderer, Dali::FrameBuffer frameBuffer)
{
- if( frameBuffer )
+ if(frameBuffer)
{
Dali::Texture texture = frameBuffer.GetColorTexture();
- SetRendererTexture( renderer, texture );
+ SetRendererTexture(renderer, texture);
}
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "effects-view-impl.h"
// EXTERNAL INCLUDES
+#include <dali/devel-api/common/stage.h>
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/animation/constraints.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/public-api/object/property.h>
#include <dali/public-api/object/property-map.h>
-#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/object/property.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/render-tasks/render-task-list.h>
#include <dali/public-api/rendering/renderer.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/controls/control/control-renderers.h>
#include <dali-toolkit/internal/filters/blur-two-pass-filter.h>
#include <dali-toolkit/internal/filters/emboss-filter.h>
#include <dali-toolkit/internal/filters/spread-filter.h>
-#include <dali-toolkit/internal/controls/control/control-renderers.h>
-#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
Dali::BaseHandle Create()
{
return EffectsView::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::EffectsView, Toolkit::Control, Create )
-DALI_PROPERTY_REGISTRATION( Toolkit, EffectsView, "effectSize", INTEGER, EFFECT_SIZE )
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, EffectsView, "effectOffset", VECTOR3, EFFECT_OFFSET )
-DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT( Toolkit, EffectsView, "effectColor", Color::WHITE, EFFECT_COLOR )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::EffectsView, Toolkit::Control, Create)
+DALI_PROPERTY_REGISTRATION(Toolkit, EffectsView, "effectSize", INTEGER, EFFECT_SIZE)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, EffectsView, "effectOffset", VECTOR3, EFFECT_OFFSET)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT(Toolkit, EffectsView, "effectColor", Color::WHITE, EFFECT_COLOR)
DALI_TYPE_REGISTRATION_END()
const Pixel::Format EFFECTS_VIEW_DEFAULT_PIXEL_FORMAT = Pixel::RGBA8888;
-const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f;
-const Vector4 EFFECTS_VIEW_DEFAULT_BACKGROUND_COLOR( 0.0f, 0.0f, 0.0f, 0.0 );
+const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f;
+const Vector4 EFFECTS_VIEW_DEFAULT_BACKGROUND_COLOR(0.0f, 0.0f, 0.0f, 0.0);
const bool EFFECTS_VIEW_REFRESH_ON_DEMAND(false);
-const float BLUR_KERNEL0[] = { 12.0f/16.0f,
- 2.0f/16.0f, 2.0f/16.0f };
-
-const float BLUR_KERNEL1[] = { 8.0f/16.0f,
- 4.0f/16.0f, 4.0f/16.0f };
-
-const float BLUR_KERNEL2[] = { 6.0f/16.0f,
- 2.5f/16.0f, 2.5f/16.0f,
- 1.5f/16.0f, 1.5f/16.0f,
- 1.0f/16.0f, 1.0f/16.0f };
-
-const float BLUR_KERNEL3[] = { 4.0f/16.0f,
- 3.0f/16.0f, 2.0f/16.0f,
- 2.0f/16.0f, 2.0f/16.0f,
- 1.0f/16.0f, 1.0f/16.0f };
-
-const float BLUR_KERNEL4[] = { 3.0f/16.0f,
- 2.5f/16.0f, 2.5f/16.0f,
- 1.75f/16.0f, 1.75f/16.0f,
- 1.25f/16.0f, 1.25f/16.0f,
- 1.0f/16.0f, 1.0f/16.0f };
-
+// clang-format off
+const float BLUR_KERNEL0[] = {12.0f/16.0f,
+ 2.0f/16.0f, 2.0f/16.0f};
+
+const float BLUR_KERNEL1[] = {8.0f/16.0f,
+ 4.0f/16.0f, 4.0f/16.0f };
+
+const float BLUR_KERNEL2[] = {6.0f/16.0f,
+ 2.5f/16.0f, 2.5f/16.0f,
+ 1.5f/16.0f, 1.5f/16.0f,
+ 1.0f/16.0f, 1.0f/16.0f};
+
+const float BLUR_KERNEL3[] = {4.0f/16.0f,
+ 3.0f/16.0f, 2.0f/16.0f,
+ 2.0f/16.0f, 2.0f/16.0f,
+ 1.0f/16.0f, 1.0f/16.0f};
+
+const float BLUR_KERNEL4[] = {3.0f/16.0f,
+ 2.5f/16.0f, 2.5f/16.0f,
+ 1.75f/16.0f, 1.75f/16.0f,
+ 1.25f/16.0f, 1.25f/16.0f,
+ 1.0f/16.0f, 1.0f/16.0f};
+// clang-format on
} // namespace
Toolkit::EffectsView EffectsView::New()
{
EffectsView* effectsView = new EffectsView;
- Toolkit::EffectsView handle = Toolkit::EffectsView( *effectsView );
+ Toolkit::EffectsView handle = Toolkit::EffectsView(*effectsView);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
}
EffectsView::EffectsView()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mChildrenRoot(Actor::New()),
- mBackgroundColor( EFFECTS_VIEW_DEFAULT_BACKGROUND_COLOR ),
- mTargetSize( Vector2::ZERO ),
- mLastSize( Vector2::ZERO ),
+ mBackgroundColor(EFFECTS_VIEW_DEFAULT_BACKGROUND_COLOR),
+ mTargetSize(Vector2::ZERO),
+ mLastSize(Vector2::ZERO),
mEffectSize(0),
- mEffectType( Toolkit::EffectsView::INVALID_TYPE ),
- mPixelFormat( EFFECTS_VIEW_DEFAULT_PIXEL_FORMAT ),
- mEnabled( false ),
- mRefreshOnDemand( EFFECTS_VIEW_REFRESH_ON_DEMAND )
+ mEffectType(Toolkit::EffectsView::INVALID_TYPE),
+ mPixelFormat(EFFECTS_VIEW_DEFAULT_PIXEL_FORMAT),
+ mEnabled(false),
+ mRefreshOnDemand(EFFECTS_VIEW_REFRESH_ON_DEMAND)
{
}
RemoveFilters();
}
-void EffectsView::SetType( Toolkit::EffectsView::EffectType type )
+void EffectsView::SetType(Toolkit::EffectsView::EffectType type)
{
- if( mEffectType != type )
+ if(mEffectType != type)
{
RemoveFilters();
Actor self = Self();
- switch( type )
+ switch(type)
{
case Toolkit::EffectsView::DROP_SHADOW:
{
- mFilters.PushBack( new SpreadFilter );
- mFilters.PushBack( new BlurTwoPassFilter );
+ mFilters.PushBack(new SpreadFilter);
+ mFilters.PushBack(new BlurTwoPassFilter);
break;
}
case Toolkit::EffectsView::EMBOSS:
{
- mFilters.PushBack( new SpreadFilter );
- mFilters.PushBack( new EmbossFilter );
- mFilters.PushBack( new BlurTwoPassFilter );
+ mFilters.PushBack(new SpreadFilter);
+ mFilters.PushBack(new EmbossFilter);
+ mFilters.PushBack(new BlurTwoPassFilter);
break;
}
default:
// stop render tasks processing
RemoveRenderTasks();
mLastSize = Vector2::ZERO; // Ensure resources are reallocated on subsequent enable
- mEnabled = false;
+ mEnabled = false;
}
void EffectsView::Refresh()
RefreshRenderTasks();
}
-void EffectsView::SetRefreshOnDemand( bool onDemand )
+void EffectsView::SetRefreshOnDemand(bool onDemand)
{
mRefreshOnDemand = onDemand;
RefreshRenderTasks();
}
-void EffectsView::SetPixelFormat( Pixel::Format pixelFormat )
+void EffectsView::SetPixelFormat(Pixel::Format pixelFormat)
{
mPixelFormat = pixelFormat;
}
-void EffectsView::SetBackgroundColor( const Vector4& color )
+void EffectsView::SetBackgroundColor(const Vector4& color)
{
mBackgroundColor = color;
}
return mBackgroundColor;
}
-void EffectsView::SetEffectSize( int effectSize )
+void EffectsView::SetEffectSize(int effectSize)
{
mEffectSize = effectSize;
- if( mEnabled )
+ if(mEnabled)
{
- const size_t numFilters( mFilters.Size() );
- for( size_t i = 0; i < numFilters; ++i )
+ const size_t numFilters(mFilters.Size());
+ for(size_t i = 0; i < numFilters; ++i)
{
mFilters[i]->Disable();
}
SetupFilters();
- for( size_t i = 0; i < numFilters; ++i )
+ for(size_t i = 0; i < numFilters; ++i)
{
mFilters[i]->Enable();
}
void EffectsView::OnInitialize()
{
CustomActor self = Self();
- mChildrenRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- self.Add( mChildrenRoot );
+ mChildrenRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ self.Add(mChildrenRoot);
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER));
+ });
}
void EffectsView::OnSizeSet(const Vector3& targetSize)
// if we are already on stage, need to update render target sizes now to reflect the new size of this actor
if(mEnabled)
{
- if( mLastSize != Vector2::ZERO )
+ if(mLastSize != Vector2::ZERO)
{
Disable();
}
Enable();
}
- mChildrenRoot.SetProperty( Actor::Property::SIZE, targetSize );
+ mChildrenRoot.SetProperty(Actor::Property::SIZE, targetSize);
- Control::OnSizeSet( targetSize );
+ Control::OnSizeSet(targetSize);
}
-void EffectsView::OnSceneConnection( int depth )
+void EffectsView::OnSceneConnection(int depth)
{
- Actor self( Self() );
+ Actor self(Self());
// Create renderers
- mRendererPostFilter = CreateRenderer( SHADER_EFFECTS_VIEW_VERT,
- SHADER_EFFECTS_VIEW_FRAG );
- mRendererPostFilter.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT );
- self.AddRenderer( mRendererPostFilter );
+ mRendererPostFilter = CreateRenderer(SHADER_EFFECTS_VIEW_VERT,
+ SHADER_EFFECTS_VIEW_FRAG);
+ mRendererPostFilter.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT);
+ self.AddRenderer(mRendererPostFilter);
- mRendererForChildren = CreateRenderer( BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE );
- mRendererForChildren.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + 1 );
- self.AddRenderer( mRendererForChildren );
+ mRendererForChildren = CreateRenderer(BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE);
+ mRendererForChildren.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + 1);
+ self.AddRenderer(mRendererForChildren);
Enable();
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
}
void EffectsView::OnSceneDisconnection()
{
- Actor self( Self() );
+ Actor self(Self());
Disable();
- const size_t numFilters( mFilters.Size() );
- for( size_t i = 0; i < numFilters; ++i )
+ const size_t numFilters(mFilters.Size());
+ for(size_t i = 0; i < numFilters; ++i)
{
mFilters[i]->Disable();
}
// Remove renderers
- self.RemoveRenderer( mRendererForChildren );
+ self.RemoveRenderer(mRendererForChildren);
mRendererForChildren.Reset();
- self.RemoveRenderer( mRendererPostFilter );
+ self.RemoveRenderer(mRendererPostFilter);
mRendererPostFilter.Reset();
Control::OnSceneDisconnection();
}
-void EffectsView::OnChildAdd( Actor& child )
+void EffectsView::OnChildAdd(Actor& child)
{
- if( child != mChildrenRoot && child != mCameraForChildren )
+ if(child != mChildrenRoot && child != mCameraForChildren)
{
- mChildrenRoot.Add( child );
+ mChildrenRoot.Add(child);
}
- Control::OnChildAdd( child );
+ Control::OnChildAdd(child);
}
-void EffectsView::OnChildRemove( Actor& child )
+void EffectsView::OnChildRemove(Actor& child)
{
- mChildrenRoot.Remove( child );
+ mChildrenRoot.Remove(child);
- Control::OnChildRemove( child );
+ Control::OnChildRemove(child);
}
void EffectsView::SetupFilters()
{
- switch( mEffectType )
+ switch(mEffectType)
{
case Toolkit::EffectsView::DROP_SHADOW:
{
- SpreadFilter* spreadFilter = static_cast< SpreadFilter* >( mFilters[0] );
- spreadFilter->SetInputTexture( mFrameBufferForChildren.GetColorTexture() );
- spreadFilter->SetOutputFrameBuffer( mFrameBufferPostFilter );
- spreadFilter->SetRootActor( mChildrenRoot );
- spreadFilter->SetBackgroundColor( mBackgroundColor );
- spreadFilter->SetPixelFormat( mPixelFormat );
- spreadFilter->SetSize( mTargetSize );
- spreadFilter->SetSpread( mEffectSize );
-
- BlurTwoPassFilter* blurFilter = static_cast< BlurTwoPassFilter* >( mFilters[1] );
- blurFilter->SetInputTexture( mFrameBufferPostFilter.GetColorTexture() );
- blurFilter->SetOutputFrameBuffer( mFrameBufferPostFilter );
- blurFilter->SetRootActor( mChildrenRoot );
- blurFilter->SetBackgroundColor( mBackgroundColor );
- blurFilter->SetPixelFormat( mPixelFormat );
- blurFilter->SetSize( mTargetSize );
+ SpreadFilter* spreadFilter = static_cast<SpreadFilter*>(mFilters[0]);
+ spreadFilter->SetInputTexture(mFrameBufferForChildren.GetColorTexture());
+ spreadFilter->SetOutputFrameBuffer(mFrameBufferPostFilter);
+ spreadFilter->SetRootActor(mChildrenRoot);
+ spreadFilter->SetBackgroundColor(mBackgroundColor);
+ spreadFilter->SetPixelFormat(mPixelFormat);
+ spreadFilter->SetSize(mTargetSize);
+ spreadFilter->SetSpread(mEffectSize);
+
+ BlurTwoPassFilter* blurFilter = static_cast<BlurTwoPassFilter*>(mFilters[1]);
+ blurFilter->SetInputTexture(mFrameBufferPostFilter.GetColorTexture());
+ blurFilter->SetOutputFrameBuffer(mFrameBufferPostFilter);
+ blurFilter->SetRootActor(mChildrenRoot);
+ blurFilter->SetBackgroundColor(mBackgroundColor);
+ blurFilter->SetPixelFormat(mPixelFormat);
+ blurFilter->SetSize(mTargetSize);
const float* kernel(NULL);
- size_t kernelSize(0);
- switch( mEffectSize )
+ size_t kernelSize(0);
+ switch(mEffectSize)
{
- case 4: { kernel = BLUR_KERNEL4; kernelSize = sizeof(BLUR_KERNEL4)/sizeof(BLUR_KERNEL4[0]); break; }
- case 3: { kernel = BLUR_KERNEL3; kernelSize = sizeof(BLUR_KERNEL3)/sizeof(BLUR_KERNEL3[0]); break; }
- case 2: { kernel = BLUR_KERNEL2; kernelSize = sizeof(BLUR_KERNEL2)/sizeof(BLUR_KERNEL2[0]); break; }
- case 1: { kernel = BLUR_KERNEL1; kernelSize = sizeof(BLUR_KERNEL1)/sizeof(BLUR_KERNEL1[0]); break; }
+ case 4:
+ {
+ kernel = BLUR_KERNEL4;
+ kernelSize = sizeof(BLUR_KERNEL4) / sizeof(BLUR_KERNEL4[0]);
+ break;
+ }
+ case 3:
+ {
+ kernel = BLUR_KERNEL3;
+ kernelSize = sizeof(BLUR_KERNEL3) / sizeof(BLUR_KERNEL3[0]);
+ break;
+ }
+ case 2:
+ {
+ kernel = BLUR_KERNEL2;
+ kernelSize = sizeof(BLUR_KERNEL2) / sizeof(BLUR_KERNEL2[0]);
+ break;
+ }
+ case 1:
+ {
+ kernel = BLUR_KERNEL1;
+ kernelSize = sizeof(BLUR_KERNEL1) / sizeof(BLUR_KERNEL1[0]);
+ break;
+ }
case 0:
- default: { kernel = BLUR_KERNEL0; kernelSize = sizeof(BLUR_KERNEL0)/sizeof(BLUR_KERNEL0[0]); break; }
+ default:
+ {
+ kernel = BLUR_KERNEL0;
+ kernelSize = sizeof(BLUR_KERNEL0) / sizeof(BLUR_KERNEL0[0]);
+ break;
+ }
}
- blurFilter->CreateKernel( kernel, kernelSize );
+ blurFilter->CreateKernel(kernel, kernelSize);
break;
}
case Toolkit::EffectsView::EMBOSS:
{
- SpreadFilter* spreadFilter = static_cast< SpreadFilter* >( mFilters[0] );
- spreadFilter->SetInputTexture( mFrameBufferForChildren.GetColorTexture() );
- spreadFilter->SetOutputFrameBuffer( mFrameBufferPostFilter );
- spreadFilter->SetRootActor( mChildrenRoot );
- spreadFilter->SetBackgroundColor( mBackgroundColor );
- spreadFilter->SetPixelFormat( Pixel::RGBA8888 );
- spreadFilter->SetSize( mTargetSize );
- spreadFilter->SetSpread( mEffectSize );
-
- EmbossFilter* embossFilter = static_cast< EmbossFilter* >( mFilters[1] );
- embossFilter->SetInputTexture( mFrameBufferPostFilter.GetColorTexture() );
- embossFilter->SetOutputFrameBuffer( mFrameBufferPostFilter );
- embossFilter->SetRootActor( mChildrenRoot );
- embossFilter->SetBackgroundColor( mBackgroundColor );
- embossFilter->SetPixelFormat( Pixel::RGBA8888 );
- embossFilter->SetSize( mTargetSize );
-
- BlurTwoPassFilter* blurFilter = static_cast< BlurTwoPassFilter* >( mFilters[2] );
- blurFilter->SetInputTexture( mFrameBufferPostFilter.GetColorTexture() );
- blurFilter->SetOutputFrameBuffer( mFrameBufferPostFilter );
- blurFilter->SetRootActor( mChildrenRoot );
- blurFilter->SetBackgroundColor( Vector4( 0.5f, 0.5f, 0.5f, 0.0 ) );
- blurFilter->SetPixelFormat( Pixel::RGBA8888 );
- blurFilter->SetSize( mTargetSize );
- blurFilter->CreateKernel( BLUR_KERNEL0, sizeof(BLUR_KERNEL0)/sizeof(BLUR_KERNEL0[0]) );
+ SpreadFilter* spreadFilter = static_cast<SpreadFilter*>(mFilters[0]);
+ spreadFilter->SetInputTexture(mFrameBufferForChildren.GetColorTexture());
+ spreadFilter->SetOutputFrameBuffer(mFrameBufferPostFilter);
+ spreadFilter->SetRootActor(mChildrenRoot);
+ spreadFilter->SetBackgroundColor(mBackgroundColor);
+ spreadFilter->SetPixelFormat(Pixel::RGBA8888);
+ spreadFilter->SetSize(mTargetSize);
+ spreadFilter->SetSpread(mEffectSize);
+
+ EmbossFilter* embossFilter = static_cast<EmbossFilter*>(mFilters[1]);
+ embossFilter->SetInputTexture(mFrameBufferPostFilter.GetColorTexture());
+ embossFilter->SetOutputFrameBuffer(mFrameBufferPostFilter);
+ embossFilter->SetRootActor(mChildrenRoot);
+ embossFilter->SetBackgroundColor(mBackgroundColor);
+ embossFilter->SetPixelFormat(Pixel::RGBA8888);
+ embossFilter->SetSize(mTargetSize);
+
+ BlurTwoPassFilter* blurFilter = static_cast<BlurTwoPassFilter*>(mFilters[2]);
+ blurFilter->SetInputTexture(mFrameBufferPostFilter.GetColorTexture());
+ blurFilter->SetOutputFrameBuffer(mFrameBufferPostFilter);
+ blurFilter->SetRootActor(mChildrenRoot);
+ blurFilter->SetBackgroundColor(Vector4(0.5f, 0.5f, 0.5f, 0.0));
+ blurFilter->SetPixelFormat(Pixel::RGBA8888);
+ blurFilter->SetSize(mTargetSize);
+ blurFilter->CreateKernel(BLUR_KERNEL0, sizeof(BLUR_KERNEL0) / sizeof(BLUR_KERNEL0[0]));
break;
}
mLastSize = mTargetSize;
SetupCameras();
- Actor self( Self() );
+ Actor self(Self());
- mFrameBufferForChildren = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture textureForChildren = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mFrameBufferForChildren.AttachColorTexture( textureForChildren );
+ mFrameBufferForChildren = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture textureForChildren = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mFrameBufferForChildren.AttachColorTexture(textureForChildren);
- SetRendererTexture( mRendererForChildren, textureForChildren );
+ SetRendererTexture(mRendererForChildren, textureForChildren);
- mFrameBufferPostFilter = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture texturePostFilter = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mFrameBufferPostFilter.AttachColorTexture( texturePostFilter );
+ mFrameBufferPostFilter = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture texturePostFilter = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mFrameBufferPostFilter.AttachColorTexture(texturePostFilter);
- SetRendererTexture( mRendererPostFilter, texturePostFilter );
+ SetRendererTexture(mRendererPostFilter, texturePostFilter);
SetupFilters();
}
void EffectsView::SetupCameras()
{
- if( !mCameraForChildren )
+ if(!mCameraForChildren)
{
// Create a camera for the children render, corresponding to its render target size
mCameraForChildren = CameraActor::New(mTargetSize);
- mCameraForChildren.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- mCameraForChildren.SetInvertYAxis( true );
- Self().Add( mCameraForChildren );
+ mCameraForChildren.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mCameraForChildren.SetInvertYAxis(true);
+ Self().Add(mCameraForChildren);
}
else
{
// place the camera for the children render, corresponding to its render target size
- const float cameraPosScale( 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f) );
+ const float cameraPosScale(0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f));
mCameraForChildren.SetFieldOfView(ARBITRARY_FIELD_OF_VIEW);
mCameraForChildren.SetNearClippingPlane(1.0f);
mCameraForChildren.SetAspectRatio(mTargetSize.width / mTargetSize.height);
mCameraForChildren.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
- mCameraForChildren.SetProperty( Actor::Property::POSITION, Vector3( 0.0f, 0.0f, mTargetSize.height * cameraPosScale ) );
- mCameraForChildren.SetProperty( Actor::Property::POSITION_Z, mTargetSize.height * cameraPosScale );
+ mCameraForChildren.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, mTargetSize.height * cameraPosScale));
+ mCameraForChildren.SetProperty(Actor::Property::POSITION_Z, mTargetSize.height * cameraPosScale);
}
}
void EffectsView::CreateRenderTasks()
{
- if( mTargetSize == Vector2::ZERO )
+ if(mTargetSize == Vector2::ZERO)
{
return;
}
// create render task to render our child actors to offscreen buffer
mRenderTaskForChildren = taskList.CreateTask();
- mRenderTaskForChildren.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForChildren.SetSourceActor( mChildrenRoot );
+ mRenderTaskForChildren.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForChildren.SetSourceActor(mChildrenRoot);
mRenderTaskForChildren.SetExclusive(true);
- mRenderTaskForChildren.SetInputEnabled( false );
- mRenderTaskForChildren.SetClearColor( mBackgroundColor );
- mRenderTaskForChildren.SetClearEnabled( true );
- mRenderTaskForChildren.SetFrameBuffer( mFrameBufferForChildren );
+ mRenderTaskForChildren.SetInputEnabled(false);
+ mRenderTaskForChildren.SetClearColor(mBackgroundColor);
+ mRenderTaskForChildren.SetClearEnabled(true);
+ mRenderTaskForChildren.SetFrameBuffer(mFrameBufferForChildren);
mRenderTaskForChildren.SetCameraActor(mCameraForChildren); // use camera that covers render target exactly
// Enable image filters
- const size_t numFilters( mFilters.Size() );
- for( size_t i = 0; i < numFilters; ++i )
+ const size_t numFilters(mFilters.Size());
+ for(size_t i = 0; i < numFilters; ++i)
{
mFilters[i]->Enable();
}
void EffectsView::RemoveRenderTasks()
{
- if( mTargetSize == Vector2::ZERO )
+ if(mTargetSize == Vector2::ZERO)
{
return;
}
taskList.RemoveTask(mRenderTaskForChildren);
- const size_t numFilters( mFilters.Size() );
- for( size_t i = 0; i < numFilters; ++i )
+ const size_t numFilters(mFilters.Size());
+ for(size_t i = 0; i < numFilters; ++i)
{
mFilters[i]->Disable();
}
{
RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
- if( mRenderTaskForChildren )
+ if(mRenderTaskForChildren)
{
- mRenderTaskForChildren.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
+ mRenderTaskForChildren.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
}
- const size_t numFilters( mFilters.Size() );
- for( size_t i = 0; i < numFilters; ++i )
+ const size_t numFilters(mFilters.Size());
+ for(size_t i = 0; i < numFilters; ++i)
{
mFilters[i]->Refresh();
}
void EffectsView::RemoveFilters()
{
- const size_t numFilters( mFilters.Size() );
- for( size_t i = 0; i < numFilters; ++i )
+ const size_t numFilters(mFilters.Size());
+ for(size_t i = 0; i < numFilters; ++i)
{
delete mFilters[i];
}
mFilters.Release();
}
-void EffectsView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void EffectsView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::EffectsView effectsView = Toolkit::EffectsView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::EffectsView effectsView = Toolkit::EffectsView::DownCast(Dali::BaseHandle(object));
- if ( effectsView )
+ if(effectsView)
{
- switch ( index )
+ switch(index)
{
case Toolkit::EffectsView::Property::EFFECT_SIZE:
{
int effectSize;
- if( value.Get( effectSize ) )
+ if(value.Get(effectSize))
{
- GetImpl( effectsView ).SetEffectSize( effectSize );
+ GetImpl(effectsView).SetEffectSize(effectSize);
}
break;
}
}
}
-Property::Value EffectsView::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value EffectsView::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::EffectsView imageview = Toolkit::EffectsView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::EffectsView imageview = Toolkit::EffectsView::DownCast(Dali::BaseHandle(object));
- if ( imageview )
+ if(imageview)
{
- EffectsView& impl = GetImpl( imageview );
- switch ( propertyIndex )
+ EffectsView& impl = GetImpl(imageview);
+ switch(propertyIndex)
{
case Toolkit::EffectsView::Property::EFFECT_SIZE:
{
- value = impl.GetEffectSize();
+ value = impl.GetEffectSize();
break;
}
default:
/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/flex-container/flex-container-impl.h>
// EXTERNAL INCLUDES
-#include <sstream>
-#include <dali/public-api/object/ref-object.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/devel-api/actors/actor-devel.h>
#include <dali/devel-api/scripting/scripting.h>
-#include <dali/public-api/size-negotiation/relayout-container.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/ref-object.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/size-negotiation/relayout-container.h>
+#include <sstream>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
namespace
{
-
#if defined(DEBUG_ENABLED)
// debugging support, very useful when new features are added or bugs are hunted down
// currently not called from code so compiler will optimize these away, kept here for future debugging
#define FLEX_CONTAINER_TAG "DALI Toolkit::FlexContainer "
-#define FC_LOG(fmt, args,...) Debug::LogMessage(Debug::DebugInfo, FLEX_CONTAINER_TAG fmt, ## args)
+#define FC_LOG(fmt, args, ...) Debug::LogMessage(Debug::DebugInfo, FLEX_CONTAINER_TAG fmt, ##args)
// #define FLEX_CONTAINER_DEBUG 1
#if defined(FLEX_CONTAINER_DEBUG)
-void PrintNodes( Toolkit::Internal::FlexContainer::FlexItemNodeContainer itemNodes )
+void PrintNodes(Toolkit::Internal::FlexContainer::FlexItemNodeContainer itemNodes)
{
// Print the style property and layout of all the children
- for( unsigned int i = 0; i < itemNodes.size(); ++i )
+ for(unsigned int i = 0; i < itemNodes.size(); ++i)
{
- FC_LOG( "Item %d style: \n", i );
- YGNodePrint( itemNodes[i].node, (YGPrintOptions)( YGPrintOptionsStyle | YGPrintOptionsChildren ) );
- FC_LOG( "\n" );
- FC_LOG( "Item %d layout: \n", i );
- YGNodePrint( itemNodes[i].node, (YGPrintOptions)( YGPrintOptionsLayout | YGPrintOptionsChildren ) );
- FC_LOG( "\n" );
+ FC_LOG("Item %d style: \n", i);
+ YGNodePrint(itemNodes[i].node, (YGPrintOptions)(YGPrintOptionsStyle | YGPrintOptionsChildren));
+ FC_LOG("\n");
+ FC_LOG("Item %d layout: \n", i);
+ YGNodePrint(itemNodes[i].node, (YGPrintOptions)(YGPrintOptionsLayout | YGPrintOptionsChildren));
+ FC_LOG("\n");
}
}
#endif // defined(FLEX_CONTAINER_DEBUG)
#endif // defined(DEBUG_ENABLED)
-
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// Type registration
BaseHandle Create()
{
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::FlexContainer, Toolkit::Control, Create );
-
-DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "contentDirection", INTEGER, CONTENT_DIRECTION )
-DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "flexDirection", INTEGER, FLEX_DIRECTION )
-DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "flexWrap", INTEGER, FLEX_WRAP )
-DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "justifyContent", INTEGER, JUSTIFY_CONTENT )
-DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "alignItems", INTEGER, ALIGN_ITEMS )
-DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "alignContent", INTEGER, ALIGN_CONTENT )
-DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "flex", FLOAT, FLEX )
-DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "alignSelf", INTEGER, ALIGN_SELF )
-DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "flexMargin", VECTOR4, FLEX_MARGIN )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::FlexContainer, Toolkit::Control, Create);
+
+DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "contentDirection", INTEGER, CONTENT_DIRECTION)
+DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "flexDirection", INTEGER, FLEX_DIRECTION)
+DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "flexWrap", INTEGER, FLEX_WRAP)
+DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "justifyContent", INTEGER, JUSTIFY_CONTENT)
+DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "alignItems", INTEGER, ALIGN_ITEMS)
+DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "alignContent", INTEGER, ALIGN_CONTENT)
+DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "flex", FLOAT, FLEX)
+DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "alignSelf", INTEGER, ALIGN_SELF)
+DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "flexMargin", VECTOR4, FLEX_MARGIN)
DALI_TYPE_REGISTRATION_END()
const Scripting::StringEnum ALIGN_SELF_STRING_TABLE[] =
-{
- { "auto", Toolkit::FlexContainer::ALIGN_AUTO },
- { "flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START },
- { "center", Toolkit::FlexContainer::ALIGN_CENTER },
- { "flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END },
- { "stretch", Toolkit::FlexContainer::ALIGN_STRETCH }
-};
-const unsigned int ALIGN_SELF_STRING_TABLE_COUNT = sizeof( ALIGN_SELF_STRING_TABLE ) / sizeof( ALIGN_SELF_STRING_TABLE[0] );
+ {
+ {"auto", Toolkit::FlexContainer::ALIGN_AUTO},
+ {"flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START},
+ {"center", Toolkit::FlexContainer::ALIGN_CENTER},
+ {"flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END},
+ {"stretch", Toolkit::FlexContainer::ALIGN_STRETCH}};
+const unsigned int ALIGN_SELF_STRING_TABLE_COUNT = sizeof(ALIGN_SELF_STRING_TABLE) / sizeof(ALIGN_SELF_STRING_TABLE[0]);
const Scripting::StringEnum CONTENT_DIRECTION_STRING_TABLE[] =
-{
- { "inherit", Toolkit::FlexContainer::INHERIT },
- { "LTR", Toolkit::FlexContainer::LTR },
- { "RTL", Toolkit::FlexContainer::RTL }
-};
-const unsigned int CONTENT_DIRECTION_STRING_TABLE_COUNT = sizeof( CONTENT_DIRECTION_STRING_TABLE ) / sizeof( CONTENT_DIRECTION_STRING_TABLE[0] );
+ {
+ {"inherit", Toolkit::FlexContainer::INHERIT},
+ {"LTR", Toolkit::FlexContainer::LTR},
+ {"RTL", Toolkit::FlexContainer::RTL}};
+const unsigned int CONTENT_DIRECTION_STRING_TABLE_COUNT = sizeof(CONTENT_DIRECTION_STRING_TABLE) / sizeof(CONTENT_DIRECTION_STRING_TABLE[0]);
const Scripting::StringEnum FLEX_DIRECTION_STRING_TABLE[] =
-{
- { "column", Toolkit::FlexContainer::COLUMN },
- { "columnReverse", Toolkit::FlexContainer::COLUMN_REVERSE },
- { "row", Toolkit::FlexContainer::ROW },
- { "rowReverse", Toolkit::FlexContainer::ROW_REVERSE }
-};
-const unsigned int FLEX_DIRECTION_STRING_TABLE_COUNT = sizeof( FLEX_DIRECTION_STRING_TABLE ) / sizeof( FLEX_DIRECTION_STRING_TABLE[0] );
+ {
+ {"column", Toolkit::FlexContainer::COLUMN},
+ {"columnReverse", Toolkit::FlexContainer::COLUMN_REVERSE},
+ {"row", Toolkit::FlexContainer::ROW},
+ {"rowReverse", Toolkit::FlexContainer::ROW_REVERSE}};
+const unsigned int FLEX_DIRECTION_STRING_TABLE_COUNT = sizeof(FLEX_DIRECTION_STRING_TABLE) / sizeof(FLEX_DIRECTION_STRING_TABLE[0]);
const Scripting::StringEnum FLEX_WRAP_STRING_TABLE[] =
-{
- { "noWrap", Toolkit::FlexContainer::NO_WRAP },
- { "wrap", Toolkit::FlexContainer::WRAP }
-};
-const unsigned int FLEX_WRAP_STRING_TABLE_COUNT = sizeof( FLEX_WRAP_STRING_TABLE ) / sizeof( FLEX_WRAP_STRING_TABLE[0] );
+ {
+ {"noWrap", Toolkit::FlexContainer::NO_WRAP},
+ {"wrap", Toolkit::FlexContainer::WRAP}};
+const unsigned int FLEX_WRAP_STRING_TABLE_COUNT = sizeof(FLEX_WRAP_STRING_TABLE) / sizeof(FLEX_WRAP_STRING_TABLE[0]);
const Scripting::StringEnum JUSTIFY_CONTENT_STRING_TABLE[] =
-{
- { "flexStart", Toolkit::FlexContainer::JUSTIFY_FLEX_START },
- { "center", Toolkit::FlexContainer::JUSTIFY_CENTER },
- { "flexEnd", Toolkit::FlexContainer::JUSTIFY_FLEX_END },
- { "spaceBetween", Toolkit::FlexContainer::JUSTIFY_SPACE_BETWEEN },
- { "spaceAround", Toolkit::FlexContainer::JUSTIFY_SPACE_AROUND }
-};
-const unsigned int JUSTIFY_CONTENT_STRING_TABLE_COUNT = sizeof( JUSTIFY_CONTENT_STRING_TABLE ) / sizeof( JUSTIFY_CONTENT_STRING_TABLE[0] );
+ {
+ {"flexStart", Toolkit::FlexContainer::JUSTIFY_FLEX_START},
+ {"center", Toolkit::FlexContainer::JUSTIFY_CENTER},
+ {"flexEnd", Toolkit::FlexContainer::JUSTIFY_FLEX_END},
+ {"spaceBetween", Toolkit::FlexContainer::JUSTIFY_SPACE_BETWEEN},
+ {"spaceAround", Toolkit::FlexContainer::JUSTIFY_SPACE_AROUND}};
+const unsigned int JUSTIFY_CONTENT_STRING_TABLE_COUNT = sizeof(JUSTIFY_CONTENT_STRING_TABLE) / sizeof(JUSTIFY_CONTENT_STRING_TABLE[0]);
const Scripting::StringEnum ALIGN_ITEMS_STRING_TABLE[] =
-{
- { "flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START },
- { "center", Toolkit::FlexContainer::ALIGN_CENTER },
- { "flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END },
- { "stretch", Toolkit::FlexContainer::ALIGN_STRETCH }
-};
-const unsigned int ALIGN_ITEMS_STRING_TABLE_COUNT = sizeof( ALIGN_ITEMS_STRING_TABLE ) / sizeof( ALIGN_ITEMS_STRING_TABLE[0] );
+ {
+ {"flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START},
+ {"center", Toolkit::FlexContainer::ALIGN_CENTER},
+ {"flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END},
+ {"stretch", Toolkit::FlexContainer::ALIGN_STRETCH}};
+const unsigned int ALIGN_ITEMS_STRING_TABLE_COUNT = sizeof(ALIGN_ITEMS_STRING_TABLE) / sizeof(ALIGN_ITEMS_STRING_TABLE[0]);
const Scripting::StringEnum ALIGN_CONTENT_STRING_TABLE[] =
-{
- { "flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START },
- { "center", Toolkit::FlexContainer::ALIGN_CENTER },
- { "flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END },
- { "stretch", Toolkit::FlexContainer::ALIGN_STRETCH }
-};
-const unsigned int ALIGN_CONTENT_STRING_TABLE_COUNT = sizeof( ALIGN_CONTENT_STRING_TABLE ) / sizeof( ALIGN_CONTENT_STRING_TABLE[0] );
+ {
+ {"flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START},
+ {"center", Toolkit::FlexContainer::ALIGN_CENTER},
+ {"flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END},
+ {"stretch", Toolkit::FlexContainer::ALIGN_STRETCH}};
+const unsigned int ALIGN_CONTENT_STRING_TABLE_COUNT = sizeof(ALIGN_CONTENT_STRING_TABLE) / sizeof(ALIGN_CONTENT_STRING_TABLE[0]);
} // Unnamed namespace
Toolkit::FlexContainer FlexContainer::New()
{
// Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< FlexContainer > impl = new FlexContainer();
+ IntrusivePtr<FlexContainer> impl = new FlexContainer();
// Pass ownership to CustomActor handle
- Toolkit::FlexContainer handle( *impl );
+ Toolkit::FlexContainer handle(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
FlexContainer::~FlexContainer()
{
- YGNodeFree( mRootNode.node );
+ YGNodeFree(mRootNode.node);
- for( unsigned int i = 0; i < mChildrenNodes.size(); i++ )
+ for(unsigned int i = 0; i < mChildrenNodes.size(); i++)
{
- YGNodeFree( mChildrenNodes[i].node );
+ YGNodeFree(mChildrenNodes[i].node);
}
mChildrenNodes.clear();
}
-void FlexContainer::SetContentDirection( Toolkit::FlexContainer::ContentDirection contentDirection)
+void FlexContainer::SetContentDirection(Toolkit::FlexContainer::ContentDirection contentDirection)
{
- if( mContentDirection != contentDirection )
+ if(mContentDirection != contentDirection)
{
Dali::CustomActor ownerActor(GetOwner());
- if( Toolkit::FlexContainer::INHERIT != contentDirection )
+ if(Toolkit::FlexContainer::INHERIT != contentDirection)
{
mContentDirection = contentDirection;
- ownerActor.SetProperty( Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION, false );
+ ownerActor.SetProperty(Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION, false);
- if( Toolkit::FlexContainer::LTR == contentDirection )
+ if(Toolkit::FlexContainer::LTR == contentDirection)
{
ownerActor.SetProperty(Dali::Actor::Property::LAYOUT_DIRECTION, Dali::LayoutDirection::LEFT_TO_RIGHT);
}
}
else
{
- ownerActor.SetProperty( Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION, true );
+ ownerActor.SetProperty(Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION, true);
- Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>( ownerActor.GetParent().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(ownerActor.GetParent().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
- if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
+ if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
{
mContentDirection = Toolkit::FlexContainer::RTL;
}
return mContentDirection;
}
-void FlexContainer::SetFlexDirection( Toolkit::FlexContainer::FlexDirection flexDirection )
+void FlexContainer::SetFlexDirection(Toolkit::FlexContainer::FlexDirection flexDirection)
{
- if( mFlexDirection != flexDirection )
+ if(mFlexDirection != flexDirection)
{
mFlexDirection = flexDirection;
- YGNodeStyleSetFlexDirection( mRootNode.node, static_cast<YGFlexDirection>( flexDirection ) );
+ YGNodeStyleSetFlexDirection(mRootNode.node, static_cast<YGFlexDirection>(flexDirection));
RelayoutRequest();
}
return mFlexDirection;
}
-void FlexContainer::SetFlexWrap( Toolkit::FlexContainer::WrapType flexWrap )
+void FlexContainer::SetFlexWrap(Toolkit::FlexContainer::WrapType flexWrap)
{
- if( mFlexWrap != flexWrap )
+ if(mFlexWrap != flexWrap)
{
mFlexWrap = flexWrap;
- YGNodeStyleSetFlexWrap( mRootNode.node, static_cast<YGWrap>( flexWrap ) );
+ YGNodeStyleSetFlexWrap(mRootNode.node, static_cast<YGWrap>(flexWrap));
RelayoutRequest();
}
return mFlexWrap;
}
-void FlexContainer::SetJustifyContent( Toolkit::FlexContainer::Justification justifyContent )
+void FlexContainer::SetJustifyContent(Toolkit::FlexContainer::Justification justifyContent)
{
- if( mJustifyContent != justifyContent )
+ if(mJustifyContent != justifyContent)
{
mJustifyContent = justifyContent;
- YGNodeStyleSetJustifyContent( mRootNode.node, static_cast<YGJustify>( justifyContent ) );
+ YGNodeStyleSetJustifyContent(mRootNode.node, static_cast<YGJustify>(justifyContent));
RelayoutRequest();
}
return mJustifyContent;
}
-void FlexContainer::SetAlignItems( Toolkit::FlexContainer::Alignment alignItems )
+void FlexContainer::SetAlignItems(Toolkit::FlexContainer::Alignment alignItems)
{
- if( mAlignItems != alignItems )
+ if(mAlignItems != alignItems)
{
mAlignItems = alignItems;
- YGNodeStyleSetAlignItems( mRootNode.node, static_cast<YGAlign>( alignItems ) );
+ YGNodeStyleSetAlignItems(mRootNode.node, static_cast<YGAlign>(alignItems));
RelayoutRequest();
}
return mAlignItems;
}
-void FlexContainer::SetAlignContent( Toolkit::FlexContainer::Alignment alignContent )
+void FlexContainer::SetAlignContent(Toolkit::FlexContainer::Alignment alignContent)
{
- if( mAlignContent != alignContent )
+ if(mAlignContent != alignContent)
{
mAlignContent = alignContent;
- YGNodeStyleSetAlignContent( mRootNode.node, static_cast<YGAlign>( alignContent ) );
+ YGNodeStyleSetAlignContent(mRootNode.node, static_cast<YGAlign>(alignContent));
RelayoutRequest();
}
return mAlignContent;
}
-void FlexContainer::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void FlexContainer::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast(Dali::BaseHandle(object));
- if( flexContainer )
+ if(flexContainer)
{
- FlexContainer& flexContainerImpl( GetImpl( flexContainer ) );
- switch( index )
+ FlexContainer& flexContainerImpl(GetImpl(flexContainer));
+ switch(index)
{
case Toolkit::FlexContainer::Property::CONTENT_DIRECTION:
{
- Toolkit::FlexContainer::ContentDirection contentDirection( Toolkit::FlexContainer::INHERIT );
+ Toolkit::FlexContainer::ContentDirection contentDirection(Toolkit::FlexContainer::INHERIT);
- if( value.GetType() == Property::INTEGER )
+ if(value.GetType() == Property::INTEGER)
{
- flexContainerImpl.SetContentDirection( static_cast<Toolkit::FlexContainer::ContentDirection>( value.Get< int >() ) );
+ flexContainerImpl.SetContentDirection(static_cast<Toolkit::FlexContainer::ContentDirection>(value.Get<int>()));
}
- else if( Scripting::GetEnumeration< Toolkit::FlexContainer::ContentDirection >( value.Get< std::string >().c_str(),
- CONTENT_DIRECTION_STRING_TABLE,
- CONTENT_DIRECTION_STRING_TABLE_COUNT,
- contentDirection ) )
+ else if(Scripting::GetEnumeration<Toolkit::FlexContainer::ContentDirection>(value.Get<std::string>().c_str(),
+ CONTENT_DIRECTION_STRING_TABLE,
+ CONTENT_DIRECTION_STRING_TABLE_COUNT,
+ contentDirection))
{
flexContainerImpl.SetContentDirection(contentDirection);
}
}
case Toolkit::FlexContainer::Property::FLEX_DIRECTION:
{
- Toolkit::FlexContainer::FlexDirection flexDirection( Toolkit::FlexContainer::COLUMN );
+ Toolkit::FlexContainer::FlexDirection flexDirection(Toolkit::FlexContainer::COLUMN);
- if( value.GetType() == Property::INTEGER )
+ if(value.GetType() == Property::INTEGER)
{
- flexContainerImpl.SetFlexDirection( static_cast<Toolkit::FlexContainer::FlexDirection>( value.Get< int >() ) );
+ flexContainerImpl.SetFlexDirection(static_cast<Toolkit::FlexContainer::FlexDirection>(value.Get<int>()));
}
- else if( Scripting::GetEnumeration< Toolkit::FlexContainer::FlexDirection >( value.Get< std::string >().c_str(),
- FLEX_DIRECTION_STRING_TABLE,
- FLEX_DIRECTION_STRING_TABLE_COUNT,
- flexDirection ) )
+ else if(Scripting::GetEnumeration<Toolkit::FlexContainer::FlexDirection>(value.Get<std::string>().c_str(),
+ FLEX_DIRECTION_STRING_TABLE,
+ FLEX_DIRECTION_STRING_TABLE_COUNT,
+ flexDirection))
{
flexContainerImpl.SetFlexDirection(flexDirection);
}
}
case Toolkit::FlexContainer::Property::FLEX_WRAP:
{
- Toolkit::FlexContainer::WrapType flexWrap( Toolkit::FlexContainer::NO_WRAP );
+ Toolkit::FlexContainer::WrapType flexWrap(Toolkit::FlexContainer::NO_WRAP);
- if( value.GetType() == Property::INTEGER )
+ if(value.GetType() == Property::INTEGER)
{
- flexContainerImpl.SetFlexWrap( static_cast<Toolkit::FlexContainer::WrapType>( value.Get< int >() ) );
+ flexContainerImpl.SetFlexWrap(static_cast<Toolkit::FlexContainer::WrapType>(value.Get<int>()));
}
- else if( Scripting::GetEnumeration< Toolkit::FlexContainer::WrapType >( value.Get< std::string >().c_str(),
- FLEX_WRAP_STRING_TABLE,
- FLEX_WRAP_STRING_TABLE_COUNT,
- flexWrap ) )
+ else if(Scripting::GetEnumeration<Toolkit::FlexContainer::WrapType>(value.Get<std::string>().c_str(),
+ FLEX_WRAP_STRING_TABLE,
+ FLEX_WRAP_STRING_TABLE_COUNT,
+ flexWrap))
{
flexContainerImpl.SetFlexWrap(flexWrap);
}
}
case Toolkit::FlexContainer::Property::JUSTIFY_CONTENT:
{
- Toolkit::FlexContainer::Justification justifyContent( Toolkit::FlexContainer::JUSTIFY_FLEX_START );
+ Toolkit::FlexContainer::Justification justifyContent(Toolkit::FlexContainer::JUSTIFY_FLEX_START);
- if( value.GetType() == Property::INTEGER )
+ if(value.GetType() == Property::INTEGER)
{
- flexContainerImpl.SetJustifyContent( static_cast<Toolkit::FlexContainer::Justification>( value.Get< int >() ) );
+ flexContainerImpl.SetJustifyContent(static_cast<Toolkit::FlexContainer::Justification>(value.Get<int>()));
}
- else if( Scripting::GetEnumeration< Toolkit::FlexContainer::Justification >( value.Get< std::string >().c_str(),
- JUSTIFY_CONTENT_STRING_TABLE,
- JUSTIFY_CONTENT_STRING_TABLE_COUNT,
- justifyContent ) )
+ else if(Scripting::GetEnumeration<Toolkit::FlexContainer::Justification>(value.Get<std::string>().c_str(),
+ JUSTIFY_CONTENT_STRING_TABLE,
+ JUSTIFY_CONTENT_STRING_TABLE_COUNT,
+ justifyContent))
{
flexContainerImpl.SetJustifyContent(justifyContent);
}
}
case Toolkit::FlexContainer::Property::ALIGN_ITEMS:
{
- Toolkit::FlexContainer::Alignment alignItems( Toolkit::FlexContainer::ALIGN_STRETCH );
+ Toolkit::FlexContainer::Alignment alignItems(Toolkit::FlexContainer::ALIGN_STRETCH);
- if( value.GetType() == Property::INTEGER )
+ if(value.GetType() == Property::INTEGER)
{
- flexContainerImpl.SetAlignItems( static_cast<Toolkit::FlexContainer::Alignment>( value.Get< int >() ) );
+ flexContainerImpl.SetAlignItems(static_cast<Toolkit::FlexContainer::Alignment>(value.Get<int>()));
}
- else if( Scripting::GetEnumeration< Toolkit::FlexContainer::Alignment >( value.Get< std::string >().c_str(),
- ALIGN_ITEMS_STRING_TABLE,
- ALIGN_ITEMS_STRING_TABLE_COUNT,
- alignItems ) )
+ else if(Scripting::GetEnumeration<Toolkit::FlexContainer::Alignment>(value.Get<std::string>().c_str(),
+ ALIGN_ITEMS_STRING_TABLE,
+ ALIGN_ITEMS_STRING_TABLE_COUNT,
+ alignItems))
{
flexContainerImpl.SetAlignItems(alignItems);
}
}
case Toolkit::FlexContainer::Property::ALIGN_CONTENT:
{
- Toolkit::FlexContainer::Alignment alignContent( Toolkit::FlexContainer::ALIGN_FLEX_START );
+ Toolkit::FlexContainer::Alignment alignContent(Toolkit::FlexContainer::ALIGN_FLEX_START);
- if( value.GetType() == Property::INTEGER )
+ if(value.GetType() == Property::INTEGER)
{
- flexContainerImpl.SetAlignContent( static_cast<Toolkit::FlexContainer::Alignment>( value.Get< int >() ) );
+ flexContainerImpl.SetAlignContent(static_cast<Toolkit::FlexContainer::Alignment>(value.Get<int>()));
}
- else if( Scripting::GetEnumeration< Toolkit::FlexContainer::Alignment >( value.Get< std::string >().c_str(),
- ALIGN_CONTENT_STRING_TABLE,
- ALIGN_CONTENT_STRING_TABLE_COUNT,
- alignContent ) )
+ else if(Scripting::GetEnumeration<Toolkit::FlexContainer::Alignment>(value.Get<std::string>().c_str(),
+ ALIGN_CONTENT_STRING_TABLE,
+ ALIGN_CONTENT_STRING_TABLE_COUNT,
+ alignContent))
{
flexContainerImpl.SetAlignContent(alignContent);
}
}
}
-Property::Value FlexContainer::GetProperty( BaseObject* object, Property::Index index )
+Property::Value FlexContainer::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast(Dali::BaseHandle(object));
- if( flexContainer )
+ if(flexContainer)
{
- FlexContainer& flexContainerImpl( GetImpl( flexContainer ) );
- switch( index )
+ FlexContainer& flexContainerImpl(GetImpl(flexContainer));
+ switch(index)
{
case Toolkit::FlexContainer::Property::CONTENT_DIRECTION:
{
return value;
}
-void FlexContainer::OnChildAdd( Actor& child )
+void FlexContainer::OnChildAdd(Actor& child)
{
// Create a new node for the child.
FlexItemNode childNode;
childNode.actor = child;
- childNode.node = YGNodeNew();
+ childNode.node = YGNodeNew();
- mChildrenNodes.push_back( childNode );
- YGNodeInsertChild( mRootNode.node, childNode.node, mChildrenNodes.size() - 1 );
+ mChildrenNodes.push_back(childNode);
+ YGNodeInsertChild(mRootNode.node, childNode.node, mChildrenNodes.size() - 1);
- Control::OnChildAdd( child );
+ Control::OnChildAdd(child);
}
-void FlexContainer::OnChildRemove( Actor& child )
+void FlexContainer::OnChildRemove(Actor& child)
{
- for( unsigned int i = 0; i < mChildrenNodes.size(); i++ )
+ for(unsigned int i = 0; i < mChildrenNodes.size(); i++)
{
- if( mChildrenNodes[i].actor.GetHandle() == child )
+ if(mChildrenNodes[i].actor.GetHandle() == child)
{
- YGNodeRemoveChild( mRootNode.node, mChildrenNodes[i].node );
- YGNodeFree( mChildrenNodes[i].node );
+ YGNodeRemoveChild(mRootNode.node, mChildrenNodes[i].node);
+ YGNodeFree(mChildrenNodes[i].node);
- mChildrenNodes.erase( mChildrenNodes.begin() + i );
+ mChildrenNodes.erase(mChildrenNodes.begin() + i);
// Relayout the container only if instances were found
RelayoutRequest();
}
}
- Control::OnChildRemove( child );
+ Control::OnChildRemove(child);
}
-void FlexContainer::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void FlexContainer::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- for( unsigned int i = 0; i < mChildrenNodes.size(); i++ )
+ for(unsigned int i = 0; i < mChildrenNodes.size(); i++)
{
Actor child = mChildrenNodes[i].actor.GetHandle();
- if( child )
+ if(child)
{
// Anchor actor to top left of the container
- if( child.GetProperty( Actor::Property::POSITION_USES_ANCHOR_POINT ).Get< bool >() )
+ if(child.GetProperty(Actor::Property::POSITION_USES_ANCHOR_POINT).Get<bool>())
{
- child.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
+ child.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
}
- child.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
+ child.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
- float negotiatedWidth = child.GetRelayoutSize(Dimension::WIDTH);
+ float negotiatedWidth = child.GetRelayoutSize(Dimension::WIDTH);
float negotiatedHeight = child.GetRelayoutSize(Dimension::HEIGHT);
- if( negotiatedWidth > 0 )
+ if(negotiatedWidth > 0)
{
- YGNodeStyleSetWidth( mChildrenNodes[i].node, negotiatedWidth );
+ YGNodeStyleSetWidth(mChildrenNodes[i].node, negotiatedWidth);
}
- if( negotiatedHeight > 0 )
+ if(negotiatedHeight > 0)
{
- YGNodeStyleSetHeight( mChildrenNodes[i].node, negotiatedHeight );
+ YGNodeStyleSetHeight(mChildrenNodes[i].node, negotiatedHeight);
}
}
}
// Relayout the container
RelayoutChildren();
#if defined(FLEX_CONTAINER_DEBUG)
- PrintNodes( mChildrenNodes );
+ PrintNodes(mChildrenNodes);
#endif
- for( unsigned int i = 0; i < mChildrenNodes.size(); i++ )
+ for(unsigned int i = 0; i < mChildrenNodes.size(); i++)
{
Actor child = mChildrenNodes[i].actor.GetHandle();
- if( child )
+ if(child)
{
- if( child.GetPropertyType( Toolkit::FlexContainer::ChildProperty::FLEX ) != Property::NONE )
+ if(child.GetPropertyType(Toolkit::FlexContainer::ChildProperty::FLEX) != Property::NONE)
{
// Only Set to USE_ASSIGNED_SIZE if the child actor is flexible.
- if( child.GetResizePolicy( Dimension::WIDTH ) != ResizePolicy::USE_ASSIGNED_SIZE )
+ if(child.GetResizePolicy(Dimension::WIDTH) != ResizePolicy::USE_ASSIGNED_SIZE)
{
- child.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH );
+ child.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH);
}
- if( child.GetResizePolicy( Dimension::HEIGHT ) != ResizePolicy::USE_ASSIGNED_SIZE )
+ if(child.GetResizePolicy(Dimension::HEIGHT) != ResizePolicy::USE_ASSIGNED_SIZE)
{
- child.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::HEIGHT );
+ child.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::HEIGHT);
}
}
- container.Add( child, Vector2(YGNodeLayoutGetWidth(mChildrenNodes[i].node), YGNodeLayoutGetHeight(mChildrenNodes[i].node) ) );
+ container.Add(child, Vector2(YGNodeLayoutGetWidth(mChildrenNodes[i].node), YGNodeLayoutGetHeight(mChildrenNodes[i].node)));
}
}
}
-bool FlexContainer::RelayoutDependentOnChildren( Dimension::Type dimension )
+bool FlexContainer::RelayoutDependentOnChildren(Dimension::Type dimension)
{
return true;
}
-void FlexContainer::OnSizeSet( const Vector3& size )
+void FlexContainer::OnSizeSet(const Vector3& size)
{
- if( mRootNode.node )
+ if(mRootNode.node)
{
Actor self = Self();
- YGNodeStyleSetWidth( mRootNode.node, size.x );
- YGNodeStyleSetHeight( mRootNode.node, size.y );
+ YGNodeStyleSetWidth(mRootNode.node, size.x);
+ YGNodeStyleSetHeight(mRootNode.node, size.y);
RelayoutRequest();
}
- Control::OnSizeSet( size );
+ Control::OnSizeSet(size);
}
-void FlexContainer::OnLayoutDirectionChanged( Dali::Actor actor, Dali::LayoutDirection::Type type )
+void FlexContainer::OnLayoutDirectionChanged(Dali::Actor actor, Dali::LayoutDirection::Type type)
{
- Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast(actor);
+ Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast(actor);
Toolkit::FlexContainer::ContentDirection direction;
- if( type == Dali::LayoutDirection::RIGHT_TO_LEFT )
+ if(type == Dali::LayoutDirection::RIGHT_TO_LEFT)
{
direction = Toolkit::FlexContainer::RTL;
}
direction = Toolkit::FlexContainer::LTR;
}
- Toolkit::Internal::FlexContainer &flexContainerImpl = GetImpl( flexContainer );
+ Toolkit::Internal::FlexContainer& flexContainerImpl = GetImpl(flexContainer);
- if( flexContainerImpl.mContentDirection != direction )
+ if(flexContainerImpl.mContentDirection != direction)
{
Dali::CustomActor ownerActor(flexContainerImpl.GetOwner());
flexContainerImpl.mContentDirection = direction;
void FlexContainer::ComputeLayout()
{
- if( mRootNode.node )
+ if(mRootNode.node)
{
- for( unsigned int i = 0; i < mChildrenNodes.size(); i++ )
+ for(unsigned int i = 0; i < mChildrenNodes.size(); i++)
{
- YGNodeRef childNode = mChildrenNodes[i].node;
- Actor childActor = mChildrenNodes[i].actor.GetHandle();
+ YGNodeRef childNode = mChildrenNodes[i].node;
+ Actor childActor = mChildrenNodes[i].actor.GetHandle();
// Intialize the style of the child.
- YGNodeStyleSetMinWidth( childNode, childActor.GetProperty< Vector2 >( Actor::Property::MINIMUM_SIZE ).x );
- YGNodeStyleSetMinHeight( childNode, childActor.GetProperty< Vector2 >( Actor::Property::MINIMUM_SIZE ).y );
- YGNodeStyleSetMaxWidth( childNode, childActor.GetProperty< Vector2 >( Actor::Property::MAXIMUM_SIZE ).x );
- YGNodeStyleSetMaxHeight( childNode, childActor.GetProperty< Vector2 >( Actor::Property::MAXIMUM_SIZE ).y );
+ YGNodeStyleSetMinWidth(childNode, childActor.GetProperty<Vector2>(Actor::Property::MINIMUM_SIZE).x);
+ YGNodeStyleSetMinHeight(childNode, childActor.GetProperty<Vector2>(Actor::Property::MINIMUM_SIZE).y);
+ YGNodeStyleSetMaxWidth(childNode, childActor.GetProperty<Vector2>(Actor::Property::MAXIMUM_SIZE).x);
+ YGNodeStyleSetMaxHeight(childNode, childActor.GetProperty<Vector2>(Actor::Property::MAXIMUM_SIZE).y);
// Check child properties on the child for how to layout it.
// These properties should be dynamically registered to the child which
// would be added to FlexContainer.
- if( childActor.GetPropertyType( Toolkit::FlexContainer::ChildProperty::FLEX ) != Property::NONE )
+ if(childActor.GetPropertyType(Toolkit::FlexContainer::ChildProperty::FLEX) != Property::NONE)
{
- YGNodeStyleSetFlex( childNode, childActor.GetProperty( Toolkit::FlexContainer::ChildProperty::FLEX ).Get<float>() );
+ YGNodeStyleSetFlex(childNode, childActor.GetProperty(Toolkit::FlexContainer::ChildProperty::FLEX).Get<float>());
}
- Toolkit::FlexContainer::Alignment alignSelf( Toolkit::FlexContainer::ALIGN_AUTO );
- if( childActor.GetPropertyType( Toolkit::FlexContainer::ChildProperty::ALIGN_SELF ) != Property::NONE )
+ Toolkit::FlexContainer::Alignment alignSelf(Toolkit::FlexContainer::ALIGN_AUTO);
+ if(childActor.GetPropertyType(Toolkit::FlexContainer::ChildProperty::ALIGN_SELF) != Property::NONE)
{
- Property::Value alignSelfPropertyValue = childActor.GetProperty( Toolkit::FlexContainer::ChildProperty::ALIGN_SELF );
- if( alignSelfPropertyValue.GetType() == Property::INTEGER )
+ Property::Value alignSelfPropertyValue = childActor.GetProperty(Toolkit::FlexContainer::ChildProperty::ALIGN_SELF);
+ if(alignSelfPropertyValue.GetType() == Property::INTEGER)
{
- alignSelf = static_cast<Toolkit::FlexContainer::Alignment>( alignSelfPropertyValue.Get< int >() );
+ alignSelf = static_cast<Toolkit::FlexContainer::Alignment>(alignSelfPropertyValue.Get<int>());
}
- else if( alignSelfPropertyValue.GetType() == Property::STRING )
+ else if(alignSelfPropertyValue.GetType() == Property::STRING)
{
std::string value = alignSelfPropertyValue.Get<std::string>();
- Scripting::GetEnumeration< Toolkit::FlexContainer::Alignment >( value.c_str(),
- ALIGN_SELF_STRING_TABLE,
- ALIGN_SELF_STRING_TABLE_COUNT,
- alignSelf );
+ Scripting::GetEnumeration<Toolkit::FlexContainer::Alignment>(value.c_str(),
+ ALIGN_SELF_STRING_TABLE,
+ ALIGN_SELF_STRING_TABLE_COUNT,
+ alignSelf);
}
- YGNodeStyleSetAlignSelf( childNode, static_cast<YGAlign>(alignSelf) );
+ YGNodeStyleSetAlignSelf(childNode, static_cast<YGAlign>(alignSelf));
}
- if( childActor.GetPropertyType( Toolkit::FlexContainer::ChildProperty::FLEX_MARGIN ) != Property::NONE )
+ if(childActor.GetPropertyType(Toolkit::FlexContainer::ChildProperty::FLEX_MARGIN) != Property::NONE)
{
- Vector4 flexMargin = childActor.GetProperty( Toolkit::FlexContainer::ChildProperty::FLEX_MARGIN ).Get<Vector4>();
- YGNodeStyleSetMargin( childNode, YGEdgeLeft, flexMargin.x );
- YGNodeStyleSetMargin( childNode, YGEdgeTop, flexMargin.y );
- YGNodeStyleSetMargin( childNode, YGEdgeRight, flexMargin.z );
- YGNodeStyleSetMargin( childNode, YGEdgeBottom, flexMargin.w );
+ Vector4 flexMargin = childActor.GetProperty(Toolkit::FlexContainer::ChildProperty::FLEX_MARGIN).Get<Vector4>();
+ YGNodeStyleSetMargin(childNode, YGEdgeLeft, flexMargin.x);
+ YGNodeStyleSetMargin(childNode, YGEdgeTop, flexMargin.y);
+ YGNodeStyleSetMargin(childNode, YGEdgeRight, flexMargin.z);
+ YGNodeStyleSetMargin(childNode, YGEdgeBottom, flexMargin.w);
}
}
// Calculate the layout
YGDirection nodeLayoutDirection = YGDirectionInherit;
- switch( mContentDirection )
+ switch(mContentDirection)
{
- case Dali::Toolkit::FlexContainer::LTR:
- {
- nodeLayoutDirection = YGDirectionLTR;
- break;
- }
+ case Dali::Toolkit::FlexContainer::LTR:
+ {
+ nodeLayoutDirection = YGDirectionLTR;
+ break;
+ }
- case Dali::Toolkit::FlexContainer::RTL:
- {
- nodeLayoutDirection = YGDirectionRTL;
- break;
- }
+ case Dali::Toolkit::FlexContainer::RTL:
+ {
+ nodeLayoutDirection = YGDirectionRTL;
+ break;
+ }
- case Dali::Toolkit::FlexContainer::INHERIT:
- {
- nodeLayoutDirection = YGDirectionInherit;
- break;
- }
+ case Dali::Toolkit::FlexContainer::INHERIT:
+ {
+ nodeLayoutDirection = YGDirectionInherit;
+ break;
+ }
}
#if defined(FLEX_CONTAINER_DEBUG)
- YGNodePrint( mRootNode.node, (YGPrintOptions)( YGPrintOptionsLayout | YGPrintOptionsStyle | YGPrintOptionsChildren ) );
+ YGNodePrint(mRootNode.node, (YGPrintOptions)(YGPrintOptionsLayout | YGPrintOptionsStyle | YGPrintOptionsChildren));
#endif
- YGNodeCalculateLayout( mRootNode.node, Self().GetProperty< Vector2 >( Actor::Property::MAXIMUM_SIZE ).x, Self().GetProperty< Vector2 >( Actor::Property::MAXIMUM_SIZE ).y, nodeLayoutDirection );
+ YGNodeCalculateLayout(mRootNode.node, Self().GetProperty<Vector2>(Actor::Property::MAXIMUM_SIZE).x, Self().GetProperty<Vector2>(Actor::Property::MAXIMUM_SIZE).y, nodeLayoutDirection);
#if defined(FLEX_CONTAINER_DEBUG)
- YGNodePrint( mRootNode.node, (YGPrintOptions)( YGPrintOptionsLayout | YGPrintOptionsStyle | YGPrintOptionsChildren ) );
+ YGNodePrint(mRootNode.node, (YGPrintOptions)(YGPrintOptionsLayout | YGPrintOptionsStyle | YGPrintOptionsChildren));
#endif
}
}
ComputeLayout();
// Set size and position of children according to the layout calculation
- for( unsigned int i = 0; i < mChildrenNodes.size(); i++ )
+ for(unsigned int i = 0; i < mChildrenNodes.size(); i++)
{
Dali::Actor child = mChildrenNodes[i].actor.GetHandle();
- if( child )
+ if(child)
{
- child.SetProperty( Actor::Property::POSITION_X, YGNodeLayoutGetLeft( mChildrenNodes[i].node ) );
- child.SetProperty( Actor::Property::POSITION_Y, YGNodeLayoutGetTop( mChildrenNodes[i].node ) );
+ child.SetProperty(Actor::Property::POSITION_X, YGNodeLayoutGetLeft(mChildrenNodes[i].node));
+ child.SetProperty(Actor::Property::POSITION_Y, YGNodeLayoutGetTop(mChildrenNodes[i].node));
}
}
}
Actor nextFocusableActor;
// First check whether there is any items in the container
- if( mChildrenNodes.size() > 0 )
+ if(mChildrenNodes.size() > 0)
{
- if ( !currentFocusedActor || currentFocusedActor == Self() )
+ if(!currentFocusedActor || currentFocusedActor == Self())
{
// Nothing is currently focused, so the first child in the container should be focused.
nextFocusableActor = mChildrenNodes[0].actor.GetHandle();
{
// Check whether the current focused actor is within flex container
int currentFocusedActorIndex = -1;
- for( unsigned int index = 0; index < mChildrenNodes.size(); index++ )
+ for(unsigned int index = 0; index < mChildrenNodes.size(); index++)
{
- if( currentFocusedActor == mChildrenNodes[index].actor.GetHandle() )
+ if(currentFocusedActor == mChildrenNodes[index].actor.GetHandle())
{
currentFocusedActorIndex = index;
break;
}
}
- if( currentFocusedActorIndex > -1 )
+ if(currentFocusedActorIndex > -1)
{
int previousCheckedActorIndex = -1;
- int nextFocusedActorIndex = currentFocusedActorIndex;
- switch ( direction )
+ int nextFocusedActorIndex = currentFocusedActorIndex;
+ switch(direction)
{
case Toolkit::Control::KeyboardFocus::LEFT:
case Toolkit::Control::KeyboardFocus::UP:
do
{
nextFocusedActorIndex--;
- if( nextFocusedActorIndex < 0 )
+ if(nextFocusedActorIndex < 0)
{
nextFocusedActorIndex = loopEnabled ? mChildrenNodes.size() - 1 : 0;
}
- if( nextFocusedActorIndex != previousCheckedActorIndex && nextFocusedActorIndex != currentFocusedActorIndex )
+ if(nextFocusedActorIndex != previousCheckedActorIndex && nextFocusedActorIndex != currentFocusedActorIndex)
{
previousCheckedActorIndex = nextFocusedActorIndex;
}
{
break;
}
- } while ( !mChildrenNodes[nextFocusedActorIndex].actor.GetHandle().GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) );
+ } while(!mChildrenNodes[nextFocusedActorIndex].actor.GetHandle().GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE));
break;
}
case Toolkit::Control::KeyboardFocus::RIGHT:
do
{
nextFocusedActorIndex++;
- if( nextFocusedActorIndex > static_cast<int>(mChildrenNodes.size() - 1) )
+ if(nextFocusedActorIndex > static_cast<int>(mChildrenNodes.size() - 1))
{
nextFocusedActorIndex = loopEnabled ? 0 : mChildrenNodes.size() - 1;
}
- if( nextFocusedActorIndex != previousCheckedActorIndex && nextFocusedActorIndex != currentFocusedActorIndex )
+ if(nextFocusedActorIndex != previousCheckedActorIndex && nextFocusedActorIndex != currentFocusedActorIndex)
{
previousCheckedActorIndex = nextFocusedActorIndex;
}
{
break;
}
- } while ( !mChildrenNodes[nextFocusedActorIndex].actor.GetHandle().GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) );
+ } while(!mChildrenNodes[nextFocusedActorIndex].actor.GetHandle().GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE));
break;
}
default:
}
}
- if( nextFocusedActorIndex != currentFocusedActorIndex )
+ if(nextFocusedActorIndex != currentFocusedActorIndex)
{
nextFocusableActor = mChildrenNodes[nextFocusedActorIndex].actor.GetHandle();
}
}
FlexContainer::FlexContainer()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mContentDirection( Toolkit::FlexContainer::INHERIT ),
- mFlexDirection( Toolkit::FlexContainer::COLUMN ),
- mFlexWrap( Toolkit::FlexContainer::NO_WRAP ),
- mJustifyContent( Toolkit::FlexContainer::JUSTIFY_FLEX_START ),
- mAlignItems( Toolkit::FlexContainer::ALIGN_STRETCH ),
- mAlignContent( Toolkit::FlexContainer::ALIGN_FLEX_START )
-{
- SetKeyboardNavigationSupport( true );
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mContentDirection(Toolkit::FlexContainer::INHERIT),
+ mFlexDirection(Toolkit::FlexContainer::COLUMN),
+ mFlexWrap(Toolkit::FlexContainer::NO_WRAP),
+ mJustifyContent(Toolkit::FlexContainer::JUSTIFY_FLEX_START),
+ mAlignItems(Toolkit::FlexContainer::ALIGN_STRETCH),
+ mAlignContent(Toolkit::FlexContainer::ALIGN_FLEX_START)
+{
+ SetKeyboardNavigationSupport(true);
}
void FlexContainer::OnInitialize()
{
// Initialize the node for the flex container itself
Dali::Actor self = Self();
- self.LayoutDirectionChangedSignal().Connect( this, &FlexContainer::OnLayoutDirectionChanged );
+ self.LayoutDirectionChangedSignal().Connect(this, &FlexContainer::OnLayoutDirectionChanged);
mRootNode.actor = self;
- mRootNode.node = YGNodeNew();
- YGNodeSetContext( mRootNode.node, &mChildrenNodes );
+ mRootNode.node = YGNodeNew();
+ YGNodeSetContext(mRootNode.node, &mChildrenNodes);
// Set default style
- YGNodeStyleSetFlexDirection( mRootNode.node, static_cast<YGFlexDirection>( mFlexDirection ) );
- YGNodeStyleSetFlexWrap( mRootNode.node, static_cast<YGWrap>( mFlexWrap ) );
- YGNodeStyleSetJustifyContent( mRootNode.node, static_cast<YGJustify>( mJustifyContent ) );
- YGNodeStyleSetAlignItems( mRootNode.node, static_cast<YGAlign>( mAlignItems ) );
- YGNodeStyleSetAlignContent( mRootNode.node, static_cast<YGAlign>( mAlignContent ) );
+ YGNodeStyleSetFlexDirection(mRootNode.node, static_cast<YGFlexDirection>(mFlexDirection));
+ YGNodeStyleSetFlexWrap(mRootNode.node, static_cast<YGWrap>(mFlexWrap));
+ YGNodeStyleSetJustifyContent(mRootNode.node, static_cast<YGJustify>(mJustifyContent));
+ YGNodeStyleSetAlignItems(mRootNode.node, static_cast<YGAlign>(mAlignItems));
+ YGNodeStyleSetAlignContent(mRootNode.node, static_cast<YGAlign>(mAlignContent));
// Make self as keyboard focusable and focus group
- self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true );
- SetAsKeyboardFocusGroup( true );
+ self.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true);
+ SetAsKeyboardFocusGroup(true);
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER));
+ });
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "gaussian-blur-view-impl.h"
// EXTERNAL INCLUDES
-#include <sstream>
-#include <iomanip>
+#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/devel-api/common/stage.h>
+#include <dali/integration-api/debug.h>
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/animation/constraints.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/render-tasks/render-task-list.h>
#include <dali/public-api/rendering/geometry.h>
#include <dali/public-api/rendering/renderer.h>
#include <dali/public-api/rendering/shader.h>
-#include <dali/public-api/render-tasks/render-task-list.h>
-#include <dali/integration-api/debug.h>
-#include <dali/devel-api/actors/actor-devel.h>
+#include <iomanip>
+#include <sstream>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/controls/control/control-renderers.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/controls/control/control-renderers.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
// TODO:
// pixel format / size - set from JSON
// default near clip value
// Manager object - re-use render targets if there are multiple GaussianBlurViews created
-
/////////////////////////////////////////////////////////
// IMPLEMENTATION NOTES
// to take account of the changed GaussianBlurView object size, projecting to the unchanged render target sizes. This is done relative to the fixed render target / actor sizes
// by using constraints relative to the GaussianBlurView actor size.
-
// 2 modes:
// 1st mode, this control has a tree of actors (use Add() to add children) that are rendered and blurred.
// mRenderChildrenTask renders children to FB mRenderTargetForRenderingChildren
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
using namespace Dali;
BaseHandle Create()
return Toolkit::GaussianBlurView::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::GaussianBlurView, Toolkit::Control, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::GaussianBlurView, Toolkit::Control, Create)
DALI_TYPE_REGISTRATION_END()
-const unsigned int GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5;
-const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f;
+const unsigned int GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5;
+const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f;
const Pixel::Format GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888;
-const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH = 1.0f; // default, fully blurred
-const char* const GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME = "GaussianBlurStrengthPropertyName";
-const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
-const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
+const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH = 1.0f; // default, fully blurred
+const char* const GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME = "GaussianBlurStrengthPropertyName";
+const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
+const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f;
} // namespace
-
GaussianBlurView::GaussianBlurView()
-: Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS ) ),
+: Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
mNumSamples(GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES),
- mBlurBellCurveWidth( 0.001f ),
+ mBlurBellCurveWidth(0.001f),
mPixelFormat(GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT),
mDownsampleWidthScale(GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE),
mDownsampleHeightScale(GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE),
- mDownsampledWidth( 0.0f ),
- mDownsampledHeight( 0.0f ),
- mBlurUserImage( false ),
- mRenderOnce( false ),
- mBackgroundColor( Color::BLACK ),
+ mDownsampledWidth(0.0f),
+ mDownsampledHeight(0.0f),
+ mBlurUserImage(false),
+ mRenderOnce(false),
+ mBackgroundColor(Color::BLACK),
mTargetSize(Vector2::ZERO),
mLastSize(Vector2::ZERO),
mChildrenRoot(Actor::New()),
mInternalRoot(Actor::New()),
mBlurStrengthPropertyIndex(Property::INVALID_INDEX),
- mActivated( false )
+ mActivated(false)
{
SetBlurBellCurveWidth(GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH);
}
-GaussianBlurView::GaussianBlurView( const unsigned int numSamples,
- const float blurBellCurveWidth,
- const Pixel::Format renderTargetPixelFormat,
- const float downsampleWidthScale,
- const float downsampleHeightScale,
- bool blurUserImage)
-: Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS ) ),
+GaussianBlurView::GaussianBlurView(const unsigned int numSamples,
+ const float blurBellCurveWidth,
+ const Pixel::Format renderTargetPixelFormat,
+ const float downsampleWidthScale,
+ const float downsampleHeightScale,
+ bool blurUserImage)
+: Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
mNumSamples(numSamples),
- mBlurBellCurveWidth( 0.001f ),
+ mBlurBellCurveWidth(0.001f),
mPixelFormat(renderTargetPixelFormat),
mDownsampleWidthScale(downsampleWidthScale),
mDownsampleHeightScale(downsampleHeightScale),
- mDownsampledWidth( 0.0f ),
- mDownsampledHeight( 0.0f ),
- mBlurUserImage( blurUserImage ),
- mRenderOnce( false ),
- mBackgroundColor( Color::BLACK ),
+ mDownsampledWidth(0.0f),
+ mDownsampledHeight(0.0f),
+ mBlurUserImage(blurUserImage),
+ mRenderOnce(false),
+ mBackgroundColor(Color::BLACK),
mTargetSize(Vector2::ZERO),
mLastSize(Vector2::ZERO),
mChildrenRoot(Actor::New()),
mInternalRoot(Actor::New()),
mBlurStrengthPropertyIndex(Property::INVALID_INDEX),
- mActivated( false )
+ mActivated(false)
{
SetBlurBellCurveWidth(blurBellCurveWidth);
}
{
}
-
Toolkit::GaussianBlurView GaussianBlurView::New()
{
GaussianBlurView* impl = new GaussianBlurView();
- Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView( *impl );
+ Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-Toolkit::GaussianBlurView GaussianBlurView::New(const unsigned int numSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat,
- const float downsampleWidthScale, const float downsampleHeightScale,
- bool blurUserImage)
+Toolkit::GaussianBlurView GaussianBlurView::New(const unsigned int numSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, const float downsampleWidthScale, const float downsampleHeightScale, bool blurUserImage)
{
- GaussianBlurView* impl = new GaussianBlurView( numSamples, blurBellCurveWidth, renderTargetPixelFormat,
- downsampleWidthScale, downsampleHeightScale,
- blurUserImage);
+ GaussianBlurView* impl = new GaussianBlurView(numSamples, blurBellCurveWidth, renderTargetPixelFormat, downsampleWidthScale, downsampleHeightScale, blurUserImage);
- Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView( *impl );
+ Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
mUserInputImage = inputImage;
- SetRendererTexture( mHorizBlurActor.GetRendererAt(0), inputImage );
+ SetRendererTexture(mHorizBlurActor.GetRendererAt(0), inputImage);
mUserOutputRenderTarget = outputRenderTarget;
}
return mUserOutputRenderTarget;
}
-void GaussianBlurView::SetBackgroundColor( const Vector4& color )
+void GaussianBlurView::SetBackgroundColor(const Vector4& color)
{
mBackgroundColor = color;
}
void GaussianBlurView::OnInitialize()
{
// root actor to parent all user added actors, needed to allow us to set that subtree as exclusive for our child render task
- mChildrenRoot.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- mInternalRoot.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
+ mChildrenRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mInternalRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
//////////////////////////////////////////////////////
// Create shaders
// Create an actor for performing a horizontal blur on the texture
mHorizBlurActor = Actor::New();
- mHorizBlurActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
+ mHorizBlurActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
- Renderer renderer = CreateRenderer( BASIC_VERTEX_SOURCE, fragmentSource.c_str() );
- mHorizBlurActor.AddRenderer( renderer );
+ Renderer renderer = CreateRenderer(BASIC_VERTEX_SOURCE, fragmentSource.c_str());
+ mHorizBlurActor.AddRenderer(renderer);
// Create an actor for performing a vertical blur on the texture
mVertBlurActor = Actor::New();
- mVertBlurActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- renderer = CreateRenderer( BASIC_VERTEX_SOURCE, fragmentSource.c_str() );
- mVertBlurActor.AddRenderer( renderer );
+ mVertBlurActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ renderer = CreateRenderer(BASIC_VERTEX_SOURCE, fragmentSource.c_str());
+ mVertBlurActor.AddRenderer(renderer);
// Register a property that the user can control to fade the blur in / out via the GaussianBlurView object
- Actor self = Self();
+ Actor self = Self();
mBlurStrengthPropertyIndex = self.RegisterProperty(GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME, GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH);
// Create an image view for compositing the blur and the original child actors render
if(!mBlurUserImage)
{
mCompositingActor = Actor::New();
- mCompositingActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- mCompositingActor.SetProperty( Actor::Property::OPACITY,GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH); // ensure alpha is enabled for this object and set default value
- renderer = CreateRenderer( BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE );
- mCompositingActor.AddRenderer( renderer );
+ mCompositingActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mCompositingActor.SetProperty(Actor::Property::OPACITY, GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH); // ensure alpha is enabled for this object and set default value
+ renderer = CreateRenderer(BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE);
+ mCompositingActor.AddRenderer(renderer);
- Constraint blurStrengthConstraint = Constraint::New<float>( mCompositingActor, Actor::Property::COLOR_ALPHA, EqualToConstraint());
- blurStrengthConstraint.AddSource( Source( self, mBlurStrengthPropertyIndex) );
+ Constraint blurStrengthConstraint = Constraint::New<float>(mCompositingActor, Actor::Property::COLOR_ALPHA, EqualToConstraint());
+ blurStrengthConstraint.AddSource(Source(self, mBlurStrengthPropertyIndex));
blurStrengthConstraint.Apply();
// Create an image view for holding final result, i.e. the blurred image. This will get rendered to screen later, via default / user render task
mTargetActor = Actor::New();
- mTargetActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- renderer = CreateRenderer( BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE );
- mTargetActor.AddRenderer( renderer );
+ mTargetActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ renderer = CreateRenderer(BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE);
+ mTargetActor.AddRenderer(renderer);
//////////////////////////////////////////////////////
// Create cameras for the renders corresponding to the view size
mRenderFullSizeCamera = CameraActor::New();
- mRenderFullSizeCamera.SetInvertYAxis( true );
- mRenderFullSizeCamera.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
+ mRenderFullSizeCamera.SetInvertYAxis(true);
+ mRenderFullSizeCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
//////////////////////////////////////////////////////
// Connect to actor tree
- mInternalRoot.Add( mCompositingActor );
- mInternalRoot.Add( mTargetActor );
- mInternalRoot.Add( mRenderFullSizeCamera );
+ mInternalRoot.Add(mCompositingActor);
+ mInternalRoot.Add(mTargetActor);
+ mInternalRoot.Add(mRenderFullSizeCamera);
}
//////////////////////////////////////////////////////
// Create camera for the renders corresponding to the (potentially downsampled) render targets' size
mRenderDownsampledCamera = CameraActor::New();
- mRenderDownsampledCamera.SetInvertYAxis( true );
- mRenderDownsampledCamera.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
+ mRenderDownsampledCamera.SetInvertYAxis(true);
+ mRenderDownsampledCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
//////////////////////////////////////////////////////
// Connect to actor tree
- Self().Add( mChildrenRoot );
- mInternalRoot.Add( mHorizBlurActor );
- mInternalRoot.Add( mVertBlurActor );
- mInternalRoot.Add( mRenderDownsampledCamera );
-
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
- } );
+ Self().Add(mChildrenRoot);
+ mInternalRoot.Add(mHorizBlurActor);
+ mInternalRoot.Add(mVertBlurActor);
+ mInternalRoot.Add(mRenderDownsampledCamera);
+
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER));
+ });
}
-
void GaussianBlurView::OnSizeSet(const Vector3& targetSize)
{
mTargetSize = Vector2(targetSize);
- mChildrenRoot.SetProperty( Actor::Property::SIZE, targetSize);
+ mChildrenRoot.SetProperty(Actor::Property::SIZE, targetSize);
- if( !mBlurUserImage )
+ if(!mBlurUserImage)
{
- mCompositingActor.SetProperty( Actor::Property::SIZE, targetSize);
- mTargetActor.SetProperty( Actor::Property::SIZE, targetSize);
+ mCompositingActor.SetProperty(Actor::Property::SIZE, targetSize);
+ mTargetActor.SetProperty(Actor::Property::SIZE, targetSize);
// Children render camera must move when GaussianBlurView object is resized. This is since we cannot change render target size - so we need to remap the child actors' rendering
// accordingly so they still exactly fill the render target. Note that this means the effective resolution of the child render changes as the GaussianBlurView object changes
// size, this is the trade off for not being able to modify render target size
// Change camera z position based on GaussianBlurView actor height
float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f);
- mRenderFullSizeCamera.SetProperty( Actor::Property::POSITION_Z, mTargetSize.height * cameraPosConstraintScale);
+ mRenderFullSizeCamera.SetProperty(Actor::Property::POSITION_Z, mTargetSize.height * cameraPosConstraintScale);
}
-
// if we have already activated the blur, need to update render target sizes now to reflect the new size of this actor
if(mActivated)
{
Activate();
}
- Control::OnSizeSet( targetSize );
+ Control::OnSizeSet(targetSize);
}
-void GaussianBlurView::OnChildAdd( Actor& child )
+void GaussianBlurView::OnChildAdd(Actor& child)
{
- if( child != mChildrenRoot && child != mInternalRoot)
+ if(child != mChildrenRoot && child != mInternalRoot)
{
- mChildrenRoot.Add( child );
+ mChildrenRoot.Add(child);
}
- Control::OnChildAdd( child );
+ Control::OnChildAdd(child);
}
-void GaussianBlurView::OnChildRemove( Actor& child )
+void GaussianBlurView::OnChildRemove(Actor& child)
{
- mChildrenRoot.Remove( child );
+ mChildrenRoot.Remove(child);
- Control::OnChildRemove( child );
+ Control::OnChildRemove(child);
}
void GaussianBlurView::AllocateResources()
mLastSize = mTargetSize;
// get size of downsampled render targets
- mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale;
+ mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale;
mDownsampledHeight = mTargetSize.height * mDownsampleHeightScale;
// Create and place a camera for the renders corresponding to the (potentially downsampled) render targets' size
mRenderDownsampledCamera.SetAspectRatio(mDownsampledWidth / mDownsampledHeight);
mRenderDownsampledCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
- mRenderDownsampledCamera.SetProperty( Actor::Property::POSITION, Vector3(0.0f, 0.0f, ((mDownsampledHeight * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f))));
+ mRenderDownsampledCamera.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, ((mDownsampledHeight * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f))));
// setup for normal operation
if(!mBlurUserImage)
mRenderFullSizeCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f);
- mRenderFullSizeCamera.SetProperty( Actor::Property::POSITION, Vector3(0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale));
+ mRenderFullSizeCamera.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale));
// create offscreen buffer of new size to render our child actors to
- mRenderTargetForRenderingChildren = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture texture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mRenderTargetForRenderingChildren.AttachColorTexture( texture );
+ mRenderTargetForRenderingChildren = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mRenderTargetForRenderingChildren.AttachColorTexture(texture);
// Set actor for performing a horizontal blur
- SetRendererTexture( mHorizBlurActor.GetRendererAt(0), mRenderTargetForRenderingChildren );
+ SetRendererTexture(mHorizBlurActor.GetRendererAt(0), mRenderTargetForRenderingChildren);
// Create offscreen buffer for vert blur pass
- mRenderTarget1 = FrameBuffer::New( mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE );
- texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight));
- mRenderTarget1.AttachColorTexture( texture );
+ mRenderTarget1 = FrameBuffer::New(mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE);
+ texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight));
+ mRenderTarget1.AttachColorTexture(texture);
// use the completed blur in the first buffer and composite with the original child actors render
- SetRendererTexture( mCompositingActor.GetRendererAt(0), mRenderTarget1 );
+ SetRendererTexture(mCompositingActor.GetRendererAt(0), mRenderTarget1);
// set up target actor for rendering result, i.e. the blurred image
- SetRendererTexture( mTargetActor.GetRendererAt(0), mRenderTargetForRenderingChildren );
+ SetRendererTexture(mTargetActor.GetRendererAt(0), mRenderTargetForRenderingChildren);
}
// Create offscreen buffer for horiz blur pass
- mRenderTarget2 = FrameBuffer::New( mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE );
+ mRenderTarget2 = FrameBuffer::New(mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE);
Texture texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight));
- mRenderTarget2.AttachColorTexture( texture );
+ mRenderTarget2.AttachColorTexture(texture);
// size needs to match render target
- mHorizBlurActor.SetProperty( Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight) );
+ mHorizBlurActor.SetProperty(Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight));
// size needs to match render target
- mVertBlurActor.SetProperty( Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight) );
- SetRendererTexture( mVertBlurActor.GetRendererAt(0), mRenderTarget2 );
+ mVertBlurActor.SetProperty(Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight));
+ SetRendererTexture(mVertBlurActor.GetRendererAt(0), mRenderTarget2);
// set gaussian blur up for new sized render targets
SetShaderConstants();
{
// create render task to render our child actors to offscreen buffer
mRenderChildrenTask = taskList.CreateTask();
- mRenderChildrenTask.SetSourceActor( mChildrenRoot );
+ mRenderChildrenTask.SetSourceActor(mChildrenRoot);
mRenderChildrenTask.SetExclusive(true);
- mRenderChildrenTask.SetInputEnabled( false );
- mRenderChildrenTask.SetClearEnabled( true );
- mRenderChildrenTask.SetClearColor( mBackgroundColor );
+ mRenderChildrenTask.SetInputEnabled(false);
+ mRenderChildrenTask.SetClearEnabled(true);
+ mRenderChildrenTask.SetClearColor(mBackgroundColor);
mRenderChildrenTask.SetCameraActor(mRenderFullSizeCamera);
- mRenderChildrenTask.SetFrameBuffer( mRenderTargetForRenderingChildren );
+ mRenderChildrenTask.SetFrameBuffer(mRenderTargetForRenderingChildren);
- if( mRenderOnce )
+ if(mRenderOnce)
{
mRenderChildrenTask.SetRefreshRate(RenderTask::REFRESH_ONCE);
}
// perform a horizontal blur targeting the second buffer
mHorizBlurTask = taskList.CreateTask();
- mHorizBlurTask.SetSourceActor( mHorizBlurActor );
+ mHorizBlurTask.SetSourceActor(mHorizBlurActor);
mHorizBlurTask.SetExclusive(true);
- mHorizBlurTask.SetInputEnabled( false );
- mHorizBlurTask.SetClearEnabled( true );
- mHorizBlurTask.SetClearColor( mBackgroundColor );
+ mHorizBlurTask.SetInputEnabled(false);
+ mHorizBlurTask.SetClearEnabled(true);
+ mHorizBlurTask.SetClearColor(mBackgroundColor);
mHorizBlurTask.SetCameraActor(mRenderDownsampledCamera);
- mHorizBlurTask.SetFrameBuffer( mRenderTarget2 );
- if( mRenderOnce || ( mRenderOnce && mBlurUserImage ) )
+ mHorizBlurTask.SetFrameBuffer(mRenderTarget2);
+ if(mRenderOnce || (mRenderOnce && mBlurUserImage))
{
mHorizBlurTask.SetRefreshRate(RenderTask::REFRESH_ONCE);
}
// use the second buffer and perform a horizontal blur targeting the first buffer
mVertBlurTask = taskList.CreateTask();
- mVertBlurTask.SetSourceActor( mVertBlurActor );
+ mVertBlurTask.SetSourceActor(mVertBlurActor);
mVertBlurTask.SetExclusive(true);
- mVertBlurTask.SetInputEnabled( false );
- mVertBlurTask.SetClearEnabled( true );
- mVertBlurTask.SetClearColor( mBackgroundColor );
+ mVertBlurTask.SetInputEnabled(false);
+ mVertBlurTask.SetClearEnabled(true);
+ mVertBlurTask.SetClearColor(mBackgroundColor);
mVertBlurTask.SetCameraActor(mRenderDownsampledCamera);
if(mUserOutputRenderTarget)
{
- mVertBlurTask.SetFrameBuffer( mUserOutputRenderTarget );
+ mVertBlurTask.SetFrameBuffer(mUserOutputRenderTarget);
}
else
{
- mVertBlurTask.SetFrameBuffer( mRenderTarget1 );
+ mVertBlurTask.SetFrameBuffer(mRenderTarget1);
}
- if( mRenderOnce || ( mRenderOnce && mBlurUserImage ) )
+ if(mRenderOnce || (mRenderOnce && mBlurUserImage))
{
mVertBlurTask.SetRefreshRate(RenderTask::REFRESH_ONCE);
- mVertBlurTask.FinishedSignal().Connect( this, &GaussianBlurView::OnRenderTaskFinished );
+ mVertBlurTask.FinishedSignal().Connect(this, &GaussianBlurView::OnRenderTaskFinished);
}
// use the completed blur in the first buffer and composite with the original child actors render
if(!mBlurUserImage)
{
mCompositeTask = taskList.CreateTask();
- mCompositeTask.SetSourceActor( mCompositingActor );
+ mCompositeTask.SetSourceActor(mCompositingActor);
mCompositeTask.SetExclusive(true);
- mCompositeTask.SetInputEnabled( false );
+ mCompositeTask.SetInputEnabled(false);
mCompositeTask.SetCameraActor(mRenderFullSizeCamera);
- mCompositeTask.SetFrameBuffer( mRenderTargetForRenderingChildren );
+ mCompositeTask.SetFrameBuffer(mRenderTargetForRenderingChildren);
- if( mRenderOnce )
+ if(mRenderOnce)
{
mCompositeTask.SetRefreshRate(RenderTask::REFRESH_ONCE);
}
void GaussianBlurView::Activate()
{
- if( !mActivated )
+ if(!mActivated)
{
// make sure resources are allocated and start the render tasks processing
- Self().Add( mInternalRoot );
+ Self().Add(mInternalRoot);
AllocateResources();
CreateRenderTasks();
mActivated = true;
void GaussianBlurView::Deactivate()
{
- if( mActivated )
+ if(mActivated)
{
// stop render tasks processing
// Note: render target resources are automatically freed since we set the Image::Unused flag
mRenderTarget2.Reset();
RemoveRenderTasks();
mRenderOnce = false;
- mActivated = false;
+ mActivated = false;
}
}
void GaussianBlurView::SetBlurBellCurveWidth(float blurBellCurveWidth)
{
// a value of zero leads to undefined Gaussian weights, do not allow user to do this
- mBlurBellCurveWidth = std::max( blurBellCurveWidth, 0.001f );
+ mBlurBellCurveWidth = std::max(blurBellCurveWidth, 0.001f);
}
float GaussianBlurView::CalcGaussianWeight(float x)
void GaussianBlurView::SetShaderConstants()
{
- Vector2 *uvOffsets;
- float ofs;
- float *weights;
- float w, totalWeights;
+ Vector2* uvOffsets;
+ float ofs;
+ float* weights;
+ float w, totalWeights;
unsigned int i;
uvOffsets = new Vector2[mNumSamples + 1];
- weights = new float[mNumSamples + 1];
+ weights = new float[mNumSamples + 1];
totalWeights = weights[0] = CalcGaussianWeight(0);
- uvOffsets[0].x = 0.0f;
- uvOffsets[0].y = 0.0f;
+ uvOffsets[0].x = 0.0f;
+ uvOffsets[0].y = 0.0f;
- for(i=0; i<mNumSamples >> 1; i++)
+ for(i = 0; i < mNumSamples >> 1; i++)
{
- w = CalcGaussianWeight((float)(i + 1));
+ w = CalcGaussianWeight((float)(i + 1));
weights[(i << 1) + 1] = w;
weights[(i << 1) + 2] = w;
totalWeights += w * 2.0f;
ofs = ((float)(i << 1)) + 1.5f;
// get offsets from units of pixels into uv coordinates in [0..1]
- float ofsX = ofs / mDownsampledWidth;
- float ofsY = ofs / mDownsampledHeight;
+ float ofsX = ofs / mDownsampledWidth;
+ float ofsY = ofs / mDownsampledHeight;
uvOffsets[(i << 1) + 1].x = ofsX;
uvOffsets[(i << 1) + 1].y = ofsY;
uvOffsets[(i << 1) + 2].y = -ofsY;
}
- for(i=0; i<mNumSamples; i++)
+ for(i = 0; i < mNumSamples; i++)
{
weights[i] /= totalWeights;
}
// set shader constants
Vector2 xAxis(1.0f, 0.0f);
Vector2 yAxis(0.0f, 1.0f);
- for (i = 0; i < mNumSamples; ++i )
+ for(i = 0; i < mNumSamples; ++i)
{
- mHorizBlurActor.RegisterProperty( GetSampleOffsetsPropertyName( i ), uvOffsets[ i ] * xAxis );
- mHorizBlurActor.RegisterProperty( GetSampleWeightsPropertyName( i ), weights[ i ] );
+ mHorizBlurActor.RegisterProperty(GetSampleOffsetsPropertyName(i), uvOffsets[i] * xAxis);
+ mHorizBlurActor.RegisterProperty(GetSampleWeightsPropertyName(i), weights[i]);
- mVertBlurActor.RegisterProperty( GetSampleOffsetsPropertyName( i ), uvOffsets[ i ] * yAxis );
- mVertBlurActor.RegisterProperty( GetSampleWeightsPropertyName( i ), weights[ i ] );
+ mVertBlurActor.RegisterProperty(GetSampleOffsetsPropertyName(i), uvOffsets[i] * yAxis);
+ mVertBlurActor.RegisterProperty(GetSampleWeightsPropertyName(i), weights[i]);
}
delete[] uvOffsets;
delete[] weights;
}
-std::string GaussianBlurView::GetSampleOffsetsPropertyName( unsigned int index ) const
+std::string GaussianBlurView::GetSampleOffsetsPropertyName(unsigned int index) const
{
- DALI_ASSERT_ALWAYS( index < mNumSamples );
+ DALI_ASSERT_ALWAYS(index < mNumSamples);
std::ostringstream oss;
oss << "uSampleOffsets[" << index << "]";
return oss.str();
}
-std::string GaussianBlurView::GetSampleWeightsPropertyName( unsigned int index ) const
+std::string GaussianBlurView::GetSampleWeightsPropertyName(unsigned int index) const
{
- DALI_ASSERT_ALWAYS( index < mNumSamples );
+ DALI_ASSERT_ALWAYS(index < mNumSamples);
std::ostringstream oss;
oss << "uSampleWeights[" << index << "]";
void GaussianBlurView::OnRenderTaskFinished(Dali::RenderTask& renderTask)
{
- Toolkit::GaussianBlurView handle( GetOwner() );
- mFinishedSignal.Emit( handle );
+ Toolkit::GaussianBlurView handle(GetOwner());
+ mFinishedSignal.Emit(handle);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "image-view-impl.h"
// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/devel-api/scripting/scripting.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
-#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-impl.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
+#include <dali-toolkit/internal/visuals/visual-base-impl.h>
+#include <dali-toolkit/internal/visuals/visual-string-constants.h>
+#include <dali-toolkit/public-api/controls/image-view/image-view.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
BaseHandle Create()
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ImageView, Toolkit::Control, Create );
-DALI_PROPERTY_REGISTRATION( Toolkit, ImageView, "image", MAP, IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, ImageView, "preMultipliedAlpha", BOOLEAN, PRE_MULTIPLIED_ALPHA )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ImageView, Toolkit::Control, Create);
+DALI_PROPERTY_REGISTRATION(Toolkit, ImageView, "image", MAP, IMAGE)
+DALI_PROPERTY_REGISTRATION(Toolkit, ImageView, "preMultipliedAlpha", BOOLEAN, PRE_MULTIPLIED_ALPHA)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT( Toolkit, ImageView, "pixelArea", Vector4(0.f, 0.f, 1.f, 1.f), PIXEL_AREA )
+DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT(Toolkit, ImageView, "pixelArea", Vector4(0.f, 0.f, 1.f, 1.f), PIXEL_AREA)
DALI_TYPE_REGISTRATION_END()
} // anonymous namespace
using namespace Dali;
ImageView::ImageView()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mImageSize(),
- mImageVisualPaddingSetByTransform( false ),
- mImageViewPixelAreaSetByFittingMode( false )
+ mImageVisualPaddingSetByTransform(false),
+ mImageViewPixelAreaSetByFittingMode(false)
{
}
{
ImageView* impl = new ImageView();
- Toolkit::ImageView handle = Toolkit::ImageView( *impl );
+ Toolkit::ImageView handle = Toolkit::ImageView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
void ImageView::OnInitialize()
{
// ImageView can relayout in the OnImageReady, alternative to a signal would be to have a upcall from the Control to ImageView
- Dali::Toolkit::Control handle( GetOwner() );
- handle.ResourceReadySignal().Connect( this, &ImageView::OnResourceReady );
+ Dali::Toolkit::Control handle(GetOwner());
+ handle.ResourceReadySignal().Connect(this, &ImageView::OnResourceReady);
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::IMAGE ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::IMAGE));
+ });
//Enable highightability
- Self().SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true );
-
+ Self().SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
}
-void ImageView::SetImage( const Property::Map& map )
+void ImageView::SetImage(const Property::Map& map)
{
// Comparing a property map is too expensive so just creating a new visual
mPropertyMap = map;
mUrl.clear();
- Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( mPropertyMap );
- if( visual )
+ Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(mPropertyMap);
+ if(visual)
{
// Don't set mVisual until it is ready and shown. Getters will still use current visual.
- if( !mVisual )
+ if(!mVisual)
{
mVisual = visual;
}
- if( !mShaderMap.Empty() )
+ if(!mShaderMap.Empty())
{
- Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
- visualImpl.SetCustomShader( mShaderMap );
+ Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
+ visualImpl.SetCustomShader(mShaderMap);
}
- DevelControl::RegisterVisual( *this, Toolkit::ImageView::Property::IMAGE, visual );
+ DevelControl::RegisterVisual(*this, Toolkit::ImageView::Property::IMAGE, visual);
}
else
{
// Unregister the exsiting visual
- DevelControl::UnregisterVisual( *this, Toolkit::ImageView::Property::IMAGE );
+ DevelControl::UnregisterVisual(*this, Toolkit::ImageView::Property::IMAGE);
// Trigger a size negotiation request that may be needed when unregistering a visual.
RelayoutRequest();
// Signal that a Relayout may be needed
}
-void ImageView::SetImage( const std::string& url, ImageDimensions size )
+void ImageView::SetImage(const std::string& url, ImageDimensions size)
{
// Don't bother comparing if we had a visual previously, just drop old visual and create new one
- mUrl = url;
+ mUrl = url;
mImageSize = size;
mPropertyMap.Clear();
// Don't set mVisual until it is ready and shown. Getters will still use current visual.
- Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, size );
- if( visual )
+ Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(url, size);
+ if(visual)
{
- if( !mVisual )
+ if(!mVisual)
{
mVisual = visual;
}
- if( !mShaderMap.Empty() )
+ if(!mShaderMap.Empty())
{
- Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
- visualImpl.SetCustomShader( mShaderMap );
+ Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
+ visualImpl.SetCustomShader(mShaderMap);
}
- DevelControl::RegisterVisual( *this, Toolkit::ImageView::Property::IMAGE, visual );
+ DevelControl::RegisterVisual(*this, Toolkit::ImageView::Property::IMAGE, visual);
}
else
{
// Unregister the exsiting visual
- DevelControl::UnregisterVisual( *this, Toolkit::ImageView::Property::IMAGE );
+ DevelControl::UnregisterVisual(*this, Toolkit::ImageView::Property::IMAGE);
// Trigger a size negotiation request that may be needed when unregistering a visual.
RelayoutRequest();
// Signal that a Relayout may be needed
}
-void ImageView::EnablePreMultipliedAlpha( bool preMultipled )
+void ImageView::EnablePreMultipliedAlpha(bool preMultipled)
{
- if( mVisual )
+ if(mVisual)
{
- Toolkit::GetImplementation( mVisual ).EnablePreMultipliedAlpha( preMultipled );
+ Toolkit::GetImplementation(mVisual).EnablePreMultipliedAlpha(preMultipled);
}
}
bool ImageView::IsPreMultipliedAlphaEnabled() const
{
- if( mVisual )
+ if(mVisual)
{
- return Toolkit::GetImplementation( mVisual ).IsPreMultipliedAlphaEnabled();
+ return Toolkit::GetImplementation(mVisual).IsPreMultipliedAlphaEnabled();
}
return false;
}
-void ImageView::SetDepthIndex( int depthIndex )
+void ImageView::SetDepthIndex(int depthIndex)
{
- if( mVisual )
+ if(mVisual)
{
- mVisual.SetDepthIndex( depthIndex );
+ mVisual.SetDepthIndex(depthIndex);
}
}
Vector3 ImageView::GetNaturalSize()
{
- if( mVisual )
+ if(mVisual)
{
Vector2 rendererNaturalSize;
- mVisual.GetNaturalSize( rendererNaturalSize );
+ mVisual.GetNaturalSize(rendererNaturalSize);
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
- rendererNaturalSize.width += ( padding.start + padding.end );
- rendererNaturalSize.height += ( padding.top + padding.bottom );
- return Vector3( rendererNaturalSize );
+ rendererNaturalSize.width += (padding.start + padding.end);
+ rendererNaturalSize.height += (padding.top + padding.bottom);
+ return Vector3(rendererNaturalSize);
}
// if no visual then use Control's natural size
return Control::GetNaturalSize();
}
-float ImageView::GetHeightForWidth( float width )
+float ImageView::GetHeightForWidth(float width)
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
- if( mVisual )
+ if(mVisual)
{
- return mVisual.GetHeightForWidth( width ) + padding.top + padding.bottom;
+ return mVisual.GetHeightForWidth(width) + padding.top + padding.bottom;
}
else
{
- return Control::GetHeightForWidth( width ) + padding.top + padding.bottom;
+ return Control::GetHeightForWidth(width) + padding.top + padding.bottom;
}
}
-float ImageView::GetWidthForHeight( float height )
+float ImageView::GetWidthForHeight(float height)
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
- if( mVisual )
+ if(mVisual)
{
- return mVisual.GetWidthForHeight( height ) + padding.start + padding.end;
+ return mVisual.GetWidthForHeight(height) + padding.start + padding.end;
}
else
{
- return Control::GetWidthForHeight( height ) + padding.start + padding.end;
+ return Control::GetWidthForHeight(height) + padding.start + padding.end;
}
}
-void ImageView::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void ImageView::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- Control::OnRelayout( size, container );
- if( mVisual )
+ Control::OnRelayout(size, container);
+ if(mVisual)
{
Property::Map transformMap = Property::Map();
- Extents padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ Extents padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
- bool zeroPadding = ( padding == Extents() );
+ bool zeroPadding = (padding == Extents());
Vector2 naturalSize;
- mVisual.GetNaturalSize( naturalSize );
+ mVisual.GetNaturalSize(naturalSize);
Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(
- Self().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
- if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
+ Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
+ if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
{
- std::swap( padding.start, padding.end );
+ std::swap(padding.start, padding.end);
}
// remove padding from the size to know how much is left for the visual
- Vector2 finalSize = size - Vector2( padding.start + padding.end, padding.top + padding.bottom );
- Vector2 finalOffset = Vector2( padding.start, padding.top );
+ Vector2 finalSize = size - Vector2(padding.start + padding.end, padding.top + padding.bottom);
+ Vector2 finalOffset = Vector2(padding.start, padding.top);
- ApplyFittingMode( finalSize, naturalSize, finalOffset, zeroPadding , transformMap );
+ ApplyFittingMode(finalSize, naturalSize, finalOffset, zeroPadding, transformMap);
- mVisual.SetTransformAndSize( transformMap, size );
+ mVisual.SetTransformAndSize(transformMap, size);
// mVisual is not updated util the resource is ready in the case of visual replacement.
// in this case, the Property Map must be initialized so that the previous value is not reused.
// after mVisual is updated, the correct value will be reset.
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::ImageView::Property::IMAGE );
- if( visual && visual != mVisual )
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, Toolkit::ImageView::Property::IMAGE);
+ if(visual && visual != mVisual)
{
- visual.SetTransformAndSize( Property::Map(), size );
+ visual.SetTransformAndSize(Property::Map(), size);
}
}
}
-void ImageView::OnResourceReady( Toolkit::Control control )
+void ImageView::OnResourceReady(Toolkit::Control control)
{
// Visual ready so update visual attached to this ImageView, following call to RelayoutRequest will use this visual.
- mVisual = DevelControl::GetVisual( *this, Toolkit::ImageView::Property::IMAGE );
+ mVisual = DevelControl::GetVisual(*this, Toolkit::ImageView::Property::IMAGE);
// Signal that a Relayout may be needed
}
-void ImageView::SetTransformMapForFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, Visual::FittingMode fittingMode, Property::Map& transformMap )
+void ImageView::SetTransformMapForFittingMode(Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, Visual::FittingMode fittingMode, Property::Map& transformMap)
{
switch(fittingMode)
{
auto availableVisualSize = finalSize;
// scale to fit the padded area
- finalSize = naturalSize * std::min( ( naturalSize.width ? ( availableVisualSize.width / naturalSize.width ) : 0 ),
- ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
+ finalSize = naturalSize * std::min((naturalSize.width ? (availableVisualSize.width / naturalSize.width) : 0),
+ (naturalSize.height ? (availableVisualSize.height / naturalSize.height) : 0));
// calculate final offset within the padded area
- finalOffset += ( availableVisualSize - finalSize ) * .5f;
+ finalOffset += (availableVisualSize - finalSize) * .5f;
// populate the transform map
- transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
- .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
+ transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, finalOffset)
+ .Add(Toolkit::Visual::Transform::Property::SIZE, finalSize);
break;
}
case Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO:
{
mImageViewPixelAreaSetByFittingMode = true;
- auto availableVisualSize = finalSize;
- finalSize = naturalSize * std::max( ( naturalSize.width ? ( availableVisualSize.width / naturalSize.width ) : 0 ),
- ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
+ auto availableVisualSize = finalSize;
+ finalSize = naturalSize * std::max((naturalSize.width ? (availableVisualSize.width / naturalSize.width) : 0),
+ (naturalSize.height ? (availableVisualSize.height / naturalSize.height) : 0));
auto originalOffset = finalOffset;
- finalOffset += ( availableVisualSize - finalSize ) * .5f;
+ finalOffset += (availableVisualSize - finalSize) * .5f;
- float x = abs( (availableVisualSize.width - finalSize.width ) / finalSize.width )* .5f;
- float y = abs( (availableVisualSize.height - finalSize.height ) / finalSize.height ) * .5f;
- float widthRatio = 1.f - abs( (availableVisualSize.width - finalSize.width ) / finalSize.width );
- float heightRatio = 1.f - abs( (availableVisualSize.height - finalSize.height ) / finalSize.height );
- Vector4 pixelArea = Vector4( x, y, widthRatio, heightRatio);
- Self().SetProperty( Toolkit::ImageView::Property::PIXEL_AREA, pixelArea );
+ float x = abs((availableVisualSize.width - finalSize.width) / finalSize.width) * .5f;
+ float y = abs((availableVisualSize.height - finalSize.height) / finalSize.height) * .5f;
+ float widthRatio = 1.f - abs((availableVisualSize.width - finalSize.width) / finalSize.width);
+ float heightRatio = 1.f - abs((availableVisualSize.height - finalSize.height) / finalSize.height);
+ Vector4 pixelArea = Vector4(x, y, widthRatio, heightRatio);
+ Self().SetProperty(Toolkit::ImageView::Property::PIXEL_AREA, pixelArea);
// populate the transform map
- transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, originalOffset )
- .Add( Toolkit::Visual::Transform::Property::SIZE, availableVisualSize );
+ transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, originalOffset)
+ .Add(Toolkit::Visual::Transform::Property::SIZE, availableVisualSize);
break;
}
case Visual::FittingMode::CENTER:
{
auto availableVisualSize = finalSize;
- if( availableVisualSize.width > naturalSize.width && availableVisualSize.height > naturalSize.height )
+ if(availableVisualSize.width > naturalSize.width && availableVisualSize.height > naturalSize.height)
{
finalSize = naturalSize;
}
else
{
- finalSize = naturalSize * std::min( ( naturalSize.width ? ( availableVisualSize.width / naturalSize.width ) : 0 ),
- ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) );
+ finalSize = naturalSize * std::min((naturalSize.width ? (availableVisualSize.width / naturalSize.width) : 0),
+ (naturalSize.height ? (availableVisualSize.height / naturalSize.height) : 0));
}
- finalOffset += ( availableVisualSize - finalSize ) * .5f;
+ finalOffset += (availableVisualSize - finalSize) * .5f;
// populate the transform map
- transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
- .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
+ transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, finalOffset)
+ .Add(Toolkit::Visual::Transform::Property::SIZE, finalSize);
break;
}
case Visual::FittingMode::FILL:
{
- transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset )
- .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize );
+ transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, finalOffset)
+ .Add(Toolkit::Visual::Transform::Property::SIZE, finalSize);
break;
}
case Visual::FittingMode::FIT_WIDTH:
}
}
-void ImageView::ApplyFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, bool zeroPadding , Property::Map& transformMap )
+void ImageView::ApplyFittingMode(Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, bool zeroPadding, Property::Map& transformMap)
{
- Visual::FittingMode fittingMode = Toolkit::GetImplementation(mVisual).GetFittingMode();
-
- // Reset PIXEL_AREA after using OVER_FIT_KEEP_ASPECT_RATIO
- if( mImageViewPixelAreaSetByFittingMode )
- {
- Self().SetProperty( Toolkit::ImageView::Property::PIXEL_AREA, FULL_TEXTURE_RECT );
- mImageViewPixelAreaSetByFittingMode = false;
- }
-
- if( ( !zeroPadding ) || // If padding is not zero
- ( fittingMode != Visual::FittingMode::FILL ) )
- {
- mImageVisualPaddingSetByTransform = true;
+ Visual::FittingMode fittingMode = Toolkit::GetImplementation(mVisual).GetFittingMode();
- // If FittingMode use FIT_WIDTH or FIT_HEIGTH, it need to change proper fittingMode
- if( fittingMode == Visual::FittingMode::FIT_WIDTH )
- {
- fittingMode = ( finalSize.height / naturalSize.height ) < ( finalSize.width / naturalSize.width ) ? Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::FIT_KEEP_ASPECT_RATIO;
- }
- else if( fittingMode == Visual::FittingMode::FIT_HEIGHT )
- {
- fittingMode = ( finalSize.height / naturalSize.height ) < ( finalSize.width / naturalSize.width ) ? Visual::FittingMode::FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO;
- }
+ // Reset PIXEL_AREA after using OVER_FIT_KEEP_ASPECT_RATIO
+ if(mImageViewPixelAreaSetByFittingMode)
+ {
+ Self().SetProperty(Toolkit::ImageView::Property::PIXEL_AREA, FULL_TEXTURE_RECT);
+ mImageViewPixelAreaSetByFittingMode = false;
+ }
- SetTransformMapForFittingMode( finalSize, naturalSize, finalOffset, fittingMode, transformMap );
+ if((!zeroPadding) || // If padding is not zero
+ (fittingMode != Visual::FittingMode::FILL))
+ {
+ mImageVisualPaddingSetByTransform = true;
- // Set extra value for applying transformMap
- transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY,
- Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN )
- .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY,
- Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) );
+ // If FittingMode use FIT_WIDTH or FIT_HEIGTH, it need to change proper fittingMode
+ if(fittingMode == Visual::FittingMode::FIT_WIDTH)
+ {
+ fittingMode = (finalSize.height / naturalSize.height) < (finalSize.width / naturalSize.width) ? Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::FIT_KEEP_ASPECT_RATIO;
}
- else if ( mImageVisualPaddingSetByTransform && zeroPadding ) // Reset offset to zero only if padding applied previously
+ else if(fittingMode == Visual::FittingMode::FIT_HEIGHT)
{
- mImageVisualPaddingSetByTransform = false;
- // Reset the transform map
- transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, Vector2::ZERO )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY,
- Vector2( Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE, Vector2::ONE )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY,
- Vector2( Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE ) );
+ fittingMode = (finalSize.height / naturalSize.height) < (finalSize.width / naturalSize.width) ? Visual::FittingMode::FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO;
}
+
+ SetTransformMapForFittingMode(finalSize, naturalSize, finalOffset, fittingMode, transformMap);
+
+ // Set extra value for applying transformMap
+ transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY,
+ Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN)
+ .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN)
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY,
+ Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE));
+ }
+ else if(mImageVisualPaddingSetByTransform && zeroPadding) // Reset offset to zero only if padding applied previously
+ {
+ mImageVisualPaddingSetByTransform = false;
+ // Reset the transform map
+ transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, Vector2::ZERO)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY,
+ Vector2(Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE))
+ .Add(Toolkit::Visual::Transform::Property::SIZE, Vector2::ONE)
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY,
+ Vector2(Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE));
+ }
}
///////////////////////////////////////////////////////////
// Properties
//
-void ImageView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void ImageView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::ImageView imageView = Toolkit::ImageView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ImageView imageView = Toolkit::ImageView::DownCast(Dali::BaseHandle(object));
- if ( imageView )
+ if(imageView)
{
- ImageView& impl = GetImpl( imageView );
- switch ( index )
+ ImageView& impl = GetImpl(imageView);
+ switch(index)
{
case Toolkit::ImageView::Property::IMAGE:
{
- std::string imageUrl;
+ std::string imageUrl;
const Property::Map* map;
- if( value.Get( imageUrl ) )
+ if(value.Get(imageUrl))
{
- impl.SetImage( imageUrl, ImageDimensions() );
+ impl.SetImage(imageUrl, ImageDimensions());
}
// if its not a string then get a Property::Map from the property if possible.
else
{
map = value.GetMap();
- if( map )
+ if(map)
{
- Property::Value* shaderValue = map->Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER );
+ Property::Value* shaderValue = map->Find(Toolkit::Visual::Property::SHADER, CUSTOM_SHADER);
// set image only if property map contains image information other than custom shader
- if( map->Count() > 1u || !shaderValue )
+ if(map->Count() > 1u || !shaderValue)
{
- impl.SetImage( *map );
+ impl.SetImage(*map);
}
// the property map contains only the custom shader
- else if( ( map->Count() == 1u )&&( shaderValue ) )
+ else if((map->Count() == 1u) && (shaderValue))
{
Property::Map* shaderMap = shaderValue->GetMap();
- if( shaderMap )
+ if(shaderMap)
{
impl.mShaderMap = *shaderMap;
- if( !impl.mUrl.empty() )
+ if(!impl.mUrl.empty())
{
- impl.SetImage( impl.mUrl, impl.mImageSize );
+ impl.SetImage(impl.mUrl, impl.mImageSize);
}
- else if( !impl.mPropertyMap.Empty() )
+ else if(!impl.mPropertyMap.Empty())
{
- impl.SetImage( impl.mPropertyMap );
+ impl.SetImage(impl.mPropertyMap);
}
}
}
case Toolkit::ImageView::Property::PRE_MULTIPLIED_ALPHA:
{
bool isPre;
- if( value.Get( isPre ) )
+ if(value.Get(isPre))
{
- impl.EnablePreMultipliedAlpha( isPre );
+ impl.EnablePreMultipliedAlpha(isPre);
}
break;
}
}
}
-Property::Value ImageView::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value ImageView::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::ImageView imageview = Toolkit::ImageView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ImageView imageview = Toolkit::ImageView::DownCast(Dali::BaseHandle(object));
- if ( imageview )
+ if(imageview)
{
- ImageView& impl = GetImpl( imageview );
- switch ( propertyIndex )
+ ImageView& impl = GetImpl(imageview);
+ switch(propertyIndex)
{
case Toolkit::ImageView::Property::IMAGE:
{
- if ( !impl.mUrl.empty() )
+ if(!impl.mUrl.empty())
{
value = impl.mUrl;
}
else
{
- Property::Map map;
- Toolkit::Visual::Base visual = DevelControl::GetVisual( impl, Toolkit::ImageView::Property::IMAGE );
- if( visual )
+ Property::Map map;
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(impl, Toolkit::ImageView::Property::IMAGE);
+ if(visual)
{
- visual.CreatePropertyMap( map );
+ visual.CreatePropertyMap(map);
}
value = map;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/magnifier/magnifier-impl.h>
// EXTERNAL INCLUDES
+#include <dali/devel-api/common/stage.h>
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/animation/constraints.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/public-api/render-tasks/render-task-list.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/public-api/object/property-map.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/render-tasks/render-task-list.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/border-visual-properties.h>
#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
+#include <dali-toolkit/internal/controls/control/control-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/public-api/visuals/border-visual-properties.h>
#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/controls/control/control-data-impl.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace // unnamed namespace
{
-
-
Dali::BaseHandle Create()
{
return Toolkit::Magnifier::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Magnifier, Toolkit::Control, Create )
+// clang-format off
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Magnifier, Toolkit::Control, Create)
-DALI_PROPERTY_REGISTRATION( Toolkit, Magnifier, "frameVisibility", BOOLEAN, FRAME_VISIBILITY )
-DALI_PROPERTY_REGISTRATION( Toolkit, Magnifier, "magnificationFactor", FLOAT, MAGNIFICATION_FACTOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, Magnifier, "frameVisibility", BOOLEAN, FRAME_VISIBILITY )
+DALI_PROPERTY_REGISTRATION(Toolkit, Magnifier, "magnificationFactor", FLOAT, MAGNIFICATION_FACTOR)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Magnifier, "sourcePosition", VECTOR3, SOURCE_POSITION )
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Magnifier, "sourcePosition", VECTOR3, SOURCE_POSITION)
DALI_TYPE_REGISTRATION_END()
+// clang-format on
-const float IMAGE_BORDER_INDENT = 5.0f; ///< Indent of border in pixels.
+const float IMAGE_BORDER_INDENT = 5.0f; ///< Indent of border in pixels.
struct CameraActorPositionConstraint
{
{
}
- void operator()( Vector3& current, const PropertyInputContainer& inputs )
+ void operator()(Vector3& current, const PropertyInputContainer& inputs)
{
const Vector3& sourcePosition = inputs[0]->GetVector3();
}
Vector2 mStageSize;
- float mDefaultCameraDistance;
-
+ float mDefaultCameraDistance;
};
struct RenderTaskViewportPositionConstraint
{
}
- void operator()( Vector2& current, const PropertyInputContainer& inputs )
+ void operator()(Vector2& current, const PropertyInputContainer& inputs)
{
current = inputs[0]->GetVector3(); // World position?
Vector3 size = inputs[1]->GetVector3() * inputs[2]->GetVector3(); /* magnifier-size * magnifier-scale */
// Reposition, and resize viewport to reflect the world bounds of this Magnifier actor.
- current.x += ( mStageSize.width - size.width ) * 0.5f;
- current.y += ( mStageSize.height - size.height ) * 0.5f;
+ current.x += (mStageSize.width - size.width) * 0.5f;
+ current.y += (mStageSize.height - size.height) * 0.5f;
}
Vector2 mStageSize;
{
}
- void operator()( Vector2& current, const PropertyInputContainer& inputs )
+ void operator()(Vector2& current, const PropertyInputContainer& inputs)
{
current = inputs[0]->GetVector3() * inputs[1]->GetVector3(); /* magnifier-size * magnifier-scale */
}
}
Magnifier::Magnifier()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mDefaultCameraDistance(1000.f),
mActorSize(Vector3::ZERO),
mMagnificationFactor(1.0f)
void Magnifier::SetSourceActor(Actor actor)
{
- mTask.SetSourceActor( actor );
+ mTask.SetSourceActor(actor);
}
void Magnifier::Initialize()
{
- Actor self = Self();
+ Actor self = Self();
Vector2 stageSize(Stage::GetCurrent().GetSize());
// NOTE:
// and what is not.
mSourceActor = Actor::New();
Stage().GetCurrent().Add(mSourceActor);
- mSourceActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- Constraint constraint = Constraint::New<Vector3>( mSourceActor, Actor::Property::POSITION, EqualToConstraint() );
- constraint.AddSource( Source( self, Toolkit::Magnifier::Property::SOURCE_POSITION ) );
+ mSourceActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ Constraint constraint = Constraint::New<Vector3>(mSourceActor, Actor::Property::POSITION, EqualToConstraint());
+ constraint.AddSource(Source(self, Toolkit::Magnifier::Property::SOURCE_POSITION));
constraint.Apply();
// create the render task this will render content on top of everything
// But we can determine the initial position using the same formula:
// distance = stage.height * 0.5 / tan(FOV * 0.5)
- RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
- RenderTask renderTask = taskList.GetTask(0u);
- float fov = renderTask.GetCameraActor().GetFieldOfView();
- mDefaultCameraDistance = (stageSize.height * 0.5f) / tanf(fov * 0.5f);
+ RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
+ RenderTask renderTask = taskList.GetTask(0u);
+ float fov = renderTask.GetCameraActor().GetFieldOfView();
+ mDefaultCameraDistance = (stageSize.height * 0.5f) / tanf(fov * 0.5f);
// Use a 1 frame delayed source position to determine the camera actor's position.
// This is necessary as the viewport is determined by the Magnifier's Actor's World position (which is computed
// at the end of the update cycle i.e. after constraints have been applied.)
//Property::Index propertySourcePositionDelayed = mCameraActor.RegisterProperty("delayedSourcePosition", Vector3::ZERO);
- constraint = Constraint::New<Vector3>( mCameraActor, Actor::Property::POSITION, CameraActorPositionConstraint(stageSize, mDefaultCameraDistance) );
- constraint.AddSource( Source( mSourceActor, Actor::Property::WORLD_POSITION ) );
+ constraint = Constraint::New<Vector3>(mCameraActor, Actor::Property::POSITION, CameraActorPositionConstraint(stageSize, mDefaultCameraDistance));
+ constraint.AddSource(Source(mSourceActor, Actor::Property::WORLD_POSITION));
constraint.Apply();
// Apply constraint to render-task viewport position
- constraint = Constraint::New<Vector2>( mTask, RenderTask::Property::VIEWPORT_POSITION, RenderTaskViewportPositionConstraint(stageSize) );
- constraint.AddSource( Source( self, Actor::Property::WORLD_POSITION ) );
- constraint.AddSource( Source( self, Actor::Property::SIZE ) );
- constraint.AddSource( Source( self, Actor::Property::WORLD_SCALE ) );
+ constraint = Constraint::New<Vector2>(mTask, RenderTask::Property::VIEWPORT_POSITION, RenderTaskViewportPositionConstraint(stageSize));
+ constraint.AddSource(Source(self, Actor::Property::WORLD_POSITION));
+ constraint.AddSource(Source(self, Actor::Property::SIZE));
+ constraint.AddSource(Source(self, Actor::Property::WORLD_SCALE));
constraint.Apply();
// Apply constraint to render-task viewport position
- constraint = Constraint::New<Vector2>( mTask, RenderTask::Property::VIEWPORT_SIZE, RenderTaskViewportSizeConstraint() );
- constraint.AddSource( Source( self, Actor::Property::SIZE ) );
- constraint.AddSource( Source( self, Actor::Property::WORLD_SCALE ) );
+ constraint = Constraint::New<Vector2>(mTask, RenderTask::Property::VIEWPORT_SIZE, RenderTaskViewportSizeConstraint());
+ constraint.AddSource(Source(self, Actor::Property::SIZE));
+ constraint.AddSource(Source(self, Actor::Property::WORLD_SCALE));
constraint.Apply();
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER));
+ });
}
Magnifier::~Magnifier()
{
-
}
void Magnifier::InitializeRenderTask()
mCameraActor.SetType(Camera::FREE_LOOK);
stage.Add(mCameraActor);
- mTask.SetCameraActor( mCameraActor );
+ mTask.SetCameraActor(mCameraActor);
SetFrameVisibility(true);
}
{
Actor self(Self());
- mFrame = Actor::New( );
- mFrame.SetProperty( Actor::Property::INHERIT_POSITION, false );
- mFrame.SetProperty( Actor::Property::INHERIT_SCALE, true );
- mFrame.SetResizePolicy( ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS );
- Vector3 sizeOffset(IMAGE_BORDER_INDENT*2.f - 2.f, IMAGE_BORDER_INDENT*2.f - 2.f, 0.0f);
- mFrame.SetProperty( Actor::Property::SIZE_MODE_FACTOR, sizeOffset );
+ mFrame = Actor::New();
+ mFrame.SetProperty(Actor::Property::INHERIT_POSITION, false);
+ mFrame.SetProperty(Actor::Property::INHERIT_SCALE, true);
+ mFrame.SetResizePolicy(ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS);
+ Vector3 sizeOffset(IMAGE_BORDER_INDENT * 2.f - 2.f, IMAGE_BORDER_INDENT * 2.f - 2.f, 0.0f);
+ mFrame.SetProperty(Actor::Property::SIZE_MODE_FACTOR, sizeOffset);
Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get();
Property::Map map;
- map[ Toolkit::Visual::Property::TYPE ] = Toolkit::Visual::BORDER;
- map[ Toolkit::BorderVisual::Property::COLOR ] = Color::WHITE;
- map[ Toolkit::BorderVisual::Property::SIZE ] = IMAGE_BORDER_INDENT;
- Toolkit::Visual::Base borderVisual = visualFactory.CreateVisual( map );
- Toolkit::GetImplementation(borderVisual).SetOnScene( mFrame );
-
- Constraint constraint = Constraint::New<Vector3>( mFrame, Actor::Property::POSITION, EqualToConstraint() );
- constraint.AddSource( ParentSource( Actor::Property::WORLD_POSITION ) );
+ map[Toolkit::Visual::Property::TYPE] = Toolkit::Visual::BORDER;
+ map[Toolkit::BorderVisual::Property::COLOR] = Color::WHITE;
+ map[Toolkit::BorderVisual::Property::SIZE] = IMAGE_BORDER_INDENT;
+ Toolkit::Visual::Base borderVisual = visualFactory.CreateVisual(map);
+ Toolkit::GetImplementation(borderVisual).SetOnScene(mFrame);
+
+ Constraint constraint = Constraint::New<Vector3>(mFrame, Actor::Property::POSITION, EqualToConstraint());
+ constraint.AddSource(ParentSource(Actor::Property::WORLD_POSITION));
constraint.Apply();
self.Add(mFrame);
mActorSize = targetSize;
Update();
- Control::OnSizeSet( targetSize );
+ Control::OnSizeSet(targetSize);
}
float Magnifier::GetMagnificationFactor() const
// should be updated when:
// Magnifier's world size/scale changes.
- Actor self(Self());
- Vector3 worldSize = mActorSize * self.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_SCALE );
+ Actor self(Self());
+ Vector3 worldSize = mActorSize * self.GetCurrentProperty<Vector3>(Actor::Property::WORLD_SCALE);
// Adjust field of view to scale content
// |./
// |/ <--- fov/2 radians.
//
- const float fov = atanf( 0.5f * worldSize.height / mDefaultCameraDistance / mMagnificationFactor) * 2.0f;
- mCameraActor.SetFieldOfView( fov );
+ const float fov = atanf(0.5f * worldSize.height / mDefaultCameraDistance / mMagnificationFactor) * 2.0f;
+ mCameraActor.SetFieldOfView(fov);
// Adjust aspect ratio to compensate for rectangular viewports.
- mCameraActor.SetAspectRatio( worldSize.width / worldSize.height );
+ mCameraActor.SetAspectRatio(worldSize.width / worldSize.height);
}
-void Magnifier::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void Magnifier::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::Magnifier magnifier = Toolkit::Magnifier::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Magnifier magnifier = Toolkit::Magnifier::DownCast(Dali::BaseHandle(object));
- if( magnifier )
+ if(magnifier)
{
- Magnifier& magnifierImpl( GetImpl( magnifier ) );
- switch( index )
+ Magnifier& magnifierImpl(GetImpl(magnifier));
+ switch(index)
{
case Toolkit::Magnifier::Property::FRAME_VISIBILITY:
{
- magnifierImpl.SetFrameVisibility( value.Get< bool >() );
+ magnifierImpl.SetFrameVisibility(value.Get<bool>());
break;
}
case Toolkit::Magnifier::Property::MAGNIFICATION_FACTOR:
{
- magnifierImpl.SetMagnificationFactor( value.Get< float >() );
+ magnifierImpl.SetMagnificationFactor(value.Get<float>());
break;
}
}
}
}
-Property::Value Magnifier::GetProperty( BaseObject* object, Property::Index index )
+Property::Value Magnifier::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::Magnifier magnifier = Toolkit::Magnifier::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Magnifier magnifier = Toolkit::Magnifier::DownCast(Dali::BaseHandle(object));
- if( magnifier )
+ if(magnifier)
{
- Magnifier& magnifierImpl( GetImpl( magnifier ) );
- switch( index )
+ Magnifier& magnifierImpl(GetImpl(magnifier));
+ switch(index)
{
case Toolkit::Magnifier::Property::FRAME_VISIBILITY:
{
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "model3d-view-impl.h"
// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/animation/constraint.h>
-#include <dali/public-api/animation/constraint-source.h>
-#include <dali/public-api/animation/constraints.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali-toolkit/public-api/controls/model3d-view/model3d-view.h>
#include <dali/devel-api/adaptor-framework/file-loader.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
+#include <dali/public-api/animation/constraint-source.h>
+#include <dali/public-api/animation/constraint.h>
+#include <dali/public-api/animation/constraints.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
-#include <dali-toolkit/internal/controls/model3d-view/obj-loader.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/controls/model3d-view/obj-loader.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// Texture indices are constants.
enum TextureIndex
{
* @param[in] imageUrl The URL of the file
* @return A texture if loading succeeds, an empty handle otherwise
*/
-Texture LoadTexture( const char* imageUrl )
+Texture LoadTexture(const char* imageUrl)
{
- Texture texture;
- Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl );
- if( pixelBuffer )
+ Texture texture;
+ Devel::PixelBuffer pixelBuffer = LoadImageFromFile(imageUrl);
+ if(pixelBuffer)
{
- texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
- PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
- texture.Upload( pixelData );
+ texture = Texture::New(TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
+ PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
+ texture.Upload(pixelData);
texture.GenerateMipmaps();
}
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Model3dView, Toolkit::Control, Create );
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Model3dView, Toolkit::Control, Create);
-DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "geometryUrl", STRING, GEOMETRY_URL)
-DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "materialUrl", STRING, MATERIAL_URL)
-DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "imagesUrl", STRING, IMAGES_URL)
-DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "illuminationType", INTEGER, ILLUMINATION_TYPE)
-DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "texture0Url", STRING, TEXTURE0_URL)
-DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "texture1Url", STRING, TEXTURE1_URL)
-DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "texture2Url", STRING, TEXTURE2_URL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "geometryUrl", STRING, GEOMETRY_URL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "materialUrl", STRING, MATERIAL_URL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "imagesUrl", STRING, IMAGES_URL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "illuminationType", INTEGER, ILLUMINATION_TYPE)
+DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "texture0Url", STRING, TEXTURE0_URL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "texture1Url", STRING, TEXTURE1_URL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "texture2Url", STRING, TEXTURE2_URL)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Model3dView, "lightPosition", VECTOR3, LIGHT_POSITION)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Model3dView, "lightPosition", VECTOR3, LIGHT_POSITION)
DALI_TYPE_REGISTRATION_END()
using namespace Dali;
Model3dView::Model3dView()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) )
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT))
{
mIlluminationType = Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP;
mCameraFOV = Math::PI_OVER_180 * 45.f;
- mControlSize = Vector2(100.,100.);
+ mControlSize = Vector2(100., 100.);
}
Model3dView::~Model3dView()
{
Model3dView* impl = new Model3dView();
- Dali::Toolkit::Model3dView handle = Dali::Toolkit::Model3dView( *impl );
+ Dali::Toolkit::Model3dView handle = Dali::Toolkit::Model3dView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-void Model3dView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void Model3dView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::Model3dView model3dView = Toolkit::Model3dView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Model3dView model3dView = Toolkit::Model3dView::DownCast(Dali::BaseHandle(object));
- if( model3dView )
+ if(model3dView)
{
- Model3dView& impl( GetImpl( model3dView ) );
- switch( index )
+ Model3dView& impl(GetImpl(model3dView));
+ switch(index)
{
case Toolkit::Model3dView::Property::GEOMETRY_URL:
{
- if( value.Get(impl.mObjUrl) )
+ if(value.Get(impl.mObjUrl))
{
impl.LoadGeometry();
impl.CreateGeometry();
}
case Toolkit::Model3dView::Property::MATERIAL_URL:
{
- if( value.Get(impl.mTextureSetUrl) )
+ if(value.Get(impl.mTextureSetUrl))
{
impl.LoadMaterial();
impl.CreateMaterial();
}
case Toolkit::Model3dView::Property::IMAGES_URL:
{
- if( value.Get(impl.mImagesUrl) )
+ if(value.Get(impl.mImagesUrl))
{
impl.LoadTextures();
}
case Toolkit::Model3dView::Property::ILLUMINATION_TYPE:
{
int illuminationType;
- if( value.Get(illuminationType) )
+ if(value.Get(illuminationType))
{
impl.mIlluminationType = Toolkit::Model3dView::IlluminationType(illuminationType);
impl.CreateGeometry();
}
}
-Property::Value Model3dView::GetProperty( BaseObject* object, Property::Index index )
+Property::Value Model3dView::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::Model3dView model3dView = Toolkit::Model3dView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Model3dView model3dView = Toolkit::Model3dView::DownCast(Dali::BaseHandle(object));
- if( model3dView )
+ if(model3dView)
{
- Model3dView& impl( GetImpl( model3dView ) );
- switch( index )
+ Model3dView& impl(GetImpl(model3dView));
+ switch(index)
{
case Toolkit::Model3dView::Property::GEOMETRY_URL:
{
/////////////////////////////////////////////////////////////
-
-void Model3dView::OnSceneConnection( int depth )
+void Model3dView::OnSceneConnection(int depth)
{
CustomActor self = Self();
- self.AddRenderer( mRenderer );
+ self.AddRenderer(mRenderer);
- if( mObjLoader.IsSceneLoaded() )
+ if(mObjLoader.IsSceneLoaded())
{
- mMesh = mObjLoader.CreateGeometry( GetShaderProperties( mIlluminationType ), true );
+ mMesh = mObjLoader.CreateGeometry(GetShaderProperties(mIlluminationType), true);
CreateMaterial();
LoadTextures();
- mRenderer.SetGeometry( mMesh );
+ mRenderer.SetGeometry(mMesh);
//create constraint for lightPosition Property with uLightPosition in the shader
- Vector3 lightPosition( 0, 0, 0 );
- Dali::Property::Index lightProperty = mShader.RegisterProperty( "uLightPosition", lightPosition );
- Constraint constraint = Constraint::New<Vector3>( mShader, lightProperty, EqualToConstraint() );
- constraint.AddSource( Source( self, Toolkit::Model3dView::Property::LIGHT_POSITION ) );
+ Vector3 lightPosition(0, 0, 0);
+ Dali::Property::Index lightProperty = mShader.RegisterProperty("uLightPosition", lightPosition);
+ Constraint constraint = Constraint::New<Vector3>(mShader, lightProperty, EqualToConstraint());
+ constraint.AddSource(Source(self, Toolkit::Model3dView::Property::LIGHT_POSITION));
constraint.Apply();
}
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
}
///////////////////////////////////////////////////////////
void Model3dView::OnInitialize()
{
//Create empty versions of the geometry and material so we always have a Renderer
- Geometry mesh = Geometry::New();
- Shader shader = Shader::New( SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG );
- mRenderer = Renderer::New( mesh, shader );
-
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::IMAGE ) );
- } );
+ Geometry mesh = Geometry::New();
+ Shader shader = Shader::New(SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG);
+ mRenderer = Renderer::New(mesh, shader);
+
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::IMAGE));
+ });
}
void Model3dView::LoadGeometry()
{
//Load file in adaptor
- std::streampos fileSize;
+ std::streampos fileSize;
Dali::Vector<char> fileContent;
- if (FileLoader::ReadFile(mObjUrl,fileSize,fileContent,FileLoader::TEXT))
+ if(FileLoader::ReadFile(mObjUrl, fileSize, fileContent, FileLoader::TEXT))
{
mObjLoader.ClearArrays();
mObjLoader.LoadObject(fileContent.Begin(), fileSize);
//Get size information from the obj loaded
mSceneCenter = mObjLoader.GetCenter();
- mSceneSize = mObjLoader.GetSize();
+ mSceneSize = mObjLoader.GetSize();
}
else
{
void Model3dView::LoadMaterial()
{
//Load file in adaptor
- std::streampos fileSize;
+ std::streampos fileSize;
Dali::Vector<char> fileContent;
- if( FileLoader::ReadFile(mTextureSetUrl, fileSize, fileContent, FileLoader::TEXT) )
+ if(FileLoader::ReadFile(mTextureSetUrl, fileSize, fileContent, FileLoader::TEXT))
{
mObjLoader.LoadMaterial(fileContent.Begin(), fileSize, mTexture0Url, mTexture1Url, mTexture2Url);
}
LoadMaterial();
}
-void Model3dView::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void Model3dView::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
UpdateView();
}
void Model3dView::UpdateView()
{
- if( mObjLoader.IsSceneLoaded() )
+ if(mObjLoader.IsSceneLoaded())
{
//The object will always be centred
Matrix scaleMatrix;
scaleMatrix.SetIdentityAndScale(Vector3(1.0, -1.0, 1.0));
- mShader.RegisterProperty( "uObjectMatrix", scaleMatrix );
+ mShader.RegisterProperty("uObjectMatrix", scaleMatrix);
}
}
void Model3dView::CreateGeometry()
{
- if( mObjLoader.IsSceneLoaded() )
+ if(mObjLoader.IsSceneLoaded())
{
- mMesh = mObjLoader.CreateGeometry( GetShaderProperties( mIlluminationType ), true );
+ mMesh = mObjLoader.CreateGeometry(GetShaderProperties(mIlluminationType), true);
- if( mRenderer )
+ if(mRenderer)
{
- mRenderer.SetGeometry( mMesh );
- mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
- mRenderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON );
+ mRenderer.SetGeometry(mMesh);
+ mRenderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON);
+ mRenderer.SetProperty(Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON);
}
}
}
void Model3dView::UpdateShaderUniforms()
{
- if( mShader )
+ if(mShader)
{
//Update shader related info, uniforms, etc. for the new shader
UpdateView();
- Vector3 lightPosition( 0, 0, 0 );
- Dali::Property::Index lightProperty = mShader.RegisterProperty( "uLightPosition", lightPosition );
+ Vector3 lightPosition(0, 0, 0);
+ Dali::Property::Index lightProperty = mShader.RegisterProperty("uLightPosition", lightPosition);
CustomActor self = Self();
//create constraint for lightPosition Property with uLightPosition in the shader
- if( lightProperty )
+ if(lightProperty)
{
- Constraint constraint = Constraint::New<Vector3>( mShader, lightProperty, EqualToConstraint() );
- constraint.AddSource( Source( self, Toolkit::Model3dView::Property::LIGHT_POSITION ) );
+ Constraint constraint = Constraint::New<Vector3>(mShader, lightProperty, EqualToConstraint());
+ constraint.AddSource(Source(self, Toolkit::Model3dView::Property::LIGHT_POSITION));
constraint.Apply();
}
}
void Model3dView::CreateMaterial()
{
- if( mObjLoader.IsMaterialLoaded() && (mTexture0Url != "") && mObjLoader.IsTexturePresent() )
+ if(mObjLoader.IsMaterialLoaded() && (mTexture0Url != "") && mObjLoader.IsTexturePresent())
{
- if( (mTexture2Url != "") && (mTexture1Url != "") && (mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP) )
+ if((mTexture2Url != "") && (mTexture1Url != "") && (mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP))
{
- mShader = Shader::New( SHADER_MODEL3D_VIEW_NRMMAP_SHADER_VERT, SHADER_MODEL3D_VIEW_NRMMAP_SHADER_FRAG );
+ mShader = Shader::New(SHADER_MODEL3D_VIEW_NRMMAP_SHADER_VERT, SHADER_MODEL3D_VIEW_NRMMAP_SHADER_FRAG);
}
- else if( mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE ||
- mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP )
+ else if(mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE ||
+ mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP)
{
- mShader = Shader::New( SHADER_MODEL3D_VIEW_SHADER_VERT, SHADER_MODEL3D_VIEW_SHADER_FRAG );
+ mShader = Shader::New(SHADER_MODEL3D_VIEW_SHADER_VERT, SHADER_MODEL3D_VIEW_SHADER_FRAG);
}
else
{
- mShader = Shader::New( SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG );
+ mShader = Shader::New(SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG);
}
}
else
{
- mShader = Shader::New( SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG );
+ mShader = Shader::New(SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG);
}
mTextureSet = TextureSet::New();
- if( mRenderer )
+ if(mRenderer)
{
- mRenderer.SetTextures( mTextureSet );
- mRenderer.SetShader( mShader );
- mRenderer.SetProperty( Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK );
+ mRenderer.SetTextures(mTextureSet);
+ mRenderer.SetShader(mShader);
+ mRenderer.SetProperty(Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK);
}
UpdateShaderUniforms();
void Model3dView::LoadTextures()
{
- if( !mTextureSet )
+ if(!mTextureSet)
{
return;
}
Sampler sampler = Sampler::New();
- sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR );
+ sampler.SetFilterMode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR);
// Setup diffuse texture.
- if( !mTexture0Url.empty() && ( mIlluminationType != Toolkit::Model3dView::DIFFUSE ) )
+ if(!mTexture0Url.empty() && (mIlluminationType != Toolkit::Model3dView::DIFFUSE))
{
std::string imageUrl = mImagesUrl + mTexture0Url;
//Load textures
- Texture diffuseTexture = LoadTexture( imageUrl.c_str() );
- if( diffuseTexture )
+ Texture diffuseTexture = LoadTexture(imageUrl.c_str());
+ if(diffuseTexture)
{
- mTextureSet.SetTexture( DIFFUSE_TEXTURE_INDEX, diffuseTexture );
- mTextureSet.SetSampler( DIFFUSE_TEXTURE_INDEX, sampler );
+ mTextureSet.SetTexture(DIFFUSE_TEXTURE_INDEX, diffuseTexture);
+ mTextureSet.SetSampler(DIFFUSE_TEXTURE_INDEX, sampler);
}
}
- if( mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP )
+ if(mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP)
{
// Setup normal map texture.
- if( !mTexture1Url.empty() )
+ if(!mTexture1Url.empty())
{
std::string imageUrl = mImagesUrl + mTexture1Url;
//Load textures
- Texture normalTexture = LoadTexture( imageUrl.c_str() );
- if( normalTexture )
+ Texture normalTexture = LoadTexture(imageUrl.c_str());
+ if(normalTexture)
{
- mTextureSet.SetTexture( NORMAL_TEXTURE_INDEX, normalTexture );
- mTextureSet.SetSampler( NORMAL_TEXTURE_INDEX, sampler );
+ mTextureSet.SetTexture(NORMAL_TEXTURE_INDEX, normalTexture);
+ mTextureSet.SetSampler(NORMAL_TEXTURE_INDEX, sampler);
}
}
- if( !mTexture2Url.empty() )
+ if(!mTexture2Url.empty())
{
// Setup gloss map texture.
std::string imageUrl = mImagesUrl + mTexture2Url;
//Load textures
- Texture glossTexture = LoadTexture( imageUrl.c_str() );
- if( glossTexture )
+ Texture glossTexture = LoadTexture(imageUrl.c_str());
+ if(glossTexture)
{
- mTextureSet.SetTexture( GLOSS_TEXTURE_INDEX, glossTexture );
- mTextureSet.SetSampler( GLOSS_TEXTURE_INDEX, sampler );
+ mTextureSet.SetTexture(GLOSS_TEXTURE_INDEX, glossTexture);
+ mTextureSet.SetSampler(GLOSS_TEXTURE_INDEX, sampler);
}
}
}
}
-int Model3dView::GetShaderProperties( Toolkit::Model3dView::IlluminationType illuminationType )
+int Model3dView::GetShaderProperties(Toolkit::Model3dView::IlluminationType illuminationType)
{
int objectProperties = 0;
- if( illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE ||
- illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP )
+ if(illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE ||
+ illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP)
{
objectProperties |= ObjLoader::TEXTURE_COORDINATES;
}
- if( illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP )
+ if(illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP)
{
objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS;
}
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
-#include <string>
-#include <sstream>
#include <string.h>
+#include <sstream>
+#include <string>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
- const int MAX_POINT_INDICES = 4;
+const int MAX_POINT_INDICES = 4;
}
using namespace Dali;
ObjLoader::ObjLoader()
{
- mSceneLoaded = false;
- mMaterialLoaded = false;
+ mSceneLoaded = false;
+ mMaterialLoaded = false;
mHasTexturePoints = false;
- mHasDiffuseMap = false;
- mHasNormalMap = false;
- mHasSpecularMap = false;
+ mHasDiffuseMap = false;
+ mHasNormalMap = false;
+ mHasSpecularMap = false;
mSceneAABB.Init();
}
return mMaterialLoaded;
}
-void ObjLoader::CalculateHardFaceNormals( const Dali::Vector<Vector3>& vertices, Dali::Vector<TriIndex>& triangles,
- Dali::Vector<Vector3>& normals )
+void ObjLoader::CalculateHardFaceNormals(const Dali::Vector<Vector3>& vertices, Dali::Vector<TriIndex>& triangles, Dali::Vector<Vector3>& normals)
{
- int numFaceVertices = 3 * triangles.Size(); //Vertex per face, as each point has different normals for each face.
- int normalIndex = 0; //Tracks progress through the array of normals.
+ int numFaceVertices = 3 * triangles.Size(); //Vertex per face, as each point has different normals for each face.
+ int normalIndex = 0; //Tracks progress through the array of normals.
normals.Clear();
- normals.Resize( numFaceVertices );
+ normals.Resize(numFaceVertices);
//For each triangle, calculate the normal by crossing two vectors on the triangle's plane.
- for( unsigned long i = 0; i < triangles.Size(); i++ )
+ for(unsigned long i = 0; i < triangles.Size(); i++)
{
//Triangle vertices.
const Vector3& v0 = vertices[triangles[i].pointIndex[0]];
normalVector.Normalize();
//Assign normals to points.
- for( unsigned long j = 0; j < 3; j++, normalIndex++ )
+ for(unsigned long j = 0; j < 3; j++, normalIndex++)
{
triangles[i].normalIndex[j] = normalIndex;
- normals[normalIndex] = normalVector;
+ normals[normalIndex] = normalVector;
}
}
}
-void ObjLoader::CalculateSoftFaceNormals( const Dali::Vector<Vector3>& vertices, Dali::Vector<TriIndex>& triangles,
- Dali::Vector<Vector3>& normals )
+void ObjLoader::CalculateSoftFaceNormals(const Dali::Vector<Vector3>& vertices, Dali::Vector<TriIndex>& triangles, Dali::Vector<Vector3>& normals)
{
- int normalIndex = 0; //Tracks progress through the array of normals.
+ int normalIndex = 0; //Tracks progress through the array of normals.
normals.Clear();
- normals.Resize( vertices.Size() ); //One (averaged) normal per point.
+ normals.Resize(vertices.Size()); //One (averaged) normal per point.
//For each triangle, calculate the normal by crossing two vectors on the triangle's plane
//We then add the triangle's normal to the cumulative normals at each point of it
- for( unsigned long i = 0; i < triangles.Size(); i++ )
+ for(unsigned long i = 0; i < triangles.Size(); i++)
{
//Triangle vertices.
const Vector3& v0 = vertices[triangles[i].pointIndex[0]];
Vector3 normalVector = edge1.Cross(edge2);
//Add this triangle's normal to the cumulative normal of each constituent point and set the index of the normal accordingly.
- for( unsigned long j = 0; j < 3; j++, normalIndex++ )
+ for(unsigned long j = 0; j < 3; j++, normalIndex++)
{
triangles[i].normalIndex[j] = triangles[i].pointIndex[j]; //Normal index matches up to vertex index, as one normal per vertex.
normals[triangles[i].normalIndex[j]] += normalVector;
}
//Normalise the normals.
- for( unsigned long i = 0; i < normals.Size(); i++ )
+ for(unsigned long i = 0; i < normals.Size(); i++)
{
normals[i].Normalize();
}
//Reset tangent and bitangent vectors to hold new values.
mTangents.Clear();
mBiTangents.Clear();
- mTangents.Resize( mPoints.Size() );
- mBiTangents.Resize( mPoints.Size() );
+ mTangents.Resize(mPoints.Size());
+ mBiTangents.Resize(mPoints.Size());
//For each triangle, calculate the tangent vector and then add it to the total tangent vector of each point.
- for ( unsigned long a = 0; a < mTriangles.Size(); a++ )
+ for(unsigned long a = 0; a < mTriangles.Size(); a++)
{
Vector3 tangentVector;
float f = 1.0f / (deltaU1 * deltaV2 - deltaU2 * deltaV1);
- tangentVector.x = f * ( deltaV2 * edge1.x - deltaV1 * edge2.x );
- tangentVector.y = f * ( deltaV2 * edge1.y - deltaV1 * edge2.y );
- tangentVector.z = f * ( deltaV2 * edge1.z - deltaV1 * edge2.z );
+ tangentVector.x = f * (deltaV2 * edge1.x - deltaV1 * edge2.x);
+ tangentVector.y = f * (deltaV2 * edge1.y - deltaV1 * edge2.y);
+ tangentVector.z = f * (deltaV2 * edge1.z - deltaV1 * edge2.z);
mTangents[mTriangles[a].pointIndex[0]] += tangentVector;
mTangents[mTriangles[a].pointIndex[1]] += tangentVector;
}
//Orthogonalize tangents and set binormals.
- for ( unsigned long a = 0; a < mTangents.Size(); a++ )
+ for(unsigned long a = 0; a < mTangents.Size(); a++)
{
const Vector3& n = mNormals[a];
const Vector3& t = mTangents[a];
mTangents[a] = t - n * n.Dot(t);
mTangents[a].Normalize();
- mBiTangents[a] = mNormals[a].Cross( mTangents[a] );
+ mBiTangents[a] = mNormals[a].Cross(mTangents[a]);
}
}
-void ObjLoader::CenterAndScale( bool center, Dali::Vector<Vector3>& points )
+void ObjLoader::CenterAndScale(bool center, Dali::Vector<Vector3>& points)
{
BoundingVolume newAABB;
Vector3 sceneSize = GetSize();
float biggestDimension = sceneSize.x;
- if( sceneSize.y > biggestDimension )
+ if(sceneSize.y > biggestDimension)
{
biggestDimension = sceneSize.y;
}
- if( sceneSize.z > biggestDimension )
+ if(sceneSize.z > biggestDimension)
{
biggestDimension = sceneSize.z;
}
newAABB.Init();
- for( unsigned int ui = 0; ui < points.Size(); ++ui )
+ for(unsigned int ui = 0; ui < points.Size(); ++ui)
{
points[ui] = points[ui] - GetCenter();
points[ui] = points[ui] / biggestDimension;
mSceneAABB = newAABB;
}
-void ObjLoader::CreateGeometryArray( Dali::Vector<Vertex> & vertices,
- Dali::Vector<Vector2> & textures,
- Dali::Vector<VertexExt> & verticesExt,
- Dali::Vector<unsigned short> & indices,
- bool useSoftNormals )
+void ObjLoader::CreateGeometryArray(Dali::Vector<Vertex>& vertices,
+ Dali::Vector<Vector2>& textures,
+ Dali::Vector<VertexExt>& verticesExt,
+ Dali::Vector<unsigned short>& indices,
+ bool useSoftNormals)
{
//We must calculate the tangents and bitangents if they weren't supplied, or if they don't match up.
bool mustCalculateTangents = mTangents.Size() == 0 || mBiTangents.Size() == 0 ||
//We also have to recalculate the normals if we need to calculate tangents,
// as we need just one normal, tangent and bitangent per vertex, rather than the supplied per-face vertices.
//Alternatively, we need to calculate the normals if there weren't any to begin with.
- if( mNormals.Size() == 0 || mustCalculateTangents )
+ if(mNormals.Size() == 0 || mustCalculateTangents)
{
- if( useSoftNormals || mustCalculateTangents )
+ if(useSoftNormals || mustCalculateTangents)
{
- CalculateSoftFaceNormals( mPoints, mTriangles, mNormals );
+ CalculateSoftFaceNormals(mPoints, mTriangles, mNormals);
}
else
{
- CalculateHardFaceNormals( mPoints, mTriangles, mNormals );
+ CalculateHardFaceNormals(mPoints, mTriangles, mNormals);
}
}
//TODO: Use a better function to calculate tangents
- if( mHasTexturePoints && mustCalculateTangents )
+ if(mHasTexturePoints && mustCalculateTangents)
{
CalculateTangentFrame();
}
bool mapsCorrespond; //True if the sizes of the arrays necessary for the object agree.
- if ( mHasTexturePoints )
+ if(mHasTexturePoints)
{
- mapsCorrespond = ( mPoints.Size() == mTextures.Size() ) && ( mTextures.Size() == mNormals.Size() );
+ mapsCorrespond = (mPoints.Size() == mTextures.Size()) && (mTextures.Size() == mNormals.Size());
}
else
{
- mapsCorrespond = ( mPoints.Size() == mNormals.Size() );
+ mapsCorrespond = (mPoints.Size() == mNormals.Size());
}
//Check the number of points textures and normals
- if ( mapsCorrespond )
+ if(mapsCorrespond)
{
- int numPoints = mPoints.Size();
+ int numPoints = mPoints.Size();
int numIndices = 3 * mTriangles.Size();
- vertices.Resize( numPoints );
- textures.Resize( numPoints );
- verticesExt.Resize( numPoints );
- indices.Resize( numIndices );
+ vertices.Resize(numPoints);
+ textures.Resize(numPoints);
+ verticesExt.Resize(numPoints);
+ indices.Resize(numIndices);
//We create the vertices array. For now we just copy points info
- for (unsigned int ui = 0 ; ui < mPoints.Size() ; ++ui )
+ for(unsigned int ui = 0; ui < mPoints.Size(); ++ui)
{
Vertex vertex;
vertex.position = mPoints[ui];
- vertices[ui] = vertex;
+ vertices[ui] = vertex;
- if ( mHasTexturePoints )
+ if(mHasTexturePoints)
{
- textures[ui] = Vector2();
+ textures[ui] = Vector2();
verticesExt[ui] = VertexExt();
}
}
int indiceIndex = 0;
//We copy the indices
- for ( unsigned int ui = 0 ; ui < mTriangles.Size() ; ++ui )
+ for(unsigned int ui = 0; ui < mTriangles.Size(); ++ui)
{
- for ( int j = 0 ; j < 3 ; ++j )
+ for(int j = 0; j < 3; ++j)
{
indices[indiceIndex] = mTriangles[ui].pointIndex[j];
indiceIndex++;
vertices[mTriangles[ui].pointIndex[j]].normal = mNormals[mTriangles[ui].normalIndex[j]];
- if ( mHasTexturePoints )
+ if(mHasTexturePoints)
{
- textures[mTriangles[ui].pointIndex[j]] = mTextures[mTriangles[ui].textureIndex[j]];
- verticesExt[mTriangles[ui].pointIndex[j]].tangent = mTangents[mTriangles[ui].normalIndex[j]];
+ textures[mTriangles[ui].pointIndex[j]] = mTextures[mTriangles[ui].textureIndex[j]];
+ verticesExt[mTriangles[ui].pointIndex[j]].tangent = mTangents[mTriangles[ui].normalIndex[j]];
verticesExt[mTriangles[ui].pointIndex[j]].bitangent = mBiTangents[mTriangles[ui].normalIndex[j]];
}
}
else
{
int numVertices = 3 * mTriangles.Size();
- vertices.Resize( numVertices );
- textures.Resize( numVertices );
- verticesExt.Resize( numVertices );
+ vertices.Resize(numVertices);
+ textures.Resize(numVertices);
+ verticesExt.Resize(numVertices);
int index = 0;
//We have to normalize the arrays so we can draw we just one index array
- for ( unsigned int ui = 0 ; ui < mTriangles.Size() ; ++ui )
+ for(unsigned int ui = 0; ui < mTriangles.Size(); ++ui)
{
- for ( int j = 0 ; j < 3 ; ++j )
+ for(int j = 0; j < 3; ++j)
{
Vertex vertex;
vertex.position = mPoints[mTriangles[ui].pointIndex[j]];
- vertex.normal = mNormals[mTriangles[ui].normalIndex[j]];
+ vertex.normal = mNormals[mTriangles[ui].normalIndex[j]];
vertices[index] = vertex;
- if ( mHasTexturePoints )
+ if(mHasTexturePoints)
{
textures[index] = mTextures[mTriangles[ui].textureIndex[j]];
VertexExt vertexExt;
- vertexExt.tangent = mTangents[mTriangles[ui].normalIndex[j]];
+ vertexExt.tangent = mTangents[mTriangles[ui].normalIndex[j]];
vertexExt.bitangent = mBiTangents[mTriangles[ui].normalIndex[j]];
- verticesExt[index] = vertexExt;
+ verticesExt[index] = vertexExt;
}
index++;
}
}
-bool ObjLoader::LoadObject( char* objBuffer, std::streampos fileSize )
+bool ObjLoader::LoadObject(char* objBuffer, std::streampos fileSize)
{
- Vector3 point;
- Vector2 texture;
+ Vector3 point;
+ Vector2 texture;
std::string vet[MAX_POINT_INDICES], name;
- int ptIdx[MAX_POINT_INDICES];
- int nrmIdx[MAX_POINT_INDICES];
- int texIdx[MAX_POINT_INDICES];
- TriIndex triangle,triangle2;
- int pntAcum = 0, texAcum = 0, nrmAcum = 0;
- bool iniObj = false;
- bool hasTexture = false;
- int face = 0;
+ int ptIdx[MAX_POINT_INDICES];
+ int nrmIdx[MAX_POINT_INDICES];
+ int texIdx[MAX_POINT_INDICES];
+ TriIndex triangle, triangle2;
+ int pntAcum = 0, texAcum = 0, nrmAcum = 0;
+ bool iniObj = false;
+ bool hasTexture = false;
+ int face = 0;
//Init AABB for the file
mSceneAABB.Init();
std::string strMatActual;
- std::string input( objBuffer, fileSize );
+ std::string input(objBuffer, fileSize);
std::istringstream ss(input);
- ss.imbue( std::locale( "C" ) );
-
+ ss.imbue(std::locale("C"));
std::string line;
- std::getline( ss, line );
+ std::getline(ss, line);
- while ( std::getline( ss, line ) )
+ while(std::getline(ss, line))
{
- std::istringstream isline( line, std::istringstream::in );
- std::string tag;
+ std::istringstream isline(line, std::istringstream::in);
+ std::string tag;
isline >> tag;
- if ( tag == "v" )
+ if(tag == "v")
{
//Two different objects in the same file
isline >> point.x;
isline >> point.y;
isline >> point.z;
- mPoints.PushBack( point );
+ mPoints.PushBack(point);
- mSceneAABB.ConsiderNewPointInVolume( point );
+ mSceneAABB.ConsiderNewPointInVolume(point);
}
- else if ( tag == "vn" )
+ else if(tag == "vn")
{
isline >> point.x;
isline >> point.y;
isline >> point.z;
- mNormals.PushBack( point );
+ mNormals.PushBack(point);
}
- else if ( tag == "#_#tangent" )
+ else if(tag == "#_#tangent")
{
isline >> point.x;
isline >> point.y;
isline >> point.z;
- mTangents.PushBack( point );
+ mTangents.PushBack(point);
}
- else if ( tag == "#_#binormal" )
+ else if(tag == "#_#binormal")
{
isline >> point.x;
isline >> point.y;
isline >> point.z;
- mBiTangents.PushBack( point );
+ mBiTangents.PushBack(point);
}
- else if ( tag == "vt" )
+ else if(tag == "vt")
{
isline >> texture.x;
isline >> texture.y;
- texture.y = 1.0-texture.y;
- mTextures.PushBack( texture );
+ texture.y = 1.0 - texture.y;
+ mTextures.PushBack(texture);
}
- else if ( tag == "#_#vt1" )
+ else if(tag == "#_#vt1")
{
isline >> texture.x;
isline >> texture.y;
- texture.y = 1.0-texture.y;
- mTextures2.PushBack( texture );
+ texture.y = 1.0 - texture.y;
+ mTextures2.PushBack(texture);
}
- else if ( tag == "s" )
+ else if(tag == "s")
{
}
- else if ( tag == "f" )
+ else if(tag == "f")
{
- if ( !iniObj )
+ if(!iniObj)
{
//name assign
}
int numIndices = 0;
- while( ( numIndices < MAX_POINT_INDICES ) && ( isline >> vet[numIndices] ) )
+ while((numIndices < MAX_POINT_INDICES) && (isline >> vet[numIndices]))
{
numIndices++;
}
char separator;
char separator2;
- const char * subString; //A pointer to the position in the string as we move through it.
+ const char* subString; //A pointer to the position in the string as we move through it.
- subString = strstr( vet[0].c_str(),"/" ); //Search for the first '/'
+ subString = strstr(vet[0].c_str(), "/"); //Search for the first '/'
- if( subString )
+ if(subString)
{
- if( subString[1] == '/' ) // Of the form A//C, so has points and normals but no texture coordinates.
+ if(subString[1] == '/') // Of the form A//C, so has points and normals but no texture coordinates.
{
- for( int i = 0 ; i < numIndices; i++)
+ for(int i = 0; i < numIndices; i++)
{
- std::istringstream isindex( vet[i] );
+ std::istringstream isindex(vet[i]);
isindex >> ptIdx[i] >> separator >> separator2 >> nrmIdx[i];
texIdx[i] = 0;
}
}
- else if( strstr( subString, "/" ) ) // Of the form A/B/C, so has points, textures and normals.
+ else if(strstr(subString, "/")) // Of the form A/B/C, so has points, textures and normals.
{
- for( int i = 0 ; i < numIndices; i++ )
+ for(int i = 0; i < numIndices; i++)
{
- std::istringstream isindex( vet[i] );
+ std::istringstream isindex(vet[i]);
isindex >> ptIdx[i] >> separator >> texIdx[i] >> separator2 >> nrmIdx[i];
}
}
else // Of the form A/B, so has points and textures but no normals.
{
- for( int i = 0 ; i < numIndices; i++ )
+ for(int i = 0; i < numIndices; i++)
{
- std::istringstream isindex( vet[i] );
+ std::istringstream isindex(vet[i]);
isindex >> ptIdx[i] >> separator >> texIdx[i];
nrmIdx[i] = 0;
}
}
else // Simply of the form A, as in, point indices only.
{
- for( int i = 0 ; i < numIndices; i++ )
+ for(int i = 0; i < numIndices; i++)
{
- std::istringstream isindex( vet[i] );
+ std::istringstream isindex(vet[i]);
isindex >> ptIdx[i];
texIdx[i] = 0;
nrmIdx[i] = 0;
}
//If it is a triangle
- if( numIndices == 3 )
+ if(numIndices == 3)
{
- for( int i = 0 ; i < 3; i++ )
+ for(int i = 0; i < 3; i++)
{
- triangle.pointIndex[i] = ptIdx[i] - 1 - pntAcum;
- triangle.normalIndex[i] = nrmIdx[i] - 1 - nrmAcum;
+ triangle.pointIndex[i] = ptIdx[i] - 1 - pntAcum;
+ triangle.normalIndex[i] = nrmIdx[i] - 1 - nrmAcum;
triangle.textureIndex[i] = texIdx[i] - 1 - texAcum;
}
- mTriangles.PushBack( triangle );
+ mTriangles.PushBack(triangle);
face++;
}
//If on the other hand it is a quad, we will create two triangles
- else if( numIndices == 4 )
+ else if(numIndices == 4)
{
- for( int i = 0 ; i < 3; i++ )
+ for(int i = 0; i < 3; i++)
{
- triangle.pointIndex[i] = ptIdx[i] - 1 - pntAcum;
- triangle.normalIndex[i] = nrmIdx[i] - 1 - nrmAcum;
+ triangle.pointIndex[i] = ptIdx[i] - 1 - pntAcum;
+ triangle.normalIndex[i] = nrmIdx[i] - 1 - nrmAcum;
triangle.textureIndex[i] = texIdx[i] - 1 - texAcum;
}
- mTriangles.PushBack( triangle );
+ mTriangles.PushBack(triangle);
face++;
- for( int i = 0 ; i < 3; i++ )
+ for(int i = 0; i < 3; i++)
{
- int idx = ( i + 2 ) % numIndices;
- triangle2.pointIndex[i] = ptIdx[idx] - 1 - pntAcum;
- triangle2.normalIndex[i] = nrmIdx[idx] - 1 - nrmAcum;
+ int idx = (i + 2) % numIndices;
+ triangle2.pointIndex[i] = ptIdx[idx] - 1 - pntAcum;
+ triangle2.normalIndex[i] = nrmIdx[idx] - 1 - nrmAcum;
triangle2.textureIndex[i] = texIdx[idx] - 1 - texAcum;
}
- mTriangles.PushBack( triangle2 );
+ mTriangles.PushBack(triangle2);
face++;
}
}
- else if ( tag == "usemtl" )
+ else if(tag == "usemtl")
{
isline >> strMatActual;
}
- else if ( tag == "mtllib" )
+ else if(tag == "mtllib")
{
isline >> strMatActual;
}
- else if ( tag == "g" )
+ else if(tag == "g")
{
isline >> name;
}
}
- if ( iniObj )
+ if(iniObj)
{
- CenterAndScale( true, mPoints );
- mSceneLoaded = true;
+ CenterAndScale(true, mPoints);
+ mSceneLoaded = true;
mHasTexturePoints = hasTexture;
return true;
}
return false;
}
-void ObjLoader::LoadMaterial( char* objBuffer, std::streampos fileSize, std::string& diffuseTextureUrl,
- std::string& normalTextureUrl, std::string& glossTextureUrl )
+void ObjLoader::LoadMaterial(char* objBuffer, std::streampos fileSize, std::string& diffuseTextureUrl, std::string& normalTextureUrl, std::string& glossTextureUrl)
{
- float fR,fG,fB;
+ float fR, fG, fB;
std::string info;
- std::string input( objBuffer, fileSize );
+ std::string input(objBuffer, fileSize);
std::istringstream ss(input);
ss.imbue(std::locale("C"));
std::string line;
- std::getline( ss, line );
+ std::getline(ss, line);
- while ( std::getline( ss, line ) )
+ while(std::getline(ss, line))
{
- std::istringstream isline( line, std::istringstream::in );
- std::string tag;
+ std::istringstream isline(line, std::istringstream::in);
+ std::string tag;
isline >> tag;
- if ( tag == "newmtl" ) //name of the material
+ if(tag == "newmtl") //name of the material
{
isline >> info;
}
- else if ( tag == "Ka" ) //ambient color
+ else if(tag == "Ka") //ambient color
{
isline >> fR >> fG >> fB;
}
- else if ( tag == "Kd" ) //diffuse color
+ else if(tag == "Kd") //diffuse color
{
isline >> fR >> fG >> fB;
}
- else if ( tag == "Ks" ) //specular color
+ else if(tag == "Ks") //specular color
{
isline >> fR >> fG >> fB;
}
- else if ( tag == "Tf" ) //color
+ else if(tag == "Tf") //color
{
}
- else if ( tag == "Ni" )
+ else if(tag == "Ni")
{
}
- else if ( tag == "map_Kd" )
+ else if(tag == "map_Kd")
{
isline >> info;
diffuseTextureUrl = info;
- mHasDiffuseMap = true;
+ mHasDiffuseMap = true;
}
- else if ( tag == "bump" )
+ else if(tag == "bump")
{
isline >> info;
normalTextureUrl = info;
- mHasNormalMap = true;
+ mHasNormalMap = true;
}
- else if ( tag == "map_Ks" )
+ else if(tag == "map_Ks")
{
isline >> info;
glossTextureUrl = info;
mMaterialLoaded = true;
}
-Geometry ObjLoader::CreateGeometry( int objectProperties, bool useSoftNormals )
+Geometry ObjLoader::CreateGeometry(int objectProperties, bool useSoftNormals)
{
Geometry surface = Geometry::New();
- Dali::Vector<Vertex> vertices;
- Dali::Vector<Vector2> textures;
- Dali::Vector<VertexExt> verticesExt;
+ Dali::Vector<Vertex> vertices;
+ Dali::Vector<Vector2> textures;
+ Dali::Vector<VertexExt> verticesExt;
Dali::Vector<unsigned short> indices;
- CreateGeometryArray( vertices, textures, verticesExt, indices, useSoftNormals );
+ CreateGeometryArray(vertices, textures, verticesExt, indices, useSoftNormals);
//All vertices need at least Position and Normal
Property::Map vertexFormat;
- vertexFormat["aPosition"] = Property::VECTOR3;
- vertexFormat["aNormal"] = Property::VECTOR3;
- VertexBuffer surfaceVertices = VertexBuffer::New( vertexFormat );
- surfaceVertices.SetData( &vertices[0], vertices.Size() );
- surface.AddVertexBuffer( surfaceVertices );
+ vertexFormat["aPosition"] = Property::VECTOR3;
+ vertexFormat["aNormal"] = Property::VECTOR3;
+ VertexBuffer surfaceVertices = VertexBuffer::New(vertexFormat);
+ surfaceVertices.SetData(&vertices[0], vertices.Size());
+ surface.AddVertexBuffer(surfaceVertices);
//Some need texture coordinates
- if( ( objectProperties & TEXTURE_COORDINATES ) && mHasTexturePoints && mHasDiffuseMap )
+ if((objectProperties & TEXTURE_COORDINATES) && mHasTexturePoints && mHasDiffuseMap)
{
Property::Map textureFormat;
textureFormat["aTexCoord"] = Property::VECTOR2;
- VertexBuffer extraVertices = VertexBuffer::New( textureFormat );
- extraVertices.SetData( &textures[0], textures.Size() );
+ VertexBuffer extraVertices = VertexBuffer::New(textureFormat);
+ extraVertices.SetData(&textures[0], textures.Size());
- surface.AddVertexBuffer( extraVertices );
+ surface.AddVertexBuffer(extraVertices);
}
//Some need tangent and bitangent
- if( ( objectProperties & TANGENTS ) && ( objectProperties & BINORMALS ) && mHasTexturePoints )
+ if((objectProperties & TANGENTS) && (objectProperties & BINORMALS) && mHasTexturePoints)
{
Property::Map vertexExtFormat;
- vertexExtFormat["aTangent"] = Property::VECTOR3;
+ vertexExtFormat["aTangent"] = Property::VECTOR3;
vertexExtFormat["aBiNormal"] = Property::VECTOR3;
- VertexBuffer extraVertices = VertexBuffer::New( vertexExtFormat );
- extraVertices.SetData( &verticesExt[0], verticesExt.Size() );
+ VertexBuffer extraVertices = VertexBuffer::New(vertexExtFormat);
+ extraVertices.SetData(&verticesExt[0], verticesExt.Size());
- surface.AddVertexBuffer( extraVertices );
+ surface.AddVertexBuffer(extraVertices);
}
//If indices are required, we set them.
- if ( indices.Size() )
+ if(indices.Size())
{
- surface.SetIndexBuffer ( &indices[0], indices.Size() );
+ surface.SetIndexBuffer(&indices[0], indices.Size());
}
return surface;
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace // to register type
{
-
BaseHandle Create()
{
return Toolkit::NavigationView::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::NavigationView, Toolkit::Control, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::NavigationView, Toolkit::Control, Create)
DALI_TYPE_REGISTRATION_END()
} // namespace
NavigationView::NavigationView()
-: Control(ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) )
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT))
{
}
Toolkit::NavigationView NavigationView::New()
{
// Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< NavigationView > internalNavigationView = new NavigationView();
+ IntrusivePtr<NavigationView> internalNavigationView = new NavigationView();
// Pass ownership to CustomActor handle
- Toolkit::NavigationView navigationView( *internalNavigationView );
+ Toolkit::NavigationView navigationView(*internalNavigationView);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
void NavigationView::OnInitialize()
{
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER));
+ });
}
-void NavigationView::OnSceneConnection( int depth )
+void NavigationView::OnSceneConnection(int depth)
{
- Self().SetProperty( Actor::Property::SENSITIVE,true);
+ Self().SetProperty(Actor::Property::SENSITIVE, true);
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
}
-void NavigationView::Push( Actor& actor )
+void NavigationView::Push(Actor& actor)
{
// check the uninitialized item
// check the duplicated push for the top item
- if(!actor )
+ if(!actor)
{
return;
}
- if( mContentStack.size() > 0 )
+ if(mContentStack.size() > 0)
{
- Self().Remove( mContentStack.back() );
+ Self().Remove(mContentStack.back());
}
//push the new item into the stack and show it
{
// cannot pop out the bottom-most item
Actor poppedItem;
- if( mContentStack.size() > 1 )
+ if(mContentStack.size() > 1)
{
// pop out the top item of the stack and show the new item right under the old one.
Self().Remove(mContentStack.back());
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
// EXTERNAL INCLUDES
-#include <string.h>
-#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/actors/actor.h>
+#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/object/property-map.h>
+#include <string.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/controls/page-turn-view/page-turn-effect.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
using namespace Dali;
using namespace Dali::Toolkit;
namespace
{
-const char * const PROPERTY_COMMON_PARAMETERS( "uCommonParameters" );
-const char * const PROPERTY_ORIGINAL_CENTER( "originalCenter" );
-const char * const PROPERTY_CURRENT_CENTER( "currentCenter" );
-}
+const char* const PROPERTY_COMMON_PARAMETERS("uCommonParameters");
+const char* const PROPERTY_ORIGINAL_CENTER("originalCenter");
+const char* const PROPERTY_CURRENT_CENTER("currentCenter");
+} // namespace
/**
* This constraint updates the common parameter values used by every vertex.
*/
struct CommonParametersConstraint
{
- CommonParametersConstraint( float pageHeight )
- : mPageHeight( pageHeight )
- {}
+ CommonParametersConstraint(float pageHeight)
+ : mPageHeight(pageHeight)
+ {
+ }
- void operator()( Dali::Matrix& current, const PropertyInputContainer& inputs )
+ void operator()(Dali::Matrix& current, const PropertyInputContainer& inputs)
{
const Vector2& originalCenter = inputs[0]->GetVector2();
- Vector2 currentCenter = inputs[1]->GetVector2();
+ Vector2 currentCenter = inputs[1]->GetVector2();
// calculate the curve direction and the vanishing point
// here, the vanishing point is the intersection of spine with the line passing through original center and vertical to curve direction
- Vector2 curveDirection( currentCenter - originalCenter );
+ Vector2 curveDirection(currentCenter - originalCenter);
curveDirection.Normalize();
- if( fabs(curveDirection.y) < 0.01f) // eliminate the possibility of division by zero in the next step
+ if(fabs(curveDirection.y) < 0.01f) // eliminate the possibility of division by zero in the next step
{
curveDirection.y = 0.01f;
}
float vanishingPointY = originalCenter.y + curveDirection.x * originalCenter.x / curveDirection.y;
- float curveEndY, cosTheta ,sinTheta ,translateX, translateY;
+ float curveEndY, cosTheta, sinTheta, translateX, translateY;
// when the vanishing point is very far away, make it infinitely, in this case, the page bent horizontally
const float THRESHOLD(20.0);
- if( fabs(vanishingPointY-mPageHeight*0.5f) >= mPageHeight*THRESHOLD )
+ if(fabs(vanishingPointY - mPageHeight * 0.5f) >= mPageHeight * THRESHOLD)
{
- curveDirection = Vector2(-1.f,0.f);
+ curveDirection = Vector2(-1.f, 0.f);
currentCenter.y = originalCenter.y;
- curveEndY = originalCenter.y;
- cosTheta = 1.f;
- sinTheta = 0.f;
+ curveEndY = originalCenter.y;
+ cosTheta = 1.f;
+ sinTheta = 0.f;
translateX = currentCenter.x - originalCenter.x;
translateY = vanishingPointY;
}
else
{
- curveEndY = currentCenter.y - curveDirection.y * (currentCenter.x/curveDirection.x) ;
- Vector2 v1( currentCenter.x, currentCenter.y - vanishingPointY );
+ curveEndY = currentCenter.y - curveDirection.y * (currentCenter.x / curveDirection.x);
+ Vector2 v1(currentCenter.x, currentCenter.y - vanishingPointY);
v1.Normalize();
- Vector2 v2( originalCenter.x, originalCenter.y - vanishingPointY );
+ Vector2 v2(originalCenter.x, originalCenter.y - vanishingPointY);
v2.Normalize();
- cosTheta = v1.x*v2.x + v1.y*v2.y;
- sinTheta = ( vanishingPointY > mPageHeight*0.5f ) ? sqrt(1.0-cosTheta*cosTheta) : -sqrt(1.0-cosTheta*cosTheta);
- translateX = currentCenter.x - cosTheta*originalCenter.x - sinTheta*( originalCenter.y-vanishingPointY );
- translateY = currentCenter.y + sinTheta*originalCenter.x - cosTheta*( originalCenter.y-vanishingPointY );
+ cosTheta = v1.x * v2.x + v1.y * v2.y;
+ sinTheta = (vanishingPointY > mPageHeight * 0.5f) ? sqrt(1.0 - cosTheta * cosTheta) : -sqrt(1.0 - cosTheta * cosTheta);
+ translateX = currentCenter.x - cosTheta * originalCenter.x - sinTheta * (originalCenter.y - vanishingPointY);
+ translateY = currentCenter.y + sinTheta * originalCenter.x - cosTheta * (originalCenter.y - vanishingPointY);
}
- float originalLength = fabs(originalCenter.x/curveDirection.x);
- float currentLength = fabs(currentCenter.x/curveDirection.x);
- float curveHeight = 0.45f*sqrt(originalLength*originalLength - currentLength*currentLength);
+ float originalLength = fabs(originalCenter.x / curveDirection.x);
+ float currentLength = fabs(currentCenter.x / curveDirection.x);
+ float curveHeight = 0.45f * sqrt(originalLength * originalLength - currentLength * currentLength);
float* parameterArray = current.AsFloat();
- parameterArray[0] = cosTheta;
- parameterArray[1] = -sinTheta;
- parameterArray[2] = originalCenter.x;
- parameterArray[3] = originalCenter.y;
- parameterArray[4] = sinTheta;
- parameterArray[5] = cosTheta;
- parameterArray[6] = currentCenter.x;
- parameterArray[7] = currentCenter.y;
- parameterArray[8] = translateX;
- parameterArray[9] = translateY;
- parameterArray[10] = vanishingPointY;
- parameterArray[11] = curveEndY;
- parameterArray[12] = curveDirection.x;
- parameterArray[13] = curveDirection.y;
- parameterArray[14] = curveHeight;
- parameterArray[15] = currentLength;
+ parameterArray[0] = cosTheta;
+ parameterArray[1] = -sinTheta;
+ parameterArray[2] = originalCenter.x;
+ parameterArray[3] = originalCenter.y;
+ parameterArray[4] = sinTheta;
+ parameterArray[5] = cosTheta;
+ parameterArray[6] = currentCenter.x;
+ parameterArray[7] = currentCenter.y;
+ parameterArray[8] = translateX;
+ parameterArray[9] = translateY;
+ parameterArray[10] = vanishingPointY;
+ parameterArray[11] = curveEndY;
+ parameterArray[12] = curveDirection.x;
+ parameterArray[13] = curveDirection.y;
+ parameterArray[14] = curveHeight;
+ parameterArray[15] = currentLength;
}
float mPageHeight;
};
-void Dali::Toolkit::Internal::PageTurnApplyInternalConstraint( Actor& actor, float pageHeight )
+void Dali::Toolkit::Internal::PageTurnApplyInternalConstraint(Actor& actor, float pageHeight)
{
- Constraint constraint = Constraint::New<Dali::Matrix>( actor, actor.GetPropertyIndex( PROPERTY_COMMON_PARAMETERS ) , CommonParametersConstraint( pageHeight ) );
- constraint.AddSource( LocalSource( actor.GetPropertyIndex( PROPERTY_ORIGINAL_CENTER ) ) );
- constraint.AddSource( LocalSource( actor.GetPropertyIndex( PROPERTY_CURRENT_CENTER ) ) );
+ Constraint constraint = Constraint::New<Dali::Matrix>(actor, actor.GetPropertyIndex(PROPERTY_COMMON_PARAMETERS), CommonParametersConstraint(pageHeight));
+ constraint.AddSource(LocalSource(actor.GetPropertyIndex(PROPERTY_ORIGINAL_CENTER)));
+ constraint.AddSource(LocalSource(actor.GetPropertyIndex(PROPERTY_CURRENT_CENTER)));
constraint.Apply();
}
Property::Map customShader;
- customShader[ Toolkit::Visual::Shader::Property::VERTEX_SHADER ] = SHADER_PAGE_TURN_EFFECT_VERT.data();
- customShader[ Toolkit::Visual::Shader::Property::FRAGMENT_SHADER ] = SHADER_PAGE_TURN_EFFECT_FRAG.data();
- customShader[ Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X ] = 20;
- customShader[ Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y ] = 20;
+ customShader[Toolkit::Visual::Shader::Property::VERTEX_SHADER] = SHADER_PAGE_TURN_EFFECT_VERT.data();
+ customShader[Toolkit::Visual::Shader::Property::FRAGMENT_SHADER] = SHADER_PAGE_TURN_EFFECT_FRAG.data();
+ customShader[Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X] = 20;
+ customShader[Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y] = 20;
- map[ Toolkit::Visual::Property::SHADER ] = customShader;
+ map[Toolkit::Visual::Property::SHADER] = customShader;
return map;
-
}
#include <dali-toolkit/internal/controls/page-turn-view/page-turn-landscape-view-impl.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnLandscapeView, Toolkit::PageTurnView, NULL )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::PageTurnLandscapeView, Toolkit::PageTurnView, NULL)
DALI_TYPE_REGISTRATION_END()
-}
+} // namespace
-PageTurnLandscapeView::PageTurnLandscapeView( PageFactory& pageFactory, const Vector2& viewPageSize )
-: PageTurnView( pageFactory, viewPageSize )
+PageTurnLandscapeView::PageTurnLandscapeView(PageFactory& pageFactory, const Vector2& viewPageSize)
+: PageTurnView(pageFactory, viewPageSize)
{
}
PageTurnLandscapeView::~PageTurnLandscapeView()
-{}
+{
+}
-Toolkit::PageTurnLandscapeView PageTurnLandscapeView::New( PageFactory& pageFactory, const Vector2& viewPageSize )
+Toolkit::PageTurnLandscapeView PageTurnLandscapeView::New(PageFactory& pageFactory, const Vector2& viewPageSize)
{
// Create the implementation, temporarily owned on stack
- IntrusivePtr< PageTurnLandscapeView > internalPageTurnView = new PageTurnLandscapeView( pageFactory, viewPageSize );
+ IntrusivePtr<PageTurnLandscapeView> internalPageTurnView = new PageTurnLandscapeView(pageFactory, viewPageSize);
// Pass ownership to CustomActor
- Dali::Toolkit::PageTurnLandscapeView pageTurnView( *internalPageTurnView );
+ Dali::Toolkit::PageTurnLandscapeView pageTurnView(*internalPageTurnView);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
void PageTurnLandscapeView::OnPageTurnViewInitialize()
{
- mTurnEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 2.f );
- mSpineEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 2.f );
+ mTurnEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 2.f);
+ mSpineEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 2.f);
- mControlSize = Vector2( mPageSize.width * 2.f, mPageSize.height );
- Self().SetProperty( Actor::Property::SIZE, mControlSize );
- mTurningPageLayer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mControlSize = Vector2(mPageSize.width * 2.f, mPageSize.height);
+ Self().SetProperty(Actor::Property::SIZE, mControlSize);
+ mTurningPageLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
}
-void PageTurnLandscapeView::OnAddPage( Actor newPage, bool isLeftSide )
+void PageTurnLandscapeView::OnAddPage(Actor newPage, bool isLeftSide)
{
- newPage.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ newPage.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
}
-Vector2 PageTurnLandscapeView::SetPanPosition( const Vector2& gesturePosition )
+Vector2 PageTurnLandscapeView::SetPanPosition(const Vector2& gesturePosition)
{
- if( mPages[mIndex].isTurnBack )
+ if(mPages[mIndex].isTurnBack)
{
- return Vector2( mPageSize.width - gesturePosition.x, gesturePosition.y );
+ return Vector2(mPageSize.width - gesturePosition.x, gesturePosition.y);
}
else
{
- return Vector2( gesturePosition.x - mPageSize.width, gesturePosition.y );
+ return Vector2(gesturePosition.x - mPageSize.width, gesturePosition.y);
}
}
-void PageTurnLandscapeView::SetPanActor( const Vector2& panPosition )
+void PageTurnLandscapeView::SetPanActor(const Vector2& panPosition)
{
- if( panPosition.x > mPageSize.width && mCurrentPageIndex < mTotalPageCount )
+ if(panPosition.x > mPageSize.width && mCurrentPageIndex < mTotalPageCount)
{
mTurningPageIndex = mCurrentPageIndex;
}
- else if( panPosition.x <= mPageSize.width && mCurrentPageIndex > 0 )
+ else if(panPosition.x <= mPageSize.width && mCurrentPageIndex > 0)
{
mTurningPageIndex = mCurrentPageIndex - 1;
}
// EXTERNAL INCLUDES
#include <dali/public-api/animation/animation.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
//INTERNAL INCLUDES
#include <dali-toolkit/internal/controls/page-turn-view/page-turn-effect.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnPortraitView, Toolkit::PageTurnView, NULL )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::PageTurnPortraitView, Toolkit::PageTurnView, NULL)
DALI_TYPE_REGISTRATION_END()
// the panning speed threshold, no matter how far is the pan displacement, pan fast to left/right quickly (speed > 0.3) will turn over/back the page
// the animation duration of turning the previous page back when an outwards flick is detected
const float PAGE_TURN_OVER_ANIMATION_DURATION(0.5f);
-}
+} // namespace
-PageTurnPortraitView::PageTurnPortraitView( PageFactory& pageFactory, const Vector2& viewPageSize )
-: PageTurnView( pageFactory, viewPageSize )
+PageTurnPortraitView::PageTurnPortraitView(PageFactory& pageFactory, const Vector2& viewPageSize)
+: PageTurnView(pageFactory, viewPageSize)
{
}
{
}
-Toolkit::PageTurnPortraitView PageTurnPortraitView::New( PageFactory& pageFactory, const Vector2& viewPageSize )
+Toolkit::PageTurnPortraitView PageTurnPortraitView::New(PageFactory& pageFactory, const Vector2& viewPageSize)
{
// Create the implementation, temporarily owned on stack
- IntrusivePtr< PageTurnPortraitView > internalPageTurnView = new PageTurnPortraitView( pageFactory, viewPageSize );
+ IntrusivePtr<PageTurnPortraitView> internalPageTurnView = new PageTurnPortraitView(pageFactory, viewPageSize);
// Pass ownership to CustomActor
- Dali::Toolkit::PageTurnPortraitView pageTurnView( *internalPageTurnView );
+ Dali::Toolkit::PageTurnPortraitView pageTurnView(*internalPageTurnView);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
void PageTurnPortraitView::OnPageTurnViewInitialize()
{
- mTurnEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 1.f );
- mSpineEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 1.f );
+ mTurnEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 1.f);
+ mSpineEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 1.f);
mControlSize = mPageSize;
- Self().SetProperty( Actor::Property::SIZE, mPageSize );
- mTurningPageLayer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT );
+ Self().SetProperty(Actor::Property::SIZE, mPageSize);
+ mTurningPageLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT);
}
-Vector2 PageTurnPortraitView::SetPanPosition( const Vector2& gesturePosition )
+Vector2 PageTurnPortraitView::SetPanPosition(const Vector2& gesturePosition)
{
return gesturePosition;
}
-void PageTurnPortraitView::SetPanActor( const Vector2& panPosition )
+void PageTurnPortraitView::SetPanActor(const Vector2& panPosition)
{
- if( mCurrentPageIndex < mTotalPageCount )
+ if(mCurrentPageIndex < mTotalPageCount)
{
mTurningPageIndex = mCurrentPageIndex;
}
}
}
-void PageTurnPortraitView::OnPossibleOutwardsFlick( const Vector2& panPosition, float gestureSpeed )
+void PageTurnPortraitView::OnPossibleOutwardsFlick(const Vector2& panPosition, float gestureSpeed)
{
Vector2 offset = panPosition - mPressDownPosition;
// There is previous page and an outwards flick is detected
- if( mCurrentPageIndex > 0 && gestureSpeed > GESTURE_SPEED_THRESHOLD && offset.x > fabs( offset.y ))
+ if(mCurrentPageIndex > 0 && gestureSpeed > GESTURE_SPEED_THRESHOLD && offset.x > fabs(offset.y))
{
- int actorIndex = (mCurrentPageIndex-1) % NUMBER_OF_CACHED_PAGES;
- Actor actor = mPages[ actorIndex ].actor;
+ int actorIndex = (mCurrentPageIndex - 1) % NUMBER_OF_CACHED_PAGES;
+ Actor actor = mPages[actorIndex].actor;
if(actor.GetParent() != Self())
{
return;
// Guard against destruction during signal emission
//Emit signal, to notify that page[mCurrentPageIndex-1] is turning backwards
- Toolkit::PageTurnView handle( GetOwner() );
- mTurningPageIndex = mCurrentPageIndex-1;
- mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), false );
+ Toolkit::PageTurnView handle(GetOwner());
+ mTurningPageIndex = mCurrentPageIndex - 1;
+ mPageTurnStartedSignal.Emit(handle, static_cast<unsigned int>(mTurningPageIndex), false);
//update pages
mCurrentPageIndex--;
- RemovePage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE );
- AddPage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE );
+ RemovePage(mCurrentPageIndex + NUMBER_OF_CACHED_PAGES_EACH_SIDE);
+ AddPage(mCurrentPageIndex - NUMBER_OF_CACHED_PAGES_EACH_SIDE);
OrganizePageDepth();
mPageUpdated = true;
- actor.SetProperty( Actor::Property::VISIBLE,true);
+ actor.SetProperty(Actor::Property::VISIBLE, true);
// Add the page to tuning page layer and set up PageTurnEffect
- mShadowView.Add( actor );
- mPages[actorIndex].UseEffect( mTurnEffectShader );
+ mShadowView.Add(actor);
+ mPages[actorIndex].UseEffect(mTurnEffectShader);
mAnimatingCount++;
- Vector2 originalCenter( mPageSize.width*1.5f, 0.5f*mPageSize.height );
- mPages[actorIndex].SetOriginalCenter( originalCenter );
- mPages[actorIndex].SetCurrentCenter( Vector2( mPageSize.width*0.5f, mPageSize.height*0.5f ) );
+ Vector2 originalCenter(mPageSize.width * 1.5f, 0.5f * mPageSize.height);
+ mPages[actorIndex].SetOriginalCenter(originalCenter);
+ mPages[actorIndex].SetCurrentCenter(Vector2(mPageSize.width * 0.5f, mPageSize.height * 0.5f));
PageTurnApplyInternalConstraint(actor, mPageSize.height);
// Start an animation to turn the previous page back
- Animation animation = Animation::New( PAGE_TURN_OVER_ANIMATION_DURATION );
+ Animation animation = Animation::New(PAGE_TURN_OVER_ANIMATION_DURATION);
mAnimationPageIdPair[animation] = mCurrentPageIndex;
- animation.AnimateTo( Property( actor, mPages[actorIndex].propertyCurrentCenter ),
- originalCenter,
- AlphaFunction::EASE_OUT, TimePeriod(PAGE_TURN_OVER_ANIMATION_DURATION*0.75f) );
- animation.AnimateBy( Property( actor, Actor::Property::ORIENTATION ), AngleAxis( Degree( 180.0f ), Vector3::YAXIS ) ,AlphaFunction::EASE_OUT );
+ animation.AnimateTo(Property(actor, mPages[actorIndex].propertyCurrentCenter),
+ originalCenter,
+ AlphaFunction::EASE_OUT,
+ TimePeriod(PAGE_TURN_OVER_ANIMATION_DURATION * 0.75f));
+ animation.AnimateBy(Property(actor, Actor::Property::ORIENTATION), AngleAxis(Degree(180.0f), Vector3::YAXIS), AlphaFunction::EASE_OUT);
animation.Play();
- animation.FinishedSignal().Connect( this, &PageTurnPortraitView::TurnedOverBackwards );
+ animation.FinishedSignal().Connect(this, &PageTurnPortraitView::TurnedOverBackwards);
}
}
-void PageTurnPortraitView::OnTurnedOver( Actor actor, bool isLeftSide )
+void PageTurnPortraitView::OnTurnedOver(Actor actor, bool isLeftSide)
{
- if( isLeftSide )
+ if(isLeftSide)
{
- actor.SetProperty( Actor::Property::VISIBLE, false );
+ actor.SetProperty(Actor::Property::VISIBLE, false);
}
}
-void PageTurnPortraitView::TurnedOverBackwards( Animation& animation )
+void PageTurnPortraitView::TurnedOverBackwards(Animation& animation)
{
- TurnedOver( animation );
+ TurnedOver(animation);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.h>
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
+#include <dali/integration-api/debug.h>
#include <dali/public-api/animation/animation.h>
#include <dali/public-api/animation/constraint.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/controls/page-turn-view/page-turn-effect.h>
+#include <dali-toolkit/internal/controls/control/control-data-impl.h>
#include <dali-toolkit/internal/controls/page-turn-view/page-turn-book-spine-effect.h>
+#include <dali-toolkit/internal/controls/page-turn-view/page-turn-effect.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
using namespace Dali;
namespace //Unnamed namespace
{
// properties set on shader, these properties have the constant value in regardless of the page status
-const char * const PROPERTY_SPINE_SHADOW ( "uSpineShadowParameter" ); // uniform for both spine and turn effect
+const char* const PROPERTY_SPINE_SHADOW("uSpineShadowParameter"); // uniform for both spine and turn effect
// properties set on actor, the value of these properties varies depending on the page status
// properties used in turn effect
-const char * const PROPERTY_TURN_DIRECTION( "uIsTurningBack" ); // uniform
-const char * const PROPERTY_COMMON_PARAMETERS( "uCommonParameters" ); //uniform
+const char* const PROPERTY_TURN_DIRECTION("uIsTurningBack"); // uniform
+const char* const PROPERTY_COMMON_PARAMETERS("uCommonParameters"); //uniform
-const char * const PROPERTY_PAN_DISPLACEMENT( "panDisplacement" );// property used to constrain the uniforms
-const char * const PROPERTY_PAN_CENTER( "panCenter" );// property used to constrain the uniforms
+const char* const PROPERTY_PAN_DISPLACEMENT("panDisplacement"); // property used to constrain the uniforms
+const char* const PROPERTY_PAN_CENTER("panCenter"); // property used to constrain the uniforms
// default grid density for page turn effect, 20 pixels by 20 pixels
const float DEFAULT_GRID_DENSITY(20.0f);
const Vector2 DEFAULT_SPINE_SHADOW_PARAMETER(50.0f, 20.0f);
// constants for shadow casting
-const float POINT_LIGHT_HEIGHT_RATIO(2.f);
+const float POINT_LIGHT_HEIGHT_RATIO(2.f);
const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.5f);
// constraints ////////////////////////////////////////////////////////////////
struct OriginalCenterConstraint
{
OriginalCenterConstraint(const Vector2& originalCenter, const Vector2& offset)
- : mOldCenter( originalCenter )
+ : mOldCenter(originalCenter)
{
mNewCenter = originalCenter + offset;
- mDistance = offset.Length() * 0.5f;
- mDirection = offset / mDistance;
+ mDistance = offset.Length() * 0.5f;
+ mDirection = offset / mDistance;
}
- void operator()( Vector2& current, const PropertyInputContainer& inputs )
+ void operator()(Vector2& current, const PropertyInputContainer& inputs)
{
float displacement = inputs[0]->GetFloat();
- if( displacement < mDistance )
+ if(displacement < mDistance)
{
current = mOldCenter + mDirection * displacement;
}
else
{
- current = mNewCenter + Vector2(0.25f*(displacement-mDistance), 0.f);
+ current = mNewCenter + Vector2(0.25f * (displacement - mDistance), 0.f);
}
}
Vector2 mOldCenter;
Vector2 mNewCenter;
- float mDistance;
+ float mDistance;
Vector2 mDirection;
};
*/
struct RotationConstraint
{
- RotationConstraint( float distance, float pageWidth, bool isTurnBack )
- : mDistance( distance*0.5f )
+ RotationConstraint(float distance, float pageWidth, bool isTurnBack)
+ : mDistance(distance * 0.5f)
{
- mStep = 1.f / pageWidth;
- mSign = isTurnBack ? -1.0f : 1.0f;
- mConst = isTurnBack ? -1.0f : 0.f;
- mRotation = isTurnBack ? Quaternion( Radian( -Math::PI ), Vector3::YAXIS ) : Quaternion( Radian(0.f), Vector3::YAXIS );
+ mStep = 1.f / pageWidth;
+ mSign = isTurnBack ? -1.0f : 1.0f;
+ mConst = isTurnBack ? -1.0f : 0.f;
+ mRotation = isTurnBack ? Quaternion(Radian(-Math::PI), Vector3::YAXIS) : Quaternion(Radian(0.f), Vector3::YAXIS);
}
- void operator()( Quaternion& current, const PropertyInputContainer& inputs )
+ void operator()(Quaternion& current, const PropertyInputContainer& inputs)
{
float displacement = inputs[0]->GetFloat();
- if( displacement < mDistance)
+ if(displacement < mDistance)
{
current = mRotation;
}
else
{
- float coef = std::max(-1.0f, mStep*(mDistance-displacement));
- float angle = Math::PI * ( mConst + mSign * coef );
- current = Quaternion( Radian( angle ), Vector3::YAXIS );
+ float coef = std::max(-1.0f, mStep * (mDistance - displacement));
+ float angle = Math::PI * (mConst + mSign * coef);
+ current = Quaternion(Radian(angle), Vector3::YAXIS);
}
}
- float mDistance;
- float mStep;
- float mConst;
- float mSign;
+ float mDistance;
+ float mStep;
+ float mConst;
+ float mSign;
Quaternion mRotation;
};
*/
struct CurrentCenterConstraint
{
- CurrentCenterConstraint( float pageWidth )
- : mPageWidth( pageWidth )
+ CurrentCenterConstraint(float pageWidth)
+ : mPageWidth(pageWidth)
{
mThres = pageWidth * PAGE_TURN_OVER_THRESHOLD_RATIO * 0.5f;
}
- void operator()( Vector2& current, const PropertyInputContainer& inputs )
+ void operator()(Vector2& current, const PropertyInputContainer& inputs)
{
const Vector2& centerPosition = inputs[0]->GetVector2();
- if( centerPosition.x > 0.f )
+ if(centerPosition.x > 0.f)
{
- current.x = mThres+centerPosition.x * 0.5f;
+ current.x = mThres + centerPosition.x * 0.5f;
current.y = centerPosition.y;
}
else
{
const Vector2& centerOrigin = inputs[1]->GetVector2();
- Vector2 direction = centerOrigin - Vector2(mThres, centerPosition.y);
- float coef = 1.f+(centerPosition.x*2.f / mPageWidth);
+ Vector2 direction = centerOrigin - Vector2(mThres, centerPosition.y);
+ float coef = 1.f + (centerPosition.x * 2.f / mPageWidth);
// when coef <= 0, the page is flat, slow down the last moment of the page stretch by 10 times to avoid a small bounce
if(coef < 0.025f)
{
- coef = (coef+0.225f)/10.0f;
+ coef = (coef + 0.225f) / 10.0f;
}
current = centerOrigin - direction * coef;
}
struct ShadowBlurStrengthConstraint
{
- ShadowBlurStrengthConstraint( float thres )
- : mThres( thres )
- {}
+ ShadowBlurStrengthConstraint(float thres)
+ : mThres(thres)
+ {
+ }
- void operator()( float& blurStrength, const PropertyInputContainer& inputs )
+ void operator()(float& blurStrength, const PropertyInputContainer& inputs)
{
float displacement = inputs[2]->GetFloat();
- if( EqualsZero(displacement))
+ if(EqualsZero(displacement))
{
const Vector2& cur = inputs[0]->GetVector2();
const Vector2& ori = inputs[1]->GetVector2();
- blurStrength = 5.f*(ori-cur).Length() / mThres;
+ blurStrength = 5.f * (ori - cur).Length() / mThres;
}
else
{
- blurStrength = 1.f - (displacement-2.f*mThres)/mThres;
+ blurStrength = 1.f - (displacement - 2.f * mThres) / mThres;
}
- blurStrength = blurStrength > 1.f ? 1.f : ( blurStrength < 0.f ? 0.f : blurStrength );
+ blurStrength = blurStrength > 1.f ? 1.f : (blurStrength < 0.f ? 0.f : blurStrength);
}
float mThres;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
// empty handle as we cannot create PageTurnView(but type registered for page turn signal)
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnView, Toolkit::Control, Create );
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::PageTurnView, Toolkit::Control, Create);
-DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "viewPageSize", VECTOR2, VIEW_PAGE_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "currentPageId", INTEGER, CURRENT_PAGE_ID )
-DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "spineShadow", VECTOR2, SPINE_SHADOW )
+DALI_PROPERTY_REGISTRATION(Toolkit, PageTurnView, "viewPageSize", VECTOR2, VIEW_PAGE_SIZE)
+DALI_PROPERTY_REGISTRATION(Toolkit, PageTurnView, "currentPageId", INTEGER, CURRENT_PAGE_ID)
+DALI_PROPERTY_REGISTRATION(Toolkit, PageTurnView, "spineShadow", VECTOR2, SPINE_SHADOW)
-DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnStarted", SIGNAL_PAGE_TURN_STARTED )
-DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnFinished", SIGNAL_PAGE_TURN_FINISHED )
-DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanStarted", SIGNAL_PAGE_PAN_STARTED )
-DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanFinished", SIGNAL_PAGE_PAN_FINISHED )
+DALI_SIGNAL_REGISTRATION(Toolkit, PageTurnView, "pageTurnStarted", SIGNAL_PAGE_TURN_STARTED)
+DALI_SIGNAL_REGISTRATION(Toolkit, PageTurnView, "pageTurnFinished", SIGNAL_PAGE_TURN_FINISHED)
+DALI_SIGNAL_REGISTRATION(Toolkit, PageTurnView, "pagePanStarted", SIGNAL_PAGE_PAN_STARTED)
+DALI_SIGNAL_REGISTRATION(Toolkit, PageTurnView, "pagePanFinished", SIGNAL_PAGE_PAN_FINISHED)
DALI_TYPE_REGISTRATION_END()
-}
+} // namespace
// these several constants are also used in the derived classes
-const char * const PageTurnView::PROPERTY_TEXTURE_WIDTH( "uTextureWidth" ); // uniform name
-const char * const PageTurnView::PROPERTY_ORIGINAL_CENTER( "originalCenter" ); // property used to constrain the uniform
-const char * const PageTurnView::PROPERTY_CURRENT_CENTER( "currentCenter" );// property used to constrain the uniform
-const int PageTurnView::MAXIMUM_TURNING_NUM = 4;
-const int PageTurnView::NUMBER_OF_CACHED_PAGES_EACH_SIDE = MAXIMUM_TURNING_NUM + 1;
-const int PageTurnView::NUMBER_OF_CACHED_PAGES = NUMBER_OF_CACHED_PAGES_EACH_SIDE*2;
-const float PageTurnView::STATIC_PAGE_INTERVAL_DISTANCE = 1.0f;
+const char* const PageTurnView::PROPERTY_TEXTURE_WIDTH("uTextureWidth"); // uniform name
+const char* const PageTurnView::PROPERTY_ORIGINAL_CENTER("originalCenter"); // property used to constrain the uniform
+const char* const PageTurnView::PROPERTY_CURRENT_CENTER("currentCenter"); // property used to constrain the uniform
+const int PageTurnView::MAXIMUM_TURNING_NUM = 4;
+const int PageTurnView::NUMBER_OF_CACHED_PAGES_EACH_SIDE = MAXIMUM_TURNING_NUM + 1;
+const int PageTurnView::NUMBER_OF_CACHED_PAGES = NUMBER_OF_CACHED_PAGES_EACH_SIDE * 2;
+const float PageTurnView::STATIC_PAGE_INTERVAL_DISTANCE = 1.0f;
PageTurnView::Page::Page()
-: isTurnBack( false )
+: isTurnBack(false)
{
actor = Actor::New();
- actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT );
- actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT );
- actor.SetProperty( Actor::Property::VISIBLE, false );
+ actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT);
+ actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT);
+ actor.SetProperty(Actor::Property::VISIBLE, false);
- propertyPanDisplacement = actor.RegisterProperty( PROPERTY_PAN_DISPLACEMENT, 0.f );
- propertyPanCenter = actor.RegisterProperty(PROPERTY_PAN_CENTER, Vector2::ZERO);
+ propertyPanDisplacement = actor.RegisterProperty(PROPERTY_PAN_DISPLACEMENT, 0.f);
+ propertyPanCenter = actor.RegisterProperty(PROPERTY_PAN_CENTER, Vector2::ZERO);
propertyOriginalCenter = actor.RegisterProperty(PROPERTY_ORIGINAL_CENTER, Vector2::ZERO);
- propertyCurrentCenter = actor.RegisterProperty(PROPERTY_CURRENT_CENTER, Vector2::ZERO);
+ propertyCurrentCenter = actor.RegisterProperty(PROPERTY_CURRENT_CENTER, Vector2::ZERO);
Matrix zeroMatrix(true);
actor.RegisterProperty(PROPERTY_COMMON_PARAMETERS, zeroMatrix);
propertyTurnDirection = actor.RegisterProperty(PROPERTY_TURN_DIRECTION, -1.f);
}
-void PageTurnView::Page::SetTexture( Texture texture )
+void PageTurnView::Page::SetTexture(Texture texture)
{
- if( !textureSet )
+ if(!textureSet)
{
textureSet = TextureSet::New();
}
- textureSet.SetTexture( 0u, texture );
+ textureSet.SetTexture(0u, texture);
}
void PageTurnView::Page::UseEffect(Shader newShader)
{
shader = newShader;
- if( renderer )
+ if(renderer)
{
- renderer.SetShader( shader );
+ renderer.SetShader(shader);
}
}
void PageTurnView::Page::UseEffect(Shader newShader, Geometry geometry)
{
- UseEffect( newShader );
+ UseEffect(newShader);
- if( !renderer )
+ if(!renderer)
{
- renderer = Renderer::New( geometry, shader );
+ renderer = Renderer::New(geometry, shader);
- if( !textureSet )
+ if(!textureSet)
{
textureSet = TextureSet::New();
}
- renderer.SetTextures( textureSet );
- renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
- actor.AddRenderer( renderer );
+ renderer.SetTextures(textureSet);
+ renderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON);
+ actor.AddRenderer(renderer);
}
}
void PageTurnView::Page::ChangeTurnDirection()
{
isTurnBack = !isTurnBack;
- actor.SetProperty( propertyTurnDirection, isTurnBack ? 1.f : -1.f );
+ actor.SetProperty(propertyTurnDirection, isTurnBack ? 1.f : -1.f);
}
void PageTurnView::Page::SetPanDisplacement(float value)
{
- actor.SetProperty( propertyPanDisplacement, value );
+ actor.SetProperty(propertyPanDisplacement, value);
}
-void PageTurnView::Page::SetPanCenter( const Vector2& value )
+void PageTurnView::Page::SetPanCenter(const Vector2& value)
{
- actor.SetProperty( propertyPanCenter, value );
+ actor.SetProperty(propertyPanCenter, value);
}
-void PageTurnView::Page::SetOriginalCenter( const Vector2& value )
+void PageTurnView::Page::SetOriginalCenter(const Vector2& value)
{
- actor.SetProperty( propertyOriginalCenter, value );
+ actor.SetProperty(propertyOriginalCenter, value);
}
-void PageTurnView::Page::SetCurrentCenter( const Vector2& value )
+void PageTurnView::Page::SetCurrentCenter(const Vector2& value)
{
- actor.SetProperty( propertyCurrentCenter, value );
+ actor.SetProperty(propertyCurrentCenter, value);
}
-PageTurnView::PageTurnView( PageFactory& pageFactory, const Vector2& viewPageSize )
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mPageFactory( &pageFactory ),
- mPageSize( viewPageSize ),
- mSpineShadowParameter( DEFAULT_SPINE_SHADOW_PARAMETER ),
- mDistanceUpCorner( 0.f ),
- mDistanceBottomCorner( 0.f ),
- mPanDisplacement( 0.f ),
- mTotalPageCount( 0 ),
- mCurrentPageIndex( 0 ),
- mTurningPageIndex( 0 ),
- mIndex( 0 ),
- mSlidingCount( 0 ),
- mAnimatingCount( 0 ),
- mConstraints( false ),
- mPress( false ),
- mPageUpdated( true ),
+PageTurnView::PageTurnView(PageFactory& pageFactory, const Vector2& viewPageSize)
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mPageFactory(&pageFactory),
+ mPageSize(viewPageSize),
+ mSpineShadowParameter(DEFAULT_SPINE_SHADOW_PARAMETER),
+ mDistanceUpCorner(0.f),
+ mDistanceBottomCorner(0.f),
+ mPanDisplacement(0.f),
+ mTotalPageCount(0),
+ mCurrentPageIndex(0),
+ mTurningPageIndex(0),
+ mIndex(0),
+ mSlidingCount(0),
+ mAnimatingCount(0),
+ mConstraints(false),
+ mPress(false),
+ mPageUpdated(true),
mPageTurnStartedSignal(),
mPageTurnFinishedSignal(),
mPagePanStartedSignal(),
void PageTurnView::OnInitialize()
{
- // create the book spine effect for static pages
+ // create the book spine effect for static pages
Property::Map spineEffectMap = CreatePageTurnBookSpineEffect();
- mSpineEffectShader = CreateShader( spineEffectMap );
- mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
+ mSpineEffectShader = CreateShader(spineEffectMap);
+ mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter);
// create the turn effect for turning pages
Property::Map turnEffectMap = CreatePageTurnEffect();
- mTurnEffectShader = CreateShader( turnEffectMap );
- mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
+ mTurnEffectShader = CreateShader(turnEffectMap);
+ mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter);
// create the grid geometry for pages
- uint16_t width = static_cast<uint16_t>(mPageSize.width / DEFAULT_GRID_DENSITY + 0.5f);
+ uint16_t width = static_cast<uint16_t>(mPageSize.width / DEFAULT_GRID_DENSITY + 0.5f);
uint16_t height = static_cast<uint16_t>(mPageSize.height / DEFAULT_GRID_DENSITY + 0.5f);
- mGeometry = VisualFactoryCache::CreateGridGeometry( Uint16Pair( width, height ) );
+ mGeometry = VisualFactoryCache::CreateGridGeometry(Uint16Pair(width, height));
- mPages.reserve( NUMBER_OF_CACHED_PAGES );
- for( int i = 0; i < NUMBER_OF_CACHED_PAGES; i++ )
+ mPages.reserve(NUMBER_OF_CACHED_PAGES);
+ for(int i = 0; i < NUMBER_OF_CACHED_PAGES; i++)
{
- mPages.push_back( Page() );
- mPages[i].actor.SetProperty( Actor::Property::SIZE, mPageSize );
- Self().Add( mPages[i].actor );
+ mPages.push_back(Page());
+ mPages[i].actor.SetProperty(Actor::Property::SIZE, mPageSize);
+ Self().Add(mPages[i].actor);
}
// create the layer for turning pages
mTurningPageLayer = Layer::New();
- mTurningPageLayer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT );
- mTurningPageLayer.SetProperty( Layer::Property::BEHAVIOR, Layer::LAYER_3D );
+ mTurningPageLayer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT);
+ mTurningPageLayer.SetProperty(Layer::Property::BEHAVIOR, Layer::LAYER_3D);
mTurningPageLayer.Raise();
// Set control size and the parent origin of page layers
Self().Add(mTurningPageLayer);
- mTotalPageCount = static_cast<int>( mPageFactory->GetNumberOfPages() );
+ mTotalPageCount = static_cast<int>(mPageFactory->GetNumberOfPages());
// add pages to the scene, and set depth for the stacked pages
- for( int i = 0; i < NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ )
+ for(int i = 0; i < NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++)
{
- AddPage( i );
- mPages[i].actor.SetProperty( Actor::Property::POSITION_Z, -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
+ AddPage(i);
+ mPages[i].actor.SetProperty(Actor::Property::POSITION_Z, -static_cast<float>(i) * STATIC_PAGE_INTERVAL_DISTANCE);
}
- mPages[0].actor.SetProperty( Actor::Property::VISIBLE,true);
+ mPages[0].actor.SetProperty(Actor::Property::VISIBLE, true);
// enable the pan gesture which is attached to the control
EnableGestureDetection(GestureType::Value(GestureType::PAN));
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::PAGE_TAB_LIST ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::PAGE_TAB_LIST));
+ });
}
-Shader PageTurnView::CreateShader( const Property::Map& shaderMap )
+Shader PageTurnView::CreateShader(const Property::Map& shaderMap)
{
- Shader shader;
- Property::Value* shaderValue = shaderMap.Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER );
- Property::Map shaderSource;
- if( shaderValue && shaderValue->Get( shaderSource ) )
+ Shader shader;
+ Property::Value* shaderValue = shaderMap.Find(Toolkit::Visual::Property::SHADER, CUSTOM_SHADER);
+ Property::Map shaderSource;
+ if(shaderValue && shaderValue->Get(shaderSource))
{
- std::string vertexShader;
- Property::Value* vertexShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER );
- if( !vertexShaderValue || !vertexShaderValue->Get( vertexShader ) )
+ std::string vertexShader;
+ Property::Value* vertexShaderValue = shaderSource.Find(Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER);
+ if(!vertexShaderValue || !vertexShaderValue->Get(vertexShader))
{
DALI_LOG_ERROR("PageTurnView::CreateShader failed: vertex shader source is not available.\n");
}
- std::string fragmentShader;
- Property::Value* fragmentShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER );
- if( !fragmentShaderValue || !fragmentShaderValue->Get( fragmentShader ) )
+ std::string fragmentShader;
+ Property::Value* fragmentShaderValue = shaderSource.Find(Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER);
+ if(!fragmentShaderValue || !fragmentShaderValue->Get(fragmentShader))
{
DALI_LOG_ERROR("PageTurnView::CreateShader failed: fragment shader source is not available.\n");
}
- shader = Shader::New( vertexShader, fragmentShader );
+ shader = Shader::New(vertexShader, fragmentShader);
}
else
{
void PageTurnView::SetupShadowView()
{
- mShadowView = Toolkit::ShadowView::New( 0.25f, 0.25f );
- Vector3 origin = mTurningPageLayer.GetCurrentProperty< Vector3 >( Actor::Property::PARENT_ORIGIN );
- mShadowView.SetProperty( Actor::Property::PARENT_ORIGIN, origin );
- mShadowView.SetProperty( Actor::Property::ANCHOR_POINT, origin );
- mShadowView.SetPointLightFieldOfView( Math::PI / 2.0f);
+ mShadowView = Toolkit::ShadowView::New(0.25f, 0.25f);
+ Vector3 origin = mTurningPageLayer.GetCurrentProperty<Vector3>(Actor::Property::PARENT_ORIGIN);
+ mShadowView.SetProperty(Actor::Property::PARENT_ORIGIN, origin);
+ mShadowView.SetProperty(Actor::Property::ANCHOR_POINT, origin);
+ mShadowView.SetPointLightFieldOfView(Math::PI / 2.0f);
mShadowView.SetShadowColor(DEFAULT_SHADOW_COLOR);
mShadowPlaneBackground = Actor::New();
- mShadowPlaneBackground.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mShadowPlaneBackground.SetProperty( Actor::Property::SIZE, mControlSize );
- Self().Add( mShadowPlaneBackground );
- mShadowView.SetShadowPlaneBackground( mShadowPlaneBackground );
+ mShadowPlaneBackground.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mShadowPlaneBackground.SetProperty(Actor::Property::SIZE, mControlSize);
+ Self().Add(mShadowPlaneBackground);
+ mShadowView.SetShadowPlaneBackground(mShadowPlaneBackground);
mPointLight = Actor::New();
- mPointLight.SetProperty( Actor::Property::ANCHOR_POINT, origin );
- mPointLight.SetProperty( Actor::Property::PARENT_ORIGIN, origin );
- mPointLight.SetProperty( Actor::Property::POSITION, Vector3( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO ));
- Self().Add( mPointLight );
- mShadowView.SetPointLight( mPointLight );
+ mPointLight.SetProperty(Actor::Property::ANCHOR_POINT, origin);
+ mPointLight.SetProperty(Actor::Property::PARENT_ORIGIN, origin);
+ mPointLight.SetProperty(Actor::Property::POSITION, Vector3(0.f, 0.f, mPageSize.width * POINT_LIGHT_HEIGHT_RATIO));
+ Self().Add(mPointLight);
+ mShadowView.SetPointLight(mPointLight);
- mTurningPageLayer.Add( mShadowView );
+ mTurningPageLayer.Add(mShadowView);
mShadowView.Activate();
}
-void PageTurnView::OnSceneConnection( int depth )
+void PageTurnView::OnSceneConnection(int depth)
{
SetupShadowView();
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
}
void PageTurnView::OnSceneDisconnection()
Control::OnSceneDisconnection();
}
-void PageTurnView::SetPageSize( const Vector2& viewPageSize )
+void PageTurnView::SetPageSize(const Vector2& viewPageSize)
{
mPageSize = viewPageSize;
- if( mPointLight )
+ if(mPointLight)
{
- mPointLight.SetProperty( Actor::Property::POSITION, Vector3( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO ));
+ mPointLight.SetProperty(Actor::Property::POSITION, Vector3(0.f, 0.f, mPageSize.width * POINT_LIGHT_HEIGHT_RATIO));
}
- for( size_t i=0; i<mPages.size(); i++ )
+ for(size_t i = 0; i < mPages.size(); i++)
{
- mPages[i].actor.SetProperty( Actor::Property::SIZE, mPageSize );
+ mPages[i].actor.SetProperty(Actor::Property::SIZE, mPageSize);
}
OnPageTurnViewInitialize();
- if( mShadowPlaneBackground )
+ if(mShadowPlaneBackground)
{
- mShadowPlaneBackground.SetProperty( Actor::Property::SIZE, mControlSize );
+ mShadowPlaneBackground.SetProperty(Actor::Property::SIZE, mControlSize);
}
}
return mPageSize;
}
-void PageTurnView::SetSpineShadowParameter( const Vector2& spineShadowParameter )
+void PageTurnView::SetSpineShadowParameter(const Vector2& spineShadowParameter)
{
mSpineShadowParameter = spineShadowParameter;
// set spine shadow parameter to all the shader effects
- mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
- mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
+ mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter);
+ mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter);
}
Vector2 PageTurnView::GetSpineShadowParameter()
return mSpineShadowParameter;
}
-void PageTurnView::GoToPage( unsigned int pageId )
+void PageTurnView::GoToPage(unsigned int pageId)
{
- int pageIdx = Clamp( static_cast<int>(pageId), 0, mTotalPageCount-1);
+ int pageIdx = Clamp(static_cast<int>(pageId), 0, mTotalPageCount - 1);
- if( mCurrentPageIndex == pageIdx )
+ if(mCurrentPageIndex == pageIdx)
{
return;
}
// record the new current page index
mCurrentPageIndex = pageIdx;
-
// add the current page and the pages right before and after it
- for( int i = pageIdx - NUMBER_OF_CACHED_PAGES_EACH_SIDE; i < pageIdx + NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ )
+ for(int i = pageIdx - NUMBER_OF_CACHED_PAGES_EACH_SIDE; i < pageIdx + NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++)
{
- AddPage( i );
+ AddPage(i);
}
- mPages[pageId%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,true);
- if( pageId > 0 )
+ mPages[pageId % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, true);
+ if(pageId > 0)
{
- mPages[(pageId-1)%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,true);
+ mPages[(pageId - 1) % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, true);
}
// set ordered depth to the stacked pages
OrganizePageDepth();
unsigned int PageTurnView::GetCurrentPage()
{
- DALI_ASSERT_ALWAYS( mCurrentPageIndex >= 0 );
- return static_cast< unsigned int >( mCurrentPageIndex );
+ DALI_ASSERT_ALWAYS(mCurrentPageIndex >= 0);
+ return static_cast<unsigned int>(mCurrentPageIndex);
}
-void PageTurnView::AddPage( int pageIndex )
+void PageTurnView::AddPage(int pageIndex)
{
- if(pageIndex > -1 && pageIndex < mTotalPageCount) // whether the page is available from the page factory
+ if(pageIndex > -1 && pageIndex < mTotalPageCount) // whether the page is available from the page factory
{
int index = pageIndex % NUMBER_OF_CACHED_PAGES;
Texture newPage;
- newPage = mPageFactory->NewPage( pageIndex );
- DALI_ASSERT_ALWAYS( newPage && "must pass in valid texture" );
+ newPage = mPageFactory->NewPage(pageIndex);
+ DALI_ASSERT_ALWAYS(newPage && "must pass in valid texture");
- bool isLeftSide = ( pageIndex < mCurrentPageIndex );
- if( mPages[index].isTurnBack != isLeftSide )
+ bool isLeftSide = (pageIndex < mCurrentPageIndex);
+ if(mPages[index].isTurnBack != isLeftSide)
{
mPages[index].ChangeTurnDirection();
}
- float degree = isLeftSide ? 180.f :0.f;
- mPages[index].actor.SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( degree ), Vector3::YAXIS ) );
- mPages[index].actor.SetProperty( Actor::Property::VISIBLE, false );
- mPages[index].UseEffect( mSpineEffectShader, mGeometry );
- mPages[index].SetTexture( newPage );
+ float degree = isLeftSide ? 180.f : 0.f;
+ mPages[index].actor.SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(degree), Vector3::YAXIS));
+ mPages[index].actor.SetProperty(Actor::Property::VISIBLE, false);
+ mPages[index].UseEffect(mSpineEffectShader, mGeometry);
+ mPages[index].SetTexture(newPage);
// For Portrait, nothing to do
// For Landscape, set the parent origin to CENTER
- OnAddPage( mPages[index].actor, isLeftSide );
+ OnAddPage(mPages[index].actor, isLeftSide);
}
}
-void PageTurnView::RemovePage( int pageIndex )
+void PageTurnView::RemovePage(int pageIndex)
{
- if( pageIndex > -1 && pageIndex < mTotalPageCount)
+ if(pageIndex > -1 && pageIndex < mTotalPageCount)
{
int index = pageIndex % NUMBER_OF_CACHED_PAGES;
- mPages[index].actor.SetProperty( Actor::Property::VISIBLE,false);
+ mPages[index].actor.SetProperty(Actor::Property::VISIBLE, false);
}
}
-void PageTurnView::OnPan( const PanGesture& gesture )
+void PageTurnView::OnPan(const PanGesture& gesture)
{
// the pan gesture is attached to control itself instead of each page
- switch( gesture.GetState() )
+ switch(gesture.GetState())
{
case GestureState::STARTED:
{
// check whether the undergoing turning page number already reaches the maximum allowed
- if( mPageUpdated && mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1 )
+ if(mPageUpdated && mAnimatingCount < MAXIMUM_TURNING_NUM && mSlidingCount < 1)
{
const Vector2& position = gesture.GetPosition();
- SetPanActor( position ); // determine which page actor is panned
- if( mTurningPageIndex != -1 && mPages[mTurningPageIndex % NUMBER_OF_CACHED_PAGES].actor.GetParent() != Self()) // if the page is added to turning layer,it is undergoing an animation currently
+ SetPanActor(position); // determine which page actor is panned
+ if(mTurningPageIndex != -1 && mPages[mTurningPageIndex % NUMBER_OF_CACHED_PAGES].actor.GetParent() != Self()) // if the page is added to turning layer,it is undergoing an animation currently
{
mTurningPageIndex = -1;
}
- PanStarted( SetPanPosition( position ) ); // pass in the pan position in the local page coordinate
+ PanStarted(SetPanPosition(position)); // pass in the pan position in the local page coordinate
}
else
{
}
case GestureState::CONTINUING:
{
- PanContinuing( SetPanPosition( gesture.GetPosition() ) ); // pass in the pan position in the local page coordinate
+ PanContinuing(SetPanPosition(gesture.GetPosition())); // pass in the pan position in the local page coordinate
break;
}
case GestureState::FINISHED:
case GestureState::CANCELLED:
{
- PanFinished( SetPanPosition( gesture.GetPosition() ), gesture.GetSpeed() );
+ PanFinished(SetPanPosition(gesture.GetPosition()), gesture.GetSpeed());
break;
}
case GestureState::CLEAR:
}
}
-void PageTurnView::PanStarted( const Vector2& gesturePosition )
+void PageTurnView::PanStarted(const Vector2& gesturePosition)
{
mPressDownPosition = gesturePosition;
- if( mTurningPageIndex == -1 )
+ if(mTurningPageIndex == -1)
{
return;
}
mIndex = mTurningPageIndex % NUMBER_OF_CACHED_PAGES;
mOriginalCenter = gesturePosition;
- mPress = false;
- mPageUpdated = false;
+ mPress = false;
+ mPageUpdated = false;
// Guard against destruction during signal emission
- Toolkit::PageTurnView handle( GetOwner() );
- mPagePanStartedSignal.Emit( handle );
+ Toolkit::PageTurnView handle(GetOwner());
+ mPagePanStartedSignal.Emit(handle);
}
-void PageTurnView::PanContinuing( const Vector2& gesturePosition )
+void PageTurnView::PanContinuing(const Vector2& gesturePosition)
{
- if( mTurningPageIndex == -1 )
+ if(mTurningPageIndex == -1)
{
return;
}
// Guard against destruction during signal emission
- Toolkit::PageTurnView handle( GetOwner() );
+ Toolkit::PageTurnView handle(GetOwner());
if(!mPress)
{
// when the touch down position is near the spine
// or when the panning goes outwards or some other position which would tear the paper in real situation
// we change the start position into the current panning position and update the shader parameters
- if( mOriginalCenter.x < mPageSize.width*MINIMUM_START_POSITION_RATIO
- || gesturePosition.x > mOriginalCenter.x-1.0f
- || ( ( gesturePosition.x/mOriginalCenter.x > gesturePosition.y/mOriginalCenter.y ) &&
- ( gesturePosition.x/mOriginalCenter.x > (gesturePosition.y-mPageSize.height )/(mOriginalCenter.y-mPageSize.height ) ) ) )
+ if(mOriginalCenter.x < mPageSize.width * MINIMUM_START_POSITION_RATIO || gesturePosition.x > mOriginalCenter.x - 1.0f || ((gesturePosition.x / mOriginalCenter.x > gesturePosition.y / mOriginalCenter.y) && (gesturePosition.x / mOriginalCenter.x > (gesturePosition.y - mPageSize.height) / (mOriginalCenter.y - mPageSize.height))))
{
mOriginalCenter = gesturePosition;
}
else
{
- mDistanceUpCorner = mOriginalCenter.Length();
- mDistanceBottomCorner = ( mOriginalCenter - Vector2( 0.0f, mPageSize.height ) ).Length();
- mShadowView.Add( mPages[mIndex].actor );
- mPages[mIndex].UseEffect( mTurnEffectShader );
- mPages[mIndex].SetOriginalCenter( mOriginalCenter );
+ mDistanceUpCorner = mOriginalCenter.Length();
+ mDistanceBottomCorner = (mOriginalCenter - Vector2(0.0f, mPageSize.height)).Length();
+ mShadowView.Add(mPages[mIndex].actor);
+ mPages[mIndex].UseEffect(mTurnEffectShader);
+ mPages[mIndex].SetOriginalCenter(mOriginalCenter);
mCurrentCenter = mOriginalCenter;
- mPages[mIndex].SetCurrentCenter( mCurrentCenter );
+ mPages[mIndex].SetCurrentCenter(mCurrentCenter);
mPanDisplacement = 0.f;
- mConstraints = false;
- mPress = true;
+ mConstraints = false;
+ mPress = true;
mAnimatingCount++;
- mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), !mPages[mIndex].isTurnBack );
+ mPageTurnStartedSignal.Emit(handle, static_cast<unsigned int>(mTurningPageIndex), !mPages[mIndex].isTurnBack);
int id = mTurningPageIndex + (mPages[mIndex].isTurnBack ? -1 : 1);
- if( id >=0 && id < mTotalPageCount )
+ if(id >= 0 && id < mTotalPageCount)
{
- mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,true);
+ mPages[id % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, true);
}
mShadowView.RemoveConstraints();
Actor self = Self();
- mPages[mIndex].SetPanDisplacement( 0.f );
+ mPages[mIndex].SetPanDisplacement(0.f);
- Constraint shadowBlurStrengthConstraint = Constraint::New<float>( mShadowView, mShadowView.GetBlurStrengthPropertyIndex(), ShadowBlurStrengthConstraint( mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO ) );
- shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter) );
- shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter) );
- shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement) );
+ Constraint shadowBlurStrengthConstraint = Constraint::New<float>(mShadowView, mShadowView.GetBlurStrengthPropertyIndex(), ShadowBlurStrengthConstraint(mPageSize.width * PAGE_TURN_OVER_THRESHOLD_RATIO));
+ shadowBlurStrengthConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter));
+ shadowBlurStrengthConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter));
+ shadowBlurStrengthConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement));
shadowBlurStrengthConstraint.Apply();
}
}
// Test whether the new current center would tear the paper from the top pine in real situation
// we do not forbid this totally, which would restrict the panning gesture too much
// instead, set it to the nearest allowable position
- float distanceUpCorner = currentCenter.Length();
- float distanceBottomCorner = ( currentCenter-Vector2( 0.0f, mPageSize.height ) ).Length();
- if( distanceUpCorner > mDistanceUpCorner )
+ float distanceUpCorner = currentCenter.Length();
+ float distanceBottomCorner = (currentCenter - Vector2(0.0f, mPageSize.height)).Length();
+ if(distanceUpCorner > mDistanceUpCorner)
{
- currentCenter = currentCenter*mDistanceUpCorner/distanceUpCorner;
+ currentCenter = currentCenter * mDistanceUpCorner / distanceUpCorner;
}
// would tear the paper from the bottom spine in real situation
- if( distanceBottomCorner > mDistanceBottomCorner )
+ if(distanceBottomCorner > mDistanceBottomCorner)
{
- currentCenter = ( ( currentCenter - Vector2( 0.0f, mPageSize.height ) )*mDistanceBottomCorner/distanceBottomCorner + Vector2(0.0f,mPageSize.height ) );
+ currentCenter = ((currentCenter - Vector2(0.0f, mPageSize.height)) * mDistanceBottomCorner / distanceBottomCorner + Vector2(0.0f, mPageSize.height));
}
// If direction has a very high y component, reduce it.
Vector2 curveDirection = currentCenter - mOriginalCenter;
- if( fabs( curveDirection.y ) > fabs( curveDirection.x ) )
+ if(fabs(curveDirection.y) > fabs(curveDirection.x))
{
- currentCenter.y = mOriginalCenter.y + ( currentCenter.y - mOriginalCenter.y ) * fabs( curveDirection.x/curveDirection.y );
+ currentCenter.y = mOriginalCenter.y + (currentCenter.y - mOriginalCenter.y) * fabs(curveDirection.x / curveDirection.y);
}
// If the vertical distance is high, reduce it
float yShift = currentCenter.y - mOriginalCenter.y;
- if( fabs( yShift ) > mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO )
+ if(fabs(yShift) > mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO)
{
- currentCenter.y = mOriginalCenter.y + yShift*mPageSize.height*MAXIMUM_VERTICAL_MOVEMENT_RATIO/fabs(yShift );
+ currentCenter.y = mOriginalCenter.y + yShift * mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO / fabs(yShift);
}
// use contraints to control the page shape and rotation when the pan position is near the spine
- if( currentCenter.x <= mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO && mOriginalCenter.x > mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO )
+ if(currentCenter.x <= mPageSize.width * PAGE_TURN_OVER_THRESHOLD_RATIO && mOriginalCenter.x > mPageSize.width * PAGE_TURN_OVER_THRESHOLD_RATIO)
{
// set the property values used by the constraints
- mPanDisplacement = mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO - currentCenter.x;
- mPages[mIndex].SetPanDisplacement( mPanDisplacement );
- mPages[mIndex].SetPanCenter( currentCenter );
+ mPanDisplacement = mPageSize.width * PAGE_TURN_OVER_THRESHOLD_RATIO - currentCenter.x;
+ mPages[mIndex].SetPanDisplacement(mPanDisplacement);
+ mPages[mIndex].SetPanCenter(currentCenter);
// set up the OriginalCenterConstraint and CurrentCebterConstraint to the PageTurnEdffect
// also set up the RotationConstraint to the page actor
- if( !mConstraints )
+ if(!mConstraints)
{
Vector2 corner;
// the corner position need to be a little far away from the page edge to ensure the whole page is lift up
- if( currentCenter.y >= mOriginalCenter.y )
+ if(currentCenter.y >= mOriginalCenter.y)
{
- corner = Vector2( 1.1f*mPageSize.width, 0.f );
+ corner = Vector2(1.1f * mPageSize.width, 0.f);
}
else
{
- corner = mPageSize*1.1f;
+ corner = mPageSize * 1.1f;
}
- Vector2 offset( currentCenter-mOriginalCenter );
- float k = - ( (mOriginalCenter.x-corner.x)*offset.x + (mOriginalCenter.y-corner.y)*offset.y )
- /( offset.x*offset.x + offset.y*offset.y );
+ Vector2 offset(currentCenter - mOriginalCenter);
+ float k = -((mOriginalCenter.x - corner.x) * offset.x + (mOriginalCenter.y - corner.y) * offset.y) / (offset.x * offset.x + offset.y * offset.y);
offset *= k;
Actor self = Self();
- Constraint originalCenterConstraint = Constraint::New<Vector2>( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter, OriginalCenterConstraint( mOriginalCenter, offset ));
- originalCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) );
+ Constraint originalCenterConstraint = Constraint::New<Vector2>(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter, OriginalCenterConstraint(mOriginalCenter, offset));
+ originalCenterConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement));
originalCenterConstraint.Apply();
- Constraint currentCenterConstraint = Constraint::New<Vector2>( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter, CurrentCenterConstraint(mPageSize.width));
- currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanCenter ) );
- currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter ) );
+ Constraint currentCenterConstraint = Constraint::New<Vector2>(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter, CurrentCenterConstraint(mPageSize.width));
+ currentCenterConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter));
+ currentCenterConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter));
currentCenterConstraint.Apply();
- PageTurnApplyInternalConstraint( mPages[mIndex].actor, mPageSize.height );
+ PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height);
- float distance = offset.Length();
- Constraint rotationConstraint = Constraint::New<Quaternion>( mPages[mIndex].actor, Actor::Property::ORIENTATION, RotationConstraint(distance, mPageSize.width, mPages[mIndex].isTurnBack));
- rotationConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) );
+ float distance = offset.Length();
+ Constraint rotationConstraint = Constraint::New<Quaternion>(mPages[mIndex].actor, Actor::Property::ORIENTATION, RotationConstraint(distance, mPageSize.width, mPages[mIndex].isTurnBack));
+ rotationConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement));
rotationConstraint.Apply();
mConstraints = true;
if(mConstraints) // remove the constraint is the pan position move back to far away from the spine
{
mPages[mIndex].actor.RemoveConstraints();
- mPages[mIndex].SetOriginalCenter(mOriginalCenter );
- mConstraints = false;
+ mPages[mIndex].SetOriginalCenter(mOriginalCenter);
+ mConstraints = false;
mPanDisplacement = 0.f;
}
- mPages[mIndex].SetCurrentCenter( currentCenter );
+ mPages[mIndex].SetCurrentCenter(currentCenter);
mCurrentCenter = currentCenter;
- PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height );
+ PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height);
}
}
}
-void PageTurnView::PanFinished( const Vector2& gesturePosition, float gestureSpeed )
+void PageTurnView::PanFinished(const Vector2& gesturePosition, float gestureSpeed)
{
// Guard against destruction during signal emission
- Toolkit::PageTurnView handle( GetOwner() );
+ Toolkit::PageTurnView handle(GetOwner());
- if( mTurningPageIndex == -1 )
+ if(mTurningPageIndex == -1)
{
- if( mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1)
+ if(mAnimatingCount < MAXIMUM_TURNING_NUM && mSlidingCount < 1)
{
- OnPossibleOutwardsFlick( gesturePosition, gestureSpeed );
+ OnPossibleOutwardsFlick(gesturePosition, gestureSpeed);
}
return;
}
- mPagePanFinishedSignal.Emit( handle );
+ mPagePanFinishedSignal.Emit(handle);
if(mPress)
{
if(mPages[mIndex].isTurnBack)
{
mCurrentPageIndex--;
- RemovePage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE );
- AddPage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE );
+ RemovePage(mCurrentPageIndex + NUMBER_OF_CACHED_PAGES_EACH_SIDE);
+ AddPage(mCurrentPageIndex - NUMBER_OF_CACHED_PAGES_EACH_SIDE);
}
else
{
mCurrentPageIndex++;
- RemovePage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 );
- AddPage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 );
+ RemovePage(mCurrentPageIndex - NUMBER_OF_CACHED_PAGES_EACH_SIDE - 1);
+ AddPage(mCurrentPageIndex + NUMBER_OF_CACHED_PAGES_EACH_SIDE - 1);
}
OrganizePageDepth();
// set up an animation to turn the page over
- float width = mPageSize.width*(1.f+PAGE_TURN_OVER_THRESHOLD_RATIO);
- Animation animation = Animation::New( std::max(0.1f,PAGE_TURN_OVER_ANIMATION_DURATION * (1.0f - mPanDisplacement / width)) );
- animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement),
- width,AlphaFunction::EASE_OUT_SINE);
- animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter),
- Vector2(-mPageSize.width*1.1f, 0.5f*mPageSize.height), AlphaFunction::EASE_OUT_SINE);
+ float width = mPageSize.width * (1.f + PAGE_TURN_OVER_THRESHOLD_RATIO);
+ Animation animation = Animation::New(std::max(0.1f, PAGE_TURN_OVER_ANIMATION_DURATION * (1.0f - mPanDisplacement / width)));
+ animation.AnimateTo(Property(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement),
+ width,
+ AlphaFunction::EASE_OUT_SINE);
+ animation.AnimateTo(Property(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter),
+ Vector2(-mPageSize.width * 1.1f, 0.5f * mPageSize.height),
+ AlphaFunction::EASE_OUT_SINE);
mAnimationPageIdPair[animation] = mTurningPageIndex;
animation.Play();
- animation.FinishedSignal().Connect( this, &PageTurnView::TurnedOver );
+ animation.FinishedSignal().Connect(this, &PageTurnView::TurnedOver);
}
else // the pan finished position is far away from the spine, set up an animation to slide the page back instead of turning over
{
- Animation animation= Animation::New( PAGE_SLIDE_BACK_ANIMATION_DURATION * (mOriginalCenter.x - mCurrentCenter.x) / mPageSize.width / PAGE_TURN_OVER_THRESHOLD_RATIO );
- animation.AnimateTo( Property( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter ),
- mOriginalCenter, AlphaFunction::LINEAR );
+ Animation animation = Animation::New(PAGE_SLIDE_BACK_ANIMATION_DURATION * (mOriginalCenter.x - mCurrentCenter.x) / mPageSize.width / PAGE_TURN_OVER_THRESHOLD_RATIO);
+ animation.AnimateTo(Property(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter),
+ mOriginalCenter,
+ AlphaFunction::LINEAR);
mAnimationPageIdPair[animation] = mTurningPageIndex;
animation.Play();
mSlidingCount++;
- animation.FinishedSignal().Connect( this, &PageTurnView::SliddenBack );
+ animation.FinishedSignal().Connect(this, &PageTurnView::SliddenBack);
- mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), mPages[mIndex].isTurnBack );
+ mPageTurnStartedSignal.Emit(handle, static_cast<unsigned int>(mTurningPageIndex), mPages[mIndex].isTurnBack);
}
}
else
{
// In portrait view, an outwards flick should turn the previous page back
// In landscape view, nothing to do
- OnPossibleOutwardsFlick( gesturePosition, gestureSpeed );
+ OnPossibleOutwardsFlick(gesturePosition, gestureSpeed);
}
mPageUpdated = true;
}
-void PageTurnView::TurnedOver( Animation& animation )
+void PageTurnView::TurnedOver(Animation& animation)
{
int pageId = mAnimationPageIdPair[animation];
- int index = pageId%NUMBER_OF_CACHED_PAGES;
+ int index = pageId % NUMBER_OF_CACHED_PAGES;
mPages[index].ChangeTurnDirection();
mPages[index].actor.RemoveConstraints();
Self().Add(mPages[index].actor);
mAnimatingCount--;
- mAnimationPageIdPair.erase( animation );
+ mAnimationPageIdPair.erase(animation);
float degree = mPages[index].isTurnBack ? 180.f : 0.f;
- mPages[index].actor.SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree(degree), Vector3::YAXIS ) );
- mPages[index].UseEffect( mSpineEffectShader );
+ mPages[index].actor.SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(degree), Vector3::YAXIS));
+ mPages[index].UseEffect(mSpineEffectShader);
int id = pageId + (mPages[index].isTurnBack ? -1 : 1);
- if( id >=0 && id < mTotalPageCount )
+ if(id >= 0 && id < mTotalPageCount)
{
- mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,false);
+ mPages[id % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, false);
}
- OnTurnedOver( mPages[index].actor, mPages[index].isTurnBack );
+ OnTurnedOver(mPages[index].actor, mPages[index].isTurnBack);
// Guard against destruction during signal emission
- Toolkit::PageTurnView handle( GetOwner() );
- mPageTurnFinishedSignal.Emit( handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack );
+ Toolkit::PageTurnView handle(GetOwner());
+ mPageTurnFinishedSignal.Emit(handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack);
}
-void PageTurnView::SliddenBack( Animation& animation )
+void PageTurnView::SliddenBack(Animation& animation)
{
int pageId = mAnimationPageIdPair[animation];
- int index = pageId%NUMBER_OF_CACHED_PAGES;
+ int index = pageId % NUMBER_OF_CACHED_PAGES;
Self().Add(mPages[index].actor);
mSlidingCount--;
mAnimatingCount--;
- mAnimationPageIdPair.erase( animation );
+ mAnimationPageIdPair.erase(animation);
- mPages[index].UseEffect( mSpineEffectShader );
+ mPages[index].UseEffect(mSpineEffectShader);
int id = pageId + (mPages[index].isTurnBack ? -1 : 1);
- if( id >=0 && id < mTotalPageCount )
+ if(id >= 0 && id < mTotalPageCount)
{
- mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,false);
+ mPages[id % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, false);
}
// Guard against destruction during signal emission
- Toolkit::PageTurnView handle( GetOwner() );
- mPageTurnFinishedSignal.Emit( handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack );
+ Toolkit::PageTurnView handle(GetOwner());
+ mPageTurnFinishedSignal.Emit(handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack);
}
void PageTurnView::OrganizePageDepth()
{
- for( int i=0; i<NUMBER_OF_CACHED_PAGES_EACH_SIDE;i++ )
+ for(int i = 0; i < NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++)
{
- if(mCurrentPageIndex+i < mTotalPageCount)
+ if(mCurrentPageIndex + i < mTotalPageCount)
{
- mPages[( mCurrentPageIndex+i )%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::POSITION_Z, -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
+ mPages[(mCurrentPageIndex + i) % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::POSITION_Z, -static_cast<float>(i) * STATIC_PAGE_INTERVAL_DISTANCE);
}
- if( mCurrentPageIndex >= i + 1 )
+ if(mCurrentPageIndex >= i + 1)
{
- mPages[( mCurrentPageIndex-i-1 )%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::POSITION_Z, -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
+ mPages[(mCurrentPageIndex - i - 1) % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::POSITION_Z, -static_cast<float>(i) * STATIC_PAGE_INTERVAL_DISTANCE);
}
}
}
void PageTurnView::StopTurning()
{
mAnimatingCount = 0;
- mSlidingCount = 0;
+ mSlidingCount = 0;
- if( !mPageUpdated )
+ if(!mPageUpdated)
{
int index = mTurningPageIndex % NUMBER_OF_CACHED_PAGES;
- Self().Add( mPages[ index ].actor );
- mPages[ index ].actor.RemoveConstraints();
- mPages[ index ].UseEffect( mSpineEffectShader );
- float degree = mTurningPageIndex==mCurrentPageIndex ? 0.f :180.f;
- mPages[index].actor.SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree(degree), Vector3::YAXIS ) );
+ Self().Add(mPages[index].actor);
+ mPages[index].actor.RemoveConstraints();
+ mPages[index].UseEffect(mSpineEffectShader);
+ float degree = mTurningPageIndex == mCurrentPageIndex ? 0.f : 180.f;
+ mPages[index].actor.SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(degree), Vector3::YAXIS));
mPageUpdated = true;
}
- if( !mAnimationPageIdPair.empty() )
+ if(!mAnimationPageIdPair.empty())
{
- for (std::map<Animation,int>::iterator it=mAnimationPageIdPair.begin(); it!=mAnimationPageIdPair.end(); ++it)
+ for(std::map<Animation, int>::iterator it = mAnimationPageIdPair.begin(); it != mAnimationPageIdPair.end(); ++it)
{
- static_cast<Animation>(it->first).SetCurrentProgress( 1.f );
+ static_cast<Animation>(it->first).SetCurrentProgress(1.f);
}
}
}
return mPagePanFinishedSignal;
}
-bool PageTurnView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool PageTurnView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( handle );
+ bool connected(true);
+ Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_STARTED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_PAGE_TURN_STARTED))
{
- pageTurnView.PageTurnStartedSignal().Connect( tracker, functor );
+ pageTurnView.PageTurnStartedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_FINISHED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_PAGE_TURN_FINISHED))
{
- pageTurnView.PageTurnFinishedSignal().Connect( tracker, functor );
+ pageTurnView.PageTurnFinishedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_STARTED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_PAGE_PAN_STARTED))
{
- pageTurnView.PagePanStartedSignal().Connect( tracker, functor );
+ pageTurnView.PagePanStartedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_FINISHED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_PAGE_PAN_FINISHED))
{
- pageTurnView.PagePanFinishedSignal().Connect( tracker, functor );
+ pageTurnView.PagePanFinishedSignal().Connect(tracker, functor);
}
else
{
return connected;
}
-void PageTurnView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void PageTurnView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast(Dali::BaseHandle(object));
- if( pageTurnView )
+ if(pageTurnView)
{
- PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) );
+ PageTurnView& pageTurnViewImpl(GetImplementation(pageTurnView));
- switch( index )
+ switch(index)
{
case Toolkit::PageTurnView::Property::VIEW_PAGE_SIZE:
{
- pageTurnViewImpl.SetPageSize( value.Get<Vector2>() );
+ pageTurnViewImpl.SetPageSize(value.Get<Vector2>());
break;
}
case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID:
{
- pageTurnViewImpl.GoToPage( value.Get<int>() );
+ pageTurnViewImpl.GoToPage(value.Get<int>());
break;
}
case Toolkit::PageTurnView::Property::SPINE_SHADOW:
{
- pageTurnViewImpl.SetSpineShadowParameter( value.Get<Vector2>() );
+ pageTurnViewImpl.SetSpineShadowParameter(value.Get<Vector2>());
break;
}
}
}
}
-Property::Value PageTurnView::GetProperty( BaseObject* object, Property::Index index )
+Property::Value PageTurnView::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast(Dali::BaseHandle(object));
- if( pageTurnView )
+ if(pageTurnView)
{
- PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) );
+ PageTurnView& pageTurnViewImpl(GetImplementation(pageTurnView));
- switch( index )
+ switch(index)
{
case Toolkit::PageTurnView::Property::VIEW_PAGE_SIZE:
{
}
case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID:
{
- value = static_cast<int>( pageTurnViewImpl.GetCurrentPage() );
+ value = static_cast<int>(pageTurnViewImpl.GetCurrentPage());
break;
}
case Toolkit::PageTurnView::Property::SPINE_SHADOW:
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "confirmation-popup-impl.h"
// EXTERNAL INCLUDES
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
#include <cstring>
// INTERNAL INCLUDES
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
/*
* This struct is used to define all details required about a dynamically created signal.
*/
const char* connectSignalPropertyName;
};
+// clang-format off
/* A table of all control details. These details are kept in one place for maintainability.
* Name of the signal | Name of the control | Name of the property which lets the
* the app-developer | which will provide | app developer choose which signal
* can connect to. | the signal. | within the control to connect to. */
const ControlDetailType ControlDetails[] = {
- { "controlSignalOk", "controlOk", "connectSignalOkSelected" },
- { "controlSignalCancel", "controlCancel", "connectSignalCancelSelected" },
+ {"controlSignalOk", "controlOk", "connectSignalOkSelected" },
+ {"controlSignalCancel", "controlCancel", "connectSignalCancelSelected"},
};
-const unsigned int ControlDetailsCount = sizeof( ControlDetails ) / sizeof( ControlDetails[0] );
+// clang-format on
+const unsigned int ControlDetailsCount = sizeof(ControlDetails) / sizeof(ControlDetails[0]);
// To give sensible default behaviour to save the connect signal properties being set.
const char* const DEFAULT_CONNECT_SIGNAL_NAME = "clicked";
return Toolkit::ConfirmationPopup::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ConfirmationPopup, Toolkit::Popup, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ConfirmationPopup, Toolkit::Popup, Create)
-DALI_PROPERTY_REGISTRATION( Toolkit, ConfirmationPopup, ControlDetails[0].connectSignalPropertyName, STRING, CONNECT_SIGNAL_OK_SELECTED )
-DALI_PROPERTY_REGISTRATION( Toolkit, ConfirmationPopup, ControlDetails[1].connectSignalPropertyName, STRING, CONNECT_SIGNAL_CANCEL_SELECTED )
+DALI_PROPERTY_REGISTRATION(Toolkit, ConfirmationPopup, ControlDetails[0].connectSignalPropertyName, STRING, CONNECT_SIGNAL_OK_SELECTED)
+DALI_PROPERTY_REGISTRATION(Toolkit, ConfirmationPopup, ControlDetails[1].connectSignalPropertyName, STRING, CONNECT_SIGNAL_CANCEL_SELECTED)
// Note: We do not use the macros for signal registration as we do not want to redefine the signal name strings.
// We have predefined them for optimal signal name to control name lookup.
-SignalConnectorType signalConnector1( typeRegistration, ControlDetails[0].signalName, &Toolkit::Internal::ConfirmationPopup::DoConnectSignal );
-SignalConnectorType signalConnector2( typeRegistration, ControlDetails[1].signalName, &Toolkit::Internal::ConfirmationPopup::DoConnectSignal );
+SignalConnectorType signalConnector1(typeRegistration, ControlDetails[0].signalName, &Toolkit::Internal::ConfirmationPopup::DoConnectSignal);
+SignalConnectorType signalConnector2(typeRegistration, ControlDetails[1].signalName, &Toolkit::Internal::ConfirmationPopup::DoConnectSignal);
DALI_TYPE_REGISTRATION_END()
Dali::Toolkit::ConfirmationPopup ConfirmationPopup::New()
{
// Create the implementation, temporarily owned on stack.
- IntrusivePtr< ConfirmationPopup > internalConfirmationPopup = new ConfirmationPopup();
+ IntrusivePtr<ConfirmationPopup> internalConfirmationPopup = new ConfirmationPopup();
// Pass ownership to CustomActor
- Dali::Toolkit::ConfirmationPopup confirmationPopup( *internalConfirmationPopup );
+ Dali::Toolkit::ConfirmationPopup confirmationPopup(*internalConfirmationPopup);
// Second-phase initialisation of the implementation.
// This can only be done after the CustomActor connection has been made...
ConfirmationPopup::ConfirmationPopup()
: Toolkit::Internal::Popup()
{
- mControlSignals.reserve( MAXIMUM_NUMBER_OF_CONTROLS );
- mControlSignalNames[ Toolkit::ConfirmationPopup::CONTROL_OK ] = DEFAULT_CONNECT_SIGNAL_NAME;
- mControlSignalNames[ Toolkit::ConfirmationPopup::CONTROL_CANCEL ] = DEFAULT_CONNECT_SIGNAL_NAME;
+ mControlSignals.reserve(MAXIMUM_NUMBER_OF_CONTROLS);
+ mControlSignalNames[Toolkit::ConfirmationPopup::CONTROL_OK] = DEFAULT_CONNECT_SIGNAL_NAME;
+ mControlSignalNames[Toolkit::ConfirmationPopup::CONTROL_CANCEL] = DEFAULT_CONNECT_SIGNAL_NAME;
}
ConfirmationPopup::~ConfirmationPopup()
{
- for( SignalContainerType::iterator i = mControlSignals.begin(); i != mControlSignals.end(); ++i )
+ for(SignalContainerType::iterator i = mControlSignals.begin(); i != mControlSignals.end(); ++i)
{
- delete ( i->second );
+ delete(i->second);
}
mControlSignals.clear();
}
-void ConfirmationPopup::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
+void ConfirmationPopup::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value)
{
- Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast(Dali::BaseHandle(object));
- if ( popup )
+ if(popup)
{
- ConfirmationPopup& popupImpl( GetDerivedImplementation( popup ) );
+ ConfirmationPopup& popupImpl(GetDerivedImplementation(popup));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::ConfirmationPopup::Property::CONNECT_SIGNAL_OK_SELECTED:
{
- popupImpl.SetControlSignalName( Toolkit::ConfirmationPopup::CONTROL_OK, value.Get< std::string >() );
+ popupImpl.SetControlSignalName(Toolkit::ConfirmationPopup::CONTROL_OK, value.Get<std::string>());
break;
}
case Toolkit::ConfirmationPopup::Property::CONNECT_SIGNAL_CANCEL_SELECTED:
{
- popupImpl.SetControlSignalName( Toolkit::ConfirmationPopup::CONTROL_CANCEL, value.Get< std::string >() );
+ popupImpl.SetControlSignalName(Toolkit::ConfirmationPopup::CONTROL_CANCEL, value.Get<std::string>());
break;
}
}
}
}
-Property::Value ConfirmationPopup::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value ConfirmationPopup::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast(Dali::BaseHandle(object));
- if ( popup )
+ if(popup)
{
- ConfirmationPopup& popupImpl( GetDerivedImplementation( popup ) );
+ ConfirmationPopup& popupImpl(GetDerivedImplementation(popup));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::ConfirmationPopup::Property::CONNECT_SIGNAL_OK_SELECTED:
{
- value = popupImpl.GetControlSignalName( Toolkit::ConfirmationPopup::CONTROL_OK );
+ value = popupImpl.GetControlSignalName(Toolkit::ConfirmationPopup::CONTROL_OK);
break;
}
case Toolkit::ConfirmationPopup::Property::CONNECT_SIGNAL_CANCEL_SELECTED:
{
- value = popupImpl.GetControlSignalName( Toolkit::ConfirmationPopup::CONTROL_CANCEL );
+ value = popupImpl.GetControlSignalName(Toolkit::ConfirmationPopup::CONTROL_CANCEL);
break;
}
}
return value;
}
-void ConfirmationPopup::SetControlSignalName( const unsigned int controlNumber, const std::string& signalName )
+void ConfirmationPopup::SetControlSignalName(const unsigned int controlNumber, const std::string& signalName)
{
- if( controlNumber < ControlDetailsCount )
+ if(controlNumber < ControlDetailsCount)
{
- mControlSignalNames[ controlNumber ] = signalName;
+ mControlSignalNames[controlNumber] = signalName;
}
}
-std::string ConfirmationPopup::GetControlSignalName( unsigned int controlNumber ) const
+std::string ConfirmationPopup::GetControlSignalName(unsigned int controlNumber) const
{
- if( controlNumber < ControlDetailsCount )
+ if(controlNumber < ControlDetailsCount)
{
- return mControlSignalNames[ controlNumber ];
+ return mControlSignalNames[controlNumber];
}
return "";
}
-bool ConfirmationPopup::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool ConfirmationPopup::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
- Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast( handle );
+ Dali::BaseHandle handle(object);
+ Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast(handle);
// Look up the requested signal, attempting to create it dynamically if it doesn't exist.
- SignalDelegate* signalDelegate = Dali::Toolkit::GetDerivedImplementation( popup ).GetControlSignal( signalName );
- if( signalDelegate )
+ SignalDelegate* signalDelegate = Dali::Toolkit::GetDerivedImplementation(popup).GetControlSignal(signalName);
+ if(signalDelegate)
{
// The signal delegate was created successfully, attempt to connect it to a callback if specified.
// If none is specified, the creation is still successful as the signal delegate can connect at a later time.
- if( functor )
+ if(functor)
{
- signalDelegate->Connect( tracker, functor );
+ signalDelegate->Connect(tracker, functor);
}
return true;
}
return false;
}
-SignalDelegate* ConfirmationPopup::GetControlSignal( const std::string& signalName )
+SignalDelegate* ConfirmationPopup::GetControlSignal(const std::string& signalName)
{
// Check if the specified signal name already exists.
SignalContainerType::iterator end = mControlSignals.end();
- for( SignalContainerType::iterator iter = mControlSignals.begin(); iter != end; ++iter )
+ for(SignalContainerType::iterator iter = mControlSignals.begin(); iter != end; ++iter)
{
// Find the first non-connected signal by matching signal name.
- if( ( signalName == iter->first ) && ( !iter->second->IsConnected() ) )
+ if((signalName == iter->first) && (!iter->second->IsConnected()))
{
// The requested signal (delegate) already exists, just return it.
return iter->second;
// To make a new connection to an existing signal, we need a new delegate,
// as delegates house a signal connection functor each.
// Check the signal name is valid and if so create the signal dynamically.
- for( unsigned int i = 0; i < ControlDetailsCount; ++i )
+ for(unsigned int i = 0; i < ControlDetailsCount; ++i)
{
- if( 0 == strcmp( signalName.c_str(), ControlDetails[ i ].signalName ) )
+ if(0 == strcmp(signalName.c_str(), ControlDetails[i].signalName))
{
// The signal name is valid, check the respective actor to connect to exists.
- Actor connectActor = Self().FindChildByName( ControlDetails[ i ].controlName );
- if( connectActor )
+ Actor connectActor = Self().FindChildByName(ControlDetails[i].controlName);
+ if(connectActor)
{
// The actor exists, set up a signal delegate that will allow the application developer
// to connect the actor signal directly to their callback.
// Note: We don't use the GetControlSignalName() here for speedup, as we know the array bound is capped.
- SignalDelegate* signalDelegate = new SignalDelegate( connectActor, mControlSignalNames[ i ] );
+ SignalDelegate* signalDelegate = new SignalDelegate(connectActor, mControlSignalNames[i]);
// Store the delegate with the signal name so we know what signals have been dynamically created so far.
- mControlSignals.push_back( std::make_pair( signalName, signalDelegate ) );
+ mControlSignals.push_back(std::make_pair(signalName, signalDelegate));
// Return the delegate to allow connection to the newly created signal.
return signalDelegate;
return NULL;
}
-
} // namespace Internal
} // namespace Toolkit
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/popup/popup-impl.h>
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
-#include <dali/devel-api/adaptor-framework/physical-keyboard.h>
#include <dali/devel-api/actors/actor-devel.h>
-#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/devel-api/adaptor-framework/physical-keyboard.h>
+#include <dali/devel-api/common/stage.h>
+#include <dali/devel-api/scripting/scripting.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/adaptor-framework/key.h>
#include <dali/public-api/animation/constraints.h>
-#include <dali/devel-api/common/stage.h>
#include <dali/public-api/events/key-event.h>
#include <dali/public-api/events/touch-event.h>
+#include <dali/public-api/object/type-registry-helper.h>
#include <dali/public-api/object/type-registry.h>
-#include <dali/devel-api/scripting/scripting.h>
-#include <dali/devel-api/actors/actor-devel.h>
#include <dali/public-api/size-negotiation/relayout-container.h>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
+#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
+#include <dali-toolkit/internal/controls/control/control-data-impl.h>
#include <dali-toolkit/internal/focus-manager/keyboard-focus-manager-impl.h>
#include <dali-toolkit/public-api/controls/control-impl.h>
#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/focus-manager/keyboard-focus-manager-impl.h>
-#include <dali-toolkit/internal/controls/control/control-data-impl.h>
-#include <dali-toolkit/dali-toolkit.h>
using namespace Dali;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
/**
* Creation function for main Popup type.
* @return Handle to the new popup object.
}
// Toast style defaults.
-const int DEFAULT_TOAST_AUTO_HIDE_DELAY = 3000; ///< Toast will auto-hide after 3000ms (3 seconds)
-const float DEFAULT_TOAST_TRANSITION_TIME = 0.65f; ///< Default time the toast Popup will take to show and hide.
-const Vector3 DEFAULT_TOAST_BOTTOM_PARENT_ORIGIN( 0.5f, 0.94f, 0.5f ); ///< This is similar to BOTTOM_CENTER, but vertically higher up, as a ratio of parent height.
-const Vector3 DEFAULT_TOAST_WIDTH_OF_STAGE_RATIO( 0.75f, 0.75f, 0.75f ); ///< Amount of the stage's width that the toast popup will take up.
+const int DEFAULT_TOAST_AUTO_HIDE_DELAY = 3000; ///< Toast will auto-hide after 3000ms (3 seconds)
+const float DEFAULT_TOAST_TRANSITION_TIME = 0.65f; ///< Default time the toast Popup will take to show and hide.
+const Vector3 DEFAULT_TOAST_BOTTOM_PARENT_ORIGIN(0.5f, 0.94f, 0.5f); ///< This is similar to BOTTOM_CENTER, but vertically higher up, as a ratio of parent height.
+const Vector3 DEFAULT_TOAST_WIDTH_OF_STAGE_RATIO(0.75f, 0.75f, 0.75f); ///< Amount of the stage's width that the toast popup will take up.
/**
* Creation function for named type "popupToast".
Toolkit::Popup popup = Toolkit::Popup::New();
// Setup for Toast Popup type.
- popup.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_TOAST_WIDTH_OF_STAGE_RATIO );
- popup.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::WIDTH );
- popup.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );
- popup.SetProperty( Toolkit::Popup::Property::CONTEXTUAL_MODE, Toolkit::Popup::NON_CONTEXTUAL );
- popup.SetProperty( Toolkit::Popup::Property::ANIMATION_DURATION, DEFAULT_TOAST_TRANSITION_TIME );
- popup.SetProperty( Toolkit::Popup::Property::TAIL_VISIBILITY, false );
+ popup.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_TOAST_WIDTH_OF_STAGE_RATIO);
+ popup.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::WIDTH);
+ popup.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT);
+ popup.SetProperty(Toolkit::Popup::Property::CONTEXTUAL_MODE, Toolkit::Popup::NON_CONTEXTUAL);
+ popup.SetProperty(Toolkit::Popup::Property::ANIMATION_DURATION, DEFAULT_TOAST_TRANSITION_TIME);
+ popup.SetProperty(Toolkit::Popup::Property::TAIL_VISIBILITY, false);
// Disable the dimmed backing.
- popup.SetProperty( Toolkit::Popup::Property::BACKING_ENABLED, false );
+ popup.SetProperty(Toolkit::Popup::Property::BACKING_ENABLED, false);
// The toast popup should fade in (not zoom).
- popup.SetProperty( Toolkit::Popup::Property::ANIMATION_MODE, Toolkit::Popup::FADE );
+ popup.SetProperty(Toolkit::Popup::Property::ANIMATION_MODE, Toolkit::Popup::FADE);
// The toast popup should auto-hide.
- popup.SetProperty( Toolkit::Popup::Property::AUTO_HIDE_DELAY, DEFAULT_TOAST_AUTO_HIDE_DELAY );
+ popup.SetProperty(Toolkit::Popup::Property::AUTO_HIDE_DELAY, DEFAULT_TOAST_AUTO_HIDE_DELAY);
// Align to the bottom of the screen.
- popup.SetProperty( Actor::Property::PARENT_ORIGIN, DEFAULT_TOAST_BOTTOM_PARENT_ORIGIN );
- popup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER );
+ popup.SetProperty(Actor::Property::PARENT_ORIGIN, DEFAULT_TOAST_BOTTOM_PARENT_ORIGIN);
+ popup.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER);
// Let events pass through the toast popup.
- popup.SetProperty( Toolkit::Popup::Property::TOUCH_TRANSPARENT, true );
+ popup.SetProperty(Toolkit::Popup::Property::TOUCH_TRANSPARENT, true);
return popup;
}
+// clang-format off
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Popup, Toolkit::Control, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Popup, Toolkit::Control, Create )
// Main content related properties.
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "title", MAP, TITLE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "content", MAP, CONTENT )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "footer", MAP, FOOTER )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "displayState", STRING, DISPLAY_STATE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "touchTransparent", BOOLEAN, TOUCH_TRANSPARENT )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "title", MAP, TITLE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "content", MAP, CONTENT )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "footer", MAP, FOOTER )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "displayState", STRING, DISPLAY_STATE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "touchTransparent", BOOLEAN, TOUCH_TRANSPARENT )
// Contextual related properties.
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailVisibility", BOOLEAN, TAIL_VISIBILITY )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailPosition", VECTOR3, TAIL_POSITION )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "contextualMode", STRING, CONTEXTUAL_MODE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailVisibility", BOOLEAN, TAIL_VISIBILITY )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailPosition", VECTOR3, TAIL_POSITION )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "contextualMode", STRING, CONTEXTUAL_MODE )
// Animation related properties.
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "animationDuration", FLOAT, ANIMATION_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "animationMode", STRING, ANIMATION_MODE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "entryAnimation", MAP, ENTRY_ANIMATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "exitAnimation", MAP, EXIT_ANIMATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "autoHideDelay", INTEGER, AUTO_HIDE_DELAY )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "animationDuration", FLOAT, ANIMATION_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "animationMode", STRING, ANIMATION_MODE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "entryAnimation", MAP, ENTRY_ANIMATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "exitAnimation", MAP, EXIT_ANIMATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "autoHideDelay", INTEGER, AUTO_HIDE_DELAY )
// Style related properties.
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "backingEnabled", BOOLEAN, BACKING_ENABLED )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "backingColor", VECTOR4, BACKING_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "popupBackgroundImage", STRING, POPUP_BACKGROUND_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "popupBackgroundBorder", RECTANGLE, POPUP_BACKGROUND_BORDER )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailUpImage", STRING, TAIL_UP_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailDownImage", STRING, TAIL_DOWN_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailLeftImage", STRING, TAIL_LEFT_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailRightImage", STRING, TAIL_RIGHT_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "backingEnabled", BOOLEAN, BACKING_ENABLED )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "backingColor", VECTOR4, BACKING_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "popupBackgroundImage", STRING, POPUP_BACKGROUND_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "popupBackgroundBorder", RECTANGLE, POPUP_BACKGROUND_BORDER)
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailUpImage", STRING, TAIL_UP_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailDownImage", STRING, TAIL_DOWN_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailLeftImage", STRING, TAIL_LEFT_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailRightImage", STRING, TAIL_RIGHT_IMAGE )
// Signals.
-DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "touchedOutside", SIGNAL_TOUCHED_OUTSIDE )
-DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "showing", SIGNAL_SHOWING )
-DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "shown", SIGNAL_SHOWN )
-DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "hiding", SIGNAL_HIDING )
-DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "hidden", SIGNAL_HIDDEN )
+DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "touchedOutside", SIGNAL_TOUCHED_OUTSIDE)
+DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "showing", SIGNAL_SHOWING )
+DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "shown", SIGNAL_SHOWN )
+DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "hiding", SIGNAL_HIDING )
+DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "hidden", SIGNAL_HIDDEN )
DALI_TYPE_REGISTRATION_END()
// Named type registration.
// Toast Popup: Non-modal popup that displays information at the bottom of the screen.
-TypeRegistration typeRegistrationToast( "PopupToast", typeid( Toolkit::Popup ), CreateToast );
+TypeRegistration typeRegistrationToast("PopupToast", typeid( Toolkit::Popup ), CreateToast);
// Enumeration to / from string conversion tables
-const Scripting::StringEnum DisplayStateTable[] = {
- { "SHOWING", Toolkit::Popup::SHOWING },
- { "SHOWN", Toolkit::Popup::SHOWN },
- { "HIDING", Toolkit::Popup::HIDING },
- { "HIDDEN", Toolkit::Popup::HIDDEN },
-}; const unsigned int DisplayStateTableCount = sizeof( DisplayStateTable ) / sizeof( DisplayStateTable[0] );
-
-const Scripting::StringEnum AnimationModeTable[] = {
- { "NONE", Toolkit::Popup::NONE },
- { "ZOOM", Toolkit::Popup::ZOOM },
- { "FADE", Toolkit::Popup::FADE },
- { "CUSTOM", Toolkit::Popup::CUSTOM },
-}; const unsigned int AnimationModeTableCount = sizeof( AnimationModeTable ) / sizeof( AnimationModeTable[0] );
-
-const Scripting::StringEnum ContextualModeTable[] = {
- { "NON_CONTEXTUAL", Toolkit::Popup::NON_CONTEXTUAL },
- { "ABOVE", Toolkit::Popup::ABOVE },
- { "RIGHT", Toolkit::Popup::RIGHT },
- { "BELOW", Toolkit::Popup::BELOW },
- { "LEFT", Toolkit::Popup::LEFT },
-}; const unsigned int ContextualModeTableCount = sizeof( ContextualModeTable ) / sizeof( ContextualModeTable[0] );
+const Scripting::StringEnum DisplayStateTable[] =
+{
+ {"SHOWING", Toolkit::Popup::SHOWING},
+ {"SHOWN", Toolkit::Popup::SHOWN },
+ {"HIDING", Toolkit::Popup::HIDING },
+ {"HIDDEN", Toolkit::Popup::HIDDEN },
+};
+const unsigned int DisplayStateTableCount = sizeof(DisplayStateTable) / sizeof(DisplayStateTable[0]);
+
+const Scripting::StringEnum AnimationModeTable[] =
+{
+ {"NONE", Toolkit::Popup::NONE },
+ {"ZOOM", Toolkit::Popup::ZOOM },
+ {"FADE", Toolkit::Popup::FADE },
+ {"CUSTOM", Toolkit::Popup::CUSTOM},
+};
+const unsigned int AnimationModeTableCount = sizeof(AnimationModeTable) / sizeof(AnimationModeTable[0]);
+
+const Scripting::StringEnum ContextualModeTable[] =
+{
+ {"NON_CONTEXTUAL", Toolkit::Popup::NON_CONTEXTUAL},
+ {"ABOVE", Toolkit::Popup::ABOVE },
+ {"RIGHT", Toolkit::Popup::RIGHT },
+ {"BELOW", Toolkit::Popup::BELOW },
+ {"LEFT", Toolkit::Popup::LEFT },
+};
+const unsigned int ContextualModeTableCount = sizeof(ContextualModeTable) / sizeof(ContextualModeTable[0]);
+// clang-format on
// Popup defaults.
-const Vector3 DEFAULT_POPUP_PARENT_RELATIVE_SIZE( 0.75f, 1.0f, 1.0f ); ///< Default size percentage of parent.
-const float DEFAULT_POPUP_ANIMATION_DURATION = 0.6f; ///< Duration of hide/show animations.
-const float POPUP_OUT_MARGIN_WIDTH = 16.f; ///< Space between the screen edge and the popup edge in the horizontal dimension.
-const float POPUP_OUT_MARGIN_HEIGHT = 36.f; ///< Space between the screen edge and the popup edge in the vertical dimension.
-const Vector3 DEFAULT_TAIL_POSITION( 0.5f, 1.0f, 0.0f ); ///< Position the tail will be displayed when enabled without setting the position.
+const Vector3 DEFAULT_POPUP_PARENT_RELATIVE_SIZE(0.75f, 1.0f, 1.0f); ///< Default size percentage of parent.
+const float DEFAULT_POPUP_ANIMATION_DURATION = 0.6f; ///< Duration of hide/show animations.
+const float POPUP_OUT_MARGIN_WIDTH = 16.f; ///< Space between the screen edge and the popup edge in the horizontal dimension.
+const float POPUP_OUT_MARGIN_HEIGHT = 36.f; ///< Space between the screen edge and the popup edge in the vertical dimension.
+const Vector3 DEFAULT_TAIL_POSITION(0.5f, 1.0f, 0.0f); ///< Position the tail will be displayed when enabled without setting the position.
// Contextual defaults.
-const Vector2 DEFAULT_CONTEXTUAL_ADJACENCY_MARGIN( 10.0f, 10.0f ); ///< How close the Popup will be to it's contextual parent.
-const Vector2 DEFAULT_CONTEXTUAL_STAGE_BORDER( 15.0f, 15.0f ); ///< How close the Popup can be to the stage edges.
+const Vector2 DEFAULT_CONTEXTUAL_ADJACENCY_MARGIN(10.0f, 10.0f); ///< How close the Popup will be to it's contextual parent.
+const Vector2 DEFAULT_CONTEXTUAL_STAGE_BORDER(15.0f, 15.0f); ///< How close the Popup can be to the stage edges.
// Popup style defaults.
-const char* DEFAULT_BACKGROUND_IMAGE_FILE_NAME = "00_popup_bg.9.png"; ///< Background image.
-const char* DEFAULT_TAIL_UP_IMAGE_FILE_NAME = "popup_tail_up.png"; ///< Tail up image.
-const char* DEFAULT_TAIL_DOWN_IMAGE_FILE_NAME = "popup_tail_down.png"; ///< Tail down image.
-const char* DEFAULT_TAIL_LEFT_IMAGE_FILE_NAME = "popup_tail_left.png"; ///< Tail left image.
-const char* DEFAULT_TAIL_RIGHT_IMAGE_FILE_NAME = "popup_tail_right.png"; ///< Tail right image.
-
-const Vector4 DEFAULT_BACKING_COLOR( 0.0f, 0.0f, 0.0f, 0.5f ); ///< Color of the dimmed backing.
-const Rect<int> DEFAULT_BACKGROUND_BORDER( 17, 17, 13, 13 ); ///< Default border of the background.
-const Rect<float> DEFAULT_TITLE_PADDING( 20.0f, 20.0f, 20.0f, 20.0f ); ///< Title padding used on popups with content and/or controls (from Tizen GUI UX).
-const Rect<float> DEFAULT_TITLE_ONLY_PADDING( 8.0f, 8.0f, 8.0f, 8.0f ); ///< Title padding used on popups with a title only (like toast popups).
-const Vector3 FOOTER_SIZE( 620.0f, 96.0f,0.0f ); ///< Default size of the bottom control area.
-const float DEFAULT_RELATIVE_PARENT_WIDTH = 0.75f; ///< If width is not fixed, relative size to parent is used by default.
+const char* DEFAULT_BACKGROUND_IMAGE_FILE_NAME = "00_popup_bg.9.png"; ///< Background image.
+const char* DEFAULT_TAIL_UP_IMAGE_FILE_NAME = "popup_tail_up.png"; ///< Tail up image.
+const char* DEFAULT_TAIL_DOWN_IMAGE_FILE_NAME = "popup_tail_down.png"; ///< Tail down image.
+const char* DEFAULT_TAIL_LEFT_IMAGE_FILE_NAME = "popup_tail_left.png"; ///< Tail left image.
+const char* DEFAULT_TAIL_RIGHT_IMAGE_FILE_NAME = "popup_tail_right.png"; ///< Tail right image.
+
+const Vector4 DEFAULT_BACKING_COLOR(0.0f, 0.0f, 0.0f, 0.5f); ///< Color of the dimmed backing.
+const Rect<int> DEFAULT_BACKGROUND_BORDER(17, 17, 13, 13); ///< Default border of the background.
+const Rect<float> DEFAULT_TITLE_PADDING(20.0f, 20.0f, 20.0f, 20.0f); ///< Title padding used on popups with content and/or controls (from Tizen GUI UX).
+const Rect<float> DEFAULT_TITLE_ONLY_PADDING(8.0f, 8.0f, 8.0f, 8.0f); ///< Title padding used on popups with a title only (like toast popups).
+const Vector3 FOOTER_SIZE(620.0f, 96.0f, 0.0f); ///< Default size of the bottom control area.
+const float DEFAULT_RELATIVE_PARENT_WIDTH = 0.75f; ///< If width is not fixed, relative size to parent is used by default.
} // Unnamed namespace
Dali::Toolkit::Popup Popup::New()
{
// Create the implementation
- PopupPtr popup( new Popup() );
+ PopupPtr popup(new Popup());
// Pass ownership to CustomActor via derived handle.
- Dali::Toolkit::Popup handle( *popup );
+ Dali::Toolkit::Popup handle(*popup);
// Second-phase initialisation of the implementation.
// This can only be done after the CustomActor connection has been made.
}
Popup::Popup()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mTouchedOutsideSignal(),
mShowingSignal(),
mShownSignal(),
mTailImage(),
mPopupContainer(),
mAnimation(),
- mAlterAddedChild( false ),
- mLayoutDirty( true ),
+ mAlterAddedChild(false),
+ mLayoutDirty(true),
mAutoHideTimer(),
- mTouchTransparent( false ),
+ mTouchTransparent(false),
mTitle(),
mContent(),
mFooter(),
- mDisplayState( Toolkit::Popup::HIDDEN ), // Hidden until shown with SetDisplayState()
- mTailVisible( false ),
- mTailPosition( DEFAULT_TAIL_POSITION ),
- mContextualMode( Toolkit::Popup::NON_CONTEXTUAL ),
- mAnimationDuration( DEFAULT_POPUP_ANIMATION_DURATION ),
- mAnimationMode( Toolkit::Popup::FADE ),
+ mDisplayState(Toolkit::Popup::HIDDEN), // Hidden until shown with SetDisplayState()
+ mTailVisible(false),
+ mTailPosition(DEFAULT_TAIL_POSITION),
+ mContextualMode(Toolkit::Popup::NON_CONTEXTUAL),
+ mAnimationDuration(DEFAULT_POPUP_ANIMATION_DURATION),
+ mAnimationMode(Toolkit::Popup::FADE),
mEntryAnimationData(),
mExitAnimationData(),
- mAutoHideDelay( 0 ),
- mBackingEnabled( true ),
- mBackingColor( DEFAULT_BACKING_COLOR ),
+ mAutoHideDelay(0),
+ mBackingEnabled(true),
+ mBackingColor(DEFAULT_BACKING_COLOR),
mPopupBackgroundImage(),
- mBackgroundBorder( DEFAULT_BACKGROUND_BORDER ),
+ mBackgroundBorder(DEFAULT_BACKGROUND_BORDER),
mMargin(),
mTailUpImage(),
mTailDownImage(),
mTailLeftImage(),
mTailRightImage()
{
- SetKeyboardNavigationSupport( true );
+ SetKeyboardNavigationSupport(true);
const std::string imageDirPath = AssetManager::GetDaliImagePath();
- mTailUpImage = imageDirPath + DEFAULT_TAIL_UP_IMAGE_FILE_NAME;
- mTailDownImage = imageDirPath + DEFAULT_TAIL_DOWN_IMAGE_FILE_NAME;
- mTailLeftImage = imageDirPath + DEFAULT_TAIL_LEFT_IMAGE_FILE_NAME;
- mTailRightImage = imageDirPath + DEFAULT_TAIL_RIGHT_IMAGE_FILE_NAME;
+ mTailUpImage = imageDirPath + DEFAULT_TAIL_UP_IMAGE_FILE_NAME;
+ mTailDownImage = imageDirPath + DEFAULT_TAIL_DOWN_IMAGE_FILE_NAME;
+ mTailLeftImage = imageDirPath + DEFAULT_TAIL_LEFT_IMAGE_FILE_NAME;
+ mTailRightImage = imageDirPath + DEFAULT_TAIL_RIGHT_IMAGE_FILE_NAME;
}
void Popup::OnInitialize()
{
Actor self = Self();
- self.SetProperty( Dali::Actor::Property::NAME, "popup" );
+ self.SetProperty(Dali::Actor::Property::NAME, "popup");
// Apply some default resizing rules.
- self.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- self.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ self.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ self.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
- self.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_POPUP_PARENT_RELATIVE_SIZE );
- self.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::WIDTH );
- self.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );
+ self.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_POPUP_PARENT_RELATIVE_SIZE);
+ self.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::WIDTH);
+ self.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT);
// Create a new layer so all Popup components can appear above all other actors.
mLayer = Layer::New();
- mLayer.SetProperty( Dali::Actor::Property::NAME, "popupLayer" );
+ mLayer.SetProperty(Dali::Actor::Property::NAME, "popupLayer");
- mLayer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mLayer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- mLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mLayer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mLayer.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
// Important to set as invisible as otherwise, if the popup is parented,
// but not shown yet it will appear statically on the screen.
- mLayer.SetProperty( Actor::Property::VISIBLE, false );
+ mLayer.SetProperty(Actor::Property::VISIBLE, false);
// Add the layer to the hierarchy.
- self.Add( mLayer );
+ self.Add(mLayer);
// Add Backing (Dimmed effect).
mBacking = CreateBacking();
- mLayer.Add( mBacking );
+ mLayer.Add(mBacking);
mPopupContainer = Actor::New();
- mPopupContainer.SetProperty( Dali::Actor::Property::NAME, "popupContainer" );
- mPopupContainer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mPopupContainer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- mPopupContainer.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS );
- mLayer.Add( mPopupContainer );
+ mPopupContainer.SetProperty(Dali::Actor::Property::NAME, "popupContainer");
+ mPopupContainer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mPopupContainer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mPopupContainer.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS);
+ mLayer.Add(mPopupContainer);
// Create the Popup layout to contain all main content.
- mPopupLayout = Toolkit::TableView::New( 3, 1 );
+ mPopupLayout = Toolkit::TableView::New(3, 1);
// Adds the default background image.
const std::string imageDirPath = AssetManager::GetDaliImagePath();
- SetPopupBackgroundImage( Toolkit::ImageView::New( imageDirPath + DEFAULT_BACKGROUND_IMAGE_FILE_NAME ) );
+ SetPopupBackgroundImage(Toolkit::ImageView::New(imageDirPath + DEFAULT_BACKGROUND_IMAGE_FILE_NAME));
- mPopupLayout.SetProperty( Dali::Actor::Property::NAME, "popupLayoutTable" );
- mPopupLayout.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mPopupLayout.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ mPopupLayout.SetProperty(Dali::Actor::Property::NAME, "popupLayoutTable");
+ mPopupLayout.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mPopupLayout.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
- mPopupLayout.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH );
- mPopupLayout.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );
- mPopupLayout.SetProperty( Actor::Property::SIZE, Vector2( Stage::GetCurrent().GetSize().x * DEFAULT_RELATIVE_PARENT_WIDTH, 0.0f ) );
+ mPopupLayout.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH);
+ mPopupLayout.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT);
+ mPopupLayout.SetProperty(Actor::Property::SIZE, Vector2(Stage::GetCurrent().GetSize().x * DEFAULT_RELATIVE_PARENT_WIDTH, 0.0f));
- mPopupLayout.SetFitHeight( 0 ); // Set row to fit.
- mPopupLayout.SetFitHeight( 1 ); // Set row to fit.
+ mPopupLayout.SetFitHeight(0); // Set row to fit.
+ mPopupLayout.SetFitHeight(1); // Set row to fit.
- mPopupContainer.Add( mPopupLayout );
+ mPopupContainer.Add(mPopupLayout);
// Any content after this point which is added to Self() will be re-parented to mContent.
mAlterAddedChild = true;
- SetAsKeyboardFocusGroup( true );
+ SetAsKeyboardFocusGroup(true);
SetupTouch();
DevelControl::AppendAccessibilityAttribute(self, "sub-role", "Alert");
- DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor)
- {
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
return std::unique_ptr<Dali::Accessibility::Accessible>(new AccessibleImpl(actor, Dali::Accessibility::Role::DIALOG, true));
});
}
void Popup::LayoutAnimation()
{
// Perform setup based on the currently selected animation.
- switch( mAnimationMode )
+ switch(mAnimationMode)
{
case Toolkit::Popup::ZOOM:
{
// Zoom animations start fully zoomed out.
- mPopupContainer.SetProperty( Actor::Property::SCALE, Vector3::ZERO );
+ mPopupContainer.SetProperty(Actor::Property::SCALE, Vector3::ZERO);
break;
}
case Toolkit::Popup::FADE:
{
// Fade animations start transparent.
- mPopupContainer.SetProperty( Actor::Property::OPACITY, 0.0f );
+ mPopupContainer.SetProperty(Actor::Property::OPACITY, 0.0f);
break;
}
{
// Initialise the custom animation by playing to the end of it's exit animation instantly.
// EG. If it was zooming in, then we zoom out fully instantly so the zoom in works.
- StartTransitionAnimation( false, true );
+ StartTransitionAnimation(false, true);
break;
}
}
}
-void Popup::StartTransitionAnimation( bool transitionIn, bool instantaneous /* false */ )
+void Popup::StartTransitionAnimation(bool transitionIn, bool instantaneous /* false */)
{
// Stop and recreate animation.
- if ( mAnimation )
+ if(mAnimation)
{
mAnimation.Stop();
mAnimation.Clear();
// Setup variables ready to start the animations.
// If we are performing the animation instantaneously, we do not want to emit a signal.
- if( !instantaneous )
+ if(!instantaneous)
{
- if( transitionIn )
+ if(transitionIn)
{
// Setup variables and signal that we are starting the transition.
// Note: We signal even if the transition is instant so signal order is consistent.
}
// Perform chosen animation for the Popup.
- switch( mAnimationMode )
+ switch(mAnimationMode)
{
case Toolkit::Popup::NONE:
{
- mAnimation = Animation::New( 0.0f );
+ mAnimation = Animation::New(0.0f);
break;
}
case Toolkit::Popup::ZOOM:
{
- mAnimation = Animation::New( duration );
- if( duration > Math::MACHINE_EPSILON_0 )
+ mAnimation = Animation::New(duration);
+ if(duration > Math::MACHINE_EPSILON_0)
{
- if( transitionIn )
+ if(transitionIn)
{
- mAnimation.AnimateTo( Property( mPopupContainer, Actor::Property::SCALE ), Vector3::ONE, AlphaFunction::EASE_IN_OUT, TimePeriod( duration * 0.25f, duration * 0.75f ) );
+ mAnimation.AnimateTo(Property(mPopupContainer, Actor::Property::SCALE), Vector3::ONE, AlphaFunction::EASE_IN_OUT, TimePeriod(duration * 0.25f, duration * 0.75f));
}
else
{
// Zoom out animation is twice the speed. Modify the duration variable so the backing animation speed is modified also.
duration /= 2.0f;
- mAnimation.SetDuration( duration );
- mAnimation.AnimateTo( Property( mPopupContainer, Actor::Property::SCALE ), Vector3::ZERO, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.0f, duration ) );
+ mAnimation.SetDuration(duration);
+ mAnimation.AnimateTo(Property(mPopupContainer, Actor::Property::SCALE), Vector3::ZERO, AlphaFunction::EASE_IN_OUT, TimePeriod(0.0f, duration));
}
}
else
{
- mPopupContainer.SetProperty( Actor::Property::SCALE, transitionIn ? Vector3::ONE : Vector3::ZERO );
+ mPopupContainer.SetProperty(Actor::Property::SCALE, transitionIn ? Vector3::ONE : Vector3::ZERO);
}
break;
}
case Toolkit::Popup::FADE:
{
- mAnimation = Animation::New( duration );
- if( duration > Math::MACHINE_EPSILON_0 )
+ mAnimation = Animation::New(duration);
+ if(duration > Math::MACHINE_EPSILON_0)
{
- if( transitionIn )
+ if(transitionIn)
{
- mAnimation.AnimateTo( Property( mPopupContainer, Actor::Property::COLOR_ALPHA ), 1.0f, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.30f, duration * 0.70f ) );
+ mAnimation.AnimateTo(Property(mPopupContainer, Actor::Property::COLOR_ALPHA), 1.0f, AlphaFunction::EASE_IN_OUT, TimePeriod(0.30f, duration * 0.70f));
}
else
{
- mAnimation.AnimateTo( Property( mPopupContainer, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.0f, duration * 0.70f ) );
+ mAnimation.AnimateTo(Property(mPopupContainer, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN_OUT, TimePeriod(0.0f, duration * 0.70f));
}
}
else
{
- mPopupContainer.SetProperty( Actor::Property::OPACITY, transitionIn ? 1.0f : 0.0f );
+ mPopupContainer.SetProperty(Actor::Property::OPACITY, transitionIn ? 1.0f : 0.0f);
}
break;
}
// Create a new animation from the pre-defined data in the AnimationData class.
// If there is no data, mAnimation is invalidated.
- mAnimation = animationData->CreateAnimation( mPopupContainer, duration );
+ mAnimation = animationData->CreateAnimation(mPopupContainer, duration);
// If we don't have a valid animation, provide a blank one so play() can still function generically.
- if( !mAnimation )
+ if(!mAnimation)
{
// No animation was configured (even though custom mode was specified). Create a dummy animation to avoid an exception.
- mAnimation = Animation::New( 0.0f );
+ mAnimation = Animation::New(0.0f);
}
break;
// Animate the backing, if enabled.
// This is set up last so that different animation modes can have an effect on the backing animation speed.
- if( mBackingEnabled )
+ if(mBackingEnabled)
{
// Use the alpha from the user-specified color.
float targetAlpha = mBackingColor.a;
- if( duration > Math::MACHINE_EPSILON_0 )
+ if(duration > Math::MACHINE_EPSILON_0)
{
- if( transitionIn )
+ if(transitionIn)
{
- mAnimation.AnimateTo( Property( mBacking, Actor::Property::COLOR_ALPHA ), targetAlpha, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.0f, duration * 0.70f ) );
+ mAnimation.AnimateTo(Property(mBacking, Actor::Property::COLOR_ALPHA), targetAlpha, AlphaFunction::EASE_IN_OUT, TimePeriod(0.0f, duration * 0.70f));
}
else
{
- mAnimation.AnimateTo( Property( mBacking, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.30f, duration * 0.70f ) );
+ mAnimation.AnimateTo(Property(mBacking, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN_OUT, TimePeriod(0.30f, duration * 0.70f));
}
}
else
{
- mBacking.SetProperty( Actor::Property::COLOR_ALPHA, transitionIn ? targetAlpha : 0.0f );
+ mBacking.SetProperty(Actor::Property::COLOR_ALPHA, transitionIn ? targetAlpha : 0.0f);
}
}
// If we are performing the animation instantaneously, jump to the position directly and do not signal.
- if( instantaneous )
+ if(instantaneous)
{
- mAnimation.SetCurrentProgress( 1.0f );
+ mAnimation.SetCurrentProgress(1.0f);
mAnimation.Play();
}
- else if( duration > Math::MACHINE_EPSILON_0 )
+ else if(duration > Math::MACHINE_EPSILON_0)
{
// Run the animation.
- mAnimation.FinishedSignal().Connect( this, &Popup::OnDisplayChangeAnimationFinished );
+ mAnimation.FinishedSignal().Connect(this, &Popup::OnDisplayChangeAnimationFinished);
mAnimation.Play();
}
else
}
}
-void Popup::OnDisplayChangeAnimationFinished( Animation& source )
+void Popup::OnDisplayChangeAnimationFinished(Animation& source)
{
DisplayStateChangeComplete();
}
void Popup::DisplayStateChangeComplete()
{
// Remove contents from stage if completely hidden.
- if( mDisplayState == Toolkit::Popup::HIDING )
+ if(mDisplayState == Toolkit::Popup::HIDING)
{
mDisplayState = Toolkit::Popup::HIDDEN;
- mLayer.SetProperty( Actor::Property::VISIBLE, false );
- mPopupLayout.SetProperty( Actor::Property::SENSITIVE, false );
+ mLayer.SetProperty(Actor::Property::VISIBLE, false);
+ mPopupLayout.SetProperty(Actor::Property::SENSITIVE, false);
// Guard against destruction during signal emission.
- Toolkit::Popup handle( GetOwner() );
+ Toolkit::Popup handle(GetOwner());
mHiddenSignal.Emit();
}
- else if( mDisplayState == Toolkit::Popup::SHOWING )
+ else if(mDisplayState == Toolkit::Popup::SHOWING)
{
mDisplayState = Toolkit::Popup::SHOWN;
- Toolkit::Popup handle( GetOwner() );
+ Toolkit::Popup handle(GetOwner());
mShownSignal.Emit();
// Start a timer to auto-hide if enabled.
- if( mAutoHideDelay > 0u )
+ if(mAutoHideDelay > 0u)
{
- mAutoHideTimer = Timer::New( mAutoHideDelay );
- mAutoHideTimer.TickSignal().Connect( this, &Popup::OnAutoHideTimeReached );
+ mAutoHideTimer = Timer::New(mAutoHideDelay);
+ mAutoHideTimer.TickSignal().Connect(this, &Popup::OnAutoHideTimeReached);
mAutoHideTimer.Start();
}
}
bool Popup::OnAutoHideTimeReached()
{
- if (!Dali::Accessibility::IsUp() || true) // TODO: remove 'true' in sync with EFL (UX change)
+ if(!Dali::Accessibility::IsUp() || true) // TODO: remove 'true' in sync with EFL (UX change)
{
// Display timer has expired, auto hide the popup exactly as if the user had clicked outside.
- SetDisplayState( Toolkit::Popup::HIDDEN );
+ SetDisplayState(Toolkit::Popup::HIDDEN);
}
- if( mAutoHideTimer )
+ if(mAutoHideTimer)
{
mAutoHideTimer.Stop();
- mAutoHideTimer.TickSignal().Disconnect( this, &Popup::OnAutoHideTimeReached );
+ mAutoHideTimer.TickSignal().Disconnect(this, &Popup::OnAutoHideTimeReached);
mAutoHideTimer.Reset();
}
return true;
}
-void Popup::SetPopupBackgroundImage( Actor image )
+void Popup::SetPopupBackgroundImage(Actor image)
{
// Removes any previous background.
- if( mPopupBackgroundImage )
+ if(mPopupBackgroundImage)
{
mPopupBackgroundImage.Unparent();
- if( mTailImage )
+ if(mTailImage)
{
mTailImage.Unparent();
}
// Adds new background to the dialog.
mPopupBackgroundImage = image;
- mPopupBackgroundImage.SetProperty( Dali::Actor::Property::NAME, "popupBackgroundImage" );
- mPopupBackgroundImage.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- mPopupBackgroundImage.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mPopupBackgroundImage.SetProperty(Dali::Actor::Property::NAME, "popupBackgroundImage");
+ mPopupBackgroundImage.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mPopupBackgroundImage.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
// Set the popup border to be slightly larger than the layout contents.
UpdateBackgroundPositionAndSize();
const bool prevAlter = mAlterAddedChild;
- mAlterAddedChild = false;
- mPopupContainer.Add( mPopupBackgroundImage );
+ mAlterAddedChild = false;
+ mPopupContainer.Add(mPopupBackgroundImage);
mPopupBackgroundImage.LowerToBottom();
mAlterAddedChild = prevAlter;
- if( mTailImage )
+ if(mTailImage)
{
- mPopupBackgroundImage.Add( mTailImage );
+ mPopupBackgroundImage.Add(mTailImage);
}
mLayoutDirty = true;
return mPopupBackgroundImage;
}
-void Popup::SetTitle( Actor titleActor )
+void Popup::SetTitle(Actor titleActor)
{
// Replaces the current title actor.
- if( !mPopupLayout )
+ if(!mPopupLayout)
{
return;
}
- if( mTitle )
+ if(mTitle)
{
- mPopupLayout.RemoveChildAt( Toolkit::TableView::CellPosition( 0, 0) );
+ mPopupLayout.RemoveChildAt(Toolkit::TableView::CellPosition(0, 0));
}
mTitle = titleActor;
- if( mTitle )
+ if(mTitle)
{
// Set up padding to give sensible default behaviour
// (an application developer can later override this if they wish).
- mTitle.SetProperty( Actor::Property::PADDING, DEFAULT_TITLE_PADDING );
+ mTitle.SetProperty(Actor::Property::PADDING, DEFAULT_TITLE_PADDING);
- mPopupLayout.AddChild( mTitle, Toolkit::TableView::CellPosition( 0, 0 ) );
+ mPopupLayout.AddChild(mTitle, Toolkit::TableView::CellPosition(0, 0));
}
mLayoutDirty = true;
return mTitle;
}
-void Popup::SetContent( Actor content )
+void Popup::SetContent(Actor content)
{
// Remove previous content actor.
- if( mPopupLayout )
+ if(mPopupLayout)
{
- mPopupLayout.RemoveChildAt( Toolkit::TableView::CellPosition( 1, 0 ) );
+ mPopupLayout.RemoveChildAt(Toolkit::TableView::CellPosition(1, 0));
}
- // Keep a handle to the new content.
+ // Keep a handle to the new content.
mContent = content;
- if( mContent )
+ if(mContent)
{
- mContent.SetProperty( Dali::Actor::Property::NAME, "popupContent" );
+ mContent.SetProperty(Dali::Actor::Property::NAME, "popupContent");
- mPopupLayout.AddChild( mContent, Toolkit::TableView::CellPosition( 1, 0 ) );
+ mPopupLayout.AddChild(mContent, Toolkit::TableView::CellPosition(1, 0));
}
mLayoutDirty = true;
return mContent;
}
-void Popup::SetFooter( Actor footer )
+void Popup::SetFooter(Actor footer)
{
// Remove previous content actor.
- if( mPopupLayout )
+ if(mPopupLayout)
{
- mPopupLayout.RemoveChildAt( Toolkit::TableView::CellPosition( 2, 0 ) );
+ mPopupLayout.RemoveChildAt(Toolkit::TableView::CellPosition(2, 0));
}
// Keep a handle to the new content.
mFooter = footer;
- if( mFooter )
+ if(mFooter)
{
- mFooter.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
+ mFooter.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
// The control container has a fixed height.
- mPopupLayout.SetFitHeight( 2u );
- mPopupLayout.AddChild( footer, Toolkit::TableView::CellPosition( 2, 0 ) );
+ mPopupLayout.SetFitHeight(2u);
+ mPopupLayout.AddChild(footer, Toolkit::TableView::CellPosition(2, 0));
}
mLayoutDirty = true;
return mFooter;
}
-void Popup::SetDisplayState( Toolkit::Popup::DisplayState displayState )
+void Popup::SetDisplayState(Toolkit::Popup::DisplayState displayState)
{
// Convert the 4-way state to a bool, true for show, false for hide.
- bool display = ( displayState == Toolkit::Popup::SHOWING ) || ( displayState == Toolkit::Popup::SHOWN );
+ bool display = (displayState == Toolkit::Popup::SHOWING) || (displayState == Toolkit::Popup::SHOWN);
// Ignore if we are already at the target display state.
- if( display == ( ( mDisplayState == Toolkit::Popup::SHOWING ) || ( mDisplayState == Toolkit::Popup::SHOWN ) ) )
+ if(display == ((mDisplayState == Toolkit::Popup::SHOWING) || (mDisplayState == Toolkit::Popup::SHOWN)))
{
return;
}
- auto *accessible = Dali::Accessibility::Accessible::Get(Self());
- if (display)
+ auto* accessible = Dali::Accessibility::Accessible::Get(Self());
+ if(display)
{
Dali::Accessibility::Bridge::GetCurrentBridge()->AddPopup(accessible);
accessible->EmitStateChanged(Dali::Accessibility::State::SHOWING, 1, 0);
// Convert the bool state to the actual display state to use.
mDisplayState = display ? Toolkit::Popup::SHOWING : Toolkit::Popup::HIDING;
- if ( display )
+ if(display)
{
// Update the state to indicate the current intent.
mDisplayState = Toolkit::Popup::SHOWING;
// We are displaying so bring the popup layer to the front, and set it visible so it is rendered.
mLayer.RaiseToTop();
- mLayer.SetProperty( Actor::Property::VISIBLE, true );
+ mLayer.SetProperty(Actor::Property::VISIBLE, true);
// Set up the layout if this is the first display or the layout has become dirty.
- if( mLayoutDirty )
+ if(mLayoutDirty)
{
// Bake-in any style and layout options to create the Popup layout.
LayoutPopup();
}
// Allow the popup to catch events.
- mPopupLayout.SetProperty( Actor::Property::SENSITIVE, true );
+ mPopupLayout.SetProperty(Actor::Property::SENSITIVE, true);
// Handle the keyboard focus when popup is shown.
Dali::Toolkit::KeyboardFocusManager keyboardFocusManager = Dali::Toolkit::KeyboardFocusManager::Get();
- if( keyboardFocusManager )
+ if(keyboardFocusManager)
{
mPreviousFocusedActor = keyboardFocusManager.GetCurrentFocusActor();
- if( Self().GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) )
+ if(Self().GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
// Setup the actgor to start focus from.
Actor focusActor;
- if( mContent && mContent.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) )
+ if(mContent && mContent.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
// If the content is focusable, move the focus to the content.
focusActor = mContent;
}
- else if( mFooter && mFooter.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) )
+ else if(mFooter && mFooter.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
// If the footer is focusable, move the focus to the footer.
focusActor = mFooter;
}
else
{
- DALI_LOG_WARNING( "There is no focusable in popup\n" );
+ DALI_LOG_WARNING("There is no focusable in popup\n");
}
- if( focusActor )
+ if(focusActor)
{
- keyboardFocusManager.SetCurrentFocusActor( focusActor );
+ keyboardFocusManager.SetCurrentFocusActor(focusActor);
}
}
}
ClearKeyInputFocus();
// Restore the keyboard focus when popup is hidden.
- if( mPreviousFocusedActor && mPreviousFocusedActor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) )
+ if(mPreviousFocusedActor && mPreviousFocusedActor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
Dali::Toolkit::KeyboardFocusManager keyboardFocusManager = Dali::Toolkit::KeyboardFocusManager::Get();
- if( keyboardFocusManager )
+ if(keyboardFocusManager)
{
- keyboardFocusManager.SetCurrentFocusActor( mPreviousFocusedActor );
+ keyboardFocusManager.SetCurrentFocusActor(mPreviousFocusedActor);
}
}
}
// Perform animation.
- StartTransitionAnimation( display );
+ StartTransitionAnimation(display);
}
Toolkit::Popup::DisplayState Popup::GetDisplayState() const
* | |````
* | |
*/
- mPopupContainer.SetProperty( Actor::Property::PARENT_ORIGIN, Self().GetCurrentProperty< Vector3 >( Actor::Property::PARENT_ORIGIN ) );
- mPopupContainer.SetProperty( Actor::Property::ANCHOR_POINT, Self().GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) );
+ mPopupContainer.SetProperty(Actor::Property::PARENT_ORIGIN, Self().GetCurrentProperty<Vector3>(Actor::Property::PARENT_ORIGIN));
+ mPopupContainer.SetProperty(Actor::Property::ANCHOR_POINT, Self().GetCurrentProperty<Vector3>(Actor::Property::ANCHOR_POINT));
// If there is only a title, use less padding.
- if( mTitle )
+ if(mTitle)
{
- if( !mContent && !mFooter )
+ if(!mContent && !mFooter)
{
- mTitle.SetProperty( Actor::Property::PADDING, DEFAULT_TITLE_ONLY_PADDING );
+ mTitle.SetProperty(Actor::Property::PADDING, DEFAULT_TITLE_ONLY_PADDING);
}
else
{
- mTitle.SetProperty( Actor::Property::PADDING, DEFAULT_TITLE_PADDING );
+ mTitle.SetProperty(Actor::Property::PADDING, DEFAULT_TITLE_PADDING);
}
}
OnLayoutSetup();
// Update background visibility.
- mPopupContainer.SetProperty( Actor::Property::VISIBLE, !( !mFooter && mPopupLayout.GetChildCount() == 0 ) );
+ mPopupContainer.SetProperty(Actor::Property::VISIBLE, !(!mFooter && mPopupLayout.GetChildCount() == 0));
// Create / destroy / position the tail as needed.
LayoutTail();
void Popup::LayoutTail()
{
// Removes the tail actor.
- if( mTailImage && mTailImage.GetParent() )
+ if(mTailImage && mTailImage.GetParent())
{
- mTailImage.GetParent().Remove( mTailImage );
+ mTailImage.GetParent().Remove(mTailImage);
mTailImage.Reset();
}
- if( !mTailVisible )
+ if(!mTailVisible)
{
return;
}
const Vector3& parentOrigin = GetTailPosition();
- Vector3 position;
- std::string image;
- Vector3 anchorPoint;
+ Vector3 position;
+ std::string image;
+ Vector3 anchorPoint;
// depending on position of tail around ParentOrigin, a different tail image is used...
- if( parentOrigin.y < Math::MACHINE_EPSILON_1 )
+ if(parentOrigin.y < Math::MACHINE_EPSILON_1)
{
- image = mTailUpImage;
+ image = mTailUpImage;
anchorPoint = AnchorPoint::BOTTOM_CENTER;
- position.y = mBackgroundBorder.top;
+ position.y = mBackgroundBorder.top;
}
- else if( parentOrigin.y > ( 1.0f - Math::MACHINE_EPSILON_1 ) )
+ else if(parentOrigin.y > (1.0f - Math::MACHINE_EPSILON_1))
{
- image = mTailDownImage;
+ image = mTailDownImage;
anchorPoint = AnchorPoint::TOP_CENTER;
- position.y = - mBackgroundBorder.bottom;
+ position.y = -mBackgroundBorder.bottom;
}
- else if( parentOrigin.x < Math::MACHINE_EPSILON_1 )
+ else if(parentOrigin.x < Math::MACHINE_EPSILON_1)
{
- image = mTailLeftImage;
+ image = mTailLeftImage;
anchorPoint = AnchorPoint::CENTER_RIGHT;
- position.x = mBackgroundBorder.left;
+ position.x = mBackgroundBorder.left;
}
- else if( parentOrigin.x > ( 1.0f - Math::MACHINE_EPSILON_1 ) )
+ else if(parentOrigin.x > (1.0f - Math::MACHINE_EPSILON_1))
{
- image = mTailRightImage;
+ image = mTailRightImage;
anchorPoint = AnchorPoint::CENTER_LEFT;
- position.x = - mBackgroundBorder.right;
+ position.x = -mBackgroundBorder.right;
}
- if( !image.empty() )
+ if(!image.empty())
{
// Adds the tail actor.
- mTailImage = Toolkit::ImageView::New( image );
- mTailImage.SetProperty( Dali::Actor::Property::NAME, "tailImage" );
- mTailImage.SetProperty( Actor::Property::PARENT_ORIGIN, parentOrigin );
- mTailImage.SetProperty( Actor::Property::ANCHOR_POINT, anchorPoint );
- mTailImage.SetProperty( Actor::Property::POSITION, position );
+ mTailImage = Toolkit::ImageView::New(image);
+ mTailImage.SetProperty(Dali::Actor::Property::NAME, "tailImage");
+ mTailImage.SetProperty(Actor::Property::PARENT_ORIGIN, parentOrigin);
+ mTailImage.SetProperty(Actor::Property::ANCHOR_POINT, anchorPoint);
+ mTailImage.SetProperty(Actor::Property::POSITION, position);
- if( mPopupBackgroundImage )
+ if(mPopupBackgroundImage)
{
- mPopupBackgroundImage.Add( mTailImage );
+ mPopupBackgroundImage.Add(mTailImage);
}
}
}
-void Popup::SetContextualMode( Toolkit::Popup::ContextualMode mode )
+void Popup::SetContextualMode(Toolkit::Popup::ContextualMode mode)
{
mContextualMode = mode;
- mLayoutDirty = true;
+ mLayoutDirty = true;
}
Toolkit::Popup::ContextualMode Popup::GetContextualMode() const
Toolkit::Control Popup::CreateBacking()
{
Toolkit::Control backing = Control::New();
- backing.SetProperty( Toolkit::Control::Property::BACKGROUND,
- Property::Map().Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR )
- .Add( Toolkit::ColorVisual::Property::MIX_COLOR, Vector4( mBackingColor.r, mBackingColor.g, mBackingColor.b, 1.0f ) ) );
- backing.SetProperty( Dali::Actor::Property::NAME, "popupBacking" );
+ backing.SetProperty(Toolkit::Control::Property::BACKGROUND,
+ Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(Toolkit::ColorVisual::Property::MIX_COLOR, Vector4(mBackingColor.r, mBackingColor.g, mBackingColor.b, 1.0f)));
+ backing.SetProperty(Dali::Actor::Property::NAME, "popupBacking");
// Must always be positioned top-left of stage, regardless of parent.
- backing.SetProperty( Actor::Property::INHERIT_POSITION, false );
+ backing.SetProperty(Actor::Property::INHERIT_POSITION, false);
// Always the full size of the stage.
- backing.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS );
- backing.SetProperty( Actor::Property::SIZE, Stage::GetCurrent().GetSize() );
+ backing.SetResizePolicy(ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS);
+ backing.SetProperty(Actor::Property::SIZE, Stage::GetCurrent().GetSize());
// Catch events.
- backing.SetProperty( Actor::Property::SENSITIVE, true );
+ backing.SetProperty(Actor::Property::SENSITIVE, true);
// Default to being transparent.
- backing.SetProperty( Actor::Property::COLOR_ALPHA, 0.0f );
- backing.WheelEventSignal().Connect( this, &Popup::OnBackingWheelEvent );
+ backing.SetProperty(Actor::Property::COLOR_ALPHA, 0.0f);
+ backing.WheelEventSignal().Connect(this, &Popup::OnBackingWheelEvent);
return backing;
}
return mHiddenSignal;
}
-void Popup::SetTailVisibility( bool visible )
+void Popup::SetTailVisibility(bool visible)
{
mTailVisible = visible;
mLayoutDirty = true;
return mTailVisible;
}
-void Popup::SetTailPosition( Vector3 position )
+void Popup::SetTailPosition(Vector3 position)
{
mTailPosition = position;
- mLayoutDirty = true;
+ mLayoutDirty = true;
}
const Vector3& Popup::GetTailPosition() const
return mTailPosition;
}
-void Popup::SetAnimationDuration( float duration )
+void Popup::SetAnimationDuration(float duration)
{
mAnimationDuration = duration;
- mLayoutDirty = true;
+ mLayoutDirty = true;
}
float Popup::GetAnimationDuration() const
return mAnimationDuration;
}
-void Popup::SetAnimationMode( Toolkit::Popup::AnimationMode animationMode )
+void Popup::SetAnimationMode(Toolkit::Popup::AnimationMode animationMode)
{
mAnimationMode = animationMode;
- mLayoutDirty = true;
+ mLayoutDirty = true;
}
Toolkit::Popup::AnimationMode Popup::GetAnimationMode() const
return mAnimationMode;
}
-void Popup::SetEntryAnimationData( const Property::Map& map )
+void Popup::SetEntryAnimationData(const Property::Map& map)
{
mEntryAnimationData.Clear();
- Scripting::NewAnimation( map, mEntryAnimationData );
+ Scripting::NewAnimation(map, mEntryAnimationData);
}
-void Popup::SetExitAnimationData( const Property::Map& map )
+void Popup::SetExitAnimationData(const Property::Map& map)
{
mExitAnimationData.Clear();
- Scripting::NewAnimation( map, mExitAnimationData );
+ Scripting::NewAnimation(map, mExitAnimationData);
}
void Popup::UpdateBackgroundPositionAndSize()
{
- if( mPopupBackgroundImage )
+ if(mPopupBackgroundImage)
{
- mPopupBackgroundImage.SetResizePolicy( ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS );
- mPopupBackgroundImage.SetProperty( Actor::Property::SIZE_MODE_FACTOR, Vector3( mBackgroundBorder.left + mBackgroundBorder.right, mBackgroundBorder.top + mBackgroundBorder.bottom, 0.0f ) );
+ mPopupBackgroundImage.SetResizePolicy(ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS);
+ mPopupBackgroundImage.SetProperty(Actor::Property::SIZE_MODE_FACTOR, Vector3(mBackgroundBorder.left + mBackgroundBorder.right, mBackgroundBorder.top + mBackgroundBorder.bottom, 0.0f));
// Adjust the position of the background so the transparent areas are set appropriately
- mPopupBackgroundImage.SetProperty( Actor::Property::POSITION, Vector2( ( mBackgroundBorder.right - mBackgroundBorder.left ) * 0.5f, ( mBackgroundBorder.bottom - mBackgroundBorder.top ) * 0.5f ));
+ mPopupBackgroundImage.SetProperty(Actor::Property::POSITION, Vector2((mBackgroundBorder.right - mBackgroundBorder.left) * 0.5f, (mBackgroundBorder.bottom - mBackgroundBorder.top) * 0.5f));
}
}
-void Popup::SetAutoHideDelay( int delay )
+void Popup::SetAutoHideDelay(int delay)
{
mAutoHideDelay = delay;
}
return mAutoHideDelay;
}
-void Popup::SetBackingEnabled( bool enabled )
+void Popup::SetBackingEnabled(bool enabled)
{
mBackingEnabled = enabled;
- mLayoutDirty = true;
+ mLayoutDirty = true;
}
const bool Popup::IsBackingEnabled() const
return mBackingEnabled;
}
-void Popup::SetBackingColor( Vector4 color )
+void Popup::SetBackingColor(Vector4 color)
{
mBackingColor = color;
- mBacking.SetBackgroundColor( Vector4( color.r, color.g, color.b, 1.0f ) );
+ mBacking.SetBackgroundColor(Vector4(color.r, color.g, color.b, 1.0f));
mLayoutDirty = true;
}
return mBackingColor;
}
-void Popup::SetTailUpImage( std::string image )
+void Popup::SetTailUpImage(std::string image)
{
mTailUpImage = image;
mLayoutDirty = true;
return mTailUpImage;
}
-void Popup::SetTailDownImage( std::string image )
+void Popup::SetTailDownImage(std::string image)
{
mTailDownImage = image;
- mLayoutDirty = true;
+ mLayoutDirty = true;
LayoutTail();
}
return mTailDownImage;
}
-void Popup::SetTailLeftImage( std::string image )
+void Popup::SetTailLeftImage(std::string image)
{
mTailLeftImage = image;
- mLayoutDirty = true;
+ mLayoutDirty = true;
LayoutTail();
}
return mTailLeftImage;
}
-void Popup::SetTailRightImage( std::string image )
+void Popup::SetTailRightImage(std::string image)
{
mTailRightImage = image;
- mLayoutDirty = true;
+ mLayoutDirty = true;
LayoutTail();
}
return mTailRightImage;
}
-void Popup::SetTouchTransparent( bool enabled )
+void Popup::SetTouchTransparent(bool enabled)
{
- if( mTouchTransparent != enabled )
+ if(mTouchTransparent != enabled)
{
mTouchTransparent = enabled;
SetupTouch();
return mTouchTransparent;
}
-void Popup::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
+void Popup::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value)
{
- Toolkit::Popup popup = Toolkit::Popup::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Popup popup = Toolkit::Popup::DownCast(Dali::BaseHandle(object));
- if ( popup )
+ if(popup)
{
- Popup& popupImpl( GetImpl( popup ) );
+ Popup& popupImpl(GetImpl(popup));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::Popup::Property::TITLE:
{
Property::Map valueMap;
- if( value.Get( valueMap ) )
+ if(value.Get(valueMap))
{
- popupImpl.SetTitle( Scripting::NewActor( valueMap ) );
+ popupImpl.SetTitle(Scripting::NewActor(valueMap));
}
break;
}
case Toolkit::Popup::Property::CONTENT:
{
Property::Map valueMap;
- if( value.Get( valueMap ) )
+ if(value.Get(valueMap))
{
- popupImpl.SetContent( Scripting::NewActor( valueMap ) );
+ popupImpl.SetContent(Scripting::NewActor(valueMap));
}
break;
}
case Toolkit::Popup::Property::FOOTER:
{
Property::Map valueMap;
- if( value.Get( valueMap ) )
+ if(value.Get(valueMap))
{
- popupImpl.SetFooter( Scripting::NewActor( valueMap ) );
+ popupImpl.SetFooter(Scripting::NewActor(valueMap));
}
break;
}
case Toolkit::Popup::Property::DISPLAY_STATE:
{
std::string valueString;
- if( value.Get( valueString ) )
+ if(value.Get(valueString))
{
- Toolkit::Popup::DisplayState displayState( Toolkit::Popup::HIDDEN );
- if( Scripting::GetEnumeration< Toolkit::Popup::DisplayState >( valueString.c_str(), DisplayStateTable, DisplayStateTableCount, displayState ) )
+ Toolkit::Popup::DisplayState displayState(Toolkit::Popup::HIDDEN);
+ if(Scripting::GetEnumeration<Toolkit::Popup::DisplayState>(valueString.c_str(), DisplayStateTable, DisplayStateTableCount, displayState))
{
- popupImpl.SetDisplayState( displayState );
+ popupImpl.SetDisplayState(displayState);
}
}
break;
case Toolkit::Popup::Property::TOUCH_TRANSPARENT:
{
bool valueBool;
- if( value.Get( valueBool ) )
+ if(value.Get(valueBool))
{
- popupImpl.SetTouchTransparent( valueBool );
+ popupImpl.SetTouchTransparent(valueBool);
}
break;
}
case Toolkit::Popup::Property::TAIL_VISIBILITY:
{
bool valueBool;
- if( value.Get( valueBool ) )
+ if(value.Get(valueBool))
{
- popupImpl.SetTailVisibility( valueBool );
+ popupImpl.SetTailVisibility(valueBool);
}
break;
}
case Toolkit::Popup::Property::TAIL_POSITION:
{
Vector3 valueVector3;
- if( value.Get( valueVector3 ) )
+ if(value.Get(valueVector3))
{
- popupImpl.SetTailPosition( valueVector3 );
+ popupImpl.SetTailPosition(valueVector3);
}
break;
}
case Toolkit::Popup::Property::CONTEXTUAL_MODE:
{
std::string valueString;
- if( value.Get( valueString ) )
+ if(value.Get(valueString))
{
- Toolkit::Popup::ContextualMode contextualMode( Toolkit::Popup::BELOW );
- if( Scripting::GetEnumeration< Toolkit::Popup::ContextualMode >( valueString.c_str(), ContextualModeTable, ContextualModeTableCount, contextualMode ) )
+ Toolkit::Popup::ContextualMode contextualMode(Toolkit::Popup::BELOW);
+ if(Scripting::GetEnumeration<Toolkit::Popup::ContextualMode>(valueString.c_str(), ContextualModeTable, ContextualModeTableCount, contextualMode))
{
- popupImpl.SetContextualMode( contextualMode );
+ popupImpl.SetContextualMode(contextualMode);
}
}
break;
case Toolkit::Popup::Property::ANIMATION_DURATION:
{
float valueFloat;
- if( value.Get( valueFloat ) )
+ if(value.Get(valueFloat))
{
- popupImpl.SetAnimationDuration( valueFloat );
+ popupImpl.SetAnimationDuration(valueFloat);
}
break;
}
case Toolkit::Popup::Property::ANIMATION_MODE:
{
std::string valueString;
- if( value.Get( valueString ) )
+ if(value.Get(valueString))
{
- Toolkit::Popup::AnimationMode animationMode( Toolkit::Popup::FADE );
- if( Scripting::GetEnumeration< Toolkit::Popup::AnimationMode >( valueString.c_str(), AnimationModeTable, AnimationModeTableCount, animationMode ) )
+ Toolkit::Popup::AnimationMode animationMode(Toolkit::Popup::FADE);
+ if(Scripting::GetEnumeration<Toolkit::Popup::AnimationMode>(valueString.c_str(), AnimationModeTable, AnimationModeTableCount, animationMode))
{
- popupImpl.SetAnimationMode( animationMode );
+ popupImpl.SetAnimationMode(animationMode);
}
}
break;
case Toolkit::Popup::Property::ENTRY_ANIMATION:
{
Property::Map valueMap;
- if( value.Get( valueMap ) )
+ if(value.Get(valueMap))
{
- popupImpl.SetEntryAnimationData( valueMap );
+ popupImpl.SetEntryAnimationData(valueMap);
}
break;
}
case Toolkit::Popup::Property::EXIT_ANIMATION:
{
Property::Map valueMap;
- if( value.Get( valueMap ) )
+ if(value.Get(valueMap))
{
- popupImpl.SetExitAnimationData( valueMap );
+ popupImpl.SetExitAnimationData(valueMap);
}
break;
}
case Toolkit::Popup::Property::AUTO_HIDE_DELAY:
{
int valueInt;
- if( value.Get( valueInt ) )
+ if(value.Get(valueInt))
{
- popupImpl.SetAutoHideDelay( valueInt );
+ popupImpl.SetAutoHideDelay(valueInt);
}
break;
}
case Toolkit::Popup::Property::BACKING_ENABLED:
{
bool valueBool;
- if( value.Get( valueBool ) )
+ if(value.Get(valueBool))
{
- popupImpl.SetBackingEnabled( valueBool );
+ popupImpl.SetBackingEnabled(valueBool);
}
break;
}
case Toolkit::Popup::Property::BACKING_COLOR:
{
Vector4 valueVector4;
- if( value.Get( valueVector4 ) )
+ if(value.Get(valueVector4))
{
- popupImpl.SetBackingColor( valueVector4 );
+ popupImpl.SetBackingColor(valueVector4);
}
break;
}
case Toolkit::Popup::Property::POPUP_BACKGROUND_IMAGE:
{
std::string valueString;
- if( value.Get( valueString ) )
+ if(value.Get(valueString))
{
- Toolkit::ImageView actor = Toolkit::ImageView::New( valueString );
- popupImpl.SetPopupBackgroundImage( actor );
+ Toolkit::ImageView actor = Toolkit::ImageView::New(valueString);
+ popupImpl.SetPopupBackgroundImage(actor);
}
break;
}
bool valueUpdated = false;
Vector4 valueVector4;
- if( value.Get( popupImpl.mBackgroundBorder ) )
+ if(value.Get(popupImpl.mBackgroundBorder))
{
valueUpdated = true;
}
- else if( value.Get( valueVector4 ) )
+ else if(value.Get(valueVector4))
{
popupImpl.mBackgroundBorder.left = valueVector4.x;
popupImpl.mBackgroundBorder.right = valueVector4.y;
popupImpl.mBackgroundBorder.bottom = valueVector4.z;
popupImpl.mBackgroundBorder.top = valueVector4.w;
- valueUpdated = true;
+ valueUpdated = true;
}
- if( valueUpdated )
+ if(valueUpdated)
{
- popupImpl.LayoutTail(); // Update the tail if required
+ popupImpl.LayoutTail(); // Update the tail if required
popupImpl.UpdateBackgroundPositionAndSize(); // Update the background's size and position
}
break;
case Toolkit::Popup::Property::TAIL_UP_IMAGE:
{
std::string valueString;
- if( value.Get( valueString ) )
+ if(value.Get(valueString))
{
- popupImpl.SetTailUpImage( valueString );
+ popupImpl.SetTailUpImage(valueString);
}
break;
}
case Toolkit::Popup::Property::TAIL_DOWN_IMAGE:
{
std::string valueString;
- if( value.Get( valueString ) )
+ if(value.Get(valueString))
{
- popupImpl.SetTailDownImage( valueString );
+ popupImpl.SetTailDownImage(valueString);
}
break;
}
case Toolkit::Popup::Property::TAIL_LEFT_IMAGE:
{
std::string valueString;
- if( value.Get( valueString ) )
+ if(value.Get(valueString))
{
- popupImpl.SetTailLeftImage( valueString );
+ popupImpl.SetTailLeftImage(valueString);
}
break;
}
case Toolkit::Popup::Property::TAIL_RIGHT_IMAGE:
{
std::string valueString;
- if( value.Get( valueString ) )
+ if(value.Get(valueString))
{
- popupImpl.SetTailRightImage( valueString );
+ popupImpl.SetTailRightImage(valueString);
}
break;
}
}
}
-Property::Value Popup::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value Popup::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::Popup popup = Toolkit::Popup::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Popup popup = Toolkit::Popup::DownCast(Dali::BaseHandle(object));
- if ( popup )
+ if(popup)
{
- Popup& popupImpl( GetImpl( popup ) );
+ Popup& popupImpl(GetImpl(popup));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::Popup::Property::TITLE:
{
Property::Map map;
- Scripting::CreatePropertyMap( popupImpl.GetTitle(), map );
+ Scripting::CreatePropertyMap(popupImpl.GetTitle(), map);
value = map;
break;
}
case Toolkit::Popup::Property::CONTENT:
{
Property::Map map;
- Scripting::CreatePropertyMap( popupImpl.GetContent(), map );
+ Scripting::CreatePropertyMap(popupImpl.GetContent(), map);
value = map;
break;
}
case Toolkit::Popup::Property::FOOTER:
{
Property::Map map;
- Scripting::CreatePropertyMap( popupImpl.GetFooter(), map );
+ Scripting::CreatePropertyMap(popupImpl.GetFooter(), map);
value = map;
break;
}
case Toolkit::Popup::Property::DISPLAY_STATE:
{
- value = Scripting::GetLinearEnumerationName< Toolkit::Popup::DisplayState >( popupImpl.GetDisplayState(), DisplayStateTable, DisplayStateTableCount );
+ value = Scripting::GetLinearEnumerationName<Toolkit::Popup::DisplayState>(popupImpl.GetDisplayState(), DisplayStateTable, DisplayStateTableCount);
break;
}
case Toolkit::Popup::Property::TOUCH_TRANSPARENT:
}
case Toolkit::Popup::Property::CONTEXTUAL_MODE:
{
- value = Scripting::GetLinearEnumerationName< Toolkit::Popup::ContextualMode >( popupImpl.GetContextualMode(), ContextualModeTable, ContextualModeTableCount );
+ value = Scripting::GetLinearEnumerationName<Toolkit::Popup::ContextualMode>(popupImpl.GetContextualMode(), ContextualModeTable, ContextualModeTableCount);
break;
}
case Toolkit::Popup::Property::ANIMATION_DURATION:
}
case Toolkit::Popup::Property::ANIMATION_MODE:
{
- value = Scripting::GetLinearEnumerationName< Toolkit::Popup::AnimationMode >( popupImpl.GetAnimationMode(), AnimationModeTable, AnimationModeTableCount );
+ value = Scripting::GetLinearEnumerationName<Toolkit::Popup::AnimationMode>(popupImpl.GetAnimationMode(), AnimationModeTable, AnimationModeTableCount);
break;
}
case Toolkit::Popup::Property::ENTRY_ANIMATION:
}
case Toolkit::Popup::Property::POPUP_BACKGROUND_IMAGE:
{
- Toolkit::ImageView imageView = Toolkit::ImageView::DownCast( popupImpl.GetPopupBackgroundImage() );
- if( imageView )
+ Toolkit::ImageView imageView = Toolkit::ImageView::DownCast(popupImpl.GetPopupBackgroundImage());
+ if(imageView)
{
- value = imageView.GetProperty( Toolkit::ImageView::Property::IMAGE );
+ value = imageView.GetProperty(Toolkit::ImageView::Property::IMAGE);
}
break;
}
return value;
}
-bool Popup::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool Popup::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::Popup popup = Toolkit::Popup::DownCast( handle );
+ bool connected(true);
+ Toolkit::Popup popup = Toolkit::Popup::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_TOUCHED_OUTSIDE ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_TOUCHED_OUTSIDE))
{
- popup.OutsideTouchedSignal().Connect( tracker, functor );
+ popup.OutsideTouchedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_SHOWING ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_SHOWING))
{
- popup.ShowingSignal().Connect( tracker, functor );
+ popup.ShowingSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_SHOWN ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_SHOWN))
{
- popup.ShownSignal().Connect( tracker, functor );
+ popup.ShownSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_HIDING ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_HIDING))
{
- popup.HidingSignal().Connect( tracker, functor );
+ popup.HidingSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_HIDDEN ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_HIDDEN))
{
- popup.HiddenSignal().Connect( tracker, functor );
+ popup.HiddenSignal().Connect(tracker, functor);
}
else
{
return connected;
}
-bool Popup::OnBackingTouched( Actor actor, const TouchEvent& touch )
+bool Popup::OnBackingTouched(Actor actor, const TouchEvent& touch)
{
// Allow events to pass through if the backing isn't the hit-actor
- if( (touch.GetHitActor(0) == actor) &&
- (touch.GetPointCount() > 0) &&
- (touch.GetState( 0 ) == PointState::DOWN))
+ if((touch.GetHitActor(0) == actor) &&
+ (touch.GetPointCount() > 0) &&
+ (touch.GetState(0) == PointState::DOWN))
{
// Guard against destruction during signal emission.
- Toolkit::Popup handle( GetOwner() );
+ Toolkit::Popup handle(GetOwner());
mTouchedOutsideSignal.Emit();
}
return false;
}
-bool Popup::OnBackingWheelEvent( Actor actor, const WheelEvent& event )
+bool Popup::OnBackingWheelEvent(Actor actor, const WheelEvent& event)
{
// Allow events to pass through if touch transparency is enabled.
- if( mTouchTransparent )
+ if(mTouchTransparent)
{
return false;
}
return true;
}
-bool Popup::OnDialogTouched( Actor actor, const TouchEvent& touch )
+bool Popup::OnDialogTouched(Actor actor, const TouchEvent& touch)
{
// Only connecting this so the backing does not become the default hit-actor and inadvertently closes the popup
return false;
}
-void Popup::OnSceneConnection( int depth )
+void Popup::OnSceneConnection(int depth)
{
mLayoutDirty = true;
RelayoutRequest();
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
}
-void Popup::OnChildAdd( Actor& child )
+void Popup::OnChildAdd(Actor& child)
{
// Re-parent any children added by user to the body layer.
- if( mAlterAddedChild )
+ if(mAlterAddedChild)
{
- SetContent( child );
+ SetContent(child);
}
else
{
RelayoutRequest();
}
- Control::OnChildAdd( child );
+ Control::OnChildAdd(child);
}
-void Popup::LayoutContext( const Vector2& size )
+void Popup::LayoutContext(const Vector2& size)
{
// Do nothing if not in a contextual mode (or there is no parent context).
- Actor self = Self();
+ Actor self = Self();
Actor parent = self.GetParent();
- if( ( mContextualMode == Toolkit::Popup::NON_CONTEXTUAL ) || !parent )
+ if((mContextualMode == Toolkit::Popup::NON_CONTEXTUAL) || !parent)
{
return;
}
- mPopupContainer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mPopupContainer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
// We always anchor to the CENTER, rather than a different anchor point for each contextual
// mode to allow code-reuse of the bound checking code (for maintainability).
- mPopupContainer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ mPopupContainer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
// Setup with some pre-calculations for speed.
- Vector3 halfStageSize( Stage().GetCurrent().GetSize() / 2.0f );
- Vector3 parentPosition( parent.GetCurrentProperty< Vector3 >( Actor::Property::POSITION ) );
- Vector2 halfSize( size / 2.0f );
- Vector2 halfParentSize( parent.GetRelayoutSize( Dimension::WIDTH ) / 2.0f, parent.GetRelayoutSize( Dimension::HEIGHT ) / 2.0f );
- Vector3 newPosition( Vector3::ZERO );
+ Vector3 halfStageSize(Stage().GetCurrent().GetSize() / 2.0f);
+ Vector3 parentPosition(parent.GetCurrentProperty<Vector3>(Actor::Property::POSITION));
+ Vector2 halfSize(size / 2.0f);
+ Vector2 halfParentSize(parent.GetRelayoutSize(Dimension::WIDTH) / 2.0f, parent.GetRelayoutSize(Dimension::HEIGHT) / 2.0f);
+ Vector3 newPosition(Vector3::ZERO);
// Perform different positioning based on the specified contextual layout mode.
- switch( mContextualMode )
+ switch(mContextualMode)
{
case Toolkit::Popup::BELOW:
{
// Check new position is not too far right. If so, correct it.
// Note: Check for right rather than left first, so if popup is too wide, the left check overrides
// the right check and we at least see the left portion of the popup (as this is more useful).
- if( newPosition.x >= ( halfStageSize.x - parentPosition.x - halfSize.x - DEFAULT_CONTEXTUAL_STAGE_BORDER.x ) )
+ if(newPosition.x >= (halfStageSize.x - parentPosition.x - halfSize.x - DEFAULT_CONTEXTUAL_STAGE_BORDER.x))
{
newPosition.x = halfStageSize.x - parentPosition.x - halfSize.x - DEFAULT_CONTEXTUAL_STAGE_BORDER.x;
}
// Check new position is not too far left. If so, correct it.
- if( newPosition.x < halfSize.x - ( parentPosition.x + halfStageSize.x ) + DEFAULT_CONTEXTUAL_STAGE_BORDER.x )
+ if(newPosition.x < halfSize.x - (parentPosition.x + halfStageSize.x) + DEFAULT_CONTEXTUAL_STAGE_BORDER.x)
{
- newPosition.x = halfSize.x - ( parentPosition.x + halfStageSize.x ) + DEFAULT_CONTEXTUAL_STAGE_BORDER.x;// - parentSize.x;
+ newPosition.x = halfSize.x - (parentPosition.x + halfStageSize.x) + DEFAULT_CONTEXTUAL_STAGE_BORDER.x; // - parentSize.x;
}
// Check new position is not too far down. If so, correct it.
- if( newPosition.y >= ( halfStageSize.y - parentPosition.y - halfSize.y - DEFAULT_CONTEXTUAL_STAGE_BORDER.y ) )
+ if(newPosition.y >= (halfStageSize.y - parentPosition.y - halfSize.y - DEFAULT_CONTEXTUAL_STAGE_BORDER.y))
{
newPosition.y = halfStageSize.y - parentPosition.y - halfSize.y - DEFAULT_CONTEXTUAL_STAGE_BORDER.y;
}
// Check new position is not too far up. If so, correct it.
- if( newPosition.y < halfSize.y - ( parentPosition.y + halfStageSize.y ) + DEFAULT_CONTEXTUAL_STAGE_BORDER.y )
+ if(newPosition.y < halfSize.y - (parentPosition.y + halfStageSize.y) + DEFAULT_CONTEXTUAL_STAGE_BORDER.y)
{
- newPosition.y = halfSize.y - ( parentPosition.y + halfStageSize.y ) + DEFAULT_CONTEXTUAL_STAGE_BORDER.y;
+ newPosition.y = halfSize.y - (parentPosition.y + halfStageSize.y) + DEFAULT_CONTEXTUAL_STAGE_BORDER.y;
}
// Set the final position.
- mPopupContainer.SetProperty( Actor::Property::POSITION, newPosition );
+ mPopupContainer.SetProperty(Actor::Property::POSITION, newPosition);
}
-void Popup::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void Popup::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- Vector2 useSize( size );
+ Vector2 useSize(size);
// Use the Popup layouts size, unless requested to use a fixed size.
// In which case take the size set for the Popup itself.
- ResizePolicy::Type widthPolicy = Self().GetResizePolicy( Dimension::WIDTH );
- ResizePolicy::Type heightPolicy = Self().GetResizePolicy( Dimension::HEIGHT );
+ ResizePolicy::Type widthPolicy = Self().GetResizePolicy(Dimension::WIDTH);
+ ResizePolicy::Type heightPolicy = Self().GetResizePolicy(Dimension::HEIGHT);
// Width calculations:
- if( widthPolicy == ResizePolicy::USE_NATURAL_SIZE || widthPolicy == ResizePolicy::FIT_TO_CHILDREN )
+ if(widthPolicy == ResizePolicy::USE_NATURAL_SIZE || widthPolicy == ResizePolicy::FIT_TO_CHILDREN)
{
// If we using a child-based policy, take the size from the popup layout.
- mPopupLayout.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::WIDTH );
- useSize.width = mPopupLayout.GetRelayoutSize( Dimension::WIDTH );
+ mPopupLayout.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::WIDTH);
+ useSize.width = mPopupLayout.GetRelayoutSize(Dimension::WIDTH);
- mPopupLayout.SetFitWidth( 0u );
+ mPopupLayout.SetFitWidth(0u);
}
else
{
// If we using a parent-based policy, take the size from the popup object itself (self).
- mPopupLayout.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH );
+ mPopupLayout.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH);
- mPopupLayout.SetFixedWidth( 0u, useSize.width );
+ mPopupLayout.SetFixedWidth(0u, useSize.width);
}
// Height calculations:
// Title: Let the title be as high as it needs to be.
- mPopupLayout.SetFitHeight( 0u );
+ mPopupLayout.SetFitHeight(0u);
// Footer: Convert the footer's resize policy to a TableView row policy.
- if( mFooter )
+ if(mFooter)
{
- ResizePolicy::Type footerHeightPolicy = mFooter.GetResizePolicy( Dimension::HEIGHT );
- if( ( footerHeightPolicy == ResizePolicy::USE_NATURAL_SIZE ) ||
- ( footerHeightPolicy == ResizePolicy::FIT_TO_CHILDREN ) )
+ ResizePolicy::Type footerHeightPolicy = mFooter.GetResizePolicy(Dimension::HEIGHT);
+ if((footerHeightPolicy == ResizePolicy::USE_NATURAL_SIZE) ||
+ (footerHeightPolicy == ResizePolicy::FIT_TO_CHILDREN))
{
- mPopupLayout.SetFitHeight( 2u );
+ mPopupLayout.SetFitHeight(2u);
}
- else if( footerHeightPolicy == ResizePolicy::FIXED )
+ else if(footerHeightPolicy == ResizePolicy::FIXED)
{
- mPopupLayout.SetFixedHeight( 2u, mFooter.GetRelayoutSize( Dimension::HEIGHT) );
+ mPopupLayout.SetFixedHeight(2u, mFooter.GetRelayoutSize(Dimension::HEIGHT));
}
else
{
- mPopupLayout.SetRelativeHeight( 2u, 1.0f );
+ mPopupLayout.SetRelativeHeight(2u, 1.0f);
}
}
else
{
- mPopupLayout.SetFixedHeight( 2u, 0.0f );
+ mPopupLayout.SetFixedHeight(2u, 0.0f);
}
// Popup contents: Adjust the tableview's policies based on the popup's policies.
- if( heightPolicy == ResizePolicy::USE_NATURAL_SIZE || heightPolicy == ResizePolicy::FIT_TO_CHILDREN )
+ if(heightPolicy == ResizePolicy::USE_NATURAL_SIZE || heightPolicy == ResizePolicy::FIT_TO_CHILDREN)
{
- mPopupLayout.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );
+ mPopupLayout.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT);
// Let both the contents expand as necessary.
- mPopupLayout.SetFitHeight( 1u );
- useSize.height = mPopupLayout.GetRelayoutSize( Dimension::HEIGHT );
+ mPopupLayout.SetFitHeight(1u);
+ useSize.height = mPopupLayout.GetRelayoutSize(Dimension::HEIGHT);
}
else
{
- mPopupLayout.SetResizePolicy( heightPolicy, Dimension::HEIGHT );
+ mPopupLayout.SetResizePolicy(heightPolicy, Dimension::HEIGHT);
// Let the content expand to fill the remaining space.
- mPopupLayout.SetRelativeHeight( 1u, 1.0f );
- mPopupLayout.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::HEIGHT );
+ mPopupLayout.SetRelativeHeight(1u, 1.0f);
+ mPopupLayout.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::HEIGHT);
}
// Relayout the popup-layout to give it it's new size this frame.
- container.Add( mPopupLayout, useSize );
+ container.Add(mPopupLayout, useSize);
- if( mContent )
+ if(mContent)
{
- container.Add( mContent, Vector2( mContent.GetRelayoutSize( Dimension::WIDTH ), mContent.GetRelayoutSize( Dimension::HEIGHT ) ) );
+ container.Add(mContent, Vector2(mContent.GetRelayoutSize(Dimension::WIDTH), mContent.GetRelayoutSize(Dimension::HEIGHT)));
}
// Perform contextual layout setup if required.
// This is done each time in case the parent moves.
// This will have no effect if no contextual mode is selected.
- LayoutContext( useSize );
+ LayoutContext(useSize);
}
-void Popup::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
+void Popup::OnSetResizePolicy(ResizePolicy::Type policy, Dimension::Type dimension)
{
// To get the popup to emulate fit-to-children, we need to actually set use-natural-size.
- if( ( dimension & Dimension::HEIGHT ) && ( policy == ResizePolicy::FIT_TO_CHILDREN ) )
+ if((dimension & Dimension::HEIGHT) && (policy == ResizePolicy::FIT_TO_CHILDREN))
{
- Self().SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT );
+ Self().SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT);
}
mLayoutDirty = true;
return mPopupLayout.GetNaturalSize();
}
-float Popup::GetHeightForWidth( float width )
+float Popup::GetHeightForWidth(float width)
{
- return mPopupLayout.GetHeightForWidth( width );
+ return mPopupLayout.GetHeightForWidth(width);
}
-float Popup::GetWidthForHeight( float height )
+float Popup::GetWidthForHeight(float height)
{
- return mPopupLayout.GetWidthForHeight( height );
+ return mPopupLayout.GetWidthForHeight(height);
}
-bool Popup::OnKeyEvent( const KeyEvent& event )
+bool Popup::OnKeyEvent(const KeyEvent& event)
{
// Allow events to pass through if touch transparency is enabled.
- if( mTouchTransparent )
+ if(mTouchTransparent)
{
return false;
}
bool consumed = false;
- if( event.GetState() == KeyEvent::DOWN )
+ if(event.GetState() == KeyEvent::DOWN)
{
- if (event.GetKeyCode() == Dali::DALI_KEY_ESCAPE || event.GetKeyCode() == Dali::DALI_KEY_BACK)
+ if(event.GetKeyCode() == Dali::DALI_KEY_ESCAPE || event.GetKeyCode() == Dali::DALI_KEY_BACK)
{
- SetDisplayState( Toolkit::Popup::HIDDEN );
+ SetDisplayState(Toolkit::Popup::HIDDEN);
consumed = true;
}
}
return consumed;
}
-void Popup::AddFocusableChildrenRecursive( Actor parent, std::vector< Actor >& focusableActors )
+void Popup::AddFocusableChildrenRecursive(Actor parent, std::vector<Actor>& focusableActors)
{
- if( parent )
+ if(parent)
{
- Toolkit::Control control = Toolkit::Control::DownCast( parent );
- bool layoutControl = control && GetImplementation( control ).IsKeyboardNavigationSupported();
+ Toolkit::Control control = Toolkit::Control::DownCast(parent);
+ bool layoutControl = control && GetImplementation(control).IsKeyboardNavigationSupported();
- if( parent.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) || layoutControl )
+ if(parent.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) || layoutControl)
{
- focusableActors.push_back( parent );
+ focusableActors.push_back(parent);
- if( !layoutControl )
+ if(!layoutControl)
{
- for( unsigned int i = 0, numberChildren = parent.GetChildCount(); i < numberChildren; ++i )
+ for(unsigned int i = 0, numberChildren = parent.GetChildCount(); i < numberChildren; ++i)
{
- Actor child( parent.GetChildAt( i ) );
- AddFocusableChildrenRecursive( child, focusableActors );
+ Actor child(parent.GetChildAt(i));
+ AddFocusableChildrenRecursive(child, focusableActors);
}
}
}
}
}
-void Popup::AddFocusableChildren( Actor parent, std::vector< Actor >& focusableActors )
+void Popup::AddFocusableChildren(Actor parent, std::vector<Actor>& focusableActors)
{
- if( parent )
+ if(parent)
{
- Toolkit::Control control = Toolkit::Control::DownCast( parent );
- if( !GetImplementation( control ).IsKeyboardNavigationSupported() )
+ Toolkit::Control control = Toolkit::Control::DownCast(parent);
+ if(!GetImplementation(control).IsKeyboardNavigationSupported())
{
- for( unsigned int i = 0, numberChildren = parent.GetChildCount(); i < numberChildren; ++i )
+ for(unsigned int i = 0, numberChildren = parent.GetChildCount(); i < numberChildren; ++i)
{
- Actor child( parent.GetChildAt( i ) );
- AddFocusableChildrenRecursive( child, focusableActors );
+ Actor child(parent.GetChildAt(i));
+ AddFocusableChildrenRecursive(child, focusableActors);
}
}
else
{
- focusableActors.push_back( parent );
+ focusableActors.push_back(parent);
}
}
}
-Actor Popup::GetNextKeyboardFocusableActor( Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled )
+Actor Popup::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
{
std::string currentStr;
- if( currentFocusedActor )
+ if(currentFocusedActor)
{
- currentStr = currentFocusedActor.GetProperty< std::string >( Dali::Actor::Property::NAME );
+ currentStr = currentFocusedActor.GetProperty<std::string>(Dali::Actor::Property::NAME);
}
- Actor nextFocusableActor( currentFocusedActor );
+ Actor nextFocusableActor(currentFocusedActor);
Actor currentFocusGroup;
- if( currentFocusedActor )
+ if(currentFocusedActor)
{
- currentFocusGroup = KeyboardFocusManager::Get().GetFocusGroup( currentFocusedActor );
+ currentFocusGroup = KeyboardFocusManager::Get().GetFocusGroup(currentFocusedActor);
}
// TODO: Needs to be optimised
// The following statement checks that if we have a current focused actor, then the current focus group is not the popup content or footer.
// This is to detect if the focus is currently outside the popup, and if so, move it inside.
- if( !currentFocusedActor ||
- ( currentFocusedActor && ( ( !mContent || ( currentFocusGroup != mContent ) ) && ( !mFooter || ( currentFocusGroup != mFooter ) ) ) ) )
+ if(!currentFocusedActor ||
+ (currentFocusedActor && ((!mContent || (currentFocusGroup != mContent)) && (!mFooter || (currentFocusGroup != mFooter)))))
{
// The current focused actor is not within popup.
- if( mContent && mContent.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) )
+ if(mContent && mContent.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
// If the content is focusable, move the focus to the content.
nextFocusableActor = mContent;
}
- else if( mFooter && mFooter.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) )
+ else if(mFooter && mFooter.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
// If the footer is focusable, move the focus to the footer.
nextFocusableActor = mFooter;
else
{
// Rebuild the focus chain because controls or content can be added or removed dynamically
- std::vector< Actor > focusableActors;
+ std::vector<Actor> focusableActors;
- AddFocusableChildren( mContent, focusableActors );
- AddFocusableChildren( mFooter, focusableActors );
+ AddFocusableChildren(mContent, focusableActors);
+ AddFocusableChildren(mFooter, focusableActors);
- std::vector< Actor >::iterator endIterator = focusableActors.end();
- std::vector< Actor >::iterator currentIterator = focusableActors.begin();
- for( std::vector< Actor >::iterator iterator = focusableActors.begin(); iterator != endIterator; ++iterator )
+ std::vector<Actor>::iterator endIterator = focusableActors.end();
+ std::vector<Actor>::iterator currentIterator = focusableActors.begin();
+ for(std::vector<Actor>::iterator iterator = focusableActors.begin(); iterator != endIterator; ++iterator)
{
- if( currentFocusedActor == *iterator )
+ if(currentFocusedActor == *iterator)
{
currentIterator = iterator;
}
}
- if( currentIterator != endIterator )
+ if(currentIterator != endIterator)
{
- switch( direction )
+ switch(direction)
{
case Toolkit::Control::KeyboardFocus::LEFT:
{
- if( currentIterator == focusableActors.begin() )
+ if(currentIterator == focusableActors.begin())
{
- nextFocusableActor = *( endIterator - 1 );
+ nextFocusableActor = *(endIterator - 1);
}
else
{
- nextFocusableActor = *( currentIterator - 1 );
+ nextFocusableActor = *(currentIterator - 1);
}
break;
}
case Toolkit::Control::KeyboardFocus::RIGHT:
{
- if( currentIterator == endIterator - 1 )
+ if(currentIterator == endIterator - 1)
{
- nextFocusableActor = *( focusableActors.begin() );
+ nextFocusableActor = *(focusableActors.begin());
}
else
{
- nextFocusableActor = *( currentIterator + 1 );
+ nextFocusableActor = *(currentIterator + 1);
}
break;
}
case Toolkit::Control::KeyboardFocus::UP:
{
- nextFocusableActor = *( focusableActors.begin() );
+ nextFocusableActor = *(focusableActors.begin());
break;
}
case Toolkit::Control::KeyboardFocus::DOWN:
{
- nextFocusableActor = *( endIterator - 1 );
+ nextFocusableActor = *(endIterator - 1);
break;
}
}
}
- if( !nextFocusableActor )
+ if(!nextFocusableActor)
{
- DALI_LOG_WARNING( "Can not decide next focusable actor\n" );
+ DALI_LOG_WARNING("Can not decide next focusable actor\n");
}
}
}
void Popup::SetupTouch()
{
- if( ! mTouchTransparent )
+ if(!mTouchTransparent)
{
// Connect all the signals and set us up to consume all touch events
- mBacking.TouchedSignal().Connect( this, &Popup::OnBackingTouched );
- mPopupBackgroundImage.TouchedSignal().Connect( this, &Popup::OnDialogTouched );
- mPopupLayout.TouchedSignal().Connect( this, &Popup::OnDialogTouched );
- mLayer.SetProperty( Layer::Property::CONSUMES_TOUCH, true );
+ mBacking.TouchedSignal().Connect(this, &Popup::OnBackingTouched);
+ mPopupBackgroundImage.TouchedSignal().Connect(this, &Popup::OnDialogTouched);
+ mPopupLayout.TouchedSignal().Connect(this, &Popup::OnDialogTouched);
+ mLayer.SetProperty(Layer::Property::CONSUMES_TOUCH, true);
}
else
{
// We are touch transparent so disconnect all signals and ensure our layer does not consumed all touch events
- mBacking.TouchedSignal().Disconnect( this, &Popup::OnBackingTouched );
- mPopupBackgroundImage.TouchedSignal().Disconnect( this, &Popup::OnDialogTouched );
- mPopupLayout.TouchedSignal().Disconnect( this, &Popup::OnDialogTouched );
- mLayer.SetProperty( Layer::Property::CONSUMES_TOUCH, false );
+ mBacking.TouchedSignal().Disconnect(this, &Popup::OnBackingTouched);
+ mPopupBackgroundImage.TouchedSignal().Disconnect(this, &Popup::OnDialogTouched);
+ mPopupLayout.TouchedSignal().Disconnect(this, &Popup::OnDialogTouched);
+ mLayer.SetProperty(Layer::Property::CONSUMES_TOUCH, false);
}
}
std::string Popup::AccessibleImpl::GetNameRaw()
{
- auto popup = Toolkit::Popup::DownCast( self );
+ auto popup = Toolkit::Popup::DownCast(self);
std::string title;
- Actor popupTitle = popup.GetTitle();
- if (popupTitle)
+ Actor popupTitle = popup.GetTitle();
+ if(popupTitle)
{
std::string titleText = popupTitle.GetProperty<std::string>(Toolkit::TextLabel::Property::TEXT);
- title = titleText;
+ title = titleText;
}
else
{
Actor popupContent = popup.GetContent();
- if (popupContent)
+ if(popupContent)
{
std::string contentText = popupContent.GetProperty<std::string>(Toolkit::TextLabel::Property::TEXT);
- title = contentText;
+ title = contentText;
}
}
return title;
Dali::Accessibility::States Popup::AccessibleImpl::CalculateStates()
{
- auto states = Control::Impl::AccessibleImpl::CalculateStates();
- auto popup = Toolkit::Popup::DownCast(self);
+ auto states = Control::Impl::AccessibleImpl::CalculateStates();
+ auto popup = Toolkit::Popup::DownCast(self);
auto displayState = popup.GetProperty<std::string>(Toolkit::Popup::Property::DISPLAY_STATE);
states[Dali::Accessibility::State::SHOWING] = (displayState == "SHOWN" || displayState == "SHOWING");
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/progress-bar/progress-bar-impl.h>
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
-#include <sstream>
-#include <algorithm>
-#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/public-api/size-negotiation/relayout-container.h>
-#include <dali/public-api/math/math-utils.h>
-#include <dali-toolkit/public-api/align-enumerations.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
#include <dali-toolkit/devel-api/visual-factory/visual-base.h>
+#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
+#include <dali-toolkit/devel-api/visuals/arc-visual-properties-devel.h>
#include <dali-toolkit/internal/visuals/visual-base-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/devel-api/visuals/arc-visual-properties-devel.h>
+#include <dali-toolkit/public-api/align-enumerations.h>
#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
+#include <dali/public-api/math/math-utils.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/size-negotiation/relayout-container.h>
+#include <algorithm>
+#include <cstring> // for strcmp
+#include <sstream>
#include <dali/integration-api/debug.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace // Unnamed namespace
{
-
BaseHandle Create()
{
return Dali::Toolkit::ProgressBar::New();
}
+// clang-format off
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ProgressBar, Toolkit::Control, Create )
-
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "progressValue", FLOAT, PROGRESS_VALUE )
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "secondaryProgressValue", FLOAT, SECONDARY_PROGRESS_VALUE )
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "indeterminate", BOOLEAN, INDETERMINATE )
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "trackVisual", MAP, TRACK_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "progressVisual", MAP, PROGRESS_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "secondaryProgressVisual", MAP, SECONDARY_PROGRESS_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "indeterminateVisual", MAP, INDETERMINATE_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "indeterminateVisualAnimation", ARRAY, INDETERMINATE_VISUAL_ANIMATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "labelVisual", MAP, LABEL_VISUAL )
-DALI_SIGNAL_REGISTRATION( Toolkit, ProgressBar, "valueChanged", SIGNAL_VALUE_CHANGED )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ProgressBar, Toolkit::Control, Create)
+
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "progressValue", FLOAT, PROGRESS_VALUE )
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "secondaryProgressValue", FLOAT, SECONDARY_PROGRESS_VALUE )
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "indeterminate", BOOLEAN, INDETERMINATE )
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "trackVisual", MAP, TRACK_VISUAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "progressVisual", MAP, PROGRESS_VISUAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "secondaryProgressVisual", MAP, SECONDARY_PROGRESS_VISUAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "indeterminateVisual", MAP, INDETERMINATE_VISUAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "indeterminateVisualAnimation", ARRAY, INDETERMINATE_VISUAL_ANIMATION)
+DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "labelVisual", MAP, LABEL_VISUAL )
+
+DALI_SIGNAL_REGISTRATION(Toolkit, ProgressBar, "valueChanged", SIGNAL_VALUE_CHANGED)
DALI_TYPE_REGISTRATION_END()
+// clang-format on
struct ProgressDepthIndex
{
};
};
-float DEFAULT_VALUE = 0.0f;
-float DEFAULT_LOWER_BOUND = 0.0f;
-float DEFAULT_UPPER_BOUND = 1.0f;
-float DEFAULT_FONT_SIZE = 12.0f;
+float DEFAULT_VALUE = 0.0f;
+float DEFAULT_LOWER_BOUND = 0.0f;
+float DEFAULT_UPPER_BOUND = 1.0f;
+float DEFAULT_FONT_SIZE = 12.0f;
const char* CIRCULAR_PROGRESS_BAR_STYLE_NAME = "CircularProgressBar";
-
-void BackupVisualProperties( const Control* control, Property::Index index, Property::Map& map )
+void BackupVisualProperties(const Control* control, Property::Index index, Property::Map& map)
{
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *control, index );
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*control, index);
- if( visual )
+ if(visual)
{
map.Clear();
- visual.CreatePropertyMap( map );
+ visual.CreatePropertyMap(map);
}
}
-void RestoreVisualProperties( Control* control, Property::Index index, Property::Map& map, int depth )
+void RestoreVisualProperties(Control* control, Property::Index index, Property::Map& map, int depth)
{
- if( !map.Empty() )
+ if(!map.Empty())
{
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *control, index );
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*control, index);
- Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
+ Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
- visualImpl.SetProperties( map );
+ visualImpl.SetProperties(map);
- DevelControl::UnregisterVisual( *control, index );
+ DevelControl::UnregisterVisual(*control, index);
- DevelControl::RegisterVisual( *control, index, visual, true, depth );
+ DevelControl::RegisterVisual(*control, index, visual, true, depth);
}
}
// ProgressBar
///////////////////////////////////////////////////////////////////////////////////////////////////
-Dali::Toolkit::ProgressBar ProgressBar::New( DevelProgressBar::Style progressBarStyle )
+Dali::Toolkit::ProgressBar ProgressBar::New(DevelProgressBar::Style progressBarStyle)
{
// Create the implementation
- ProgressBarPtr progressBar( new ProgressBar() );
+ ProgressBarPtr progressBar(new ProgressBar());
- Dali::Toolkit::ProgressBar handle( *progressBar );
+ Dali::Toolkit::ProgressBar handle(*progressBar);
- switch( progressBarStyle )
+ switch(progressBarStyle)
{
case DevelProgressBar::Style::CIRCULAR:
{
- progressBar->SetStyleName( CIRCULAR_PROGRESS_BAR_STYLE_NAME );
+ progressBar->SetStyleName(CIRCULAR_PROGRESS_BAR_STYLE_NAME);
break;
}
default:
}
ProgressBar::ProgressBar()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mProgressValue( DEFAULT_VALUE ),
- mSecondaryProgressValue( DEFAULT_VALUE ),
- mIndeterminate( false )
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mProgressValue(DEFAULT_VALUE),
+ mSecondaryProgressValue(DEFAULT_VALUE),
+ mIndeterminate(false)
{
}
void ProgressBar::OnInitialize()
{
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::PROGRESS_BAR ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::PROGRESS_BAR));
+ });
//Enable highightability
- Self().SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true );
+ Self().SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
}
-void ProgressBar::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void ProgressBar::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
+ Vector2 trackSize(size);
+ mDomain = CalcDomain(size);
- Vector2 trackSize( size );
- mDomain = CalcDomain( size );
-
- trackSize.width = std::max( 0.0f, size.width ); // Ensure we don't go negative
+ trackSize.width = std::max(0.0f, size.width); // Ensure we don't go negative
- Toolkit::Visual::Base trackVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::TRACK_VISUAL );
- Toolkit::Visual::Base labelVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::LABEL_VISUAL );
- Toolkit::Visual::Base indeterminateVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL );
+ Toolkit::Visual::Base trackVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::TRACK_VISUAL);
+ Toolkit::Visual::Base labelVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::LABEL_VISUAL);
+ Toolkit::Visual::Base indeterminateVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL);
- if( trackVisual )
+ if(trackVisual)
{
Property::Map visualTransform;
- visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, trackSize )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) );
+ visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, trackSize)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE));
- trackVisual.SetTransformAndSize( visualTransform, trackSize );
+ trackVisual.SetTransformAndSize(visualTransform, trackSize);
}
- ApplyProgressToVisualTransform( mSecondaryProgressValue, trackSize, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL );
+ ApplyProgressToVisualTransform(mSecondaryProgressValue, trackSize, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL);
- ApplyProgressToVisualTransform( mProgressValue, trackSize, Toolkit::ProgressBar::Property::PROGRESS_VISUAL );
+ ApplyProgressToVisualTransform(mProgressValue, trackSize, Toolkit::ProgressBar::Property::PROGRESS_VISUAL);
- if( labelVisual )
+ if(labelVisual)
{
Property::Map visualTransform;
- visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, trackSize )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) );
- labelVisual.SetTransformAndSize( visualTransform, trackSize );
+ visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, trackSize)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE));
+ labelVisual.SetTransformAndSize(visualTransform, trackSize);
}
- if( indeterminateVisual )
+ if(indeterminateVisual)
{
Property::Map visualTransform;
- visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, trackSize )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) );
- indeterminateVisual.SetTransformAndSize( visualTransform, trackSize );
+ visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, trackSize)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE));
+ indeterminateVisual.SetTransformAndSize(visualTransform, trackSize);
}
-
}
Vector3 ProgressBar::GetNaturalSize()
{
// Return the bigger size after comparing trackVisual naturalSize and labelVisual naturalSize
- Toolkit::Visual::Base trackVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::TRACK_VISUAL );
- Toolkit::Visual::Base labelVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::LABEL_VISUAL );
+ Toolkit::Visual::Base trackVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::TRACK_VISUAL);
+ Toolkit::Visual::Base labelVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::LABEL_VISUAL);
Size trackSize;
Size labelSize;
- if ( trackVisual )
+ if(trackVisual)
{
- trackVisual.GetNaturalSize( trackSize );
+ trackVisual.GetNaturalSize(trackSize);
}
- if ( labelVisual )
+ if(labelVisual)
{
- labelVisual.GetNaturalSize( labelSize );
+ labelVisual.GetNaturalSize(labelSize);
}
Vector3 naturalSize;
- naturalSize.width = ( trackSize.width > labelSize.width ) ? trackSize.width: labelSize.width;
- naturalSize.height = ( trackSize.height > labelSize.height ) ? trackSize.height: labelSize.height;
+ naturalSize.width = (trackSize.width > labelSize.width) ? trackSize.width : labelSize.width;
+ naturalSize.height = (trackSize.height > labelSize.height) ? trackSize.height : labelSize.height;
return naturalSize;
}
-ProgressBar::Domain ProgressBar::CalcDomain( const Vector2& currentSize )
+ProgressBar::Domain ProgressBar::CalcDomain(const Vector2& currentSize)
{
- return Domain( Vector2( 0.0f, 0.0f ), currentSize );
+ return Domain(Vector2(0.0f, 0.0f), currentSize);
}
Toolkit::ProgressBar::ValueChangedSignalType& ProgressBar::ValueChangedSignal()
return mValueChangedSignal;
}
-void ProgressBar::SetProgressValue( float value )
+void ProgressBar::SetProgressValue(float value)
{
// update the progress bar value (taking float precision errors into account)
// TODO : it seems 0.0f cannot into this statement.
- if( ( mProgressValue != value ) &&
- ( ( value >= DEFAULT_LOWER_BOUND ) || ( Equals( value, DEFAULT_LOWER_BOUND ) ) ) &&
- ( ( value <= DEFAULT_UPPER_BOUND ) || ( Equals( value, DEFAULT_UPPER_BOUND ) ) ) )
+ if((mProgressValue != value) &&
+ ((value >= DEFAULT_LOWER_BOUND) || (Equals(value, DEFAULT_LOWER_BOUND))) &&
+ ((value <= DEFAULT_UPPER_BOUND) || (Equals(value, DEFAULT_UPPER_BOUND))))
{
- mProgressValue = Clamp( value, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND );
+ mProgressValue = Clamp(value, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND);
- ApplyProgressToVisual( mProgressValue, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, ProgressDepthIndex::PROGRESS_VISUAL );
+ ApplyProgressToVisual(mProgressValue, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, ProgressDepthIndex::PROGRESS_VISUAL);
- Toolkit::ProgressBar self = Toolkit::ProgressBar::DownCast( Self() );
- mValueChangedSignal.Emit( self, mProgressValue, mSecondaryProgressValue );
- if (Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
+ Toolkit::ProgressBar self = Toolkit::ProgressBar::DownCast(Self());
+ mValueChangedSignal.Emit(self, mProgressValue, mSecondaryProgressValue);
+ if(Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
{
Control::Impl::GetAccessibilityObject(Self())->Emit(Dali::Accessibility::ObjectPropertyChangeEvent::VALUE);
}
return mProgressValue;
}
-void ProgressBar::SetSecondaryProgressValue( float value )
+void ProgressBar::SetSecondaryProgressValue(float value)
{
// update the progress bar value (taking float precision errors into account)
// TODO : it seems 0.0f cannot into this statement.
- if( ( mSecondaryProgressValue != value ) &&
- ( ( value >= DEFAULT_LOWER_BOUND ) || ( Equals( value, DEFAULT_LOWER_BOUND ) ) ) &&
- ( ( value <= DEFAULT_UPPER_BOUND ) || ( Equals( value, DEFAULT_UPPER_BOUND ) ) ) )
+ if((mSecondaryProgressValue != value) &&
+ ((value >= DEFAULT_LOWER_BOUND) || (Equals(value, DEFAULT_LOWER_BOUND))) &&
+ ((value <= DEFAULT_UPPER_BOUND) || (Equals(value, DEFAULT_UPPER_BOUND))))
{
- mSecondaryProgressValue = Clamp( value, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND );
+ mSecondaryProgressValue = Clamp(value, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND);
- ApplyProgressToVisual( mSecondaryProgressValue, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL );
+ ApplyProgressToVisual(mSecondaryProgressValue, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL);
- Toolkit::ProgressBar self = Toolkit::ProgressBar::DownCast( Self() );
- mValueChangedSignal.Emit( self, mProgressValue, mSecondaryProgressValue );
+ Toolkit::ProgressBar self = Toolkit::ProgressBar::DownCast(Self());
+ mValueChangedSignal.Emit(self, mProgressValue, mSecondaryProgressValue);
RelayoutRequest();
}
return mSecondaryProgressValue;
}
-void ProgressBar::SetIndeterminate( bool value )
+void ProgressBar::SetIndeterminate(bool value)
{
mIndeterminate = value;
- DevelControl::EnableVisual( *this, Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL, mIndeterminate );
+ DevelControl::EnableVisual(*this, Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL, mIndeterminate);
- if( mIndeterminate )
+ if(mIndeterminate)
{
RelayoutRequest();
- if( mIndeterminateVisualTransition )
+ if(mIndeterminateVisualTransition)
{
PlayIndeterminateVisualTransition();
}
}
else
{
- if( mIndeterminateVisualAni )
+ if(mIndeterminateVisualAni)
{
mIndeterminateVisualAni.Stop();
}
// Restore previous visual data after animation finished.
- RestoreVisualProperties( this, Toolkit::ProgressBar::Property::TRACK_VISUAL, mTrackVisualMap, ProgressDepthIndex::TRACK_VISUAL );
- RestoreVisualProperties( this, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, mSecondaryProgressVisualMap, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL );
- RestoreVisualProperties( this, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, mProgressVisualMap, ProgressDepthIndex::PROGRESS_VISUAL );
+ RestoreVisualProperties(this, Toolkit::ProgressBar::Property::TRACK_VISUAL, mTrackVisualMap, ProgressDepthIndex::TRACK_VISUAL);
+ RestoreVisualProperties(this, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, mSecondaryProgressVisualMap, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL);
+ RestoreVisualProperties(this, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, mProgressVisualMap, ProgressDepthIndex::PROGRESS_VISUAL);
RelayoutRequest();
}
return mIndeterminate;
}
-void ProgressBar::SetIndeterminateVisualTransition( Toolkit::TransitionData transition )
+void ProgressBar::SetIndeterminateVisualTransition(Toolkit::TransitionData transition)
{
mIndeterminateVisualTransition = transition;
- if( mIndeterminate )
+ if(mIndeterminate)
{
PlayIndeterminateVisualTransition();
}
void ProgressBar::PlayIndeterminateVisualTransition()
{
// Store current visual data before animation changes it.
- BackupVisualProperties( this, Toolkit::ProgressBar::Property::TRACK_VISUAL, mTrackVisualMap );
- BackupVisualProperties( this, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, mSecondaryProgressVisualMap );
- BackupVisualProperties( this, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, mProgressVisualMap );
+ BackupVisualProperties(this, Toolkit::ProgressBar::Property::TRACK_VISUAL, mTrackVisualMap);
+ BackupVisualProperties(this, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, mSecondaryProgressVisualMap);
+ BackupVisualProperties(this, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, mProgressVisualMap);
- if( mIndeterminateVisualAni )
+ if(mIndeterminateVisualAni)
{
mIndeterminateVisualAni.Stop();
mIndeterminateVisualAni.Clear();
}
- mIndeterminateVisualAni = DevelControl::CreateTransition( *this, mIndeterminateVisualTransition );
+ mIndeterminateVisualAni = DevelControl::CreateTransition(*this, mIndeterminateVisualTransition);
- if( mIndeterminate && mIndeterminateVisualAni )
+ if(mIndeterminate && mIndeterminateVisualAni)
{
mIndeterminateVisualAni.SetLooping(true);
mIndeterminateVisualAni.Play();
}
}
-Toolkit::TransitionData ProgressBar::ConvertPropertyToTransition( const Property::Value& value )
+Toolkit::TransitionData ProgressBar::ConvertPropertyToTransition(const Property::Value& value)
{
Toolkit::TransitionData transitionData;
- if( value.GetType() == Property::ARRAY )
+ if(value.GetType() == Property::ARRAY)
{
- transitionData = Toolkit::TransitionData::New( *value.GetArray() );
+ transitionData = Toolkit::TransitionData::New(*value.GetArray());
}
- else if( value.GetType() == Property::MAP )
+ else if(value.GetType() == Property::MAP)
{
- transitionData = Toolkit::TransitionData::New( *value.GetMap() );
+ transitionData = Toolkit::TransitionData::New(*value.GetMap());
}
return transitionData;
* 4) Unregister visual if empty map was provided. This is the method to remove a visual
*/
-void ProgressBar::CreateVisualsForComponent( Property::Index index, const Property::Value& value, const int visualDepth )
+void ProgressBar::CreateVisualsForComponent(Property::Index index, const Property::Value& value, const int visualDepth)
{
Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get();
- Toolkit::Visual::Base progressVisual;
+ Toolkit::Visual::Base progressVisual;
std::string imageUrl;
- if( value.Get( imageUrl ) )
+ if(value.Get(imageUrl))
{
- if ( !imageUrl.empty() )
+ if(!imageUrl.empty())
{
- progressVisual = visualFactory.CreateVisual( imageUrl, ImageDimensions() );
+ progressVisual = visualFactory.CreateVisual(imageUrl, ImageDimensions());
}
}
else // Does this code make text-visual can be accepted as visual?
{
// if its not a string then get a Property::Map from the property if possible.
- const Property::Map *map = value.GetMap();
- if( map && !map->Empty() ) // Empty map results in current visual removal.
+ const Property::Map* map = value.GetMap();
+ if(map && !map->Empty()) // Empty map results in current visual removal.
{
- progressVisual = visualFactory.CreateVisual( *map );
+ progressVisual = visualFactory.CreateVisual(*map);
}
}
- if ( progressVisual )
+ if(progressVisual)
{
- if( index == Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL )
+ if(index == Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL)
{
- DevelControl::RegisterVisual( *this, index, progressVisual, mIndeterminate, visualDepth );
+ DevelControl::RegisterVisual(*this, index, progressVisual, mIndeterminate, visualDepth);
}
else
{
- DevelControl::RegisterVisual( *this, index, progressVisual, true, visualDepth );
+ DevelControl::RegisterVisual(*this, index, progressVisual, true, visualDepth);
}
}
else
{
- DevelControl::UnregisterVisual( *this, index );
+ DevelControl::UnregisterVisual(*this, index);
}
}
-bool ProgressBar::GetPropertyMapForVisual( Property::Index visualIndex, Property::Map& retreivedMap ) const
+bool ProgressBar::GetPropertyMapForVisual(Property::Index visualIndex, Property::Map& retreivedMap) const
{
- bool success = false;
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, visualIndex );
+ bool success = false;
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, visualIndex);
- if ( visual )
+ if(visual)
{
- visual.CreatePropertyMap( retreivedMap );
+ visual.CreatePropertyMap(retreivedMap);
success = true;
}
return success;
}
-
-void ProgressBar::ApplyProgressToVisual( float progress, Property::Index index, int depth )
+void ProgressBar::ApplyProgressToVisual(float progress, Property::Index index, int depth)
{
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, index );
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, index);
- if( visual && static_cast<DevelVisual::Type>( visual.GetType() ) == DevelVisual::ARC && !mIndeterminate )
+ if(visual && static_cast<DevelVisual::Type>(visual.GetType()) == DevelVisual::ARC && !mIndeterminate)
{
- Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
+ Visual::Base& visualImpl = Toolkit::GetImplementation(visual);
Property::Map map;
- map[ Toolkit::DevelArcVisual::Property::SWEEP_ANGLE ] = Property::Value( 360.0f * progress );
+ map[Toolkit::DevelArcVisual::Property::SWEEP_ANGLE] = Property::Value(360.0f * progress);
- visualImpl.SetProperties( map );
+ visualImpl.SetProperties(map);
- DevelControl::UnregisterVisual( *this, index );
- DevelControl::RegisterVisual( *this, index, visual, true, depth );
+ DevelControl::UnregisterVisual(*this, index);
+ DevelControl::RegisterVisual(*this, index, visual, true, depth);
}
}
-void ProgressBar::ApplyProgressToVisualTransform( float progress, Vector2 trackSize, Property::Index index )
+void ProgressBar::ApplyProgressToVisualTransform(float progress, Vector2 trackSize, Property::Index index)
{
- Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, index );
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, index);
- if( visual )
+ if(visual)
{
Property::Map visualTransform;
- if( static_cast<DevelVisual::Type>( visual.GetType() ) != DevelVisual::ARC )
+ if(static_cast<DevelVisual::Type>(visual.GetType()) != DevelVisual::ARC)
{
- visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, Vector2( mDomain.from.x + progress * ( mDomain.to.x - mDomain.from.x ), trackSize.height ) )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN )
- .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN );
+ visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, Vector2(mDomain.from.x + progress * (mDomain.to.x - mDomain.from.x), trackSize.height))
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN)
+ .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN);
}
- visual.SetTransformAndSize( visualTransform, trackSize );
+ visual.SetTransformAndSize(visualTransform, trackSize);
}
}
// Static class method to support script connecting signals
-bool ProgressBar::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool ProgressBar::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected = true;
- Toolkit::ProgressBar ProgressBar = Toolkit::ProgressBar::DownCast( handle );
+ bool connected = true;
+ Toolkit::ProgressBar ProgressBar = Toolkit::ProgressBar::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_VALUE_CHANGED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_VALUE_CHANGED))
{
- ProgressBar.ValueChangedSignal().Connect( tracker, functor );
+ ProgressBar.ValueChangedSignal().Connect(tracker, functor);
}
else
{
return connected;
}
-void ProgressBar::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
+void ProgressBar::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value)
{
- Toolkit::ProgressBar progressBar = Toolkit::ProgressBar::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ProgressBar progressBar = Toolkit::ProgressBar::DownCast(Dali::BaseHandle(object));
- if ( progressBar )
+ if(progressBar)
{
- ProgressBar& progressBarImpl( GetImpl( progressBar ) );
+ ProgressBar& progressBarImpl(GetImpl(progressBar));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::ProgressBar::Property::TRACK_VISUAL:
{
- progressBarImpl.CreateVisualsForComponent( propertyIndex, value, ProgressDepthIndex::TRACK_VISUAL );
+ progressBarImpl.CreateVisualsForComponent(propertyIndex, value, ProgressDepthIndex::TRACK_VISUAL);
break;
}
case Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL:
{
- progressBarImpl.CreateVisualsForComponent( propertyIndex, value, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL );
- progressBarImpl.ApplyProgressToVisual( progressBarImpl.mSecondaryProgressValue, propertyIndex, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL );
+ progressBarImpl.CreateVisualsForComponent(propertyIndex, value, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL);
+ progressBarImpl.ApplyProgressToVisual(progressBarImpl.mSecondaryProgressValue, propertyIndex, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL);
break;
}
case Toolkit::ProgressBar::Property::PROGRESS_VISUAL:
{
- progressBarImpl.CreateVisualsForComponent( propertyIndex, value, ProgressDepthIndex::PROGRESS_VISUAL );
- progressBarImpl.ApplyProgressToVisual( progressBarImpl.mProgressValue, propertyIndex, ProgressDepthIndex::PROGRESS_VISUAL );
+ progressBarImpl.CreateVisualsForComponent(propertyIndex, value, ProgressDepthIndex::PROGRESS_VISUAL);
+ progressBarImpl.ApplyProgressToVisual(progressBarImpl.mProgressValue, propertyIndex, ProgressDepthIndex::PROGRESS_VISUAL);
break;
}
case Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL:
{
- progressBarImpl.CreateVisualsForComponent( propertyIndex, value, ProgressDepthIndex::INDETERMINATE_VISUAL );
+ progressBarImpl.CreateVisualsForComponent(propertyIndex, value, ProgressDepthIndex::INDETERMINATE_VISUAL);
break;
}
case Toolkit::ProgressBar::Property::LABEL_VISUAL:
{
Property::Map map;
- std::string textString;
+ std::string textString;
- if ( value.Get( textString ) )
+ if(value.Get(textString))
{
// set new text string as TEXT property
- Property::Map newTextMap;
- Toolkit::Visual::Base label = DevelControl::GetVisual( progressBarImpl, Toolkit::ProgressBar::Property::LABEL_VISUAL );
+ Property::Map newTextMap;
+ Toolkit::Visual::Base label = DevelControl::GetVisual(progressBarImpl, Toolkit::ProgressBar::Property::LABEL_VISUAL);
- if( label )
+ if(label)
{
- label.CreatePropertyMap( map );
+ label.CreatePropertyMap(map);
}
// if LABEL_VISUAL doesn't set before, add Visual property "TYPE" to create new text Visual
- if( map.Empty() )
+ if(map.Empty())
{
- newTextMap.Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT );
- newTextMap.Add( Toolkit::TextVisual::Property::POINT_SIZE, DEFAULT_FONT_SIZE );
+ newTextMap.Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT);
+ newTextMap.Add(Toolkit::TextVisual::Property::POINT_SIZE, DEFAULT_FONT_SIZE);
}
- newTextMap.Add( Toolkit::TextVisual::Property::TEXT, textString );
+ newTextMap.Add(Toolkit::TextVisual::Property::TEXT, textString);
- map.Merge( newTextMap );
+ map.Merge(newTextMap);
}
else
{
- value.Get( map );
+ value.Get(map);
}
- if( !map.Empty() )
+ if(!map.Empty())
{
- progressBarImpl.CreateVisualsForComponent( propertyIndex, map, ProgressDepthIndex::LABEL_VISUAL );
+ progressBarImpl.CreateVisualsForComponent(propertyIndex, map, ProgressDepthIndex::LABEL_VISUAL);
}
break;
}
case Toolkit::ProgressBar::Property::PROGRESS_VALUE:
{
- progressBarImpl.SetProgressValue( value.Get< float >() );
+ progressBarImpl.SetProgressValue(value.Get<float>());
break;
}
case Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VALUE:
{
- progressBarImpl.SetSecondaryProgressValue( value.Get< float >() );
+ progressBarImpl.SetSecondaryProgressValue(value.Get<float>());
break;
}
case Toolkit::ProgressBar::Property::INDETERMINATE:
{
- progressBarImpl.SetIndeterminate( value.Get< bool >() );
+ progressBarImpl.SetIndeterminate(value.Get<bool>());
break;
}
case Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL_ANIMATION:
{
- progressBarImpl.SetIndeterminateVisualTransition( progressBarImpl.ConvertPropertyToTransition( value ) );
+ progressBarImpl.SetIndeterminateVisualTransition(progressBarImpl.ConvertPropertyToTransition(value));
break;
}
}
}
}
-Property::Value ProgressBar::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value ProgressBar::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::ProgressBar progressBar = Toolkit::ProgressBar::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ProgressBar progressBar = Toolkit::ProgressBar::DownCast(Dali::BaseHandle(object));
- if ( progressBar )
+ if(progressBar)
{
- ProgressBar& progressBarImpl( GetImpl( progressBar ) );
+ ProgressBar& progressBarImpl(GetImpl(progressBar));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::ProgressBar::Property::TRACK_VISUAL:
case Toolkit::ProgressBar::Property::PROGRESS_VISUAL:
case Toolkit::ProgressBar::Property::LABEL_VISUAL:
{
Property::Map visualProperty;
- if ( progressBarImpl.GetPropertyMapForVisual( propertyIndex, visualProperty ) )
+ if(progressBarImpl.GetPropertyMapForVisual(propertyIndex, visualProperty))
{
value = visualProperty;
}
return value;
}
-void ProgressBar::OnSceneConnection( int depth )
+void ProgressBar::OnSceneConnection(int depth)
{
// Chain up first (ensures visuals are ready to draw)
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
- if( mIndeterminate )
+ if(mIndeterminate)
{
PlayIndeterminateVisualTransition();
}
}
-double ProgressBar::AccessibleImpl::GetMinimum() { return DEFAULT_LOWER_BOUND; }
+double ProgressBar::AccessibleImpl::GetMinimum()
+{
+ return DEFAULT_LOWER_BOUND;
+}
double ProgressBar::AccessibleImpl::GetCurrent()
{
- auto p = Toolkit::ProgressBar::DownCast( self );
- return p.GetProperty( Toolkit::ProgressBar::Property::PROGRESS_VALUE )
- .Get< float >();
+ auto p = Toolkit::ProgressBar::DownCast(self);
+ return p.GetProperty(Toolkit::ProgressBar::Property::PROGRESS_VALUE)
+ .Get<float>();
}
-double ProgressBar::AccessibleImpl::GetMaximum() { return DEFAULT_UPPER_BOUND; }
+double ProgressBar::AccessibleImpl::GetMaximum()
+{
+ return DEFAULT_UPPER_BOUND;
+}
-bool ProgressBar::AccessibleImpl::SetCurrent( double current )
+bool ProgressBar::AccessibleImpl::SetCurrent(double current)
{
- if( current < GetMinimum() || current > GetMaximum() )
+ if(current < GetMinimum() || current > GetMaximum())
return false;
- auto p = Toolkit::ProgressBar::DownCast( self );
- p.SetProperty( Toolkit::ProgressBar::Property::PROGRESS_VALUE,
- static_cast< float >( current ) );
+ auto p = Toolkit::ProgressBar::DownCast(self);
+ p.SetProperty(Toolkit::ProgressBar::Property::PROGRESS_VALUE,
+ static_cast<float>(current));
return true;
}
-double ProgressBar::AccessibleImpl::GetMinimumIncrement() { return 0.0; }
+double ProgressBar::AccessibleImpl::GetMinimumIncrement()
+{
+ return 0.0;
+}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/scene3d-view/gltf-loader.h>
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <dali/devel-api/adaptor-framework/image-loading.h>
-#include <dali/devel-api/adaptor-framework/file-stream.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali/devel-api/adaptor-framework/file-stream.h>
+#include <dali/devel-api/adaptor-framework/image-loading.h>
+#include <dali/integration-api/debug.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace Gltf
{
-
namespace
{
-
// Utility functions
-const TreeNode* Tidx( const TreeNode *node, uint32_t index )
+const TreeNode* Tidx(const TreeNode* node, uint32_t index)
{
uint32_t i = 0;
- for( auto it = node->CBegin(), end = node->CEnd(); it != end; ++it, ++i )
+ for(auto it = node->CBegin(), end = node->CEnd(); it != end; ++it, ++i)
{
- if( i == index )
+ if(i == index)
{
- return &( ( *it ).second );
+ return &((*it).second);
}
}
return NULL;
}
-bool ReadBool( const TreeNode* node, bool& num )
+bool ReadBool(const TreeNode* node, bool& num)
{
- if( !node )
+ if(!node)
{
return false;
}
bool returnValue = false;
- if( node->GetType() == TreeNode::BOOLEAN )
+ if(node->GetType() == TreeNode::BOOLEAN)
{
- num = node->GetBoolean();
+ num = node->GetBoolean();
returnValue = true;
}
return returnValue;
}
-bool ReadInt( const TreeNode* node, int32_t& num )
+bool ReadInt(const TreeNode* node, int32_t& num)
{
- if( !node )
+ if(!node)
{
return false;
}
bool returnValue = false;
- if( node->GetType() == TreeNode::INTEGER )
+ if(node->GetType() == TreeNode::INTEGER)
{
- num = node->GetInteger();
+ num = node->GetInteger();
returnValue = true;
}
- else if( node->GetType() == TreeNode::FLOAT )
+ else if(node->GetType() == TreeNode::FLOAT)
{
- num = node->GetFloat();
+ num = node->GetFloat();
returnValue = true;
}
return returnValue;
}
-bool ReadFloat( const TreeNode* node, float& num )
+bool ReadFloat(const TreeNode* node, float& num)
{
- if( !node )
+ if(!node)
{
return false;
}
bool returnValue = false;
- if( node->GetType() == TreeNode::FLOAT )
+ if(node->GetType() == TreeNode::FLOAT)
{
- num = node->GetFloat();
+ num = node->GetFloat();
returnValue = true;
}
- else if( node->GetType() == TreeNode::INTEGER )
+ else if(node->GetType() == TreeNode::INTEGER)
{
int32_t tempNum = 0;
- ReadInt( node, tempNum );
- num = static_cast<float>( tempNum );
+ ReadInt(node, tempNum);
+ num = static_cast<float>(tempNum);
returnValue = true;
}
return returnValue;
}
-bool ReadVector( const TreeNode* node, float* num, uint32_t size )
+bool ReadVector(const TreeNode* node, float* num, uint32_t size)
{
- if( !node )
+ if(!node)
{
return false;
}
bool returnValue = false;
- if( ( node->Size() >= size ) && ( node->GetType() == TreeNode::ARRAY ) )
+ if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY))
{
uint32_t offset = 0u;
- for( auto it = node->CBegin(); offset < size; ++it, ++offset )
+ for(auto it = node->CBegin(); offset < size; ++it, ++offset)
{
- const TreeNode& coord = ( *it ).second;
- if( !ReadFloat( &coord, *( num + offset ) ) )
+ const TreeNode& coord = (*it).second;
+ if(!ReadFloat(&coord, *(num + offset)))
{
return false;
}
return returnValue;
}
-bool ReadString( const TreeNode* node, std::string& strValue )
+bool ReadString(const TreeNode* node, std::string& strValue)
{
- if( !node )
+ if(!node)
{
return false;
}
bool returnValue = false;
- if( node->GetType() == TreeNode::STRING )
+ if(node->GetType() == TreeNode::STRING)
{
- strValue = node->GetString();
+ strValue = node->GetString();
returnValue = true;
}
return returnValue;
}
-template <typename T>
-float IntToFloat( T element, bool normalize )
+template<typename T>
+float IntToFloat(T element, bool normalize)
{
- if( !normalize )
+ if(!normalize)
{
- return static_cast<float>( element );
+ return static_cast<float>(element);
}
- if( std::is_same<T, int8_t>::value )
+ if(std::is_same<T, int8_t>::value)
{
- return std::max( static_cast<float>( element ) / 127.0, -1.0 );
+ return std::max(static_cast<float>(element) / 127.0, -1.0);
}
- if( std::is_same<T, uint8_t>::value )
+ if(std::is_same<T, uint8_t>::value)
{
- return static_cast<float>( element ) / 255.0;
+ return static_cast<float>(element) / 255.0;
}
- if( std::is_same<T, int16_t>::value )
+ if(std::is_same<T, int16_t>::value)
{
- return std::max( static_cast<float>( element ) / 32767.0, -1.0 );
+ return std::max(static_cast<float>(element) / 32767.0, -1.0);
}
- if( std::is_same<T, uint16_t>::value )
+ if(std::is_same<T, uint16_t>::value)
{
- return static_cast<float>( element ) / 65535.0;
+ return static_cast<float>(element) / 65535.0;
}
return -1.0;
}
-template <typename Td, typename Ts>
-void FitBuffer( Dali::Vector<Td>& bufferDestination, Dali::Vector<Ts>& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize )
+template<typename Td, typename Ts>
+void FitBuffer(Dali::Vector<Td>& bufferDestination, Dali::Vector<Ts>& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize)
{
- bufferDestination.Resize( bufferSize );
+ bufferDestination.Resize(bufferSize);
int32_t count = bufferSource.Size() / elementNumOfByteStride;
- for( int32_t i = 0; i<count; ++i )
+ for(int32_t i = 0; i < count; ++i)
{
- bufferDestination[i] = static_cast<Td>( bufferSource[i * elementNumOfByteStride] );
+ bufferDestination[i] = static_cast<Td>(bufferSource[i * elementNumOfByteStride]);
}
}
-template <typename T>
-void FitBuffer( Dali::Vector<Vector2>& bufferDestination, Dali::Vector<T>& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize )
+template<typename T>
+void FitBuffer(Dali::Vector<Vector2>& bufferDestination, Dali::Vector<T>& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize)
{
- bufferDestination.Resize( bufferSize );
+ bufferDestination.Resize(bufferSize);
int32_t count = bufferSource.Size() / elementNumOfByteStride;
- for( int32_t i = 0; i<count; ++i )
+ for(int32_t i = 0; i < count; ++i)
{
- bufferDestination[i].x = IntToFloat( bufferSource[i * elementNumOfByteStride], normalize );
- bufferDestination[i].y = IntToFloat( bufferSource[i * elementNumOfByteStride + 1], normalize );
+ bufferDestination[i].x = IntToFloat(bufferSource[i * elementNumOfByteStride], normalize);
+ bufferDestination[i].y = IntToFloat(bufferSource[i * elementNumOfByteStride + 1], normalize);
}
}
-template <typename T>
-void FitBuffer( Dali::Vector<Vector3>& bufferDestination, Dali::Vector<T>& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize )
+template<typename T>
+void FitBuffer(Dali::Vector<Vector3>& bufferDestination, Dali::Vector<T>& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize)
{
- bufferDestination.Resize( bufferSize );
+ bufferDestination.Resize(bufferSize);
int32_t count = bufferSource.Size() / elementNumOfByteStride;
- for( int32_t i = 0; i<count; ++i )
+ for(int32_t i = 0; i < count; ++i)
{
- bufferDestination[i].x = IntToFloat( bufferSource[i * elementNumOfByteStride], normalize );
- bufferDestination[i].y = IntToFloat( bufferSource[i * elementNumOfByteStride + 1], normalize );
- bufferDestination[i].z = IntToFloat( bufferSource[i * elementNumOfByteStride + 2], normalize );
+ bufferDestination[i].x = IntToFloat(bufferSource[i * elementNumOfByteStride], normalize);
+ bufferDestination[i].y = IntToFloat(bufferSource[i * elementNumOfByteStride + 1], normalize);
+ bufferDestination[i].z = IntToFloat(bufferSource[i * elementNumOfByteStride + 2], normalize);
}
}
-template <typename T>
-void FitBuffer( Dali::Vector<Vector4>& bufferDestination, Dali::Vector<T>& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize )
+template<typename T>
+void FitBuffer(Dali::Vector<Vector4>& bufferDestination, Dali::Vector<T>& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize)
{
- bufferDestination.Resize( bufferSize );
+ bufferDestination.Resize(bufferSize);
int32_t count = bufferSource.Size() / elementNumOfByteStride;
- for( int32_t i = 0; i<count; ++i )
+ for(int32_t i = 0; i < count; ++i)
{
- bufferDestination[i].x = IntToFloat( bufferSource[i * elementNumOfByteStride], normalize );
- bufferDestination[i].y = IntToFloat( bufferSource[i * elementNumOfByteStride + 1], normalize );
- bufferDestination[i].z = IntToFloat( bufferSource[i * elementNumOfByteStride + 2], normalize );
- bufferDestination[i].w = IntToFloat( bufferSource[i * elementNumOfByteStride + 3], normalize );
+ bufferDestination[i].x = IntToFloat(bufferSource[i * elementNumOfByteStride], normalize);
+ bufferDestination[i].y = IntToFloat(bufferSource[i * elementNumOfByteStride + 1], normalize);
+ bufferDestination[i].z = IntToFloat(bufferSource[i * elementNumOfByteStride + 2], normalize);
+ bufferDestination[i].w = IntToFloat(bufferSource[i * elementNumOfByteStride + 3], normalize);
}
}
// Template functions
-template <typename T>
-bool ReadBinFile( Vector<T> &dataBuffer, std::string url, int32_t offset, int32_t count )
+template<typename T>
+bool ReadBinFile(Vector<T>& dataBuffer, std::string url, int32_t offset, int32_t count)
{
- Dali::FileStream fileStream( url, FileStream::READ | FileStream::BINARY );
- FILE* fp = fileStream.GetFile();
- if( !fp )
+ Dali::FileStream fileStream(url, FileStream::READ | FileStream::BINARY);
+ FILE* fp = fileStream.GetFile();
+ if(!fp)
{
return false;
}
- dataBuffer.Resize( count );
+ dataBuffer.Resize(count);
ssize_t result = -1;
- if( !fseek( fp, offset, SEEK_SET ) )
+ if(!fseek(fp, offset, SEEK_SET))
{
- result = fread( &dataBuffer[0], sizeof( T ), count, fp );
+ result = fread(&dataBuffer[0], sizeof(T), count, fp);
}
- return ( result >= 0 );
+ return (result >= 0);
}
-template <typename T>
-void LoadDataFromAccessor( int32_t accessorIdx, Dali::Vector<T>& bufferData, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray )
+template<typename T>
+void LoadDataFromAccessor(int32_t accessorIdx, Dali::Vector<T>& bufferData, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray)
{
- AccessorInfo accessor = accessorArray[accessorIdx];
+ AccessorInfo accessor = accessorArray[accessorIdx];
BufferViewInfo bufferView = bufferViewArray[accessor.bufferView];
- std::string load_uri = bufferArray[bufferView.buffer].uri;
+ std::string load_uri = bufferArray[bufferView.buffer].uri;
// In the glTF 2.0 Specification, 5121 is UNSIGNED BYTE, 5123 is UNSIGNED SHORT
- int32_t elementByteSize = ( accessor.componentType <= 5121 ) ? 1 :
- ( ( accessor.componentType <= 5123 ) ? 2 : 4 );
- int32_t elementNum = 1;
- if( accessor.type == "VEC2" )
+ int32_t elementByteSize = (accessor.componentType <= 5121) ? 1 : ((accessor.componentType <= 5123) ? 2 : 4);
+ int32_t elementNum = 1;
+ if(accessor.type == "VEC2")
{
elementNum = 2;
}
- else if( accessor.type == "VEC3" )
+ else if(accessor.type == "VEC3")
{
elementNum = 3;
}
- else if( accessor.type == "VEC4" || accessor.type == "MAT2" )
+ else if(accessor.type == "VEC4" || accessor.type == "MAT2")
{
elementNum = 4;
}
- else if( accessor.type == "MAT3" )
+ else if(accessor.type == "MAT3")
{
elementNum = 9;
}
- else if( accessor.type == "MAT4" )
+ else if(accessor.type == "MAT4")
{
elementNum = 16;
}
elementNum = 1;
}
int32_t elementNumOfByteStride = elementNum;
- if( bufferView.byteStride > 0 )
+ if(bufferView.byteStride > 0)
{
elementNumOfByteStride = bufferView.byteStride / elementByteSize;
}
* 5125 : UNSIGNED_INT
* 5126 : FLOAT
*/
- if( accessor.componentType == 5120 )
+ if(accessor.componentType == 5120)
{
Dali::Vector<int8_t> inputBufferData;
- ReadBinFile<int8_t>( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count );
- FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized );
+ ReadBinFile<int8_t>(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count);
+ FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized);
}
- else if( accessor.componentType == 5121 )
+ else if(accessor.componentType == 5121)
{
Dali::Vector<uint8_t> inputBufferData;
- ReadBinFile<uint8_t>( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count );
- FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized );
+ ReadBinFile<uint8_t>(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count);
+ FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized);
}
- else if( accessor.componentType == 5122 )
+ else if(accessor.componentType == 5122)
{
Dali::Vector<int16_t> inputBufferData;
- ReadBinFile<int16_t>( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count );
- FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized );
+ ReadBinFile<int16_t>(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count);
+ FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized);
}
- else if( accessor.componentType == 5123 )
+ else if(accessor.componentType == 5123)
{
Dali::Vector<uint16_t> inputBufferData;
- ReadBinFile<uint16_t>( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count );
- FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized );
+ ReadBinFile<uint16_t>(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count);
+ FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized);
}
- else if( accessor.componentType == 5125 )
+ else if(accessor.componentType == 5125)
{
Dali::Vector<uint32_t> inputBufferData;
- ReadBinFile<uint32_t>( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count );
- FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized );
+ ReadBinFile<uint32_t>(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count);
+ FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized);
}
- else if( accessor.componentType == 5126 )
+ else if(accessor.componentType == 5126)
{
Dali::Vector<float> inputBufferData;
- ReadBinFile<float>( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count );
- FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized );
+ ReadBinFile<float>(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count);
+ FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized);
}
}
-void SetMeshInfoAndCanonize( MeshInfo& meshInfo, Dali::Vector<Dali::Vector3> &vertexBufferData )
+void SetMeshInfoAndCanonize(MeshInfo& meshInfo, Dali::Vector<Dali::Vector3>& vertexBufferData)
{
- Vector3 pointMin( std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max() );
- Vector3 pointMax( std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min() );
- for( auto&& data : vertexBufferData )
+ Vector3 pointMin(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
+ Vector3 pointMax(std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min());
+ for(auto&& data : vertexBufferData)
{
- pointMin.x = std::min( data.x, pointMin.x );
- pointMin.y = std::min( data.y, pointMin.y );
- pointMin.z = std::min( data.z, pointMin.z );
+ pointMin.x = std::min(data.x, pointMin.x);
+ pointMin.y = std::min(data.y, pointMin.y);
+ pointMin.z = std::min(data.z, pointMin.z);
- pointMax.x = std::max( data.x, pointMax.x );
- pointMax.y = std::max( data.y, pointMax.y );
- pointMax.z = std::max( data.z, pointMax.z );
+ pointMax.x = std::max(data.x, pointMax.x);
+ pointMax.y = std::max(data.y, pointMax.y);
+ pointMax.z = std::max(data.z, pointMax.z);
}
- meshInfo.size = pointMax - pointMin;
- meshInfo.pivot.x = ( -pointMin.x ) / ( pointMax.x - pointMin.x );
- meshInfo.pivot.y = ( -pointMin.y ) / ( pointMax.y - pointMin.y );
- meshInfo.pivot.z = ( -pointMin.z ) / ( pointMax.z - pointMin.z );
+ meshInfo.size = pointMax - pointMin;
+ meshInfo.pivot.x = (-pointMin.x) / (pointMax.x - pointMin.x);
+ meshInfo.pivot.y = (-pointMin.y) / (pointMax.y - pointMin.y);
+ meshInfo.pivot.z = (-pointMin.z) / (pointMax.z - pointMin.z);
Vector3 center = meshInfo.size * 0.5 + pointMin;
- for( auto&& data : vertexBufferData )
+ for(auto&& data : vertexBufferData)
{
data = data - center;
data.x = data.x / meshInfo.size.x;
}
}
-template <typename T>
-VertexBuffer CreateVertexBuffer( Vector<T> bufferData, std::string map, int32_t type )
+template<typename T>
+VertexBuffer CreateVertexBuffer(Vector<T> bufferData, std::string map, int32_t type)
{
Property::Map positionMap;
positionMap[map] = type;
- VertexBuffer vertexBuffer = VertexBuffer::New( positionMap );
- vertexBuffer.SetData( bufferData.Begin(), bufferData.Count() );
+ VertexBuffer vertexBuffer = VertexBuffer::New(positionMap);
+ vertexBuffer.SetData(bufferData.Begin(), bufferData.Count());
return vertexBuffer;
}
-void SetVertexBufferData( MeshInfo& meshInfo, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray, int32_t accessorIdx, std::string map, int32_t type )
+void SetVertexBufferData(MeshInfo& meshInfo, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray, int32_t accessorIdx, std::string map, int32_t type)
{
- if( accessorIdx >= 0 )
+ if(accessorIdx >= 0)
{
Dali::Vector<Vector3> bufferData;
- LoadDataFromAccessor( accessorIdx, bufferData, path, accessorArray, bufferViewArray, bufferArray );
- SetMeshInfoAndCanonize( meshInfo, bufferData );
+ LoadDataFromAccessor(accessorIdx, bufferData, path, accessorArray, bufferViewArray, bufferArray);
+ SetMeshInfoAndCanonize(meshInfo, bufferData);
- VertexBuffer vertexBuffer = CreateVertexBuffer<Vector3>( bufferData, map, type );
- meshInfo.geometry.AddVertexBuffer( vertexBuffer );
+ VertexBuffer vertexBuffer = CreateVertexBuffer<Vector3>(bufferData, map, type);
+ meshInfo.geometry.AddVertexBuffer(vertexBuffer);
}
}
-template <typename T>
-void SetAttributeBufferData( MeshInfo& meshInfo, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray, int32_t accessorIdx, std::string map, int32_t type )
+template<typename T>
+void SetAttributeBufferData(MeshInfo& meshInfo, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray, int32_t accessorIdx, std::string map, int32_t type)
{
- if( accessorIdx >= 0 )
+ if(accessorIdx >= 0)
{
Dali::Vector<T> bufferData;
- LoadDataFromAccessor( accessorIdx, bufferData, path, accessorArray, bufferViewArray, bufferArray );
+ LoadDataFromAccessor(accessorIdx, bufferData, path, accessorArray, bufferViewArray, bufferArray);
- VertexBuffer vertexBuffer = CreateVertexBuffer<T>( bufferData, map, type );
- meshInfo.geometry.AddVertexBuffer( vertexBuffer );
+ VertexBuffer vertexBuffer = CreateVertexBuffer<T>(bufferData, map, type);
+ meshInfo.geometry.AddVertexBuffer(vertexBuffer);
}
}
-void SetIndexBuffersData( MeshInfo& meshInfo, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray, int32_t indexIdx )
+void SetIndexBuffersData(MeshInfo& meshInfo, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray, int32_t indexIdx)
{
Dali::Vector<uint16_t> indexBufferData;
- LoadDataFromAccessor( indexIdx, indexBufferData, path, accessorArray, bufferViewArray, bufferArray );
- meshInfo.geometry.SetIndexBuffer( &indexBufferData[0], indexBufferData.Size() );
+ LoadDataFromAccessor(indexIdx, indexBufferData, path, accessorArray, bufferViewArray, bufferArray);
+ meshInfo.geometry.SetIndexBuffer(&indexBufferData[0], indexBufferData.Size());
}
template<typename T>
-float LoadKeyFrames( const AnimationSamplerInfo& currentSampler, const Property::Index propIndex, KeyFrames& keyframes, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray )
+float LoadKeyFrames(const AnimationSamplerInfo& currentSampler, const Property::Index propIndex, KeyFrames& keyframes, std::string path, std::vector<AccessorInfo>& accessorArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<BufferInfo>& bufferArray)
{
Dali::Vector<float> inputBufferData;
- Dali::Vector<T> outputBufferData;
+ Dali::Vector<T> outputBufferData;
- LoadDataFromAccessor<float>( currentSampler.input, inputBufferData, path, accessorArray, bufferViewArray, bufferArray );
- LoadDataFromAccessor<T>( currentSampler.output, outputBufferData, path, accessorArray, bufferViewArray, bufferArray );
+ LoadDataFromAccessor<float>(currentSampler.input, inputBufferData, path, accessorArray, bufferViewArray, bufferArray);
+ LoadDataFromAccessor<T>(currentSampler.output, outputBufferData, path, accessorArray, bufferViewArray, bufferArray);
- uint32_t keyframeNum = inputBufferData.Size();
- float lengthAnimation = inputBufferData[inputBufferData.Size() - 1];
- for( uint32_t i = 0; i < keyframeNum; i++ )
+ uint32_t keyframeNum = inputBufferData.Size();
+ float lengthAnimation = inputBufferData[inputBufferData.Size() - 1];
+ for(uint32_t i = 0; i < keyframeNum; i++)
{
- if( propIndex == Dali::Actor::Property::ORIENTATION )
+ if(propIndex == Dali::Actor::Property::ORIENTATION)
{
- Vector4 vectorOrientation( outputBufferData[i] );
- float vW = vectorOrientation.w;
- vW = ( vW < 0.0f ) ? std::max( vW, -1.0f ) : std::min( vW, 1.0f );
+ Vector4 vectorOrientation(outputBufferData[i]);
+ float vW = vectorOrientation.w;
+ vW = (vW < 0.0f) ? std::max(vW, -1.0f) : std::min(vW, 1.0f);
vectorOrientation.w = vW;
- keyframes.Add( inputBufferData[i] / lengthAnimation, Quaternion( Vector4( vectorOrientation ) ) );
+ keyframes.Add(inputBufferData[i] / lengthAnimation, Quaternion(Vector4(vectorOrientation)));
}
- else if( propIndex == Dali::Actor::Property::POSITION )
+ else if(propIndex == Dali::Actor::Property::POSITION)
{
- keyframes.Add( inputBufferData[i] / lengthAnimation, Vector3( outputBufferData[i] ) );
+ keyframes.Add(inputBufferData[i] / lengthAnimation, Vector3(outputBufferData[i]));
}
- else if( propIndex == Dali::Actor::Property::SCALE )
+ else if(propIndex == Dali::Actor::Property::SCALE)
{
- keyframes.Add( inputBufferData[i] / lengthAnimation, Vector3( outputBufferData[i] ) );
+ keyframes.Add(inputBufferData[i] / lengthAnimation, Vector3(outputBufferData[i]));
}
}
return lengthAnimation;
}
-bool LoadBuffer( const TreeNode& buffer, std::vector<BufferInfo>& bufferArray )
+bool LoadBuffer(const TreeNode& buffer, std::vector<BufferInfo>& bufferArray)
{
BufferInfo bufferInfo;
- const TreeNode* uriNode = buffer.GetChild( "uri" );
- if( uriNode )
+ const TreeNode* uriNode = buffer.GetChild("uri");
+ if(uriNode)
{
- ReadString( uriNode, bufferInfo.uri );
+ ReadString(uriNode, bufferInfo.uri);
}
- const TreeNode* byteLengthNode = buffer.GetChild( "byteLength" );
- if( byteLengthNode )
+ const TreeNode* byteLengthNode = buffer.GetChild("byteLength");
+ if(byteLengthNode)
{
- ReadInt( byteLengthNode, bufferInfo.byteLength );
- if( bufferInfo.byteLength < 0 )
+ ReadInt(byteLengthNode, bufferInfo.byteLength);
+ if(bufferInfo.byteLength < 0)
{
return false;
}
}
- const TreeNode* nameNode = buffer.GetChild( "name" );
- if( nameNode )
+ const TreeNode* nameNode = buffer.GetChild("name");
+ if(nameNode)
{
- ReadString( nameNode, bufferInfo.name );
+ ReadString(nameNode, bufferInfo.name);
}
- bufferArray.push_back( bufferInfo );
+ bufferArray.push_back(bufferInfo);
return true;
}
-bool LoadBufferView( const TreeNode& buffer, std::vector<BufferViewInfo>& bufferViewArray )
+bool LoadBufferView(const TreeNode& buffer, std::vector<BufferViewInfo>& bufferViewArray)
{
BufferViewInfo bufferViewInfo;
- const TreeNode* bufferNode = buffer.GetChild( "buffer" );
- if( bufferNode )
+ const TreeNode* bufferNode = buffer.GetChild("buffer");
+ if(bufferNode)
{
- ReadInt( bufferNode, bufferViewInfo.buffer );
- if( bufferViewInfo.buffer < 0 )
+ ReadInt(bufferNode, bufferViewInfo.buffer);
+ if(bufferViewInfo.buffer < 0)
{
return false;
}
}
- const TreeNode* byteOffsetNode = buffer.GetChild( "byteOffset" );
- if( byteOffsetNode )
+ const TreeNode* byteOffsetNode = buffer.GetChild("byteOffset");
+ if(byteOffsetNode)
{
- ReadInt( byteOffsetNode, bufferViewInfo.byteOffset );
+ ReadInt(byteOffsetNode, bufferViewInfo.byteOffset);
}
- const TreeNode* byteLengthNode = buffer.GetChild( "byteLength" );
- if( byteLengthNode )
+ const TreeNode* byteLengthNode = buffer.GetChild("byteLength");
+ if(byteLengthNode)
{
- ReadInt( byteLengthNode, bufferViewInfo.byteLength );
- if( bufferViewInfo.byteLength < 0 )
+ ReadInt(byteLengthNode, bufferViewInfo.byteLength);
+ if(bufferViewInfo.byteLength < 0)
{
return false;
}
}
- const TreeNode* byteStrideNode = buffer.GetChild( "byteStride" );
- if( byteStrideNode )
+ const TreeNode* byteStrideNode = buffer.GetChild("byteStride");
+ if(byteStrideNode)
{
- ReadInt( byteStrideNode, bufferViewInfo.byteStride );
+ ReadInt(byteStrideNode, bufferViewInfo.byteStride);
}
- const TreeNode* targetNode = buffer.GetChild( "target" );
- if( targetNode )
+ const TreeNode* targetNode = buffer.GetChild("target");
+ if(targetNode)
{
- ReadInt( targetNode, bufferViewInfo.target );
+ ReadInt(targetNode, bufferViewInfo.target);
}
- const TreeNode* nameNode = buffer.GetChild( "name" );
- if( nameNode )
+ const TreeNode* nameNode = buffer.GetChild("name");
+ if(nameNode)
{
- ReadString( nameNode, bufferViewInfo.name );
+ ReadString(nameNode, bufferViewInfo.name);
}
- bufferViewArray.push_back( bufferViewInfo );
+ bufferViewArray.push_back(bufferViewInfo);
return true;
}
-bool LoadAccessor( const TreeNode& buffer, std::vector<AccessorInfo>& accessorArray )
+bool LoadAccessor(const TreeNode& buffer, std::vector<AccessorInfo>& accessorArray)
{
AccessorInfo accessorInfo;
- const TreeNode* bufferViewNode = buffer.GetChild( "bufferView" );
- if( bufferViewNode )
+ const TreeNode* bufferViewNode = buffer.GetChild("bufferView");
+ if(bufferViewNode)
{
- ReadInt( bufferViewNode, accessorInfo.bufferView );
+ ReadInt(bufferViewNode, accessorInfo.bufferView);
}
- const TreeNode* byteOffsetNode = buffer.GetChild( "byteOffset" );
- if( byteOffsetNode )
+ const TreeNode* byteOffsetNode = buffer.GetChild("byteOffset");
+ if(byteOffsetNode)
{
- ReadInt( byteOffsetNode, accessorInfo.byteOffset );
+ ReadInt(byteOffsetNode, accessorInfo.byteOffset);
}
- const TreeNode* componentTypeNode = buffer.GetChild( "componentType" );
- if( componentTypeNode )
+ const TreeNode* componentTypeNode = buffer.GetChild("componentType");
+ if(componentTypeNode)
{
- ReadInt( componentTypeNode, accessorInfo.componentType );
- if( accessorInfo.componentType < 0 )
+ ReadInt(componentTypeNode, accessorInfo.componentType);
+ if(accessorInfo.componentType < 0)
{
return false;
}
}
- const TreeNode* normalizedNode = buffer.GetChild( "normalized" );
- if( normalizedNode )
+ const TreeNode* normalizedNode = buffer.GetChild("normalized");
+ if(normalizedNode)
{
- ReadBool( normalizedNode, accessorInfo.normalized );
+ ReadBool(normalizedNode, accessorInfo.normalized);
}
- const TreeNode* countNode = buffer.GetChild( "count" );
- if( countNode )
+ const TreeNode* countNode = buffer.GetChild("count");
+ if(countNode)
{
- ReadInt( countNode, accessorInfo.count );
- if( accessorInfo.count < 0 )
+ ReadInt(countNode, accessorInfo.count);
+ if(accessorInfo.count < 0)
{
return false;
}
}
- const TreeNode* typeNode = buffer.GetChild( "type" );
- if( typeNode )
+ const TreeNode* typeNode = buffer.GetChild("type");
+ if(typeNode)
{
- ReadString( typeNode, accessorInfo.type );
- if( accessorInfo.type == "" )
+ ReadString(typeNode, accessorInfo.type);
+ if(accessorInfo.type == "")
{
return false;
}
}
- const TreeNode* maxNode = buffer.GetChild( "max" );
- if( maxNode )
+ const TreeNode* maxNode = buffer.GetChild("max");
+ if(maxNode)
{
- ReadInt( maxNode, accessorInfo.max );
+ ReadInt(maxNode, accessorInfo.max);
}
- const TreeNode* minNode = buffer.GetChild( "min" );
- if( minNode )
+ const TreeNode* minNode = buffer.GetChild("min");
+ if(minNode)
{
- ReadInt( minNode, accessorInfo.min );
+ ReadInt(minNode, accessorInfo.min);
}
- const TreeNode* nameNode = buffer.GetChild( "name" );
- if( nameNode )
+ const TreeNode* nameNode = buffer.GetChild("name");
+ if(nameNode)
{
- ReadString( nameNode, accessorInfo.name );
+ ReadString(nameNode, accessorInfo.name);
}
- accessorArray.push_back( accessorInfo );
+ accessorArray.push_back(accessorInfo);
return true;
}
-bool LoadBinaryData( const TreeNode& root, std::vector<BufferInfo>& bufferArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<AccessorInfo>& accessorArray )
+bool LoadBinaryData(const TreeNode& root, std::vector<BufferInfo>& bufferArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<AccessorInfo>& accessorArray)
{
- const TreeNode* buffersNode = root.GetChild( "buffers" );
- if( !buffersNode )
+ const TreeNode* buffersNode = root.GetChild("buffers");
+ if(!buffersNode)
{
return false;
}
- for( auto bufferIter = buffersNode->CBegin(), end = buffersNode->CEnd(); bufferIter != end; ++bufferIter )
+ for(auto bufferIter = buffersNode->CBegin(), end = buffersNode->CEnd(); bufferIter != end; ++bufferIter)
{
- LoadBuffer( ( *bufferIter ).second, bufferArray );
+ LoadBuffer((*bufferIter).second, bufferArray);
}
- const TreeNode* bufferViewsNode = root.GetChild( "bufferViews" );
- if( !bufferViewsNode )
+ const TreeNode* bufferViewsNode = root.GetChild("bufferViews");
+ if(!bufferViewsNode)
{
return false;
}
- for( auto bufferViewIter = bufferViewsNode->CBegin(), end = bufferViewsNode->CEnd(); bufferViewIter != end; ++bufferViewIter )
+ for(auto bufferViewIter = bufferViewsNode->CBegin(), end = bufferViewsNode->CEnd(); bufferViewIter != end; ++bufferViewIter)
{
- LoadBufferView( ( *bufferViewIter ).second, bufferViewArray );
+ LoadBufferView((*bufferViewIter).second, bufferViewArray);
}
- const TreeNode* accessorsNode = root.GetChild( "accessors" );
- if( !accessorsNode )
+ const TreeNode* accessorsNode = root.GetChild("accessors");
+ if(!accessorsNode)
{
return false;
}
- for( auto accesorIter = accessorsNode->CBegin(), end = accessorsNode->CEnd(); accesorIter != end; ++accesorIter )
+ for(auto accesorIter = accessorsNode->CBegin(), end = accessorsNode->CEnd(); accesorIter != end; ++accesorIter)
{
- LoadAccessor( ( *accesorIter ).second, accessorArray );
+ LoadAccessor((*accesorIter).second, accessorArray);
}
return true;
}
-FilterMode::Type GetFilterMode( uint32_t mode )
+FilterMode::Type GetFilterMode(uint32_t mode)
{
FilterMode::Type retValue = FilterMode::DEFAULT;
/**
* 9986 : NEAREST_MIPMAP_LINEAR
* 9987 : LINEAR_MIPMAP_LINEAR
*/
- switch( mode )
+ switch(mode)
{
case 9728:
{
return retValue;
}
-WrapMode::Type GetWrapMode( uint32_t mode )
+WrapMode::Type GetWrapMode(uint32_t mode)
{
WrapMode::Type retValue = WrapMode::REPEAT;
/**
* 33648 : MIRRORED_REPEAT
* 10497 : REPEAT
*/
- switch( mode )
+ switch(mode)
{
case 33071:
{
return retValue;
}
-Texture LoadTexture( const char* imageUrl, bool generateMipmaps )
+Texture LoadTexture(const char* imageUrl, bool generateMipmaps)
{
- Texture texture;
- Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl );
- if( pixelBuffer )
+ Texture texture;
+ Devel::PixelBuffer pixelBuffer = LoadImageFromFile(imageUrl);
+ if(pixelBuffer)
{
- texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
- PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
- texture.Upload( pixelData );
+ texture = Texture::New(TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
+ PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
+ texture.Upload(pixelData);
- if( generateMipmaps )
+ if(generateMipmaps)
{
texture.GenerateMipmaps();
}
return texture;
}
-Sampler LoadSampler( const TreeNode& samplerNode )
+Sampler LoadSampler(const TreeNode& samplerNode)
{
Sampler sampler = Sampler::New();
- FilterMode::Type minFilter = FilterMode::DEFAULT;
- FilterMode::Type magFilter = FilterMode::DEFAULT;
- const TreeNode* magFilterNode = samplerNode.GetChild( "magFilter" );
- if( magFilterNode )
+ FilterMode::Type minFilter = FilterMode::DEFAULT;
+ FilterMode::Type magFilter = FilterMode::DEFAULT;
+ const TreeNode* magFilterNode = samplerNode.GetChild("magFilter");
+ if(magFilterNode)
{
int32_t magFilter_integer = 0;
- ReadInt( magFilterNode, magFilter_integer );
- magFilter = GetFilterMode( magFilter_integer );
+ ReadInt(magFilterNode, magFilter_integer);
+ magFilter = GetFilterMode(magFilter_integer);
}
- const TreeNode* minFilterNode = samplerNode.GetChild( "minFilter" );
- if( minFilterNode )
+ const TreeNode* minFilterNode = samplerNode.GetChild("minFilter");
+ if(minFilterNode)
{
int32_t minFilter_integer = 0;
- ReadInt( minFilterNode, minFilter_integer );
- minFilter = GetFilterMode( minFilter_integer );
+ ReadInt(minFilterNode, minFilter_integer);
+ minFilter = GetFilterMode(minFilter_integer);
}
- WrapMode::Type wrapR = WrapMode::REPEAT;
- WrapMode::Type wrapS = WrapMode::REPEAT;
- WrapMode::Type wrapT = WrapMode::REPEAT;
- const TreeNode* wrapNode = samplerNode.GetChild( "wrapS" );
- if( wrapNode )
+ WrapMode::Type wrapR = WrapMode::REPEAT;
+ WrapMode::Type wrapS = WrapMode::REPEAT;
+ WrapMode::Type wrapT = WrapMode::REPEAT;
+ const TreeNode* wrapNode = samplerNode.GetChild("wrapS");
+ if(wrapNode)
{
- wrapS = GetWrapMode( wrapNode->GetInteger() );
+ wrapS = GetWrapMode(wrapNode->GetInteger());
}
- wrapNode = samplerNode.GetChild( "wrapT" );
- if( wrapNode )
+ wrapNode = samplerNode.GetChild("wrapT");
+ if(wrapNode)
{
- wrapT = GetWrapMode( wrapNode->GetInteger() );
+ wrapT = GetWrapMode(wrapNode->GetInteger());
}
- sampler.SetFilterMode( minFilter, magFilter );
- sampler.SetWrapMode( wrapR, wrapS, wrapT );
+ sampler.SetFilterMode(minFilter, magFilter);
+ sampler.SetWrapMode(wrapR, wrapS, wrapT);
return sampler;
}
-bool LoadTextureArray( const TreeNode& root, std::string path, std::vector<Texture>& sourceArray, std::vector<Sampler>& samplerArray, std::vector<TextureInfo>& textureArray )
+bool LoadTextureArray(const TreeNode& root, std::string path, std::vector<Texture>& sourceArray, std::vector<Sampler>& samplerArray, std::vector<TextureInfo>& textureArray)
{
- const TreeNode* imagesNode = root.GetChild( "images" );
- if( imagesNode )
+ const TreeNode* imagesNode = root.GetChild("images");
+ if(imagesNode)
{
- for( auto imageIter = imagesNode->CBegin(), end = imagesNode->CEnd(); imageIter != end; ++imageIter )
+ for(auto imageIter = imagesNode->CBegin(), end = imagesNode->CEnd(); imageIter != end; ++imageIter)
{
- std::string imageUrl;
- const TreeNode* uriNode = ( &( ( *imageIter ).second ) )->GetChild( "uri" );
- if( uriNode )
+ std::string imageUrl;
+ const TreeNode* uriNode = (&((*imageIter).second))->GetChild("uri");
+ if(uriNode)
{
std::string uri;
- ReadString( uriNode, uri );
+ ReadString(uriNode, uri);
imageUrl = path + uri;
}
- sourceArray.push_back( LoadTexture( imageUrl.c_str(), true ) );
+ sourceArray.push_back(LoadTexture(imageUrl.c_str(), true));
}
}
- const TreeNode* samplersNode = root.GetChild( "samplers" );
- if( samplersNode )
+ const TreeNode* samplersNode = root.GetChild("samplers");
+ if(samplersNode)
{
- for( auto samplerIter = samplersNode->CBegin(), end = samplersNode->CEnd(); samplerIter != end; ++samplerIter )
+ for(auto samplerIter = samplersNode->CBegin(), end = samplersNode->CEnd(); samplerIter != end; ++samplerIter)
{
- samplerArray.push_back( LoadSampler( ( ( *samplerIter ).second ) ) );
+ samplerArray.push_back(LoadSampler(((*samplerIter).second)));
}
}
- const TreeNode* texturesNode = root.GetChild( "textures" );
- if( texturesNode )
+ const TreeNode* texturesNode = root.GetChild("textures");
+ if(texturesNode)
{
- for( auto textureIter = texturesNode->CBegin(), end = texturesNode->CEnd(); textureIter != end; ++textureIter )
+ for(auto textureIter = texturesNode->CBegin(), end = texturesNode->CEnd(); textureIter != end; ++textureIter)
{
- const TreeNode* TextureNode = &( ( *textureIter ).second );
+ const TreeNode* TextureNode = &((*textureIter).second);
- TextureInfo texture;
- const TreeNode* sourceNode = TextureNode->GetChild( "source" );
- if( sourceNode )
+ TextureInfo texture;
+ const TreeNode* sourceNode = TextureNode->GetChild("source");
+ if(sourceNode)
{
- ReadInt( sourceNode, texture.sourceIdx );
+ ReadInt(sourceNode, texture.sourceIdx);
}
- const TreeNode* samplerNode = TextureNode->GetChild( "sampler" );
- if( samplerNode )
+ const TreeNode* samplerNode = TextureNode->GetChild("sampler");
+ if(samplerNode)
{
- ReadInt( samplerNode, texture.samplerIdx );
+ ReadInt(samplerNode, texture.samplerIdx);
}
- textureArray.push_back( texture );
+ textureArray.push_back(texture);
}
}
return true;
}
-bool LoadPbrMetallicRoughness( const TreeNode& material, MaterialInfo& materialInfo )
+bool LoadPbrMetallicRoughness(const TreeNode& material, MaterialInfo& materialInfo)
{
- float floatVec[4];
- const TreeNode* pbrMetallicRoughnessNode = material.GetChild( "pbrMetallicRoughness" );
- if( !pbrMetallicRoughnessNode )
+ float floatVec[4];
+ const TreeNode* pbrMetallicRoughnessNode = material.GetChild("pbrMetallicRoughness");
+ if(!pbrMetallicRoughnessNode)
{
return true;
}
const TreeNode* tempNode;
- tempNode = pbrMetallicRoughnessNode->GetChild( "metallicFactor" );
- if( tempNode )
+ tempNode = pbrMetallicRoughnessNode->GetChild("metallicFactor");
+ if(tempNode)
{
- ReadFloat( tempNode, materialInfo.metallicFactor );
+ ReadFloat(tempNode, materialInfo.metallicFactor);
}
- tempNode = pbrMetallicRoughnessNode->GetChild( "roughnessFactor" );
- if( tempNode )
+ tempNode = pbrMetallicRoughnessNode->GetChild("roughnessFactor");
+ if(tempNode)
{
- ReadFloat( tempNode, materialInfo.roughnessFactor );
+ ReadFloat(tempNode, materialInfo.roughnessFactor);
}
- tempNode = pbrMetallicRoughnessNode->GetChild( "baseColorFactor" );
- if( tempNode && ReadVector( tempNode, floatVec, 4 ) )
+ tempNode = pbrMetallicRoughnessNode->GetChild("baseColorFactor");
+ if(tempNode && ReadVector(tempNode, floatVec, 4))
{
- materialInfo.baseColorFactor = Vector4( floatVec[0], floatVec[1], floatVec[2], floatVec[3] );
+ materialInfo.baseColorFactor = Vector4(floatVec[0], floatVec[1], floatVec[2], floatVec[3]);
}
- const TreeNode* baseColorTextureNode = pbrMetallicRoughnessNode->GetChild( "baseColorTexture" );
- if( baseColorTextureNode )
+ const TreeNode* baseColorTextureNode = pbrMetallicRoughnessNode->GetChild("baseColorTexture");
+ if(baseColorTextureNode)
{
- tempNode = baseColorTextureNode->GetChild( "index" );
- if( tempNode )
+ tempNode = baseColorTextureNode->GetChild("index");
+ if(tempNode)
{
materialInfo.baseColorTexture.index = tempNode->GetInteger();
}
- tempNode = baseColorTextureNode->GetChild( "texCoord" );
- if( tempNode )
+ tempNode = baseColorTextureNode->GetChild("texCoord");
+ if(tempNode)
{
materialInfo.baseColorTexture.texCoord = tempNode->GetInteger();
}
}
- const TreeNode* metallicRoughnessTextureNode = pbrMetallicRoughnessNode->GetChild( "metallicRoughnessTexture" );
- if( metallicRoughnessTextureNode )
+ const TreeNode* metallicRoughnessTextureNode = pbrMetallicRoughnessNode->GetChild("metallicRoughnessTexture");
+ if(metallicRoughnessTextureNode)
{
- tempNode = metallicRoughnessTextureNode->GetChild( "index" );
- if( tempNode )
+ tempNode = metallicRoughnessTextureNode->GetChild("index");
+ if(tempNode)
{
materialInfo.metallicRoughnessTexture.index = tempNode->GetInteger();
}
- tempNode = metallicRoughnessTextureNode->GetChild( "texCoord" );
- if( tempNode )
+ tempNode = metallicRoughnessTextureNode->GetChild("texCoord");
+ if(tempNode)
{
materialInfo.metallicRoughnessTexture.texCoord = tempNode->GetInteger();
}
return true;
}
-bool LoadMaterialSetArray( const TreeNode& root, std::vector<MaterialInfo>& materialArray )
+bool LoadMaterialSetArray(const TreeNode& root, std::vector<MaterialInfo>& materialArray)
{
- const TreeNode* materialsNode = root.GetChild( "materials" );
- if( !materialsNode )
+ const TreeNode* materialsNode = root.GetChild("materials");
+ if(!materialsNode)
{
return false;
}
- for( auto materialIter = materialsNode->CBegin(), end = materialsNode->CEnd(); materialIter != end; ++materialIter )
+ for(auto materialIter = materialsNode->CBegin(), end = materialsNode->CEnd(); materialIter != end; ++materialIter)
{
MaterialInfo materialInfo;
- LoadPbrMetallicRoughness( ( ( *materialIter ).second ), materialInfo );
+ LoadPbrMetallicRoughness(((*materialIter).second), materialInfo);
- const TreeNode* materialNode = &( ( *materialIter ).second );
- const TreeNode* tempNode = materialNode->GetChild( "name" );
- if( tempNode )
+ const TreeNode* materialNode = &((*materialIter).second);
+ const TreeNode* tempNode = materialNode->GetChild("name");
+ if(tempNode)
{
- ReadString( tempNode, materialInfo.name );
+ ReadString(tempNode, materialInfo.name);
}
materialInfo.alphaMode = "OPAQUE";
- tempNode = materialNode->GetChild( "alphaMode" );
- if( tempNode )
+ tempNode = materialNode->GetChild("alphaMode");
+ if(tempNode)
{
- ReadString( tempNode, materialInfo.alphaMode );
+ ReadString(tempNode, materialInfo.alphaMode);
}
materialInfo.alphaCutoff = 1.0;
- tempNode = materialNode->GetChild( "alphaCutoff" );
- if( tempNode )
+ tempNode = materialNode->GetChild("alphaCutoff");
+ if(tempNode)
{
- ReadFloat( tempNode, materialInfo.alphaCutoff );
+ ReadFloat(tempNode, materialInfo.alphaCutoff);
}
materialInfo.doubleSided = false;
- tempNode = materialNode->GetChild( "doubleSided" );
- if( tempNode )
+ tempNode = materialNode->GetChild("doubleSided");
+ if(tempNode)
{
- ReadBool( tempNode, materialInfo.doubleSided );
+ ReadBool(tempNode, materialInfo.doubleSided);
}
float floatVec[3];
- tempNode = materialNode->GetChild( "emissiveFactor" );
- if( tempNode && ReadVector( tempNode, floatVec, 3 ) )
+ tempNode = materialNode->GetChild("emissiveFactor");
+ if(tempNode && ReadVector(tempNode, floatVec, 3))
{
- materialInfo.emissiveFactor = Vector3( floatVec[0], floatVec[1], floatVec[2] );
+ materialInfo.emissiveFactor = Vector3(floatVec[0], floatVec[1], floatVec[2]);
}
- const TreeNode* texture = materialNode->GetChild( "normalTexture" );
- if( texture )
+ const TreeNode* texture = materialNode->GetChild("normalTexture");
+ if(texture)
{
- tempNode = texture->GetChild( "index" );
- if( tempNode )
+ tempNode = texture->GetChild("index");
+ if(tempNode)
{
materialInfo.normalTexture.index = tempNode->GetInteger();
}
- tempNode = texture->GetChild( "texCoord" );
- if( tempNode )
+ tempNode = texture->GetChild("texCoord");
+ if(tempNode)
{
materialInfo.normalTexture.texCoord = tempNode->GetInteger();
}
materialInfo.normalTexture.value = 1.0;
- tempNode = texture->GetChild( "scale" );
- if( tempNode )
+ tempNode = texture->GetChild("scale");
+ if(tempNode)
{
- ReadFloat( tempNode, materialInfo.normalTexture.value );
+ ReadFloat(tempNode, materialInfo.normalTexture.value);
}
}
- texture = materialNode->GetChild( "occlusionTexture" );
- if( texture )
+ texture = materialNode->GetChild("occlusionTexture");
+ if(texture)
{
- tempNode = texture->GetChild( "index" );
- if( tempNode )
+ tempNode = texture->GetChild("index");
+ if(tempNode)
{
materialInfo.occlusionTexture.index = tempNode->GetInteger();
}
- tempNode = texture->GetChild( "texCoord" );
- if( tempNode )
+ tempNode = texture->GetChild("texCoord");
+ if(tempNode)
{
materialInfo.occlusionTexture.texCoord = tempNode->GetInteger();
}
-
- tempNode = texture->GetChild( "strength" );
- if( tempNode )
+ tempNode = texture->GetChild("strength");
+ if(tempNode)
{
- ReadFloat( tempNode, materialInfo.occlusionTexture.value );
+ ReadFloat(tempNode, materialInfo.occlusionTexture.value);
}
}
- texture = materialNode->GetChild( "emissiveTexture" );
- if( texture )
+ texture = materialNode->GetChild("emissiveTexture");
+ if(texture)
{
- tempNode = texture->GetChild( "index" );
- if( tempNode )
+ tempNode = texture->GetChild("index");
+ if(tempNode)
{
materialInfo.emissiveTexture.index = tempNode->GetInteger();
}
- tempNode = texture->GetChild( "texCoord" );
- if( tempNode )
+ tempNode = texture->GetChild("texCoord");
+ if(tempNode)
{
materialInfo.emissiveTexture.texCoord = tempNode->GetInteger();
}
}
- materialArray.push_back( materialInfo );
+ materialArray.push_back(materialInfo);
}
return true;
}
-bool LoadAttribute( const TreeNode* primitive, MeshInfo& meshInfo )
+bool LoadAttribute(const TreeNode* primitive, MeshInfo& meshInfo)
{
- const TreeNode* attrbuteNode = primitive->GetChild( "attributes" );
- if( !attrbuteNode )
+ const TreeNode* attrbuteNode = primitive->GetChild("attributes");
+ if(!attrbuteNode)
{
return false;
}
const TreeNode* tempNode;
- tempNode = attrbuteNode->GetChild( "POSITION" );
- if( tempNode )
+ tempNode = attrbuteNode->GetChild("POSITION");
+ if(tempNode)
{
meshInfo.attribute.POSITION = tempNode->GetInteger();
}
- tempNode = attrbuteNode->GetChild( "NORMAL" );
- if( tempNode )
+ tempNode = attrbuteNode->GetChild("NORMAL");
+ if(tempNode)
{
meshInfo.attribute.NORMAL = tempNode->GetInteger();
}
- tempNode = attrbuteNode->GetChild( "TANGENT" );
- if( tempNode )
+ tempNode = attrbuteNode->GetChild("TANGENT");
+ if(tempNode)
{
meshInfo.attribute.TANGENT = tempNode->GetInteger();
}
uint32_t index = 0;
meshInfo.attribute.TEXCOORD.clear();
- tempNode = attrbuteNode->GetChild( "TEXCOORD_" + std::to_string( index ) );
- while( tempNode )
+ tempNode = attrbuteNode->GetChild("TEXCOORD_" + std::to_string(index));
+ while(tempNode)
{
uint32_t value = tempNode->GetInteger();
- meshInfo.attribute.TEXCOORD.push_back( value );
- tempNode = attrbuteNode->GetChild( "TEXCOORD_" + std::to_string( ++index ) );
+ meshInfo.attribute.TEXCOORD.push_back(value);
+ tempNode = attrbuteNode->GetChild("TEXCOORD_" + std::to_string(++index));
}
index = 0;
meshInfo.attribute.COLOR.clear();
- tempNode = attrbuteNode->GetChild( "COLOR_" + std::to_string( index ) );
- while( tempNode )
+ tempNode = attrbuteNode->GetChild("COLOR_" + std::to_string(index));
+ while(tempNode)
{
uint32_t value = tempNode->GetInteger();
- meshInfo.attribute.COLOR.push_back( value );
- tempNode = attrbuteNode->GetChild( "COLOR" + std::to_string( ++index ) );
+ meshInfo.attribute.COLOR.push_back(value);
+ tempNode = attrbuteNode->GetChild("COLOR" + std::to_string(++index));
}
return true;
}
-bool LoadPrimitive( const TreeNode& mesh, MeshInfo& meshInfo )
+bool LoadPrimitive(const TreeNode& mesh, MeshInfo& meshInfo)
{
- const TreeNode* primitivesNode = mesh.GetChild( "primitives" );
- if( !primitivesNode )
+ const TreeNode* primitivesNode = mesh.GetChild("primitives");
+ if(!primitivesNode)
{
return false;
}
- for( auto primitiveIter = primitivesNode->CBegin(), end = primitivesNode->CEnd(); primitiveIter != end; ++primitiveIter )
+ for(auto primitiveIter = primitivesNode->CBegin(), end = primitivesNode->CEnd(); primitiveIter != end; ++primitiveIter)
{
- const TreeNode* primitiveNode = ( &( *primitiveIter ).second );
+ const TreeNode* primitiveNode = (&(*primitiveIter).second);
const TreeNode* tempNode;
- tempNode = primitiveNode->GetChild( "indices" );
- if( tempNode )
+ tempNode = primitiveNode->GetChild("indices");
+ if(tempNode)
{
meshInfo.indicesIdx = tempNode->GetInteger();
}
- tempNode = primitiveNode->GetChild( "material" );
- if( tempNode )
+ tempNode = primitiveNode->GetChild("material");
+ if(tempNode)
{
meshInfo.materialsIdx = tempNode->GetInteger();
}
- tempNode = primitiveNode->GetChild( "mode" );
- if( tempNode )
+ tempNode = primitiveNode->GetChild("mode");
+ if(tempNode)
{
meshInfo.mode = tempNode->GetInteger();
}
- LoadAttribute( primitiveNode, meshInfo );
+ LoadAttribute(primitiveNode, meshInfo);
}
return true;
}
-bool SetGeometry( MeshInfo& meshInfo, std::string path, std::vector<BufferInfo>& bufferArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<AccessorInfo>& accessorArray )
+bool SetGeometry(MeshInfo& meshInfo, std::string path, std::vector<BufferInfo>& bufferArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<AccessorInfo>& accessorArray)
{
int32_t indicesIdx = meshInfo.indicesIdx;
- if( meshInfo.mode != 0 )
+ if(meshInfo.mode != 0)
{
- meshInfo.geometry.SetType( ( Dali::Geometry::Type )meshInfo.mode );
+ meshInfo.geometry.SetType((Dali::Geometry::Type)meshInfo.mode);
}
- if( indicesIdx >= 0 )
+ if(indicesIdx >= 0)
{
- SetIndexBuffersData( meshInfo, path, accessorArray, bufferViewArray, bufferArray, indicesIdx );
+ SetIndexBuffersData(meshInfo, path, accessorArray, bufferViewArray, bufferArray, indicesIdx);
}
- SetVertexBufferData( meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.POSITION, "aPosition", Property::VECTOR3 );
- SetAttributeBufferData<Vector3>( meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.NORMAL, "aNormal", Property::VECTOR3 );
- SetAttributeBufferData<Vector4>( meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.TANGENT, "aTangent", Property::VECTOR4 );
+ SetVertexBufferData(meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.POSITION, "aPosition", Property::VECTOR3);
+ SetAttributeBufferData<Vector3>(meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.NORMAL, "aNormal", Property::VECTOR3);
+ SetAttributeBufferData<Vector4>(meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.TANGENT, "aTangent", Property::VECTOR4);
- for( uint32_t i = 0; i < meshInfo.attribute.TEXCOORD.size(); ++i )
+ for(uint32_t i = 0; i < meshInfo.attribute.TEXCOORD.size(); ++i)
{
- int32_t accessorIdx = meshInfo.attribute.TEXCOORD[i];
+ int32_t accessorIdx = meshInfo.attribute.TEXCOORD[i];
std::ostringstream texCoordString;
texCoordString << "aTexCoord" << i;
- SetAttributeBufferData<Vector2>( meshInfo, path, accessorArray, bufferViewArray, bufferArray, accessorIdx, texCoordString.str(), Property::VECTOR2 );
+ SetAttributeBufferData<Vector2>(meshInfo, path, accessorArray, bufferViewArray, bufferArray, accessorIdx, texCoordString.str(), Property::VECTOR2);
}
- for( auto&& accessorIdx : meshInfo.attribute.COLOR )
+ for(auto&& accessorIdx : meshInfo.attribute.COLOR)
{
- if( accessorIdx < 0 )
+ if(accessorIdx < 0)
{
break;
}
- if( accessorArray[accessorIdx].type == "VEC3" )
+ if(accessorArray[accessorIdx].type == "VEC3")
{
Dali::Vector<Vector3> inputBufferData;
- LoadDataFromAccessor( accessorIdx, inputBufferData, path, accessorArray, bufferViewArray, bufferArray );
+ LoadDataFromAccessor(accessorIdx, inputBufferData, path, accessorArray, bufferViewArray, bufferArray);
Dali::Vector<Vector4> bufferData;
- bufferData.Resize( inputBufferData.Size() );
- for( uint32_t i = 0; i<inputBufferData.Size(); ++i )
+ bufferData.Resize(inputBufferData.Size());
+ for(uint32_t i = 0; i < inputBufferData.Size(); ++i)
{
bufferData[i].x = inputBufferData[i].x;
bufferData[i].y = inputBufferData[i].y;
bufferData[i].z = inputBufferData[i].z;
bufferData[i].w = 1.0;
}
- VertexBuffer vertexBuffer = CreateVertexBuffer<Vector4>( bufferData, "aVertexColor", Property::VECTOR4 );
- meshInfo.geometry.AddVertexBuffer( vertexBuffer );
+ VertexBuffer vertexBuffer = CreateVertexBuffer<Vector4>(bufferData, "aVertexColor", Property::VECTOR4);
+ meshInfo.geometry.AddVertexBuffer(vertexBuffer);
}
- else if( accessorArray[accessorIdx].type == "VEC4" )
+ else if(accessorArray[accessorIdx].type == "VEC4")
{
- SetAttributeBufferData<Vector4>( meshInfo, path, accessorArray, bufferViewArray, bufferArray, accessorIdx, "aVertexColor", Property::VECTOR4 );
+ SetAttributeBufferData<Vector4>(meshInfo, path, accessorArray, bufferViewArray, bufferArray, accessorIdx, "aVertexColor", Property::VECTOR4);
}
}
return true;
}
-bool LoadMeshArray( const TreeNode& root, std::string path, std::vector<MeshInfo>& meshArray, std::vector<BufferInfo>& bufferArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<AccessorInfo>& accessorArray )
+bool LoadMeshArray(const TreeNode& root, std::string path, std::vector<MeshInfo>& meshArray, std::vector<BufferInfo>& bufferArray, std::vector<BufferViewInfo>& bufferViewArray, std::vector<AccessorInfo>& accessorArray)
{
- const TreeNode* meshesNode = root.GetChild( "meshes" );
- if( !meshesNode )
+ const TreeNode* meshesNode = root.GetChild("meshes");
+ if(!meshesNode)
{
return false;
}
- for( auto meshIter = meshesNode->CBegin(), end = meshesNode->CEnd(); meshIter != end; ++meshIter )
+ for(auto meshIter = meshesNode->CBegin(), end = meshesNode->CEnd(); meshIter != end; ++meshIter)
{
- MeshInfo meshInfo;
- const TreeNode* nameNode = ( &( *meshIter ).second )->GetChild( "name" );
- if( nameNode )
+ MeshInfo meshInfo;
+ const TreeNode* nameNode = (&(*meshIter).second)->GetChild("name");
+ if(nameNode)
{
- ReadString( nameNode, meshInfo.name );
+ ReadString(nameNode, meshInfo.name);
}
meshInfo.geometry = Geometry::New();
//Need to add weights for Morph targets.
- LoadPrimitive( ( *meshIter ).second, meshInfo );
- SetGeometry( meshInfo, path, bufferArray, bufferViewArray, accessorArray );
- meshArray.push_back( meshInfo );
+ LoadPrimitive((*meshIter).second, meshInfo);
+ SetGeometry(meshInfo, path, bufferArray, bufferViewArray, accessorArray);
+ meshArray.push_back(meshInfo);
}
return true;
} // namespace
Loader::Loader()
- : mNodes( NULL ),
- mRoot( NULL )
+: mNodes(NULL),
+ mRoot(NULL)
{
}
{
}
-bool Loader::LoadScene( const std::string& filePath, Internal::Scene3dView& scene3dView )
+bool Loader::LoadScene(const std::string& filePath, Internal::Scene3dView& scene3dView)
{
// Extracting directory path from full path to load resources.
- if( std::string::npos != filePath.rfind('/') )
+ if(std::string::npos != filePath.rfind('/'))
{
- mPath = filePath.substr( 0, filePath.rfind('/') ) + "/";
+ mPath = filePath.substr(0, filePath.rfind('/')) + "/";
}
- if( !ParseGltf( filePath ) )
+ if(!ParseGltf(filePath))
{
- DALI_LOG_ERROR( "Fail to parse json file\n" );
+ DALI_LOG_ERROR("Fail to parse json file\n");
return false;
}
mRoot = mParser.GetRoot();
- if( mRoot &&
- LoadAssets() &&
- CreateScene( scene3dView ) )
+ if(mRoot &&
+ LoadAssets() &&
+ CreateScene(scene3dView))
{
return true;
}
return false;
}
-bool Loader::ParseGltf( const std::string& filePath )
+bool Loader::ParseGltf(const std::string& filePath)
{
- std::streampos bufferSize = 0;
+ std::streampos bufferSize = 0;
Dali::Vector<char> buffer;
- std::string fileBuffer;
- if( !Dali::FileLoader::ReadFile( filePath, bufferSize, buffer, FileLoader::FileType::BINARY ) )
+ std::string fileBuffer;
+ if(!Dali::FileLoader::ReadFile(filePath, bufferSize, buffer, FileLoader::FileType::BINARY))
{
return false;
}
- fileBuffer.assign( &buffer[0], bufferSize );
+ fileBuffer.assign(&buffer[0], bufferSize);
mParser = Dali::Toolkit::JsonParser::New();
- return mParser.Parse( fileBuffer );
+ return mParser.Parse(fileBuffer);
}
bool Loader::LoadAssets()
{
- if( LoadBinaryData( *mRoot, mBufferArray, mBufferViewArray, mAccessorArray ) &&
- LoadTextureArray( *mRoot, mPath, mSourceArray, mSamplerArray, mTextureArray ) &&
- LoadMaterialSetArray( *mRoot, mMaterialArray ) &&
- LoadMeshArray( *mRoot, mPath, mMeshArray, mBufferArray, mBufferViewArray, mAccessorArray )
- )
+ if(LoadBinaryData(*mRoot, mBufferArray, mBufferViewArray, mAccessorArray) &&
+ LoadTextureArray(*mRoot, mPath, mSourceArray, mSamplerArray, mTextureArray) &&
+ LoadMaterialSetArray(*mRoot, mMaterialArray) &&
+ LoadMeshArray(*mRoot, mPath, mMeshArray, mBufferArray, mBufferViewArray, mAccessorArray))
{
return true;
}
return false;
}
-bool Loader::CreateScene( Internal::Scene3dView& scene3dView )
+bool Loader::CreateScene(Internal::Scene3dView& scene3dView)
{
- scene3dView.SetDefaultCamera( Dali::Camera::LOOK_AT_TARGET, 0.01, Vector3::ZERO );
- LoadCamera( scene3dView );
+ scene3dView.SetDefaultCamera(Dali::Camera::LOOK_AT_TARGET, 0.01, Vector3::ZERO);
+ LoadCamera(scene3dView);
- if( LoadSceneNodes( scene3dView ) &&
- LoadAnimation( scene3dView ) )
+ if(LoadSceneNodes(scene3dView) &&
+ LoadAnimation(scene3dView))
{
return true;
}
return false;
}
-void Loader::LoadCamera( Scene3dView& scene3dView )
+void Loader::LoadCamera(Scene3dView& scene3dView)
{
- const TreeNode* camerasNode = mRoot->GetChild( "cameras" );
- if( !camerasNode )
+ const TreeNode* camerasNode = mRoot->GetChild("cameras");
+ if(!camerasNode)
{
return;
}
- for( auto cameraIter = camerasNode->CBegin(), end = camerasNode->CEnd(); cameraIter != end; ++cameraIter )
+ for(auto cameraIter = camerasNode->CBegin(), end = camerasNode->CEnd(); cameraIter != end; ++cameraIter)
{
- const TreeNode* tempNode = ( &( *cameraIter ).second )->GetChild( "name" );
- CameraInfo cameraInfo;
- if( tempNode )
+ const TreeNode* tempNode = (&(*cameraIter).second)->GetChild("name");
+ CameraInfo cameraInfo;
+ if(tempNode)
{
- ReadString( tempNode, cameraInfo.name );
+ ReadString(tempNode, cameraInfo.name);
}
- tempNode = ( &( *cameraIter ).second )->GetChild( "type" );
- if( tempNode )
+ tempNode = (&(*cameraIter).second)->GetChild("type");
+ if(tempNode)
{
- ReadString( tempNode, cameraInfo.type );
+ ReadString(tempNode, cameraInfo.type);
}
CameraActor cameraActor = CameraActor::New();
- cameraActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- cameraActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ cameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ cameraActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
- if( cameraInfo.type == "orthographic" )
+ if(cameraInfo.type == "orthographic")
{
- LoadOrthoGraphic( ( *cameraIter ).second, cameraInfo );
+ LoadOrthoGraphic((*cameraIter).second, cameraInfo);
float xMag_2 = cameraInfo.orthographic.xmag / 2.0;
float yMag_2 = cameraInfo.orthographic.ymag / 2.0;
- cameraActor.SetOrthographicProjection( -xMag_2, xMag_2, yMag_2, -yMag_2,
- cameraInfo.orthographic.znear, cameraInfo.orthographic.zfar );
+ cameraActor.SetOrthographicProjection(-xMag_2, xMag_2, yMag_2, -yMag_2, cameraInfo.orthographic.znear, cameraInfo.orthographic.zfar);
}
- else if( cameraInfo.type == "perspective" )
+ else if(cameraInfo.type == "perspective")
{
- if( !LoadPerspective( ( *cameraIter ).second, cameraInfo ) )
+ if(!LoadPerspective((*cameraIter).second, cameraInfo))
{
return;
}
- cameraActor.SetProjectionMode( Dali::Camera::PERSPECTIVE_PROJECTION );
- cameraActor.SetFieldOfView( cameraInfo.perspective.yfov );
- cameraActor.SetNearClippingPlane( cameraInfo.perspective.znear );
+ cameraActor.SetProjectionMode(Dali::Camera::PERSPECTIVE_PROJECTION);
+ cameraActor.SetFieldOfView(cameraInfo.perspective.yfov);
+ cameraActor.SetNearClippingPlane(cameraInfo.perspective.znear);
- if( cameraInfo.perspective.zfar > 0.0 )
+ if(cameraInfo.perspective.zfar > 0.0)
{
- cameraActor.SetFarClippingPlane( cameraInfo.perspective.zfar );
+ cameraActor.SetFarClippingPlane(cameraInfo.perspective.zfar);
}
- if( cameraInfo.perspective.aspectRatio > 0.0 )
+ if(cameraInfo.perspective.aspectRatio > 0.0)
{
- cameraActor.SetAspectRatio( cameraInfo.perspective.aspectRatio );
+ cameraActor.SetAspectRatio(cameraInfo.perspective.aspectRatio);
}
}
- scene3dView.AddCamera( cameraActor );
+ scene3dView.AddCamera(cameraActor);
}
}
-bool Loader::LoadOrthoGraphic( const TreeNode& camera, CameraInfo& cameraInfo )
+bool Loader::LoadOrthoGraphic(const TreeNode& camera, CameraInfo& cameraInfo)
{
- const TreeNode* orthographicNode = camera.GetChild( "orthographic" );
- if( !orthographicNode )
+ const TreeNode* orthographicNode = camera.GetChild("orthographic");
+ if(!orthographicNode)
{
return false;
}
const TreeNode* tempNode;
- tempNode = orthographicNode->GetChild( "xmag" );
- if( tempNode )
+ tempNode = orthographicNode->GetChild("xmag");
+ if(tempNode)
{
- ReadFloat( tempNode, cameraInfo.orthographic.xmag );
+ ReadFloat(tempNode, cameraInfo.orthographic.xmag);
}
- tempNode = orthographicNode->GetChild( "ymag" );
- if( tempNode )
+ tempNode = orthographicNode->GetChild("ymag");
+ if(tempNode)
{
- ReadFloat( tempNode, cameraInfo.orthographic.ymag );
+ ReadFloat(tempNode, cameraInfo.orthographic.ymag);
}
- tempNode = orthographicNode->GetChild( "zfar" );
- if( tempNode )
+ tempNode = orthographicNode->GetChild("zfar");
+ if(tempNode)
{
- ReadFloat( tempNode, cameraInfo.orthographic.zfar );
+ ReadFloat(tempNode, cameraInfo.orthographic.zfar);
}
- tempNode = orthographicNode->GetChild( "znear" );
- if( tempNode )
+ tempNode = orthographicNode->GetChild("znear");
+ if(tempNode)
{
- ReadFloat( tempNode, cameraInfo.orthographic.znear );
+ ReadFloat(tempNode, cameraInfo.orthographic.znear);
}
return true;
}
-bool Loader::LoadPerspective( const TreeNode& camera, CameraInfo& cameraInfo )
+bool Loader::LoadPerspective(const TreeNode& camera, CameraInfo& cameraInfo)
{
- const TreeNode* perspectiveNode = camera.GetChild( "perspective" );
- if( !perspectiveNode )
+ const TreeNode* perspectiveNode = camera.GetChild("perspective");
+ if(!perspectiveNode)
{
return false;
}
const TreeNode* tempNode;
- tempNode = perspectiveNode->GetChild( "aspectRatio" );
- if( tempNode )
+ tempNode = perspectiveNode->GetChild("aspectRatio");
+ if(tempNode)
{
- ReadFloat( tempNode, cameraInfo.perspective.aspectRatio );
+ ReadFloat(tempNode, cameraInfo.perspective.aspectRatio);
}
- tempNode = perspectiveNode->GetChild( "yfov" );
- if( tempNode )
+ tempNode = perspectiveNode->GetChild("yfov");
+ if(tempNode)
{
- ReadFloat( tempNode, cameraInfo.perspective.yfov );
+ ReadFloat(tempNode, cameraInfo.perspective.yfov);
}
- tempNode = perspectiveNode->GetChild( "zfar" );
- if( tempNode )
+ tempNode = perspectiveNode->GetChild("zfar");
+ if(tempNode)
{
- ReadFloat( tempNode, cameraInfo.perspective.zfar );
+ ReadFloat(tempNode, cameraInfo.perspective.zfar);
}
- tempNode = perspectiveNode->GetChild( "znear" );
- if( tempNode )
+ tempNode = perspectiveNode->GetChild("znear");
+ if(tempNode)
{
- ReadFloat( tempNode, cameraInfo.perspective.znear );
+ ReadFloat(tempNode, cameraInfo.perspective.znear);
}
return true;
}
-bool Loader::LoadSceneNodes( Scene3dView& scene3dView )
+bool Loader::LoadSceneNodes(Scene3dView& scene3dView)
{
- const TreeNode* sceneNode = mRoot->GetChild( "scene" );
- uint32_t sceneNum = 0;
- if( sceneNode )
+ const TreeNode* sceneNode = mRoot->GetChild("scene");
+ uint32_t sceneNum = 0;
+ if(sceneNode)
{
sceneNum = sceneNode->GetInteger();
}
- const TreeNode* scenesNode = mRoot->GetChild( "scenes" );
- if( !( scenesNode && ( mNodes = mRoot->GetChild( "nodes" ) ) ) )
+ const TreeNode* scenesNode = mRoot->GetChild("scenes");
+ if(!(scenesNode && (mNodes = mRoot->GetChild("nodes"))))
{
return false;
}
- const TreeNode* tempNode = Tidx( scenesNode, sceneNum );
- if( !tempNode )
+ const TreeNode* tempNode = Tidx(scenesNode, sceneNum);
+ if(!tempNode)
{
return false;
}
- tempNode = tempNode->GetChild( "nodes" );
- if( !tempNode )
+ tempNode = tempNode->GetChild("nodes");
+ if(!tempNode)
{
return false;
}
- for( auto nodeIter = tempNode->CBegin(), end = tempNode->CEnd(); nodeIter != end; ++nodeIter )
+ for(auto nodeIter = tempNode->CBegin(), end = tempNode->CEnd(); nodeIter != end; ++nodeIter)
{
- Actor actor = AddNode( scene3dView, ( ( *nodeIter ).second ).GetInteger() );
- actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- scene3dView.GetRoot().Add( actor );
+ Actor actor = AddNode(scene3dView, ((*nodeIter).second).GetInteger());
+ actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ scene3dView.GetRoot().Add(actor);
}
return true;
}
-Actor Loader::AddNode( Scene3dView& scene3dView, uint32_t index )
+Actor Loader::AddNode(Scene3dView& scene3dView, uint32_t index)
{
- const TreeNode* node = Tidx( mNodes, index );
- Actor actor = Actor::New();
- Vector3 actorSize( Vector3::ONE );
+ const TreeNode* node = Tidx(mNodes, index);
+ Actor actor = Actor::New();
+ Vector3 actorSize(Vector3::ONE);
- Vector3 translation = Vector3( 0.0, 0.0, 0.0 );
- Vector3 scale = Vector3( 1.0, 1.0, 1.0 );
- Quaternion orientation( Vector4( 0.0, 0.0, 0.0, 1.0 ) );
+ Vector3 translation = Vector3(0.0, 0.0, 0.0);
+ Vector3 scale = Vector3(1.0, 1.0, 1.0);
+ Quaternion orientation(Vector4(0.0, 0.0, 0.0, 1.0));
Vector3 anchorPoint = AnchorPoint::CENTER;
const TreeNode* tempNode = NULL;
- if( ( tempNode = node->GetChild( "translation" ) ) )
+ if((tempNode = node->GetChild("translation")))
{
- float floatVec[3] = { 0.0, 0.0, 0.0 };
- if( tempNode && ReadVector( tempNode, floatVec, 3 ) )
+ float floatVec[3] = {0.0, 0.0, 0.0};
+ if(tempNode && ReadVector(tempNode, floatVec, 3))
{
- translation = Vector3( floatVec[0], floatVec[1], floatVec[2] );
+ translation = Vector3(floatVec[0], floatVec[1], floatVec[2]);
}
}
- if( ( tempNode = node->GetChild( "scale" ) ) )
+ if((tempNode = node->GetChild("scale")))
{
- float floatVec[3] = { 1.0, 1.0, 1.0 };
- if( tempNode && ReadVector( tempNode, floatVec, 3 ) )
+ float floatVec[3] = {1.0, 1.0, 1.0};
+ if(tempNode && ReadVector(tempNode, floatVec, 3))
{
- scale = Vector3( floatVec[0], floatVec[1], floatVec[2] );
+ scale = Vector3(floatVec[0], floatVec[1], floatVec[2]);
}
}
- if( ( tempNode = node->GetChild( "rotation" ) ) )
+ if((tempNode = node->GetChild("rotation")))
{
- float floatVec[4] = { 0.0, 0.0, 0.0, 1.0 };
- if( tempNode && ReadVector( tempNode, floatVec, 4 ) )
+ float floatVec[4] = {0.0, 0.0, 0.0, 1.0};
+ if(tempNode && ReadVector(tempNode, floatVec, 4))
{
- orientation = Quaternion( Vector4( floatVec[0], floatVec[1], floatVec[2], floatVec[3] ) );
+ orientation = Quaternion(Vector4(floatVec[0], floatVec[1], floatVec[2], floatVec[3]));
}
}
- if( ( tempNode = node->GetChild( "matrix" ) ) )
+ if((tempNode = node->GetChild("matrix")))
{
- float floatVec[16] = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 };
- if( tempNode && ReadVector( tempNode, floatVec, 16 ) )
+ float floatVec[16] = {1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0};
+ if(tempNode && ReadVector(tempNode, floatVec, 16))
{
- Matrix nodeMatrix = Matrix( floatVec );
- nodeMatrix.GetTransformComponents( translation, orientation, scale );
+ Matrix nodeMatrix = Matrix(floatVec);
+ nodeMatrix.GetTransformComponents(translation, orientation, scale);
}
}
- if( ( tempNode = node->GetChild( "mesh" ) ) )
+ if((tempNode = node->GetChild("mesh")))
{
- MeshInfo meshInfo = mMeshArray[tempNode->GetInteger()];
- bool isMaterial = ( meshInfo.materialsIdx >= 0 );
+ MeshInfo meshInfo = mMeshArray[tempNode->GetInteger()];
+ bool isMaterial = (meshInfo.materialsIdx >= 0);
TextureSet textureSet;
textureSet = TextureSet::New();
- int32_t addIdx = 0;
- int32_t shaderTypeIndex = 0;
- int32_t maxMipmapLevel = 0;
- bool isBaseColorTexture = false;
- bool isMetallicRoughnessTexture = false;
- bool isNormalTexture = false;
- bool isOcclusionTexture = false;
- bool isEmissiveTexture = false;
+ int32_t addIdx = 0;
+ int32_t shaderTypeIndex = 0;
+ int32_t maxMipmapLevel = 0;
+ bool isBaseColorTexture = false;
+ bool isMetallicRoughnessTexture = false;
+ bool isNormalTexture = false;
+ bool isOcclusionTexture = false;
+ bool isEmissiveTexture = false;
std::string VERTEX_SHADER, FRAGMENT_SHADER;
VERTEX_SHADER = SHADER_GLTF_GLES_VERSION_300_DEF.data();
VERTEX_SHADER += SHADER_GLTF_PHYSICALLY_BASED_SHADER_VERT.data();
FRAGMENT_SHADER = SHADER_GLTF_GLES_VERSION_300_DEF.data();
- bool useIBL = ( scene3dView.GetLightType() >= Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT );
- if( isMaterial )
+ bool useIBL = (scene3dView.GetLightType() >= Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT);
+ if(isMaterial)
{
MaterialInfo materialInfo = mMaterialArray[meshInfo.materialsIdx];
- if( SetTextureAndSampler( textureSet, materialInfo.baseColorTexture.index, FRAGMENT_SHADER, SHADER_GLTF_BASECOLOR_TEXTURE_DEF.data(), addIdx ) )
+ if(SetTextureAndSampler(textureSet, materialInfo.baseColorTexture.index, FRAGMENT_SHADER, SHADER_GLTF_BASECOLOR_TEXTURE_DEF.data(), addIdx))
{
- shaderTypeIndex += static_cast<int32_t>( ShaderType::BASECOLOR_SHADER );
+ shaderTypeIndex += static_cast<int32_t>(ShaderType::BASECOLOR_SHADER);
isBaseColorTexture = true;
}
- if( SetTextureAndSampler( textureSet, materialInfo.metallicRoughnessTexture.index, FRAGMENT_SHADER, SHADER_GLTF_METALLICROUGHNESS_TEXTURE_DEF.data(), addIdx ) )
+ if(SetTextureAndSampler(textureSet, materialInfo.metallicRoughnessTexture.index, FRAGMENT_SHADER, SHADER_GLTF_METALLICROUGHNESS_TEXTURE_DEF.data(), addIdx))
{
- shaderTypeIndex += static_cast<int32_t>( ShaderType::METALLICROUGHNESS_SHADER );
+ shaderTypeIndex += static_cast<int32_t>(ShaderType::METALLICROUGHNESS_SHADER);
isMetallicRoughnessTexture = true;
}
- if( SetTextureAndSampler( textureSet, materialInfo.normalTexture.index, FRAGMENT_SHADER, SHADER_GLTF_NORMAL_TEXTURE_DEF.data(), addIdx ) )
+ if(SetTextureAndSampler(textureSet, materialInfo.normalTexture.index, FRAGMENT_SHADER, SHADER_GLTF_NORMAL_TEXTURE_DEF.data(), addIdx))
{
- shaderTypeIndex += static_cast<int32_t>( ShaderType::NORMAL_SHADER );
+ shaderTypeIndex += static_cast<int32_t>(ShaderType::NORMAL_SHADER);
isNormalTexture = true;
}
- if( SetTextureAndSampler( textureSet, materialInfo.occlusionTexture.index, FRAGMENT_SHADER, SHADER_GLTF_OCCULUSION_TEXTURE_DEF.data(), addIdx ) )
+ if(SetTextureAndSampler(textureSet, materialInfo.occlusionTexture.index, FRAGMENT_SHADER, SHADER_GLTF_OCCULUSION_TEXTURE_DEF.data(), addIdx))
{
- shaderTypeIndex += static_cast<int32_t>( ShaderType::OCCLUSION_SHADER );
+ shaderTypeIndex += static_cast<int32_t>(ShaderType::OCCLUSION_SHADER);
isOcclusionTexture = true;
}
- if( SetTextureAndSampler( textureSet, materialInfo.emissiveTexture.index, FRAGMENT_SHADER, SHADER_GLTF_EMIT_TEXTURE_DEF.data(), addIdx ) )
+ if(SetTextureAndSampler(textureSet, materialInfo.emissiveTexture.index, FRAGMENT_SHADER, SHADER_GLTF_EMIT_TEXTURE_DEF.data(), addIdx))
{
- shaderTypeIndex += static_cast<int32_t>( ShaderType::EMIT_SHADER );
+ shaderTypeIndex += static_cast<int32_t>(ShaderType::EMIT_SHADER);
isEmissiveTexture = true;
}
- if( useIBL )
+ if(useIBL)
{
- shaderTypeIndex += static_cast<int32_t>( ShaderType::IBL_SHADER );
+ shaderTypeIndex += static_cast<int32_t>(ShaderType::IBL_SHADER);
FRAGMENT_SHADER += SHADER_GLTF_IBL_TEXTURE_DEF.data();
Sampler sampler = Sampler::New();
- sampler.SetFilterMode( FilterMode::DEFAULT, FilterMode::DEFAULT );
- sampler.SetWrapMode( WrapMode::REPEAT, WrapMode::REPEAT, WrapMode::REPEAT );
+ sampler.SetFilterMode(FilterMode::DEFAULT, FilterMode::DEFAULT);
+ sampler.SetWrapMode(WrapMode::REPEAT, WrapMode::REPEAT, WrapMode::REPEAT);
- textureSet.SetTexture( addIdx, scene3dView.GetBRDFTexture() );
- textureSet.SetSampler( addIdx++, sampler );
+ textureSet.SetTexture(addIdx, scene3dView.GetBRDFTexture());
+ textureSet.SetSampler(addIdx++, sampler);
Sampler samplerIBL = Sampler::New();
- samplerIBL.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR );
- samplerIBL.SetWrapMode( WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE );
- textureSet.SetTexture( addIdx, scene3dView.GetDiffuseTexture() );
- textureSet.SetSampler( addIdx++, samplerIBL );
+ samplerIBL.SetFilterMode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR);
+ samplerIBL.SetWrapMode(WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE);
+ textureSet.SetTexture(addIdx, scene3dView.GetDiffuseTexture());
+ textureSet.SetSampler(addIdx++, samplerIBL);
Texture specularTexture = scene3dView.GetSpecularTexture();
- textureSet.SetTexture( addIdx, specularTexture );
- textureSet.SetSampler( addIdx++, samplerIBL );
+ textureSet.SetTexture(addIdx, specularTexture);
+ textureSet.SetSampler(addIdx++, samplerIBL);
- int32_t textureSize = std::min( specularTexture.GetWidth(), specularTexture.GetHeight() );
- maxMipmapLevel = 0;
- while( textureSize >= 1 )
+ int32_t textureSize = std::min(specularTexture.GetWidth(), specularTexture.GetHeight());
+ maxMipmapLevel = 0;
+ while(textureSize >= 1)
{
maxMipmapLevel++;
textureSize /= 2;
}
FRAGMENT_SHADER += SHADER_GLTF_PHYSICALLY_BASED_SHADER_FRAG.data();
- if( !mShaderCache[shaderTypeIndex] )
+ if(!mShaderCache[shaderTypeIndex])
{
- mShaderCache[shaderTypeIndex] = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
- scene3dView.AddShader( mShaderCache[shaderTypeIndex] );
+ mShaderCache[shaderTypeIndex] = Shader::New(VERTEX_SHADER, FRAGMENT_SHADER);
+ scene3dView.AddShader(mShaderCache[shaderTypeIndex]);
}
Shader shader = mShaderCache[shaderTypeIndex];
- Renderer renderer = Renderer::New( meshInfo.geometry, shader );
- renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
- renderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON );
- renderer.SetTextures( textureSet );
+ Renderer renderer = Renderer::New(meshInfo.geometry, shader);
+ renderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON);
+ renderer.SetProperty(Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON);
+ renderer.SetTextures(textureSet);
anchorPoint = meshInfo.pivot;
- actor.SetProperty( Actor::Property::ANCHOR_POINT, anchorPoint );
+ actor.SetProperty(Actor::Property::ANCHOR_POINT, anchorPoint);
- actor.SetProperty( Actor::Property::SIZE, Vector3( meshInfo.size.x, meshInfo.size.y, meshInfo.size.z ) );
- actor.AddRenderer( renderer );
+ actor.SetProperty(Actor::Property::SIZE, Vector3(meshInfo.size.x, meshInfo.size.y, meshInfo.size.z));
+ actor.AddRenderer(renderer);
- actor.SetProperty( Actor::Property::SCALE, scale );
- actor.RotateBy( orientation );
- actor.SetProperty( Actor::Property::POSITION, translation );
+ actor.SetProperty(Actor::Property::SCALE, scale);
+ actor.RotateBy(orientation);
+ actor.SetProperty(Actor::Property::POSITION, translation);
- shader.RegisterProperty( "uLightType", ( scene3dView.GetLightType() & ~Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT ) );
- shader.RegisterProperty( "uLightVector", scene3dView.GetLightVector() );
- shader.RegisterProperty( "uLightColor", scene3dView.GetLightColor() );
+ shader.RegisterProperty("uLightType", (scene3dView.GetLightType() & ~Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT));
+ shader.RegisterProperty("uLightVector", scene3dView.GetLightVector());
+ shader.RegisterProperty("uLightColor", scene3dView.GetLightColor());
- actor.RegisterProperty( "uIsColor", meshInfo.attribute.COLOR.size() > 0 );
- if( isMaterial )
+ actor.RegisterProperty("uIsColor", meshInfo.attribute.COLOR.size() > 0);
+ if(isMaterial)
{
MaterialInfo materialInfo = mMaterialArray[meshInfo.materialsIdx];
- actor.RegisterProperty( "uBaseColorFactor", materialInfo.baseColorFactor );
- actor.RegisterProperty( "uMetallicRoughnessFactors", Vector2( materialInfo.metallicFactor, materialInfo.roughnessFactor ) );
+ actor.RegisterProperty("uBaseColorFactor", materialInfo.baseColorFactor);
+ actor.RegisterProperty("uMetallicRoughnessFactors", Vector2(materialInfo.metallicFactor, materialInfo.roughnessFactor));
- if( materialInfo.alphaMode == "OPAQUE" )
+ if(materialInfo.alphaMode == "OPAQUE")
{
- actor.RegisterProperty( "alphaMode", 0 );
+ actor.RegisterProperty("alphaMode", 0);
}
- else if( materialInfo.alphaMode == "MASK" )
+ else if(materialInfo.alphaMode == "MASK")
{
- actor.RegisterProperty( "alphaMode", 1 );
+ actor.RegisterProperty("alphaMode", 1);
}
else
{
- actor.RegisterProperty( "alphaMode", 2 );
+ actor.RegisterProperty("alphaMode", 2);
}
- actor.RegisterProperty( "alphaCutoff", materialInfo.alphaCutoff );
+ actor.RegisterProperty("alphaCutoff", materialInfo.alphaCutoff);
- if( isBaseColorTexture )
+ if(isBaseColorTexture)
{
- actor.RegisterProperty( "uBaseColorTexCoordIndex", materialInfo.baseColorTexture.texCoord );
+ actor.RegisterProperty("uBaseColorTexCoordIndex", materialInfo.baseColorTexture.texCoord);
}
- if( isMetallicRoughnessTexture )
+ if(isMetallicRoughnessTexture)
{
- actor.RegisterProperty( "uMetallicRoughnessTexCoordIndex", materialInfo.metallicRoughnessTexture.texCoord );
+ actor.RegisterProperty("uMetallicRoughnessTexCoordIndex", materialInfo.metallicRoughnessTexture.texCoord);
}
- if( isNormalTexture )
+ if(isNormalTexture)
{
- actor.RegisterProperty( "uNormalScale", materialInfo.normalTexture.value );
- actor.RegisterProperty( "uNormalTexCoordIndex", materialInfo.normalTexture.texCoord );
+ actor.RegisterProperty("uNormalScale", materialInfo.normalTexture.value);
+ actor.RegisterProperty("uNormalTexCoordIndex", materialInfo.normalTexture.texCoord);
}
- if( isOcclusionTexture )
+ if(isOcclusionTexture)
{
- actor.RegisterProperty( "uOcclusionTexCoordIndex", materialInfo.occlusionTexture.texCoord );
- actor.RegisterProperty( "uOcclusionStrength", materialInfo.occlusionTexture.value );
+ actor.RegisterProperty("uOcclusionTexCoordIndex", materialInfo.occlusionTexture.texCoord);
+ actor.RegisterProperty("uOcclusionStrength", materialInfo.occlusionTexture.value);
}
- if( isEmissiveTexture )
+ if(isEmissiveTexture)
{
- actor.RegisterProperty( "uEmissiveTexCoordIndex", materialInfo.emissiveTexture.texCoord );
- actor.RegisterProperty( "uEmissiveFactor", materialInfo.emissiveFactor );
+ actor.RegisterProperty("uEmissiveTexCoordIndex", materialInfo.emissiveTexture.texCoord);
+ actor.RegisterProperty("uEmissiveFactor", materialInfo.emissiveFactor);
}
}
- if( isMaterial && useIBL )
+ if(isMaterial && useIBL)
{
- actor.RegisterProperty( "uScaleIBLAmbient", scene3dView.GetIBLScaleFactor() );
- actor.RegisterProperty( "uMipmapLevel", static_cast<float>( maxMipmapLevel ) );
+ actor.RegisterProperty("uScaleIBLAmbient", scene3dView.GetIBLScaleFactor());
+ actor.RegisterProperty("uMipmapLevel", static_cast<float>(maxMipmapLevel));
}
}
else
{
- actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- actor.SetProperty( Actor::Property::POSITION, translation );
- actor.RotateBy( orientation );
- actor.SetProperty( Actor::Property::SIZE, actorSize );
+ actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ actor.SetProperty(Actor::Property::POSITION, translation);
+ actor.RotateBy(orientation);
+ actor.SetProperty(Actor::Property::SIZE, actorSize);
}
- tempNode = node->GetChild( "camera" );
- if( tempNode )
+ tempNode = node->GetChild("camera");
+ if(tempNode)
{
- int32_t cameraNum = tempNode->GetInteger();
- CameraActor cameraActor = scene3dView.GetCamera( cameraNum );
- if( cameraActor )
+ int32_t cameraNum = tempNode->GetInteger();
+ CameraActor cameraActor = scene3dView.GetCamera(cameraNum);
+ if(cameraActor)
{
- actor.Add( cameraActor );
+ actor.Add(cameraActor);
}
}
- tempNode = node->GetChild( "name" );
- if( tempNode )
+ tempNode = node->GetChild("name");
+ if(tempNode)
{
std::string nameString;
- ReadString( tempNode, nameString );
- actor.SetProperty( Dali::Actor::Property::NAME, nameString );
+ ReadString(tempNode, nameString);
+ actor.SetProperty(Dali::Actor::Property::NAME, nameString);
}
- SetActorCache( actor, index );
- if( ( tempNode = node->GetChild( "children" ) ) )
+ SetActorCache(actor, index);
+ if((tempNode = node->GetChild("children")))
{
- for( auto childIter = tempNode->CBegin(), end = tempNode->CEnd(); childIter != end; ++childIter )
+ for(auto childIter = tempNode->CBegin(), end = tempNode->CEnd(); childIter != end; ++childIter)
{
- Actor childActor = AddNode( scene3dView, ( ( *childIter ).second ).GetInteger() );
- childActor.SetProperty( Actor::Property::PARENT_ORIGIN, anchorPoint );
- actor.Add( childActor );
+ Actor childActor = AddNode(scene3dView, ((*childIter).second).GetInteger());
+ childActor.SetProperty(Actor::Property::PARENT_ORIGIN, anchorPoint);
+ actor.Add(childActor);
}
}
return actor;
}
-void Loader::SetActorCache( Actor& actor, uint32_t index )
+void Loader::SetActorCache(Actor& actor, uint32_t index)
{
- if( mActorCache.size() < index + 1 )
+ if(mActorCache.size() < index + 1)
{
- mActorCache.resize( index + 1 );
+ mActorCache.resize(index + 1);
}
mActorCache[index] = actor;
}
-bool Loader::SetTextureAndSampler( TextureSet& textureSet, int32_t textureIdx, std::string& toShader, std::string shader, int32_t& addIdx )
+bool Loader::SetTextureAndSampler(TextureSet& textureSet, int32_t textureIdx, std::string& toShader, std::string shader, int32_t& addIdx)
{
- if( textureIdx >= 0 )
+ if(textureIdx >= 0)
{
toShader += shader;
TextureInfo textureInfo = mTextureArray[textureIdx];
- if( textureInfo.sourceIdx >= 0 )
+ if(textureInfo.sourceIdx >= 0)
{
- textureSet.SetTexture( addIdx, mSourceArray[textureInfo.sourceIdx] );
+ textureSet.SetTexture(addIdx, mSourceArray[textureInfo.sourceIdx]);
}
- if( textureInfo.samplerIdx >= 0 )
+ if(textureInfo.samplerIdx >= 0)
{
- textureSet.SetSampler( addIdx, mSamplerArray[textureInfo.samplerIdx] );
+ textureSet.SetSampler(addIdx, mSamplerArray[textureInfo.samplerIdx]);
}
else
{
Sampler sampler = Sampler::New();
- sampler.SetFilterMode( FilterMode::DEFAULT, FilterMode::DEFAULT );
- sampler.SetWrapMode( WrapMode::REPEAT, WrapMode::REPEAT, WrapMode::REPEAT );
- textureSet.SetSampler( addIdx, sampler );
+ sampler.SetFilterMode(FilterMode::DEFAULT, FilterMode::DEFAULT);
+ sampler.SetWrapMode(WrapMode::REPEAT, WrapMode::REPEAT, WrapMode::REPEAT);
+ textureSet.SetSampler(addIdx, sampler);
}
addIdx++;
return true;
return false;
}
-bool Loader::LoadAnimation( Scene3dView& scene3dView )
+bool Loader::LoadAnimation(Scene3dView& scene3dView)
{
- const TreeNode* animationsNode = mRoot->GetChild( "animations" );
- if( !animationsNode )
+ const TreeNode* animationsNode = mRoot->GetChild("animations");
+ if(!animationsNode)
{
return true;
}
- for( auto animationIter = animationsNode->CBegin(), end = animationsNode->CEnd(); animationIter != end; ++animationIter )
+ for(auto animationIter = animationsNode->CBegin(), end = animationsNode->CEnd(); animationIter != end; ++animationIter)
{
- const TreeNode* nameNode = ( &( *animationIter ).second )->GetChild( "name" );
- AnimationInfo animationInfo;
- if( nameNode )
+ const TreeNode* nameNode = (&(*animationIter).second)->GetChild("name");
+ AnimationInfo animationInfo;
+ if(nameNode)
{
- ReadString( nameNode, animationInfo.name );
+ ReadString(nameNode, animationInfo.name);
}
Property::Index propIndex = Property::INVALID_INDEX;
- LoadAnimationChannels( ( *animationIter ).second, animationInfo );
- if( animationInfo.channelArray.size() == 0 )
+ LoadAnimationChannels((*animationIter).second, animationInfo);
+ if(animationInfo.channelArray.size() == 0)
{
continue;
}
- LoadAnimationSamplers( ( *animationIter ).second, animationInfo );
+ LoadAnimationSamplers((*animationIter).second, animationInfo);
- for( auto&& currentChannel : animationInfo.channelArray )
+ for(auto&& currentChannel : animationInfo.channelArray)
{
- if( currentChannel.path == "rotation" )
+ if(currentChannel.path == "rotation")
{
propIndex = Dali::Actor::Property::ORIENTATION;
}
- else if( currentChannel.path == "translation" )
+ else if(currentChannel.path == "translation")
{
propIndex = Dali::Actor::Property::POSITION;
}
- else if( currentChannel.path == "scale" )
+ else if(currentChannel.path == "scale")
{
propIndex = Dali::Actor::Property::SCALE;
}
- float duration = 0.0f;
+ float duration = 0.0f;
KeyFrames keyframes = KeyFrames::New();
- if( propIndex == Dali::Actor::Property::ORIENTATION )
+ if(propIndex == Dali::Actor::Property::ORIENTATION)
{
- duration = LoadKeyFrames<Vector4>( animationInfo.samplerArray[currentChannel.sampler], propIndex, keyframes, mPath, mAccessorArray, mBufferViewArray, mBufferArray );
+ duration = LoadKeyFrames<Vector4>(animationInfo.samplerArray[currentChannel.sampler], propIndex, keyframes, mPath, mAccessorArray, mBufferViewArray, mBufferArray);
}
else
{
- duration = LoadKeyFrames<Vector3>( animationInfo.samplerArray[currentChannel.sampler], propIndex, keyframes, mPath, mAccessorArray, mBufferViewArray, mBufferArray );
+ duration = LoadKeyFrames<Vector3>(animationInfo.samplerArray[currentChannel.sampler], propIndex, keyframes, mPath, mAccessorArray, mBufferViewArray, mBufferArray);
}
- Animation animation = Animation::New( duration );
+ Animation animation = Animation::New(duration);
Animation::Interpolation interpolation = Animation::Interpolation::LINEAR;
- if( animationInfo.samplerArray[currentChannel.sampler].interpolation == "CUBICSPLINE" )
+ if(animationInfo.samplerArray[currentChannel.sampler].interpolation == "CUBICSPLINE")
{
interpolation = Animation::Interpolation::CUBIC;
}
- if( animationInfo.samplerArray[currentChannel.sampler].interpolation == "STEP" )
+ if(animationInfo.samplerArray[currentChannel.sampler].interpolation == "STEP")
{
}
- animation.AnimateBetween( Property( mActorCache[currentChannel.targetNode], propIndex ), keyframes, interpolation );
+ animation.AnimateBetween(Property(mActorCache[currentChannel.targetNode], propIndex), keyframes, interpolation);
- animation.SetLooping( false );
- scene3dView.AddAnimation( animation );
+ animation.SetLooping(false);
+ scene3dView.AddAnimation(animation);
}
}
return true;
}
-bool Loader::LoadAnimationChannels( const TreeNode& animation, AnimationInfo& animationInfo )
+bool Loader::LoadAnimationChannels(const TreeNode& animation, AnimationInfo& animationInfo)
{
- const TreeNode* channelsNode = animation.GetChild( "channels" );
- if( !channelsNode )
+ const TreeNode* channelsNode = animation.GetChild("channels");
+ if(!channelsNode)
{
return false;
}
- for( auto channelIter = channelsNode->CBegin(), end = channelsNode->CEnd(); channelIter != end; ++channelIter )
+ for(auto channelIter = channelsNode->CBegin(), end = channelsNode->CEnd(); channelIter != end; ++channelIter)
{
AnimationChannelInfo animationChannelInfo;
- const TreeNode* channelNode = ( &( *channelIter ).second );
- const TreeNode* samplerNode = channelNode->GetChild( "sampler" );
- if( samplerNode )
+ const TreeNode* channelNode = (&(*channelIter).second);
+ const TreeNode* samplerNode = channelNode->GetChild("sampler");
+ if(samplerNode)
{
animationChannelInfo.sampler = samplerNode->GetInteger();
}
- const TreeNode* targetNode = channelNode->GetChild( "target" );
- if( targetNode )
+ const TreeNode* targetNode = channelNode->GetChild("target");
+ if(targetNode)
{
- const TreeNode* tempNode = targetNode->GetChild( "node" );
- if( tempNode )
+ const TreeNode* tempNode = targetNode->GetChild("node");
+ if(tempNode)
{
animationChannelInfo.targetNode = tempNode->GetInteger();
}
continue;
}
- tempNode = targetNode->GetChild( "path" );
- if( tempNode )
+ tempNode = targetNode->GetChild("path");
+ if(tempNode)
{
- ReadString( tempNode, animationChannelInfo.path );
+ ReadString(tempNode, animationChannelInfo.path);
}
}
- animationInfo.channelArray.push_back( animationChannelInfo );
+ animationInfo.channelArray.push_back(animationChannelInfo);
}
return true;
}
-bool Loader::LoadAnimationSamplers( const TreeNode& animation, AnimationInfo& animationInfo )
+bool Loader::LoadAnimationSamplers(const TreeNode& animation, AnimationInfo& animationInfo)
{
- const TreeNode* samplersNode = animation.GetChild( "samplers" );
- if( !samplersNode )
+ const TreeNode* samplersNode = animation.GetChild("samplers");
+ if(!samplersNode)
{
return false;
}
- for( auto sampler = samplersNode->CBegin(), end = samplersNode->CEnd(); sampler != end; ++sampler )
+ for(auto sampler = samplersNode->CBegin(), end = samplersNode->CEnd(); sampler != end; ++sampler)
{
AnimationSamplerInfo animationSamplerInfo;
- const TreeNode* samplerNode = ( &( *sampler ).second );
- const TreeNode* tempNode = samplerNode->GetChild( "input" );
- if( tempNode )
+ const TreeNode* samplerNode = (&(*sampler).second);
+ const TreeNode* tempNode = samplerNode->GetChild("input");
+ if(tempNode)
{
animationSamplerInfo.input = tempNode->GetInteger();
}
- tempNode = samplerNode->GetChild( "output" );
- if( tempNode )
+ tempNode = samplerNode->GetChild("output");
+ if(tempNode)
{
animationSamplerInfo.output = tempNode->GetInteger();
}
- tempNode = samplerNode->GetChild( "interpolation" );
- if( tempNode )
+ tempNode = samplerNode->GetChild("interpolation");
+ if(tempNode)
{
- ReadString( tempNode, animationSamplerInfo.interpolation );
+ ReadString(tempNode, animationSamplerInfo.interpolation);
}
- animationInfo.samplerArray.push_back( animationSamplerInfo );
+ animationInfo.samplerArray.push_back(animationSamplerInfo);
}
return true;
}
-}//namespace Gltf
+} //namespace Gltf
-}//namespace Internal
+} //namespace Internal
-}//namespace Toolkit
+} //namespace Toolkit
-}//namespace Dali
+} //namespace Dali
/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
const char* const IMAGE_BRDF_FILE_NAME = "brdfLUT.png";
// glTF file extension
-const std::string GLTF_EXT( ".gltf" );
+const std::string GLTF_EXT(".gltf");
/**
* cube map face index
*/
-const uint32_t CUBEMAP_INDEX_X[2][6] = { { 2, 0, 1, 1, 1, 3 }, { 0, 1, 2, 3, 4, 5 } };
-const uint32_t CUBEMAP_INDEX_Y[2][6] = { { 1, 1, 0, 2, 1, 1 }, { 0, 0, 0, 0, 0, 0 } };
+const uint32_t CUBEMAP_INDEX_X[2][6] = {{2, 0, 1, 1, 1, 3}, {0, 1, 2, 3, 4, 5}};
+const uint32_t CUBEMAP_INDEX_Y[2][6] = {{1, 1, 0, 2, 1, 1}, {0, 0, 0, 0, 0, 0}};
-}//namespace
+} //namespace
Scene3dView::Scene3dView()
- : Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mRoot( Actor::New() ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mRoot(Actor::New()),
mShaderArray(),
mCameraActorArray(),
- mDefaultCamera( CameraActor::New() ),
+ mDefaultCamera(CameraActor::New()),
mAnimationArray(),
- mLightType( Toolkit::Scene3dView::LightType::NONE ),
- mLightVector( Vector3::ONE ),
- mLightColor( Vector3::ONE )
+ mLightType(Toolkit::Scene3dView::LightType::NONE),
+ mLightVector(Vector3::ONE),
+ mLightColor(Vector3::ONE)
{
}
{
}
-Toolkit::Scene3dView Scene3dView::New( const std::string& filePath )
+Toolkit::Scene3dView Scene3dView::New(const std::string& filePath)
{
Scene3dView* impl = new Scene3dView();
- Dali::Toolkit::Scene3dView handle = Dali::Toolkit::Scene3dView( *impl );
+ Dali::Toolkit::Scene3dView handle = Dali::Toolkit::Scene3dView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-Toolkit::Scene3dView Scene3dView::New( const std::string& filePath, const std::string& diffuseTexturePath, const std::string& specularTexturePath, Vector4 scaleFactor )
+Toolkit::Scene3dView Scene3dView::New(const std::string& filePath, const std::string& diffuseTexturePath, const std::string& specularTexturePath, Vector4 scaleFactor)
{
Scene3dView* impl = new Scene3dView();
- Dali::Toolkit::Scene3dView handle = Dali::Toolkit::Scene3dView( *impl );
+ Dali::Toolkit::Scene3dView handle = Dali::Toolkit::Scene3dView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
impl->mFilePath = filePath;
- impl->SetCubeMap( diffuseTexturePath, specularTexturePath, scaleFactor );
+ impl->SetCubeMap(diffuseTexturePath, specularTexturePath, scaleFactor);
impl->Initialize();
return handle;
bool Scene3dView::CreateScene()
{
- if( std::string::npos != mFilePath.rfind( GLTF_EXT ) )
+ if(std::string::npos != mFilePath.rfind(GLTF_EXT))
{
Internal::Gltf::Loader gltfloader;
- return( gltfloader.LoadScene( mFilePath, *this ) );
+ return (gltfloader.LoadScene(mFilePath, *this));
}
return false;
return mAnimationArray.size();
}
-bool Scene3dView::PlayAnimation( uint32_t index )
+bool Scene3dView::PlayAnimation(uint32_t index)
{
- if( GetAnimationCount() <= index )
+ if(GetAnimationCount() <= index)
{
return false;
}
bool Scene3dView::PlayAnimations()
{
- for( auto&& animation : mAnimationArray )
+ for(auto&& animation : mAnimationArray)
{
animation.Play();
}
return true;
}
-bool Scene3dView::SetLight( Toolkit::Scene3dView::LightType type, Vector3 lightVector, Vector3 lightColor )
+bool Scene3dView::SetLight(Toolkit::Scene3dView::LightType type, Vector3 lightVector, Vector3 lightColor)
{
- if( type > Toolkit::Scene3dView::LightType::DIRECTIONAL_LIGHT )
+ if(type > Toolkit::Scene3dView::LightType::DIRECTIONAL_LIGHT)
{
return false;
}
mLightType = static_cast<Toolkit::Scene3dView::LightType>(
- ( mLightType >= Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT ) ?
- Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT + type :
- type );
+ (mLightType >= Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT) ? Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT + type : type);
mLightVector = lightVector;
- mLightColor = lightColor;
+ mLightColor = lightColor;
- for( auto&& shader : mShaderArray )
+ for(auto&& shader : mShaderArray)
{
- shader.RegisterProperty( "uLightType", ( GetLightType() & ~Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT ) );
- shader.RegisterProperty( "uLightVector", lightVector );
- shader.RegisterProperty( "uLightColor", lightColor );
+ shader.RegisterProperty("uLightType", (GetLightType() & ~Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT));
+ shader.RegisterProperty("uLightVector", lightVector);
+ shader.RegisterProperty("uLightColor", lightColor);
}
return true;
}
-uint8_t* Scene3dView::GetCroppedBuffer( uint8_t* sourceBuffer, uint32_t bytesPerPixel, uint32_t width, uint32_t height, uint32_t xOffset, uint32_t yOffset, uint32_t xFaceSize, uint32_t yFaceSize )
+uint8_t* Scene3dView::GetCroppedBuffer(uint8_t* sourceBuffer, uint32_t bytesPerPixel, uint32_t width, uint32_t height, uint32_t xOffset, uint32_t yOffset, uint32_t xFaceSize, uint32_t yFaceSize)
{
- uint32_t byteSize = bytesPerPixel * xFaceSize * yFaceSize;
- uint8_t* destBuffer = reinterpret_cast<uint8_t*>( malloc( byteSize + 4u ) );
+ uint32_t byteSize = bytesPerPixel * xFaceSize * yFaceSize;
+ uint8_t* destBuffer = reinterpret_cast<uint8_t*>(malloc(byteSize + 4u));
- int32_t srcStride = width * bytesPerPixel;
+ int32_t srcStride = width * bytesPerPixel;
int32_t destStride = xFaceSize * bytesPerPixel;
- int32_t srcOffset = xOffset * bytesPerPixel + yOffset * srcStride;
+ int32_t srcOffset = xOffset * bytesPerPixel + yOffset * srcStride;
int32_t destOffset = 0;
- for( uint16_t row = yOffset; row < yOffset + yFaceSize; ++row )
+ for(uint16_t row = yOffset; row < yOffset + yFaceSize; ++row)
{
- memcpy( destBuffer + destOffset, sourceBuffer + srcOffset, destStride );
+ memcpy(destBuffer + destOffset, sourceBuffer + srcOffset, destStride);
srcOffset += srcStride;
destOffset += destStride;
}
return destBuffer;
}
-void Scene3dView::UploadTextureFace( Texture& texture, Devel::PixelBuffer pixelBuffer, uint32_t faceIndex )
+void Scene3dView::UploadTextureFace(Texture& texture, Devel::PixelBuffer pixelBuffer, uint32_t faceIndex)
{
- uint8_t* imageBuffer = pixelBuffer.GetBuffer();
- uint32_t bytesPerPixel = Pixel::GetBytesPerPixel( pixelBuffer.GetPixelFormat() );
- uint32_t imageWidth = pixelBuffer.GetWidth();
- uint32_t imageHeight = pixelBuffer.GetHeight();
+ uint8_t* imageBuffer = pixelBuffer.GetBuffer();
+ uint32_t bytesPerPixel = Pixel::GetBytesPerPixel(pixelBuffer.GetPixelFormat());
+ uint32_t imageWidth = pixelBuffer.GetWidth();
+ uint32_t imageHeight = pixelBuffer.GetHeight();
- CubeType cubeType = ( imageWidth / 4 == imageHeight / 3 ) ? CROSS_HORIZONTAL :
- ( ( imageWidth / 6 == imageHeight ) ? ARRAY_HORIZONTAL : NONE );
+ CubeType cubeType = (imageWidth / 4 == imageHeight / 3) ? CROSS_HORIZONTAL : ((imageWidth / 6 == imageHeight) ? ARRAY_HORIZONTAL : NONE);
uint32_t faceSize = 0;
- if( cubeType == CROSS_HORIZONTAL )
+ if(cubeType == CROSS_HORIZONTAL)
{
faceSize = imageWidth / 4;
}
- else if( cubeType == ARRAY_HORIZONTAL )
+ else if(cubeType == ARRAY_HORIZONTAL)
{
faceSize = imageWidth / 6;
}
uint32_t xOffset = CUBEMAP_INDEX_X[cubeType][faceIndex] * faceSize;
uint32_t yOffset = CUBEMAP_INDEX_Y[cubeType][faceIndex] * faceSize;
- uint8_t* tempImageBuffer = GetCroppedBuffer( imageBuffer, bytesPerPixel, imageWidth, imageHeight, xOffset, yOffset, faceSize, faceSize );
- PixelData pixelData = PixelData::New( tempImageBuffer, faceSize * faceSize * bytesPerPixel, faceSize, faceSize, pixelBuffer.GetPixelFormat(), PixelData::FREE );
- texture.Upload( pixelData, CubeMapLayer::POSITIVE_X + faceIndex, 0, 0, 0, faceSize, faceSize );
+ uint8_t* tempImageBuffer = GetCroppedBuffer(imageBuffer, bytesPerPixel, imageWidth, imageHeight, xOffset, yOffset, faceSize, faceSize);
+ PixelData pixelData = PixelData::New(tempImageBuffer, faceSize * faceSize * bytesPerPixel, faceSize, faceSize, pixelBuffer.GetPixelFormat(), PixelData::FREE);
+ texture.Upload(pixelData, CubeMapLayer::POSITIVE_X + faceIndex, 0, 0, 0, faceSize, faceSize);
}
-void Scene3dView::SetCubeMap( const std::string& diffuseTexturePath, const std::string& specularTexturePath, Vector4 scaleFactor )
+void Scene3dView::SetCubeMap(const std::string& diffuseTexturePath, const std::string& specularTexturePath, Vector4 scaleFactor)
{
mLightType = Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT;
// BRDF texture
const std::string imageDirPath = AssetManager::GetDaliImagePath();
const std::string imageBrdfUrl = imageDirPath + IMAGE_BRDF_FILE_NAME;
- mBRDFTexture = LoadTexture( imageBrdfUrl.c_str(), true );
- if( !mBRDFTexture )
+ mBRDFTexture = LoadTexture(imageBrdfUrl.c_str(), true);
+ if(!mBRDFTexture)
{
return;
}
// Diffuse Cube Map
- Devel::PixelBuffer diffusePixelBuffer = LoadImageFromFile( diffuseTexturePath );
- uint32_t diffuseFaceSize = diffusePixelBuffer.GetWidth() / 4;
- mDiffuseTexture = Texture::New( TextureType::TEXTURE_CUBE, diffusePixelBuffer.GetPixelFormat(), diffuseFaceSize, diffuseFaceSize );
- for( uint32_t i = 0; i < 6; ++i )
+ Devel::PixelBuffer diffusePixelBuffer = LoadImageFromFile(diffuseTexturePath);
+ uint32_t diffuseFaceSize = diffusePixelBuffer.GetWidth() / 4;
+ mDiffuseTexture = Texture::New(TextureType::TEXTURE_CUBE, diffusePixelBuffer.GetPixelFormat(), diffuseFaceSize, diffuseFaceSize);
+ for(uint32_t i = 0; i < 6; ++i)
{
- UploadTextureFace( mDiffuseTexture, diffusePixelBuffer, i );
+ UploadTextureFace(mDiffuseTexture, diffusePixelBuffer, i);
}
mDiffuseTexture.GenerateMipmaps();
// Specular Cube Map
- Devel::PixelBuffer specularPixelBuffer = LoadImageFromFile( specularTexturePath );
- uint32_t specularFaceSize = specularPixelBuffer.GetWidth() / 4;
- mSpecularTexture = Texture::New( TextureType::TEXTURE_CUBE, specularPixelBuffer.GetPixelFormat(), specularFaceSize, specularFaceSize );
- for( uint32_t i = 0; i < 6; ++i )
+ Devel::PixelBuffer specularPixelBuffer = LoadImageFromFile(specularTexturePath);
+ uint32_t specularFaceSize = specularPixelBuffer.GetWidth() / 4;
+ mSpecularTexture = Texture::New(TextureType::TEXTURE_CUBE, specularPixelBuffer.GetPixelFormat(), specularFaceSize, specularFaceSize);
+ for(uint32_t i = 0; i < 6; ++i)
{
- UploadTextureFace( mSpecularTexture, specularPixelBuffer, i );
+ UploadTextureFace(mSpecularTexture, specularPixelBuffer, i);
}
mSpecularTexture.GenerateMipmaps();
mIBLScaleFactor = scaleFactor;
}
-bool Scene3dView::SetDefaultCamera( const Dali::Camera::Type type, const float nearPlane, const Vector3 cameraPosition )
+bool Scene3dView::SetDefaultCamera(const Dali::Camera::Type type, const float nearPlane, const Vector3 cameraPosition)
{
- mDefaultCamera.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mDefaultCamera.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- mDefaultCamera.SetType( type );
- mDefaultCamera.SetNearClippingPlane( nearPlane );
- mDefaultCamera.SetProperty( Actor::Property::POSITION, cameraPosition );
+ mDefaultCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mDefaultCamera.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mDefaultCamera.SetType(type);
+ mDefaultCamera.SetNearClippingPlane(nearPlane);
+ mDefaultCamera.SetProperty(Actor::Property::POSITION, cameraPosition);
return true;
}
-void Scene3dView::AddCamera( CameraActor cameraActor )
+void Scene3dView::AddCamera(CameraActor cameraActor)
{
- mCameraActorArray.push_back( cameraActor );
+ mCameraActorArray.push_back(cameraActor);
}
-void Scene3dView::AddAnimation( Animation animation )
+void Scene3dView::AddAnimation(Animation animation)
{
- mAnimationArray.push_back( animation );
+ mAnimationArray.push_back(animation);
}
-void Scene3dView::AddShader( Shader shader )
+void Scene3dView::AddShader(Shader shader)
{
- mShaderArray.push_back( shader );
+ mShaderArray.push_back(shader);
}
Actor Scene3dView::GetRoot()
return mCameraActorArray.size();
}
-CameraActor Scene3dView::GetCamera( uint32_t cameraIndex )
+CameraActor Scene3dView::GetCamera(uint32_t cameraIndex)
{
CameraActor cameraActor;
- if( cameraIndex >= mCameraActorArray.size() )
+ if(cameraIndex >= mCameraActorArray.size())
{
return cameraActor;
}
return mDiffuseTexture;
}
-Texture Scene3dView::LoadTexture( const char *imageUrl, bool generateMipmaps )
+Texture Scene3dView::LoadTexture(const char* imageUrl, bool generateMipmaps)
{
Texture texture;
- Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl );
- if( pixelBuffer )
+ Devel::PixelBuffer pixelBuffer = LoadImageFromFile(imageUrl);
+ if(pixelBuffer)
{
- texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
- PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
- texture.Upload( pixelData );
+ texture = Texture::New(TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
+ PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
+ texture.Upload(pixelData);
- if( generateMipmaps )
+ if(generateMipmaps)
{
texture.GenerateMipmaps();
}
void Scene3dView::OnInitialize()
{
- mRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mRoot.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ mRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mRoot.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
Layer layer = Layer::New();
- layer.SetProperty( Layer::Property::BEHAVIOR, Layer::LAYER_3D );
- layer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- layer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- layer.Add( mRoot );
+ layer.SetProperty(Layer::Property::BEHAVIOR, Layer::LAYER_3D);
+ layer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ layer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ layer.Add(mRoot);
Actor self = Self();
// Apply some default resizing rules.
- self.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- self.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- self.Add( layer );
+ self.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ self.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ self.Add(layer);
CreateScene();
}
-}//namespace Internal
-
-}//namespace Toolkit
+} //namespace Internal
-}//namespace Dali
+} //namespace Toolkit
+} //namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/scroll-bar/scroll-bar-impl.h>
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
+#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/devel-api/object/property-helper-devel.h>
+#include <dali/integration-api/debug.h>
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/animation/constraints.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/property-array.h>
#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/integration-api/debug.h>
-#include <dali/devel-api/object/property-helper-devel.h>
-#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
namespace
{
-
const char* DEFAULT_INDICATOR_IMAGE_FILE_NAME = "popup_scroll.9.png";
const float DEFAULT_SLIDER_DEPTH(1.0f);
const float DEFAULT_INDICATOR_SHOW_DURATION(0.5f);
* @param[in] minimumHeight The minimum height for the indicator
* @param[in] padding The sum of the padding at the start & end of the indicator
*/
- IndicatorSizeConstraint( float minimumHeight, float padding )
- : mMinimumHeight( minimumHeight ),
- mPadding( padding )
+ IndicatorSizeConstraint(float minimumHeight, float padding)
+ : mMinimumHeight(minimumHeight),
+ mPadding(padding)
{
}
* @param[in] parentSizeProperty The parent size of scroll indicator.
* @return The new scroll indicator size.
*/
- void operator()( Vector3& current, const PropertyInputContainer& inputs )
+ void operator()(Vector3& current, const PropertyInputContainer& inputs)
{
- const Vector3& parentSize = inputs[0]->GetVector3();
- const float contentSize = inputs[1]->GetFloat();
+ const Vector3& parentSize = inputs[0]->GetVector3();
+ const float contentSize = inputs[1]->GetFloat();
// Take into account padding that may exist at the beginning and end of the indicator.
const float parentHeightMinusPadding = parentSize.height - mPadding;
- float height = contentSize > parentHeightMinusPadding ?
- parentHeightMinusPadding * ( parentHeightMinusPadding / contentSize ) :
- parentHeightMinusPadding * ( ( parentHeightMinusPadding - contentSize * 0.5f ) / parentHeightMinusPadding );
+ float height = contentSize > parentHeightMinusPadding ? parentHeightMinusPadding * (parentHeightMinusPadding / contentSize) : parentHeightMinusPadding * ((parentHeightMinusPadding - contentSize * 0.5f) / parentHeightMinusPadding);
- current.y = std::max( mMinimumHeight, height );
+ current.y = std::max(mMinimumHeight, height);
}
float mMinimumHeight;
* @param[in] startPadding The padding at the start of the indicator
* @param[in] endPadding The padding at the end of the indicator
*/
- IndicatorPositionConstraint( float startPadding, float endPadding )
- : mStartPadding( startPadding ),
- mEndPadding( endPadding )
+ IndicatorPositionConstraint(float startPadding, float endPadding)
+ : mStartPadding(startPadding),
+ mEndPadding(endPadding)
{
}
* @param[in] inputs Contains the size of indicator, the size of indicator's parent, and the scroll position of the scrollable container (from 0.0 -> 1.0 in each axis)
* @return The new indicator position is returned.
*/
- void operator()( Vector3& current, const PropertyInputContainer& inputs )
+ void operator()(Vector3& current, const PropertyInputContainer& inputs)
{
- const Vector3& indicatorSize = inputs[0]->GetVector3();
- const Vector3& parentSize = inputs[1]->GetVector3();
- const float scrollPosition = -inputs[2]->GetFloat();
- const float minimumScrollPosition = inputs[3]->GetFloat();
- const float maximumScrollPosition = inputs[4]->GetFloat();
+ const Vector3& indicatorSize = inputs[0]->GetVector3();
+ const Vector3& parentSize = inputs[1]->GetVector3();
+ const float scrollPosition = -inputs[2]->GetFloat();
+ const float minimumScrollPosition = inputs[3]->GetFloat();
+ const float maximumScrollPosition = inputs[4]->GetFloat();
// Take into account padding that may exist at the beginning and end of the indicator.
- const float parentHeightMinusPadding = parentSize.height - ( mStartPadding + mEndPadding );
+ const float parentHeightMinusPadding = parentSize.height - (mStartPadding + mEndPadding);
- float relativePosition = std::max( 0.0f, std::min( 1.0f, ( scrollPosition - minimumScrollPosition ) / ( maximumScrollPosition - minimumScrollPosition ) ) );
- current.y = mStartPadding + ( parentHeightMinusPadding - indicatorSize.height ) * relativePosition;
- current.z = DEFAULT_SLIDER_DEPTH;
+ float relativePosition = std::max(0.0f, std::min(1.0f, (scrollPosition - minimumScrollPosition) / (maximumScrollPosition - minimumScrollPosition)));
+ current.y = mStartPadding + (parentHeightMinusPadding - indicatorSize.height) * relativePosition;
+ current.z = DEFAULT_SLIDER_DEPTH;
}
float mStartPadding;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
using namespace Dali;
BaseHandle Create()
return Toolkit::ScrollBar::New();
}
+// clang-format off
// Setup properties, signals and actions using the type-registry.
DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ScrollBar, Toolkit::Control, Create );
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "scrollDirection", STRING, SCROLL_DIRECTION )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorHeightPolicy", STRING, INDICATOR_HEIGHT_POLICY )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorFixedHeight", FLOAT, INDICATOR_FIXED_HEIGHT )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorShowDuration", FLOAT, INDICATOR_SHOW_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorHideDuration", FLOAT, INDICATOR_HIDE_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "scrollPositionIntervals", ARRAY, SCROLL_POSITION_INTERVALS )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorMinimumHeight", FLOAT, INDICATOR_MINIMUM_HEIGHT )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorStartPadding", FLOAT, INDICATOR_START_PADDING )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorEndPadding", FLOAT, INDICATOR_END_PADDING )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorTransientDuration", FLOAT, INDICATOR_TRANSIENT_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "scrollDirection", STRING, SCROLL_DIRECTION )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorHeightPolicy", STRING, INDICATOR_HEIGHT_POLICY )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorFixedHeight", FLOAT, INDICATOR_FIXED_HEIGHT )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorShowDuration", FLOAT, INDICATOR_SHOW_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorHideDuration", FLOAT, INDICATOR_HIDE_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "scrollPositionIntervals", ARRAY, SCROLL_POSITION_INTERVALS )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorMinimumHeight", FLOAT, INDICATOR_MINIMUM_HEIGHT )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorStartPadding", FLOAT, INDICATOR_START_PADDING )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorEndPadding", FLOAT, INDICATOR_END_PADDING )
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorTransientDuration", FLOAT, INDICATOR_TRANSIENT_DURATION)
-DALI_SIGNAL_REGISTRATION( Toolkit, ScrollBar, "panFinished", PAN_FINISHED_SIGNAL )
-DALI_SIGNAL_REGISTRATION( Toolkit, ScrollBar, "scrollPositionIntervalReached", SCROLL_POSITION_INTERVAL_REACHED_SIGNAL )
+DALI_SIGNAL_REGISTRATION(Toolkit, ScrollBar, "panFinished", PAN_FINISHED_SIGNAL )
+DALI_SIGNAL_REGISTRATION(Toolkit, ScrollBar, "scrollPositionIntervalReached", SCROLL_POSITION_INTERVAL_REACHED_SIGNAL)
-DALI_ACTION_REGISTRATION( Toolkit, ScrollBar, "ShowIndicator", ACTION_SHOW_INDICATOR )
-DALI_ACTION_REGISTRATION( Toolkit, ScrollBar, "HideIndicator", ACTION_HIDE_INDICATOR )
-DALI_ACTION_REGISTRATION( Toolkit, ScrollBar, "ShowTransientIndicator", ACTION_SHOW_TRANSIENT_INDICATOR )
+DALI_ACTION_REGISTRATION(Toolkit, ScrollBar, "ShowIndicator", ACTION_SHOW_INDICATOR )
+DALI_ACTION_REGISTRATION(Toolkit, ScrollBar, "HideIndicator", ACTION_HIDE_INDICATOR )
+DALI_ACTION_REGISTRATION(Toolkit, ScrollBar, "ShowTransientIndicator", ACTION_SHOW_TRANSIENT_INDICATOR)
DALI_TYPE_REGISTRATION_END()
+// clang-format on
-const char* SCROLL_DIRECTION_NAME[] = {"VERTICAL", "HORIZONTAL"};
+const char* SCROLL_DIRECTION_NAME[] = {"VERTICAL", "HORIZONTAL"};
const char* INDICATOR_HEIGHT_POLICY_NAME[] = {"VARIABLE", "FIXED"};
-}
+} // namespace
ScrollBar::ScrollBar(Toolkit::ScrollBar::Direction direction)
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mIndicatorShowAlpha(1.0f),
mDirection(direction),
mScrollableObject(WeakHandle<Handle>()),
mIndicatorHideDuration(DEFAULT_INDICATOR_HIDE_DURATION),
mTransientIndicatorDuration(DEFAULT_INDICATOR_TRANSIENT_DURATION),
mScrollStart(0.0f),
- mGestureDisplacement( Vector2::ZERO ),
+ mGestureDisplacement(Vector2::ZERO),
mCurrentScrollPosition(0.0f),
mIndicatorHeightPolicy(Toolkit::ScrollBar::VARIABLE),
mIndicatorFixedHeight(DEFAULT_INDICATOR_FIXED_HEIGHT),
void ScrollBar::OnInitialize()
{
CreateDefaultIndicatorActor();
- Self().SetProperty( Actor::Property::DRAW_MODE,DrawMode::OVERLAY_2D);
+ Self().SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D);
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::SCROLL_BAR ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_BAR));
+ });
}
-void ScrollBar::SetScrollPropertySource( Handle handle, Property::Index propertyScrollPosition, Property::Index propertyMinScrollPosition, Property::Index propertyMaxScrollPosition, Property::Index propertyScrollContentSize )
+void ScrollBar::SetScrollPropertySource(Handle handle, Property::Index propertyScrollPosition, Property::Index propertyMinScrollPosition, Property::Index propertyMaxScrollPosition, Property::Index propertyScrollContentSize)
{
- if( handle
- && propertyScrollPosition != Property::INVALID_INDEX
- && propertyMinScrollPosition != Property::INVALID_INDEX
- && propertyMaxScrollPosition != Property::INVALID_INDEX
- && propertyScrollContentSize != Property::INVALID_INDEX )
+ if(handle && propertyScrollPosition != Property::INVALID_INDEX && propertyMinScrollPosition != Property::INVALID_INDEX && propertyMaxScrollPosition != Property::INVALID_INDEX && propertyScrollContentSize != Property::INVALID_INDEX)
{
- mScrollableObject = WeakHandle<Handle>(handle);
- mPropertyScrollPosition = propertyScrollPosition;
+ mScrollableObject = WeakHandle<Handle>(handle);
+ mPropertyScrollPosition = propertyScrollPosition;
mPropertyMinScrollPosition = propertyMinScrollPosition;
mPropertyMaxScrollPosition = propertyMaxScrollPosition;
mPropertyScrollContentSize = propertyScrollContentSize;
void ScrollBar::CreateDefaultIndicatorActor()
{
- const std::string imageDirPath = AssetManager::GetDaliImagePath();
- Toolkit::ImageView indicator = Toolkit::ImageView::New( imageDirPath + DEFAULT_INDICATOR_IMAGE_FILE_NAME );
- indicator.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- indicator.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- indicator.SetStyleName( "ScrollBarIndicator" );
- indicator.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR );
+ const std::string imageDirPath = AssetManager::GetDaliImagePath();
+ Toolkit::ImageView indicator = Toolkit::ImageView::New(imageDirPath + DEFAULT_INDICATOR_IMAGE_FILE_NAME);
+ indicator.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ indicator.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ indicator.SetStyleName("ScrollBarIndicator");
+ indicator.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR);
SetScrollIndicator(indicator);
}
-void ScrollBar::SetScrollIndicator( Actor indicator )
+void ScrollBar::SetScrollIndicator(Actor indicator)
{
// Don't allow empty handle
- if( indicator )
+ if(indicator)
{
// Remove current Indicator
- if( mIndicator )
+ if(mIndicator)
{
- Self().Remove( mIndicator );
+ Self().Remove(mIndicator);
}
mIndicator = indicator;
mIndicatorFirstShow = true;
- Self().Add( mIndicator );
+ Self().Add(mIndicator);
- EnableGestureDetection( GestureType::Value( GestureType::PAN ) );
+ EnableGestureDetection(GestureType::Value(GestureType::PAN));
- PanGestureDetector detector( GetPanGestureDetector() );
+ PanGestureDetector detector(GetPanGestureDetector());
detector.DetachAll();
- detector.Attach( mIndicator );
+ detector.Attach(mIndicator);
unsigned int childCount = mIndicator.GetChildCount();
- for ( unsigned int index = 0; index < childCount; index++ )
+ for(unsigned int index = 0; index < childCount; index++)
{
- Actor child = mIndicator.GetChildAt( index );
- if ( child )
+ Actor child = mIndicator.GetChildAt(index);
+ if(child)
{
- detector.Attach( child );
+ detector.Attach(child);
}
}
}
{
Handle scrollableHandle = mScrollableObject.GetHandle();
- if( scrollableHandle )
+ if(scrollableHandle)
{
if(mIndicatorSizeConstraint)
{
// Set indicator height according to the indicator's height policy
if(mIndicatorHeightPolicy == Toolkit::ScrollBar::FIXED)
{
- mIndicator.SetProperty( Actor::Property::SIZE, Vector2( Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).width, mIndicatorFixedHeight) );
+ mIndicator.SetProperty(Actor::Property::SIZE, Vector2(Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE).width, mIndicatorFixedHeight));
}
else
{
- mIndicatorSizeConstraint = Constraint::New<Vector3>( mIndicator, Actor::Property::SIZE,
- IndicatorSizeConstraint( mIndicatorMinimumHeight, mIndicatorStartPadding + mIndicatorEndPadding ) );
- mIndicatorSizeConstraint.AddSource( ParentSource( Actor::Property::SIZE ) );
- mIndicatorSizeConstraint.AddSource( Source( scrollableHandle, mPropertyScrollContentSize ) );
+ mIndicatorSizeConstraint = Constraint::New<Vector3>(mIndicator, Actor::Property::SIZE, IndicatorSizeConstraint(mIndicatorMinimumHeight, mIndicatorStartPadding + mIndicatorEndPadding));
+ mIndicatorSizeConstraint.AddSource(ParentSource(Actor::Property::SIZE));
+ mIndicatorSizeConstraint.AddSource(Source(scrollableHandle, mPropertyScrollContentSize));
mIndicatorSizeConstraint.Apply();
}
mIndicatorPositionConstraint.Remove();
}
- mIndicatorPositionConstraint = Constraint::New<Vector3>( mIndicator, Actor::Property::POSITION,
- IndicatorPositionConstraint( mIndicatorStartPadding, mIndicatorEndPadding ) );
- mIndicatorPositionConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
- mIndicatorPositionConstraint.AddSource( ParentSource( Actor::Property::SIZE ) );
- mIndicatorPositionConstraint.AddSource( Source( scrollableHandle, mPropertyScrollPosition ) );
- mIndicatorPositionConstraint.AddSource( Source( scrollableHandle, mPropertyMinScrollPosition ) );
- mIndicatorPositionConstraint.AddSource( Source( scrollableHandle, mPropertyMaxScrollPosition ) );
+ mIndicatorPositionConstraint = Constraint::New<Vector3>(mIndicator, Actor::Property::POSITION, IndicatorPositionConstraint(mIndicatorStartPadding, mIndicatorEndPadding));
+ mIndicatorPositionConstraint.AddSource(LocalSource(Actor::Property::SIZE));
+ mIndicatorPositionConstraint.AddSource(ParentSource(Actor::Property::SIZE));
+ mIndicatorPositionConstraint.AddSource(Source(scrollableHandle, mPropertyScrollPosition));
+ mIndicatorPositionConstraint.AddSource(Source(scrollableHandle, mPropertyMinScrollPosition));
+ mIndicatorPositionConstraint.AddSource(Source(scrollableHandle, mPropertyMaxScrollPosition));
mIndicatorPositionConstraint.Apply();
}
}
-void ScrollBar::SetScrollPositionIntervals( const Dali::Vector<float>& positions )
+void ScrollBar::SetScrollPositionIntervals(const Dali::Vector<float>& positions)
{
mScrollPositionIntervals = positions;
Handle scrollableHandle = mScrollableObject.GetHandle();
- if( scrollableHandle )
+ if(scrollableHandle)
{
- if( mPositionNotification )
+ if(mPositionNotification)
{
scrollableHandle.RemovePropertyNotification(mPositionNotification);
}
- mPositionNotification = scrollableHandle.AddPropertyNotification( mPropertyScrollPosition, VariableStepCondition(mScrollPositionIntervals) );
- mPositionNotification.NotifySignal().Connect( this, &ScrollBar::OnScrollPositionIntervalReached );
+ mPositionNotification = scrollableHandle.AddPropertyNotification(mPropertyScrollPosition, VariableStepCondition(mScrollPositionIntervals));
+ mPositionNotification.NotifySignal().Connect(this, &ScrollBar::OnScrollPositionIntervalReached);
}
}
Handle scrollableHandle = mScrollableObject.GetHandle();
if(scrollableHandle)
{
- mScrollPositionIntervalReachedSignal.Emit( scrollableHandle.GetCurrentProperty< float >( mPropertyScrollPosition ) );
- if (Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
+ mScrollPositionIntervalReachedSignal.Emit(scrollableHandle.GetCurrentProperty<float>(mPropertyScrollPosition));
+ if(Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
{
Control::Impl::GetAccessibilityObject(Self())->Emit(Dali::Accessibility::ObjectPropertyChangeEvent::VALUE);
}
mAnimation.Reset();
}
- if( mIndicatorFirstShow )
+ if(mIndicatorFirstShow)
{
// Preserve the alpha value from the stylesheet
- mIndicatorShowAlpha = Self().GetCurrentProperty< Vector4 >( Actor::Property::COLOR ).a;
+ mIndicatorShowAlpha = Self().GetCurrentProperty<Vector4>(Actor::Property::COLOR).a;
mIndicatorFirstShow = false;
}
if(mIndicatorShowDuration > 0.0f)
{
- mAnimation = Animation::New( mIndicatorShowDuration );
- mAnimation.AnimateTo( Property( mIndicator, Actor::Property::COLOR_ALPHA ), mIndicatorShowAlpha, AlphaFunction::EASE_IN );
+ mAnimation = Animation::New(mIndicatorShowDuration);
+ mAnimation.AnimateTo(Property(mIndicator, Actor::Property::COLOR_ALPHA), mIndicatorShowAlpha, AlphaFunction::EASE_IN);
mAnimation.Play();
}
else
{
- mIndicator.SetProperty( Actor::Property::OPACITY,mIndicatorShowAlpha);
+ mIndicator.SetProperty(Actor::Property::OPACITY, mIndicatorShowAlpha);
}
}
if(mIndicatorHideDuration > 0.0f)
{
- mAnimation = Animation::New( mIndicatorHideDuration );
- mAnimation.AnimateTo( Property( mIndicator, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN );
+ mAnimation = Animation::New(mIndicatorHideDuration);
+ mAnimation.AnimateTo(Property(mIndicator, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN);
mAnimation.Play();
}
else
{
- mIndicator.SetProperty( Actor::Property::OPACITY,0.0f);
+ mIndicator.SetProperty(Actor::Property::OPACITY, 0.0f);
}
}
mAnimation.Reset();
}
- mAnimation = Animation::New( mIndicatorShowDuration + mTransientIndicatorDuration + mIndicatorHideDuration );
+ mAnimation = Animation::New(mIndicatorShowDuration + mTransientIndicatorDuration + mIndicatorHideDuration);
if(mIndicatorShowDuration > 0.0f)
{
- mAnimation.AnimateTo( Property( mIndicator, Actor::Property::COLOR_ALPHA ),
- mIndicatorShowAlpha, AlphaFunction::EASE_IN, TimePeriod(0, mIndicatorShowDuration) );
+ mAnimation.AnimateTo(Property(mIndicator, Actor::Property::COLOR_ALPHA),
+ mIndicatorShowAlpha,
+ AlphaFunction::EASE_IN,
+ TimePeriod(0, mIndicatorShowDuration));
}
else
{
- mIndicator.SetProperty( Actor::Property::OPACITY,mIndicatorShowAlpha);
+ mIndicator.SetProperty(Actor::Property::OPACITY, mIndicatorShowAlpha);
}
- mAnimation.AnimateTo( Property( mIndicator, Actor::Property::COLOR_ALPHA ),
- 0.0f, AlphaFunction::EASE_IN, TimePeriod((mIndicatorShowDuration + mTransientIndicatorDuration), mIndicatorHideDuration) );
+ mAnimation.AnimateTo(Property(mIndicator, Actor::Property::COLOR_ALPHA),
+ 0.0f,
+ AlphaFunction::EASE_IN,
+ TimePeriod((mIndicatorShowDuration + mTransientIndicatorDuration), mIndicatorHideDuration));
mAnimation.Play();
}
{
// Update the scroll position property.
Handle scrollableHandle = mScrollableObject.GetHandle();
- if( scrollableHandle )
+ if(scrollableHandle)
{
scrollableHandle.SetProperty(mPropertyScrollPosition, mCurrentScrollPosition);
}
return true;
}
-void ScrollBar::OnPan( const PanGesture& gesture )
+void ScrollBar::OnPan(const PanGesture& gesture)
{
Handle scrollableHandle = mScrollableObject.GetHandle();
{
case Dali::GestureState::STARTED:
{
- if( !mPanProcessTimer )
+ if(!mPanProcessTimer)
{
// Make sure the pan gesture is only being processed once per frame.
- mPanProcessTimer = Timer::New( DEFAULT_PAN_GESTURE_PROCESS_TIME );
- mPanProcessTimer.TickSignal().Connect( this, &ScrollBar::OnPanGestureProcessTick );
+ mPanProcessTimer = Timer::New(DEFAULT_PAN_GESTURE_PROCESS_TIME);
+ mPanProcessTimer.TickSignal().Connect(this, &ScrollBar::OnPanGestureProcessTick);
mPanProcessTimer.Start();
}
ShowIndicator();
- mScrollStart = scrollableHandle.GetCurrentProperty< float >( mPropertyScrollPosition );
+ mScrollStart = scrollableHandle.GetCurrentProperty<float>(mPropertyScrollPosition);
mGestureDisplacement = Vector2::ZERO;
- mIsPanning = true;
+ mIsPanning = true;
break;
}
{
mGestureDisplacement += gesture.GetDisplacement();
- float minScrollPosition = scrollableHandle.GetCurrentProperty<float>( mPropertyMinScrollPosition );
- float maxScrollPosition = scrollableHandle.GetCurrentProperty<float>( mPropertyMaxScrollPosition );
+ float minScrollPosition = scrollableHandle.GetCurrentProperty<float>(mPropertyMinScrollPosition);
+ float maxScrollPosition = scrollableHandle.GetCurrentProperty<float>(mPropertyMaxScrollPosition);
// The domain size is the internal range
- float domainSize = maxScrollPosition - minScrollPosition;
- float logicalSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).y - ( mIndicator.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).y + mIndicatorStartPadding + mIndicatorEndPadding );
+ float domainSize = maxScrollPosition - minScrollPosition;
+ float logicalSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE).y - (mIndicator.GetCurrentProperty<Vector3>(Actor::Property::SIZE).y + mIndicatorStartPadding + mIndicatorEndPadding);
- mCurrentScrollPosition = mScrollStart - ( ( mGestureDisplacement.y * domainSize ) / logicalSize );
- mCurrentScrollPosition = -std::min( maxScrollPosition, std::max( -mCurrentScrollPosition, minScrollPosition ) );
+ mCurrentScrollPosition = mScrollStart - ((mGestureDisplacement.y * domainSize) / logicalSize);
+ mCurrentScrollPosition = -std::min(maxScrollPosition, std::max(-mCurrentScrollPosition, minScrollPosition));
break;
}
{
mIsPanning = false;
- if( mPanProcessTimer )
+ if(mPanProcessTimer)
{
// Destroy the timer when pan gesture is finished.
mPanProcessTimer.Stop();
- mPanProcessTimer.TickSignal().Disconnect( this, &ScrollBar::OnPanGestureProcessTick );
+ mPanProcessTimer.TickSignal().Disconnect(this, &ScrollBar::OnPanGestureProcessTick);
mPanProcessTimer.Reset();
}
}
}
-void ScrollBar::OnSizeSet( const Vector3& size )
+void ScrollBar::OnSizeSet(const Vector3& size)
{
if(mIndicatorHeightPolicy == Toolkit::ScrollBar::FIXED)
{
- mIndicator.SetProperty( Actor::Property::SIZE, Vector2( size.width, mIndicatorFixedHeight ) );
+ mIndicator.SetProperty(Actor::Property::SIZE, Vector2(size.width, mIndicatorFixedHeight));
}
- Control::OnSizeSet( size );
+ Control::OnSizeSet(size);
}
-void ScrollBar::SetScrollDirection( Toolkit::ScrollBar::Direction direction )
+void ScrollBar::SetScrollDirection(Toolkit::ScrollBar::Direction direction)
{
mDirection = direction;
}
return mDirection;
}
-void ScrollBar::SetIndicatorHeightPolicy( Toolkit::ScrollBar::IndicatorHeightPolicy policy )
+void ScrollBar::SetIndicatorHeightPolicy(Toolkit::ScrollBar::IndicatorHeightPolicy policy)
{
- if( policy != mIndicatorHeightPolicy )
+ if(policy != mIndicatorHeightPolicy)
{
mIndicatorHeightPolicy = policy;
ApplyConstraints();
return mIndicatorHeightPolicy;
}
-void ScrollBar::SetIndicatorFixedHeight( float height )
+void ScrollBar::SetIndicatorFixedHeight(float height)
{
mIndicatorFixedHeight = height;
if(mIndicatorHeightPolicy == Toolkit::ScrollBar::FIXED)
{
- mIndicator.SetProperty( Actor::Property::SIZE, Vector2( Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).width, mIndicatorFixedHeight) );
+ mIndicator.SetProperty(Actor::Property::SIZE, Vector2(Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE).width, mIndicatorFixedHeight));
}
}
return mIndicatorFixedHeight;
}
-void ScrollBar::SetIndicatorShowDuration( float durationSeconds )
+void ScrollBar::SetIndicatorShowDuration(float durationSeconds)
{
mIndicatorShowDuration = durationSeconds;
}
return mIndicatorShowDuration;
}
-void ScrollBar::SetIndicatorHideDuration( float durationSeconds )
+void ScrollBar::SetIndicatorHideDuration(float durationSeconds)
{
mIndicatorHideDuration = durationSeconds;
}
return mIndicatorHideDuration;
}
-void ScrollBar::OnScrollDirectionPropertySet( Property::Value propertyValue )
+void ScrollBar::OnScrollDirectionPropertySet(Property::Value propertyValue)
{
- std::string directionName( propertyValue.Get<std::string>() );
+ std::string directionName(propertyValue.Get<std::string>());
if(directionName == "VERTICAL")
{
SetScrollDirection(Toolkit::ScrollBar::VERTICAL);
}
else
{
- DALI_ASSERT_ALWAYS( !"ScrollBar::OnScrollDirectionPropertySet(). Invalid Property value." );
+ DALI_ASSERT_ALWAYS(!"ScrollBar::OnScrollDirectionPropertySet(). Invalid Property value.");
}
}
-void ScrollBar::OnIndicatorHeightPolicyPropertySet( Property::Value propertyValue )
+void ScrollBar::OnIndicatorHeightPolicyPropertySet(Property::Value propertyValue)
{
- std::string policyName( propertyValue.Get<std::string>() );
+ std::string policyName(propertyValue.Get<std::string>());
if(policyName == "VARIABLE")
{
SetIndicatorHeightPolicy(Toolkit::ScrollBar::VARIABLE);
}
else
{
- DALI_ASSERT_ALWAYS( !"ScrollBar::OnIndicatorHeightPolicyPropertySet(). Invalid Property value." );
+ DALI_ASSERT_ALWAYS(!"ScrollBar::OnIndicatorHeightPolicyPropertySet(). Invalid Property value.");
}
}
-bool ScrollBar::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool ScrollBar::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( handle );
+ bool connected(true);
+ Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), PAN_FINISHED_SIGNAL ) )
+ if(0 == strcmp(signalName.c_str(), PAN_FINISHED_SIGNAL))
{
- scrollBar.PanFinishedSignal().Connect( tracker, functor );
+ scrollBar.PanFinishedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SCROLL_POSITION_INTERVAL_REACHED_SIGNAL ) )
+ else if(0 == strcmp(signalName.c_str(), SCROLL_POSITION_INTERVAL_REACHED_SIGNAL))
{
- scrollBar.ScrollPositionIntervalReachedSignal().Connect( tracker, functor );
+ scrollBar.ScrollPositionIntervalReachedSignal().Connect(tracker, functor);
}
else
{
return connected;
}
-void ScrollBar::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void ScrollBar::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast(Dali::BaseHandle(object));
- if( scrollBar )
+ if(scrollBar)
{
- ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
- switch( index )
+ ScrollBar& scrollBarImpl(GetImpl(scrollBar));
+ switch(index)
{
case Toolkit::ScrollBar::Property::SCROLL_DIRECTION:
{
- scrollBarImpl.OnScrollDirectionPropertySet( value );
+ scrollBarImpl.OnScrollDirectionPropertySet(value);
break;
}
case Toolkit::ScrollBar::Property::INDICATOR_HEIGHT_POLICY:
{
- scrollBarImpl.OnIndicatorHeightPolicyPropertySet( value );
+ scrollBarImpl.OnIndicatorHeightPolicyPropertySet(value);
break;
}
case Toolkit::ScrollBar::Property::INDICATOR_FIXED_HEIGHT:
case Toolkit::ScrollBar::Property::SCROLL_POSITION_INTERVALS:
{
const Property::Array* array = value.GetArray();
- if( array )
+ if(array)
{
Dali::Vector<float> positions;
- size_t positionCount = array->Count();
- positions.Resize( positionCount );
- for( size_t i = 0; i != positionCount; ++i )
+ size_t positionCount = array->Count();
+ positions.Resize(positionCount);
+ for(size_t i = 0; i != positionCount; ++i)
{
- array->GetElementAt( i ).Get( positions[i] );
+ array->GetElementAt(i).Get(positions[i]);
}
scrollBarImpl.SetScrollPositionIntervals(positions);
}
}
-Property::Value ScrollBar::GetProperty( BaseObject* object, Property::Index index )
+Property::Value ScrollBar::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast(Dali::BaseHandle(object));
- if( scrollBar )
+ if(scrollBar)
{
- ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
- switch( index )
+ ScrollBar& scrollBarImpl(GetImpl(scrollBar));
+ switch(index)
{
case Toolkit::ScrollBar::Property::SCROLL_DIRECTION:
{
- value = SCROLL_DIRECTION_NAME[ scrollBarImpl.GetScrollDirection() ];
+ value = SCROLL_DIRECTION_NAME[scrollBarImpl.GetScrollDirection()];
break;
}
case Toolkit::ScrollBar::Property::INDICATOR_HEIGHT_POLICY:
{
- value = INDICATOR_HEIGHT_POLICY_NAME[ scrollBarImpl.GetIndicatorHeightPolicy() ];
+ value = INDICATOR_HEIGHT_POLICY_NAME[scrollBarImpl.GetIndicatorHeightPolicy()];
break;
}
case Toolkit::ScrollBar::Property::INDICATOR_FIXED_HEIGHT:
}
case Toolkit::ScrollBar::Property::SCROLL_POSITION_INTERVALS:
{
- Property::Value tempValue( Property::ARRAY );
+ Property::Value tempValue(Property::ARRAY);
Property::Array* array = tempValue.GetArray();
- if( array )
+ if(array)
{
Dali::Vector<float> positions = scrollBarImpl.GetScrollPositionIntervals();
- size_t positionCount( positions.Count() );
+ size_t positionCount(positions.Count());
- for( size_t i( 0 ); i != positionCount; ++i )
+ for(size_t i(0); i != positionCount; ++i)
{
- array->PushBack( positions[i] );
+ array->PushBack(positions[i]);
}
value = tempValue;
return value;
}
-bool ScrollBar::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
+bool ScrollBar::DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes)
{
bool ret = false;
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( handle );
+ Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast(handle);
- DALI_ASSERT_DEBUG( scrollBar );
+ DALI_ASSERT_DEBUG(scrollBar);
- if( scrollBar )
+ if(scrollBar)
{
- if( 0 == strcmp( actionName.c_str(), ACTION_SHOW_INDICATOR ) )
+ if(0 == strcmp(actionName.c_str(), ACTION_SHOW_INDICATOR))
{
- GetImpl( scrollBar ).ShowIndicator();
+ GetImpl(scrollBar).ShowIndicator();
ret = true;
}
- else if( 0 == strcmp( actionName.c_str(), ACTION_HIDE_INDICATOR ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_HIDE_INDICATOR))
{
- GetImpl( scrollBar ).HideIndicator();
+ GetImpl(scrollBar).HideIndicator();
ret = true;
}
- else if( 0 == strcmp( actionName.c_str(), ACTION_SHOW_TRANSIENT_INDICATOR ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_SHOW_TRANSIENT_INDICATOR))
{
- GetImpl( scrollBar ).ShowTransientIndicator();
+ GetImpl(scrollBar).ShowTransientIndicator();
ret = true;
}
}
Toolkit::ScrollBar ScrollBar::New(Toolkit::ScrollBar::Direction direction)
{
// Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< ScrollBar > impl = new ScrollBar(direction);
+ IntrusivePtr<ScrollBar> impl = new ScrollBar(direction);
// Pass ownership to CustomActor handle
- Toolkit::ScrollBar handle( *impl );
+ Toolkit::ScrollBar handle(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
double ScrollBar::AccessibleImpl::GetMinimum()
{
- auto p = Toolkit::ScrollBar::DownCast( self );
- Handle scrollableHandle = GetImpl( p ).mScrollableObject.GetHandle();
- return scrollableHandle ? scrollableHandle.GetCurrentProperty< float >( GetImpl( p ).mPropertyMinScrollPosition ) : 0.0f;
+ auto p = Toolkit::ScrollBar::DownCast(self);
+ Handle scrollableHandle = GetImpl(p).mScrollableObject.GetHandle();
+ return scrollableHandle ? scrollableHandle.GetCurrentProperty<float>(GetImpl(p).mPropertyMinScrollPosition) : 0.0f;
}
double ScrollBar::AccessibleImpl::GetCurrent()
{
- auto p = Toolkit::ScrollBar::DownCast( self );
- Handle scrollableHandle = GetImpl( p ).mScrollableObject.GetHandle();
- return scrollableHandle ? scrollableHandle.GetCurrentProperty< float >( GetImpl( p ).mPropertyScrollPosition ) : 0.0f;
+ auto p = Toolkit::ScrollBar::DownCast(self);
+ Handle scrollableHandle = GetImpl(p).mScrollableObject.GetHandle();
+ return scrollableHandle ? scrollableHandle.GetCurrentProperty<float>(GetImpl(p).mPropertyScrollPosition) : 0.0f;
}
double ScrollBar::AccessibleImpl::GetMaximum()
{
- auto p = Toolkit::ScrollBar::DownCast( self );
- Handle scrollableHandle = GetImpl( p ).mScrollableObject.GetHandle();
- return scrollableHandle ? scrollableHandle.GetCurrentProperty< float >( GetImpl( p ).mPropertyMaxScrollPosition ) : 1.0f;
+ auto p = Toolkit::ScrollBar::DownCast(self);
+ Handle scrollableHandle = GetImpl(p).mScrollableObject.GetHandle();
+ return scrollableHandle ? scrollableHandle.GetCurrentProperty<float>(GetImpl(p).mPropertyMaxScrollPosition) : 1.0f;
}
-bool ScrollBar::AccessibleImpl::SetCurrent( double current )
+bool ScrollBar::AccessibleImpl::SetCurrent(double current)
{
- if( current < GetMinimum() || current > GetMaximum() )
+ if(current < GetMinimum() || current > GetMaximum())
return false;
auto value_before = GetCurrent();
- auto p = Toolkit::ScrollBar::DownCast( self );
- Handle scrollableHandle = GetImpl( p ).mScrollableObject.GetHandle();
- if( !scrollableHandle )
+ auto p = Toolkit::ScrollBar::DownCast(self);
+ Handle scrollableHandle = GetImpl(p).mScrollableObject.GetHandle();
+ if(!scrollableHandle)
return false;
- scrollableHandle.SetProperty( GetImpl( p ).mPropertyScrollPosition, static_cast< float >( current ) );
+ scrollableHandle.SetProperty(GetImpl(p).mPropertyScrollPosition, static_cast<float>(current));
auto value_after = GetCurrent();
- if( ( current != value_before ) && ( value_before == value_after ) )
+ if((current != value_before) && (value_before == value_after))
return false;
return true;
}
-double ScrollBar::AccessibleImpl::GetMinimumIncrement() { return 1.0; }
+double ScrollBar::AccessibleImpl::GetMinimumIncrement()
+{
+ return 1.0;
+}
} // namespace Internal
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
// Bouncing effect is presented by stacked three layers with same color and opacity
const float LAYER_HEIGHTS[5] =
-{
- 1.f,
- 26.f * 4.f/ 130.f,
- 26.f * 3.f / 130.f,
- 26.f * 2.f / 130.f,
- 26.f / 130.f
-};
+ {
+ 1.f,
+ 26.f * 4.f / 130.f,
+ 26.f * 3.f / 130.f,
+ 26.f * 2.f / 130.f,
+ 26.f / 130.f};
-} // namespace Anon
+} // namespace
-Actor CreateBouncingEffectActor( Property::Index& bouncePropertyIndex )
+Actor CreateBouncingEffectActor(Property::Index& bouncePropertyIndex)
{
// Create the bouncing mesh geometry
struct VertexPosition
// 4 vertices 2 triangles per layer. The depth interval between each layer is 0.01
VertexPosition vertexData[20] = {
// bottom layer
- { Vector3( -0.5f, -0.5f, 0.f ), Vector3( -0.5f, -0.5f, 0.f ) },
- { Vector3( 0.5f, -0.5f, 0.f ), Vector3( 0.5f, -0.5f, 0.f ) },
- { Vector3( -0.5f, -0.5f, 0.f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[0], 0.f ) },
- { Vector3( 0.5f, -0.5f, 0.f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[0], 0.f ) },
+ {Vector3(-0.5f, -0.5f, 0.f), Vector3(-0.5f, -0.5f, 0.f)},
+ {Vector3(0.5f, -0.5f, 0.f), Vector3(0.5f, -0.5f, 0.f)},
+ {Vector3(-0.5f, -0.5f, 0.f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[0], 0.f)},
+ {Vector3(0.5f, -0.5f, 0.f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[0], 0.f)},
// mid-bottom layer
- { Vector3( -0.5f, -0.5f, 0.01f ), Vector3( -0.5f, -0.5f, 0.01f ) },
- { Vector3( 0.5f, -0.5f, 0.01f ), Vector3( 0.5f, -0.5f, 0.01f ) },
- { Vector3( -0.5f, -0.5f, 0.01f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[1], 0.01f ) },
- { Vector3( 0.5f, -0.5f, 0.01f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[1], 0.01f ) },
+ {Vector3(-0.5f, -0.5f, 0.01f), Vector3(-0.5f, -0.5f, 0.01f)},
+ {Vector3(0.5f, -0.5f, 0.01f), Vector3(0.5f, -0.5f, 0.01f)},
+ {Vector3(-0.5f, -0.5f, 0.01f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[1], 0.01f)},
+ {Vector3(0.5f, -0.5f, 0.01f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[1], 0.01f)},
// middle layer
- { Vector3( -0.5f, -0.5f, 0.02f ), Vector3( -0.5f, -0.5f, 0.02f ) },
- { Vector3( 0.5f, -0.5f, 0.02f ), Vector3( 0.5f, -0.5f, 0.02f ) },
- { Vector3( -0.5f, -0.5f, 0.02f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[2], 0.02f ) },
- { Vector3( 0.5f, -0.5f, 0.02f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[2], 0.02f ) },
+ {Vector3(-0.5f, -0.5f, 0.02f), Vector3(-0.5f, -0.5f, 0.02f)},
+ {Vector3(0.5f, -0.5f, 0.02f), Vector3(0.5f, -0.5f, 0.02f)},
+ {Vector3(-0.5f, -0.5f, 0.02f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[2], 0.02f)},
+ {Vector3(0.5f, -0.5f, 0.02f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[2], 0.02f)},
// mid-top layer
- { Vector3( -0.5f, -0.5f, 0.03f ), Vector3( -0.5f, -0.5f, 0.03f ) },
- { Vector3( 0.5f, -0.5f, 0.03f ), Vector3( 0.5f, -0.5f, 0.03f ) },
- { Vector3( -0.5f, -0.5f, 0.03f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[3], 0.03f ) },
- { Vector3( 0.5f, -0.5f, 0.03f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[3], 0.03f ) },
+ {Vector3(-0.5f, -0.5f, 0.03f), Vector3(-0.5f, -0.5f, 0.03f)},
+ {Vector3(0.5f, -0.5f, 0.03f), Vector3(0.5f, -0.5f, 0.03f)},
+ {Vector3(-0.5f, -0.5f, 0.03f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[3], 0.03f)},
+ {Vector3(0.5f, -0.5f, 0.03f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[3], 0.03f)},
// top layer
- { Vector3( -0.5f, -0.5f, 0.04f ), Vector3( -0.5f, -0.5f, 0.04f ) },
- { Vector3( 0.5f, -0.5f, 0.04f ), Vector3( 0.5f, -0.5f, 0.04f ) },
- { Vector3( -0.5f, -0.5f, 0.04f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[4], 0.04f ) },
- { Vector3( 0.5f, -0.5f, 0.04f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[4], 0.04f ) }
- };
+ {Vector3(-0.5f, -0.5f, 0.04f), Vector3(-0.5f, -0.5f, 0.04f)},
+ {Vector3(0.5f, -0.5f, 0.04f), Vector3(0.5f, -0.5f, 0.04f)},
+ {Vector3(-0.5f, -0.5f, 0.04f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[4], 0.04f)},
+ {Vector3(0.5f, -0.5f, 0.04f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[4], 0.04f)}};
Property::Map vertexFormat;
vertexFormat["aPosition1"] = Property::VECTOR3;
vertexFormat["aPosition2"] = Property::VECTOR3;
- VertexBuffer vertices = VertexBuffer::New( vertexFormat );
- vertices.SetData( vertexData, 20u );
+ VertexBuffer vertices = VertexBuffer::New(vertexFormat);
+ vertices.SetData(vertexData, 20u);
- unsigned short indexData[30] = { 0,3,1,0,2,3,4,7,5,4,6,7,8,11,9,8,10,11,12,15,13,12,14,15,16,19,17,16,18,19};
+ unsigned short indexData[30] = {0, 3, 1, 0, 2, 3, 4, 7, 5, 4, 6, 7, 8, 11, 9, 8, 10, 11, 12, 15, 13, 12, 14, 15, 16, 19, 17, 16, 18, 19};
Geometry meshGeometry = Geometry::New();
- meshGeometry.AddVertexBuffer( vertices );
- meshGeometry.SetIndexBuffer( indexData, sizeof(indexData)/sizeof(indexData[0]) );
+ meshGeometry.AddVertexBuffer(vertices);
+ meshGeometry.SetIndexBuffer(indexData, sizeof(indexData) / sizeof(indexData[0]));
// Create the shader
- Shader shader = Shader::New( SHADER_BOUNCING_EFFECT_MESH_SHADER_VERT, SHADER_BOUNCING_EFFECT_MESH_SHADER_FRAG );
+ Shader shader = Shader::New(SHADER_BOUNCING_EFFECT_MESH_SHADER_VERT, SHADER_BOUNCING_EFFECT_MESH_SHADER_FRAG);
// Create renderer
- Renderer renderer = Renderer::New( meshGeometry, shader );
+ Renderer renderer = Renderer::New(meshGeometry, shader);
// Create actor
- Actor meshActor= Actor::New();
- meshActor.AddRenderer( renderer );
+ Actor meshActor = Actor::New();
+ meshActor.AddRenderer(renderer);
// Register property
bouncePropertyIndex = meshActor.RegisterProperty("uBounceCoefficient", 0.f);
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/scrollable/item-view/depth-layout.h>
// EXTERNAL INCLUDES
-#include <algorithm>
#include <dali/public-api/animation/animation.h>
#include <dali/public-api/animation/constraint.h>
+#include <algorithm>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h>
#include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h>
+#include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h>
using namespace Dali;
using namespace Dali::Toolkit;
namespace // unnamed namespace
{
-
const unsigned int DEFAULT_NUMBER_OF_COLUMNS = 3;
const float DEFAULT_NUMBER_OF_ROWS = 26.0f;
const float DEFAULT_ROW_SPACING = 55.0f;
const float DEFAULT_BOTTOM_MARGIN_FACTOR = 0.2f;
-const Radian DEFAULT_TILT_ANGLE ( Math::PI*0.15f );
-const Radian DEFAULT_ITEM_TILT_ANGLE ( -Math::PI*0.025f );
-const float DEFAULT_SCROLL_SPEED_FACTOR = 0.02f;
-const float DEFAULT_MAXIMUM_SWIPE_SPEED = 50.0f;
+const Radian DEFAULT_TILT_ANGLE(Math::PI * 0.15f);
+const Radian DEFAULT_ITEM_TILT_ANGLE(-Math::PI * 0.025f);
+const float DEFAULT_SCROLL_SPEED_FACTOR = 0.02f;
+const float DEFAULT_MAXIMUM_SWIPE_SPEED = 50.0f;
const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.03f;
-inline float GetColumnPosition( unsigned int numberOfColumns, unsigned int columnNumber, const Vector3& itemSize, float layoutWidth )
+inline float GetColumnPosition(unsigned int numberOfColumns, unsigned int columnNumber, const Vector3& itemSize, float layoutWidth)
{
// Share the available space between margins & column spacings
- float availableSpace = std::max( 0.0f, ( layoutWidth - itemSize.width * numberOfColumns ) );
+ float availableSpace = std::max(0.0f, (layoutWidth - itemSize.width * numberOfColumns));
float leftMargin = availableSpace / numberOfColumns * 0.5f;
- float columnPosition = leftMargin + itemSize.width * 0.5f + columnNumber * ( itemSize.width + availableSpace / numberOfColumns );
+ float columnPosition = leftMargin + itemSize.width * 0.5f + columnNumber * (itemSize.width + availableSpace / numberOfColumns);
return columnPosition - layoutWidth * 0.5f;
}
struct DepthPositionConstraint
{
- DepthPositionConstraint( unsigned int itemId,
- unsigned int numberOfColumns,
- unsigned int columnNumber,
- const Vector3& itemSize,
- float heightScale,
- float depthScale )
- : mItemSize( itemSize ),
- mItemId( itemId ),
- mNumberOfColumns( numberOfColumns ),
- mColumnNumber( columnNumber ),
- mHeightScale( heightScale ),
- mDepthScale( depthScale )
+ DepthPositionConstraint(unsigned int itemId,
+ unsigned int numberOfColumns,
+ unsigned int columnNumber,
+ const Vector3& itemSize,
+ float heightScale,
+ float depthScale)
+ : mItemSize(itemSize),
+ mItemId(itemId),
+ mNumberOfColumns(numberOfColumns),
+ mColumnNumber(columnNumber),
+ mHeightScale(heightScale),
+ mDepthScale(depthScale)
{
}
- inline void Orientation0( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void Orientation0(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
- float rowLayoutPositon = layoutPosition - static_cast< float >( mColumnNumber );
+ float rowLayoutPositon = layoutPosition - static_cast<float>(mColumnNumber);
- current.x = GetColumnPosition( mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.width );
+ current.x = GetColumnPosition(mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.width);
current.y = rowLayoutPositon * mHeightScale + layoutSize.height * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.height - mItemSize.height * 0.5f;
current.z = -rowLayoutPositon * mDepthScale;
}
- inline void Orientation90( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void Orientation90(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
- float rowLayoutPositon = layoutPosition - static_cast< float >( mColumnNumber ) + mNumberOfColumns * 0.5f;
+ float rowLayoutPositon = layoutPosition - static_cast<float>(mColumnNumber) + mNumberOfColumns * 0.5f;
current.x = rowLayoutPositon * mHeightScale + layoutSize.width * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.width - mItemSize.height * 0.5f;
- current.y = -GetColumnPosition( mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.height );
+ current.y = -GetColumnPosition(mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.height);
current.z = -rowLayoutPositon * mDepthScale;
}
- inline void Orientation180( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void Orientation180(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
- float rowLayoutPositon = layoutPosition - static_cast< float >( mColumnNumber );
+ float rowLayoutPositon = layoutPosition - static_cast<float>(mColumnNumber);
- current.x = -GetColumnPosition( mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.width );
- current.y = -( rowLayoutPositon * mHeightScale + layoutSize.height * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.height - mItemSize.height * 0.5f );
+ current.x = -GetColumnPosition(mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.width);
+ current.y = -(rowLayoutPositon * mHeightScale + layoutSize.height * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.height - mItemSize.height * 0.5f);
current.z = -rowLayoutPositon * mDepthScale;
}
- inline void Orientation270( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void Orientation270(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
- float rowLayoutPositon = layoutPosition - static_cast< float >( mColumnNumber ) + mNumberOfColumns * 0.5f;
+ float rowLayoutPositon = layoutPosition - static_cast<float>(mColumnNumber) + mNumberOfColumns * 0.5f;
- current.x = -( rowLayoutPositon * mHeightScale + layoutSize.width * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.width - mItemSize.height * 0.5f );
- current.y = GetColumnPosition( mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.height );
+ current.x = -(rowLayoutPositon * mHeightScale + layoutSize.width * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.width - mItemSize.height * 0.5f);
+ current.y = GetColumnPosition(mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.height);
current.z = -rowLayoutPositon * mDepthScale;
}
- void Orientation0( Vector3& current, const PropertyInputContainer& inputs )
+ void Orientation0(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- Orientation0( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ Orientation0(current, layoutPosition, layoutSize);
}
- void Orientation90( Vector3& current, const PropertyInputContainer& inputs )
+ void Orientation90(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- Orientation90( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ Orientation90(current, layoutPosition, layoutSize);
}
- void Orientation180( Vector3& current, const PropertyInputContainer& inputs )
+ void Orientation180(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- Orientation180( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ Orientation180(current, layoutPosition, layoutSize);
}
- void Orientation270( Vector3& current, const PropertyInputContainer& inputs )
+ void Orientation270(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- Orientation270( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ Orientation270(current, layoutPosition, layoutSize);
}
- Vector3 mItemSize;
+ Vector3 mItemSize;
unsigned int mItemId;
unsigned int mNumberOfColumns;
unsigned int mColumnNumber;
- float mHeightScale;
- float mDepthScale;
+ float mHeightScale;
+ float mDepthScale;
};
struct DepthRotationConstraint
{
- DepthRotationConstraint( Radian angleRadians, ControlOrientation::Type orientation )
- : mTiltAngle( angleRadians ),
- mMultiplier( 0.0f )
+ DepthRotationConstraint(Radian angleRadians, ControlOrientation::Type orientation)
+ : mTiltAngle(angleRadians),
+ mMultiplier(0.0f)
{
- if ( orientation == ControlOrientation::Up )
+ if(orientation == ControlOrientation::Up)
{
mMultiplier = 0.0f;
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
mMultiplier = 1.5f;
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
mMultiplier = -1.0f;
}
}
}
- void operator()( Quaternion& current, const PropertyInputContainer& /* inputs */ )
+ void operator()(Quaternion& current, const PropertyInputContainer& /* inputs */)
{
- current = Quaternion( Radian( mMultiplier * Math::PI ), Vector3::ZAXIS ) * Quaternion( mTiltAngle, Vector3::XAXIS );
+ current = Quaternion(Radian(mMultiplier * Math::PI), Vector3::ZAXIS) * Quaternion(mTiltAngle, Vector3::XAXIS);
}
Radian mTiltAngle;
- float mMultiplier;
+ float mMultiplier;
};
struct DepthColorConstraint
{
- DepthColorConstraint( unsigned int itemId, unsigned int numberOfColumns, float numberOfRows, unsigned int columnNumber )
- : mItemId( itemId ),
- mNumberOfColumns( numberOfColumns ),
- mNumberOfRows( numberOfRows ),
- mColumnNumber( columnNumber )
+ DepthColorConstraint(unsigned int itemId, unsigned int numberOfColumns, float numberOfRows, unsigned int columnNumber)
+ : mItemId(itemId),
+ mNumberOfColumns(numberOfColumns),
+ mNumberOfRows(numberOfRows),
+ mColumnNumber(columnNumber)
{
}
- void operator()( Vector4& current, const Dali::PropertyInputContainer& inputs )
+ void operator()(Vector4& current, const Dali::PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- float row = ( layoutPosition - static_cast<float>( mColumnNumber ) ) / mNumberOfColumns;
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ float row = (layoutPosition - static_cast<float>(mColumnNumber)) / mNumberOfColumns;
float darkness(1.0f);
float alpha(1.0f);
- if (row < 0.0f)
+ if(row < 0.0f)
{
darkness = alpha = std::max(0.0f, 1.0f + row);
}
else
{
- if (row > mNumberOfRows)
+ if(row > mNumberOfRows)
{
darkness = 0.0f;
}
else
{
- darkness = 1.0f - ( 1.0f * (row / mNumberOfRows) );
+ darkness = 1.0f - (1.0f * (row / mNumberOfRows));
}
- if (row > (mNumberOfRows-1.0f))
+ if(row > (mNumberOfRows - 1.0f))
{
- alpha = std::max(0.0f, 1.0f - (row-(mNumberOfRows-1.0f)));
+ alpha = std::max(0.0f, 1.0f - (row - (mNumberOfRows - 1.0f)));
}
}
unsigned int mItemId;
unsigned int mNumberOfColumns;
- float mNumberOfRows;
+ float mNumberOfRows;
unsigned int mColumnNumber;
};
struct DepthVisibilityConstraint
{
- DepthVisibilityConstraint( unsigned int itemId, unsigned int numberOfColumns, float numberOfRows, unsigned int columnNumber )
- : mItemId( itemId ),
+ DepthVisibilityConstraint(unsigned int itemId, unsigned int numberOfColumns, float numberOfRows, unsigned int columnNumber)
+ : mItemId(itemId),
mNumberOfColumns(numberOfColumns),
mNumberOfRows(numberOfRows),
mColumnNumber(columnNumber)
{
}
- void operator()( bool& current, const Dali::PropertyInputContainer& inputs )
+ void operator()(bool& current, const Dali::PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- float row = ( layoutPosition - static_cast< float >( mColumnNumber ) ) / mNumberOfColumns;
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ float row = (layoutPosition - static_cast<float>(mColumnNumber)) / mNumberOfColumns;
- current = ( row > -1.0f ) && ( row < mNumberOfRows );
+ current = (row > -1.0f) && (row < mNumberOfRows);
}
unsigned int mItemId;
unsigned int mNumberOfColumns;
- float mNumberOfRows;
+ float mNumberOfRows;
unsigned int mColumnNumber;
};
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
struct DepthLayout::Impl
{
Impl()
void DepthLayout::SetTiltAngle(Degree angle)
{
- mImpl->mTiltAngle = Degree( Clamp( angle, -45.0f, 45.0f ) );
+ mImpl->mTiltAngle = Degree(Clamp(angle, -45.0f, 45.0f));
}
Degree DepthLayout::GetTiltAngle() const
{
- return Degree( mImpl->mTiltAngle );
+ return Degree(mImpl->mTiltAngle);
}
void DepthLayout::SetItemTiltAngle(Degree angle)
Degree DepthLayout::GetItemTiltAngle() const
{
- return Degree( mImpl->mItemTiltAngle );
+ return Degree(mImpl->mItemTiltAngle);
}
void DepthLayout::SetScrollSpeedFactor(float scrollSpeed)
float DepthLayout::GetItemScrollToPosition(unsigned int itemId) const
{
- float rowIndex = static_cast< float >( itemId ) / mImpl->mNumberOfColumns;
+ float rowIndex = static_cast<float>(itemId) / mImpl->mNumberOfColumns;
return -rowIndex * static_cast<float>(mImpl->mNumberOfColumns);
}
ItemRange DepthLayout::GetItemsWithinArea(float firstItemPosition, Vector3 layoutSize) const
{
- float firstRow = -(firstItemPosition/mImpl->mNumberOfColumns);
- float lastRow = firstRow + mImpl->mNumberOfRows * 0.5f;
+ float firstRow = -(firstItemPosition / mImpl->mNumberOfColumns);
+ float lastRow = firstRow + mImpl->mNumberOfRows * 0.5f;
unsigned int firstItem = static_cast<unsigned int>(std::max(0.0f, firstRow * mImpl->mNumberOfColumns));
- unsigned int lastItem = static_cast<unsigned int>(std::max(0.0f, lastRow * mImpl->mNumberOfColumns));
+ unsigned int lastItem = static_cast<unsigned int>(std::max(0.0f, lastRow * mImpl->mNumberOfColumns));
- return ItemRange(firstItem, lastItem+1);
+ return ItemRange(firstItem, lastItem + 1);
}
unsigned int DepthLayout::GetReserveItemCount(Vector3 layoutSize) const
return static_cast<unsigned int>(itemsWithinLayout);
}
-void DepthLayout::GetDefaultItemSize( unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize ) const
+void DepthLayout::GetDefaultItemSize(unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize) const
{
// 1x1 aspect ratio
- itemSize.width = itemSize.height = itemSize.depth = ( IsVertical( GetOrientation() ) ? layoutSize.width : layoutSize.height ) / static_cast<float>( mImpl->mNumberOfColumns + 1 );
+ itemSize.width = itemSize.height = itemSize.depth = (IsVertical(GetOrientation()) ? layoutSize.width : layoutSize.height) / static_cast<float>(mImpl->mNumberOfColumns + 1);
}
Degree DepthLayout::GetScrollDirection() const
{
- Degree scrollDirection(0.0f);
+ Degree scrollDirection(0.0f);
ControlOrientation::Type orientation = GetOrientation();
- if ( orientation == ControlOrientation::Up )
+ if(orientation == ControlOrientation::Up)
{
- scrollDirection = Degree( 180.0f );
+ scrollDirection = Degree(180.0f);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- scrollDirection = Degree( 270.0f );
+ scrollDirection = Degree(270.0f);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- scrollDirection = Degree( 0.0f );
+ scrollDirection = Degree(0.0f);
}
else // orientation == ControlOrientation::Right
{
- scrollDirection = Degree( 90.0f );
+ scrollDirection = Degree(90.0f);
}
return scrollDirection;
}
-void DepthLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor )
+void DepthLayout::ApplyConstraints(Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor)
{
-
- Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast( itemViewActor );
- if( itemView )
+ Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(itemViewActor);
+ if(itemView)
{
Vector3 itemSize;
- GetItemSize( itemId, layoutSize, itemSize );
+ GetItemSize(itemId, layoutSize, itemSize);
ControlOrientation::Type orientation = GetOrientation();
// Position constraint
- Constraint constraint;
- DepthPositionConstraint depthPositionStruct( itemId,
- mImpl->mNumberOfColumns,
- itemId % mImpl->mNumberOfColumns,
- itemSize,
- -sinf( mImpl->mTiltAngle ) * mImpl->mRowSpacing,
- cosf( mImpl->mTiltAngle ) * mImpl->mRowSpacing );
- if ( orientation == ControlOrientation::Up )
+ Constraint constraint;
+ DepthPositionConstraint depthPositionStruct(itemId,
+ mImpl->mNumberOfColumns,
+ itemId % mImpl->mNumberOfColumns,
+ itemSize,
+ -sinf(mImpl->mTiltAngle) * mImpl->mRowSpacing,
+ cosf(mImpl->mTiltAngle) * mImpl->mRowSpacing);
+ if(orientation == ControlOrientation::Up)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation0 );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation0);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation90 );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation90);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation180 );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation180);
}
else // orientation == ControlOrientation::Right
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation270 );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation270);
}
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
- constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
+ constraint.AddSource(ParentSource(Actor::Property::SIZE));
constraint.Apply();
// Rotation constraint
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, DepthRotationConstraint( mImpl->mItemTiltAngle, orientation ) );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, DepthRotationConstraint(mImpl->mItemTiltAngle, orientation));
constraint.Apply();
// Color constraint
- constraint = Constraint::New< Vector4 >( actor, Actor::Property::COLOR, DepthColorConstraint( itemId, mImpl->mNumberOfColumns, mImpl->mNumberOfRows*0.5f, itemId % mImpl->mNumberOfColumns ) );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
- constraint.SetRemoveAction( Dali::Constraint::DISCARD );
+ constraint = Constraint::New<Vector4>(actor, Actor::Property::COLOR, DepthColorConstraint(itemId, mImpl->mNumberOfColumns, mImpl->mNumberOfRows * 0.5f, itemId % mImpl->mNumberOfColumns));
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
+ constraint.SetRemoveAction(Dali::Constraint::DISCARD);
constraint.Apply();
// Visibility constraint
- constraint = Constraint::New< bool >( actor, Actor::Property::VISIBLE, DepthVisibilityConstraint( itemId, mImpl->mNumberOfColumns, mImpl->mNumberOfRows*0.5f, itemId % mImpl->mNumberOfColumns ) );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
- constraint.SetRemoveAction( Dali::Constraint::DISCARD );
+ constraint = Constraint::New<bool>(actor, Actor::Property::VISIBLE, DepthVisibilityConstraint(itemId, mImpl->mNumberOfColumns, mImpl->mNumberOfRows * 0.5f, itemId % mImpl->mNumberOfColumns));
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
+ constraint.SetRemoveAction(Dali::Constraint::DISCARD);
constraint.Apply();
}
}
void DepthLayout::SetDepthLayoutProperties(const Property::Map& properties)
{
// Set any properties specified for DepthLayout.
- for( unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx )
+ for(unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx)
{
- KeyValuePair propertyPair = properties.GetKeyValue( idx );
+ KeyValuePair propertyPair = properties.GetKeyValue(idx);
switch(DefaultItemLayoutProperty::Property(propertyPair.first.indexKey))
{
case DefaultItemLayoutProperty::DEPTH_COLUMN_NUMBER:
}
}
-Vector3 DepthLayout::GetItemPosition( int itemID, float currentLayoutPosition, const Vector3& layoutSize ) const
+Vector3 DepthLayout::GetItemPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) const
{
Vector3 itemPosition = Vector3::ZERO;
- const float heightScale = -sinf( mImpl->mTiltAngle ) * mImpl->mRowSpacing;
- const float depthScale = cosf( mImpl->mTiltAngle ) * mImpl->mRowSpacing;
+ const float heightScale = -sinf(mImpl->mTiltAngle) * mImpl->mRowSpacing;
+ const float depthScale = cosf(mImpl->mTiltAngle) * mImpl->mRowSpacing;
Vector3 itemSize;
- GetItemSize( itemID, layoutSize, itemSize );
- DepthPositionConstraint positionFunctor = DepthPositionConstraint( itemID,
- mImpl->mNumberOfColumns,
- itemID % mImpl->mNumberOfColumns,
- itemSize,
- heightScale,
- depthScale );
- ControlOrientation::Type orientation = GetOrientation();
- if ( orientation == ControlOrientation::Up )
+ GetItemSize(itemID, layoutSize, itemSize);
+ DepthPositionConstraint positionFunctor = DepthPositionConstraint(itemID,
+ mImpl->mNumberOfColumns,
+ itemID % mImpl->mNumberOfColumns,
+ itemSize,
+ heightScale,
+ depthScale);
+ ControlOrientation::Type orientation = GetOrientation();
+ if(orientation == ControlOrientation::Up)
{
- positionFunctor.Orientation0( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionFunctor.Orientation0(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- positionFunctor.Orientation90( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionFunctor.Orientation90(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- positionFunctor.Orientation180( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionFunctor.Orientation180(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
else // orientation == ControlOrientation::Right
{
- positionFunctor.Orientation270( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionFunctor.Orientation270(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
return itemPosition;
float DepthLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize)
{
float scrollTo = currentLayoutPosition;
- float row = (currentLayoutPosition + itemID - static_cast<float>(itemID % mImpl->mNumberOfColumns)) / mImpl->mNumberOfColumns;
+ float row = (currentLayoutPosition + itemID - static_cast<float>(itemID % mImpl->mNumberOfColumns)) / mImpl->mNumberOfColumns;
// Check whether item is not within viewable area
if(row <= -1.0f)
int DepthLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
{
- switch( direction )
+ switch(direction)
{
case Toolkit::Control::KeyboardFocus::LEFT:
{
itemID--;
- if( itemID < 0 )
+ if(itemID < 0)
{
itemID = loopEnabled ? maxItems - 1 : 0;
}
case Toolkit::Control::KeyboardFocus::UP:
{
itemID += mImpl->mNumberOfColumns;
- if( itemID >= maxItems )
+ if(itemID >= maxItems)
{
itemID = loopEnabled ? 0 : itemID - mImpl->mNumberOfColumns;
}
case Toolkit::Control::KeyboardFocus::RIGHT:
{
itemID++;
- if( itemID >= maxItems )
+ if(itemID >= maxItems)
{
itemID = loopEnabled ? 0 : maxItems - 1;
}
case Toolkit::Control::KeyboardFocus::DOWN:
{
itemID -= mImpl->mNumberOfColumns;
- if( itemID < 0 )
+ if(itemID < 0)
{
itemID = loopEnabled ? itemID + maxItems : itemID + mImpl->mNumberOfColumns;
}
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/scrollable/item-view/grid-layout.h>
// EXTERNAL INCLUDES
-#include <algorithm>
#include <dali/public-api/animation/animation.h>
#include <dali/public-api/animation/constraint.h>
+#include <algorithm>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h>
#include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h>
+#include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h>
using namespace Dali;
using namespace Dali::Toolkit;
namespace // unnamed namespace
{
-
-const unsigned int DEFAULT_NUMBER_OF_COLUMNS = 4;
-const float DEFAULT_TOP_MARGIN = 95.0f;
-const float DEFAULT_BOTTOM_MARGIN = 20.0f;
-const float DEFAULT_SIDE_MARGIN = 20.0f;
-const float DEFAULT_COLUMN_SPACING = 20.0f;
-const float DEFAULT_ROW_SPACING = 20.0f;
-const float DEFAULT_SCROLL_SPEED_FACTOR = 0.03f;
-const float DEFAULT_MAXIMUM_SWIPE_SPEED = 100.0f;
-const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.015f;
+const unsigned int DEFAULT_NUMBER_OF_COLUMNS = 4;
+const float DEFAULT_TOP_MARGIN = 95.0f;
+const float DEFAULT_BOTTOM_MARGIN = 20.0f;
+const float DEFAULT_SIDE_MARGIN = 20.0f;
+const float DEFAULT_COLUMN_SPACING = 20.0f;
+const float DEFAULT_ROW_SPACING = 20.0f;
+const float DEFAULT_SCROLL_SPEED_FACTOR = 0.03f;
+const float DEFAULT_MAXIMUM_SWIPE_SPEED = 100.0f;
+const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.015f;
struct GridPositionConstraint
{
GridPositionConstraint(
- unsigned int itemId,
- const unsigned int columnIndex,
- const unsigned int numberOfColumns,
- const float rowSpacing,
- const float columnSpacing,
- const float topMargin,
- const float sideMargin,
- const Vector3& itemSize,
- const float gap )
- : mItemSize( itemSize ),
- mItemId( itemId ),
- mColumnIndex( columnIndex ),
- mNumberOfColumns( numberOfColumns ),
- mRowSpacing( rowSpacing ),
- mColumnSpacing( columnSpacing ),
- mTopMargin( topMargin ),
- mSideMargin( sideMargin ),
- mZGap( gap )
+ unsigned int itemId,
+ const unsigned int columnIndex,
+ const unsigned int numberOfColumns,
+ const float rowSpacing,
+ const float columnSpacing,
+ const float topMargin,
+ const float sideMargin,
+ const Vector3& itemSize,
+ const float gap)
+ : mItemSize(itemSize),
+ mItemId(itemId),
+ mColumnIndex(columnIndex),
+ mNumberOfColumns(numberOfColumns),
+ mRowSpacing(rowSpacing),
+ mColumnSpacing(columnSpacing),
+ mTopMargin(topMargin),
+ mSideMargin(sideMargin),
+ mZGap(gap)
{
}
- inline void Orientation0( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void Orientation0(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
- current.x = mSideMargin + ( mColumnIndex * ( mItemSize.x + mColumnSpacing ) ) + mItemSize.x * 0.5f - layoutSize.x * 0.5f;
- current.y = ( ( mItemSize.y + mRowSpacing ) * ( layoutPosition - mColumnIndex) ) / mNumberOfColumns - layoutSize.height * 0.5f + mItemSize.y * 0.5f + mTopMargin;
+ current.x = mSideMargin + (mColumnIndex * (mItemSize.x + mColumnSpacing)) + mItemSize.x * 0.5f - layoutSize.x * 0.5f;
+ current.y = ((mItemSize.y + mRowSpacing) * (layoutPosition - mColumnIndex)) / mNumberOfColumns - layoutSize.height * 0.5f + mItemSize.y * 0.5f + mTopMargin;
current.z = mColumnIndex * mZGap;
}
- inline void Orientation90( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void Orientation90(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
- current.x = ( ( mItemSize.y + mRowSpacing ) * ( layoutPosition - mColumnIndex ) ) / mNumberOfColumns - layoutSize.width * 0.5f + mItemSize.y * 0.5f + mTopMargin;
- current.y = -( mSideMargin + ( mColumnIndex * ( mItemSize.x + mColumnSpacing ) ) + mItemSize.x * 0.5f - layoutSize.y * 0.5f );
+ current.x = ((mItemSize.y + mRowSpacing) * (layoutPosition - mColumnIndex)) / mNumberOfColumns - layoutSize.width * 0.5f + mItemSize.y * 0.5f + mTopMargin;
+ current.y = -(mSideMargin + (mColumnIndex * (mItemSize.x + mColumnSpacing)) + mItemSize.x * 0.5f - layoutSize.y * 0.5f);
current.z = mColumnIndex * mZGap;
}
- inline void Orientation180( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void Orientation180(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
current.x = -(mSideMargin + (mColumnIndex * (mItemSize.x + mColumnSpacing)) + mItemSize.x * 0.5f - layoutSize.x * 0.5f);
- current.y = -( ( ( mItemSize.y + mRowSpacing ) * ( layoutPosition - mColumnIndex ) ) / mNumberOfColumns - layoutSize.height * 0.5f + mItemSize.y * 0.5f + mTopMargin );
+ current.y = -(((mItemSize.y + mRowSpacing) * (layoutPosition - mColumnIndex)) / mNumberOfColumns - layoutSize.height * 0.5f + mItemSize.y * 0.5f + mTopMargin);
current.z = mColumnIndex * mZGap;
}
- inline void Orientation270( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void Orientation270(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
- current.x = -( ( ( mItemSize.y + mRowSpacing ) * ( layoutPosition - mColumnIndex ) ) / mNumberOfColumns - layoutSize.width * 0.5f + mItemSize.y * 0.5f + mTopMargin );
- current.y = mSideMargin + ( mColumnIndex * ( mItemSize.x + mColumnSpacing ) ) + mItemSize.x * 0.5f - layoutSize.y * 0.5f;
+ current.x = -(((mItemSize.y + mRowSpacing) * (layoutPosition - mColumnIndex)) / mNumberOfColumns - layoutSize.width * 0.5f + mItemSize.y * 0.5f + mTopMargin);
+ current.y = mSideMargin + (mColumnIndex * (mItemSize.x + mColumnSpacing)) + mItemSize.x * 0.5f - layoutSize.y * 0.5f;
current.z = mColumnIndex * mZGap;
}
- void Orientation0( Vector3& current, const PropertyInputContainer& inputs )
+ void Orientation0(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- Orientation0( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ Orientation0(current, layoutPosition, layoutSize);
}
- void Orientation90( Vector3& current, const PropertyInputContainer& inputs )
+ void Orientation90(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- Orientation90( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ Orientation90(current, layoutPosition, layoutSize);
}
- void Orientation180( Vector3& current, const PropertyInputContainer& inputs )
+ void Orientation180(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- Orientation180( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ Orientation180(current, layoutPosition, layoutSize);
}
- void Orientation270( Vector3& current, const PropertyInputContainer& inputs )
+ void Orientation270(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- Orientation270( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ Orientation270(current, layoutPosition, layoutSize);
}
public:
-
- Vector3 mItemSize;
+ Vector3 mItemSize;
unsigned int mItemId;
unsigned int mColumnIndex;
unsigned int mNumberOfColumns;
- float mRowSpacing;
- float mColumnSpacing;
- float mTopMargin;
- float mSideMargin;
- float mZGap;
+ float mRowSpacing;
+ float mColumnSpacing;
+ float mTopMargin;
+ float mSideMargin;
+ float mZGap;
};
-void GridRotationConstraint0( Quaternion& current, const PropertyInputContainer& /* inputs */ )
+void GridRotationConstraint0(Quaternion& current, const PropertyInputContainer& /* inputs */)
{
- current = Quaternion( Radian( 0.0f ), Vector3::ZAXIS );
+ current = Quaternion(Radian(0.0f), Vector3::ZAXIS);
}
-void GridRotationConstraint90( Quaternion& current, const PropertyInputContainer& /* inputs */ )
+void GridRotationConstraint90(Quaternion& current, const PropertyInputContainer& /* inputs */)
{
- current = Quaternion( Radian( 1.5f * Math::PI ), Vector3::ZAXIS );
+ current = Quaternion(Radian(1.5f * Math::PI), Vector3::ZAXIS);
}
-void GridRotationConstraint180( Quaternion& current, const PropertyInputContainer& /* inputs */ )
+void GridRotationConstraint180(Quaternion& current, const PropertyInputContainer& /* inputs */)
{
- current = Quaternion( Radian( Math::PI ), Vector3::ZAXIS );
+ current = Quaternion(Radian(Math::PI), Vector3::ZAXIS);
}
-void GridRotationConstraint270( Quaternion& current, const PropertyInputContainer& /* inputs */ )
+void GridRotationConstraint270(Quaternion& current, const PropertyInputContainer& /* inputs */)
{
- current = Quaternion( Radian( 0.5f * Math::PI ), Vector3::ZAXIS );
+ current = Quaternion(Radian(0.5f * Math::PI), Vector3::ZAXIS);
}
-void GridColorConstraint( Vector4& current, const PropertyInputContainer& /* inputs */ )
+void GridColorConstraint(Vector4& current, const PropertyInputContainer& /* inputs */)
{
current.r = current.g = current.b = 1.0f;
}
struct GridVisibilityConstraint
{
GridVisibilityConstraint(
- unsigned int itemId,
- const unsigned int columnIndex,
- const unsigned int numberOfColumns,
- const float rowSpacing,
- const float columnSpacing,
- const float sideMargin,
- const Vector3& itemSize )
- : mItemSize( itemSize ),
- mItemId( itemId ),
- mColumnIndex( columnIndex ),
- mNumberOfColumns( numberOfColumns ),
- mRowSpacing( rowSpacing ),
- mColumnSpacing( columnSpacing ),
- mSideMargin( sideMargin )
+ unsigned int itemId,
+ const unsigned int columnIndex,
+ const unsigned int numberOfColumns,
+ const float rowSpacing,
+ const float columnSpacing,
+ const float sideMargin,
+ const Vector3& itemSize)
+ : mItemSize(itemSize),
+ mItemId(itemId),
+ mColumnIndex(columnIndex),
+ mNumberOfColumns(numberOfColumns),
+ mRowSpacing(rowSpacing),
+ mColumnSpacing(columnSpacing),
+ mSideMargin(sideMargin)
{
}
- void Portrait( bool& current, const PropertyInputContainer& inputs )
+ void Portrait(bool& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
- float row = ( layoutPosition - static_cast< float >( mColumnIndex ) ) / mNumberOfColumns;
- int rowsPerPage = ceil( layoutSize.height / ( mItemSize.y + mRowSpacing ) );
+ float row = (layoutPosition - static_cast<float>(mColumnIndex)) / mNumberOfColumns;
+ int rowsPerPage = ceil(layoutSize.height / (mItemSize.y + mRowSpacing));
- current = ( row > -2.0f ) && ( row < rowsPerPage );
+ current = (row > -2.0f) && (row < rowsPerPage);
}
- void Landscape( bool& current, const PropertyInputContainer& inputs )
+ void Landscape(bool& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
- float row = ( layoutPosition - static_cast< float >( mColumnIndex ) ) / mNumberOfColumns;
- int rowsPerPage = ceil( layoutSize.width / ( mItemSize.y + mRowSpacing ) );
+ float row = (layoutPosition - static_cast<float>(mColumnIndex)) / mNumberOfColumns;
+ int rowsPerPage = ceil(layoutSize.width / (mItemSize.y + mRowSpacing));
- current = ( row > -2.0f ) && ( row < rowsPerPage );
+ current = (row > -2.0f) && (row < rowsPerPage);
}
public:
-
- Vector3 mItemSize;
+ Vector3 mItemSize;
unsigned int mItemId;
unsigned int mColumnIndex;
unsigned int mNumberOfColumns;
- float mRowSpacing;
- float mColumnSpacing;
- float mSideMargin;
+ float mRowSpacing;
+ float mColumnSpacing;
+ float mSideMargin;
};
} // unnamed namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
struct GridLayout::Impl
{
Impl()
}
unsigned int mNumberOfColumns;
- float mRowSpacing;
- float mColumnSpacing;
- float mTopMargin;
- float mBottomMargin;
- float mSideMargin;
- float mZGap;
+ float mRowSpacing;
+ float mColumnSpacing;
+ float mTopMargin;
+ float mBottomMargin;
+ float mSideMargin;
+ float mZGap;
float mScrollSpeedFactor;
float mMaximumSwipeSpeed;
float GridLayout::GetMinimumLayoutPosition(unsigned int numberOfItems, Vector3 layoutSize) const
{
- float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height;
+ float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height;
Vector3 itemSize;
- GetItemSize( 0, layoutSize, itemSize );
+ GetItemSize(0, layoutSize, itemSize);
unsigned int itemsLastRow = numberOfItems % mImpl->mNumberOfColumns;
- if (itemsLastRow == 0)
+ if(itemsLastRow == 0)
{
itemsLastRow = mImpl->mNumberOfColumns;
}
- float rowsLastPage = (layoutHeight - mImpl->mBottomMargin - mImpl->mTopMargin + mImpl->mRowSpacing) / (itemSize.y + mImpl->mRowSpacing);
+ float rowsLastPage = (layoutHeight - mImpl->mBottomMargin - mImpl->mTopMargin + mImpl->mRowSpacing) / (itemSize.y + mImpl->mRowSpacing);
float itemsLastPage = (rowsLastPage - 1.0f) * static_cast<float>(mImpl->mNumberOfColumns) + static_cast<float>(itemsLastRow);
return itemsLastPage - static_cast<float>(numberOfItems);
float GridLayout::GetItemScrollToPosition(unsigned int itemId) const
{
- float rowIndex = static_cast< float >( itemId ) / mImpl->mNumberOfColumns;
+ float rowIndex = static_cast<float>(itemId) / mImpl->mNumberOfColumns;
return -rowIndex * static_cast<float>(mImpl->mNumberOfColumns);
}
ItemRange GridLayout::GetItemsWithinArea(float firstItemPosition, Vector3 layoutSize) const
{
- float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height;
+ float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height;
Vector3 itemSize;
- GetItemSize( 0, layoutSize, itemSize );
+ GetItemSize(0, layoutSize, itemSize);
- int itemsPerPage = mImpl->mNumberOfColumns * ceil(layoutHeight / (itemSize.y + mImpl->mRowSpacing));
+ int itemsPerPage = mImpl->mNumberOfColumns * ceil(layoutHeight / (itemSize.y + mImpl->mRowSpacing));
int firstVisibleItem = -(static_cast<int>(firstItemPosition / mImpl->mNumberOfColumns)) * mImpl->mNumberOfColumns;
int firstItemIndex = std::max(0, firstVisibleItem - static_cast<int>(mImpl->mNumberOfColumns));
float GridLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize)
{
- Vector3 itemPosition = GetItemPosition( itemID, currentLayoutPosition, layoutSize );
- Vector3 itemSize;
+ Vector3 itemPosition = GetItemPosition(itemID, currentLayoutPosition, layoutSize);
+ Vector3 itemSize;
ControlOrientation::Type orientation = GetOrientation();
GetItemSize(itemID, layoutSize, itemSize);
- Vector3 onScreenArea = ( layoutSize - ( IsVertical( orientation ) ? itemSize : Vector3( itemSize.y, itemSize.x, itemSize.z ) ) ) * 0.5f;
- if (itemPosition.x < -onScreenArea.x
- || itemPosition.x > onScreenArea.x
- || itemPosition.y < -onScreenArea.y
- || itemPosition.y > onScreenArea.y)
+ Vector3 onScreenArea = (layoutSize - (IsVertical(orientation) ? itemSize : Vector3(itemSize.y, itemSize.x, itemSize.z))) * 0.5f;
+ if(itemPosition.x < -onScreenArea.x || itemPosition.x > onScreenArea.x || itemPosition.y < -onScreenArea.y || itemPosition.y > onScreenArea.y)
{
// item not within viewable area
- float rowHeight = itemSize.y + mImpl->mRowSpacing;
- Vector3 firstItemPosition = GetItemPosition( itemID, 0.0f, layoutSize );
- float offset = 0.0f;
- switch( orientation )
+ float rowHeight = itemSize.y + mImpl->mRowSpacing;
+ Vector3 firstItemPosition = GetItemPosition(itemID, 0.0f, layoutSize);
+ float offset = 0.0f;
+ switch(orientation)
{
case ControlOrientation::Up:
{
}
}
// work out number of rows from first item position to an item aligned to bottom of screen
- float rowDiff = offset / rowHeight;
+ float rowDiff = offset / rowHeight;
float layoutPositionOffset = rowDiff * mImpl->mNumberOfColumns;
- float scrollTo = GetItemScrollToPosition(itemID) + layoutPositionOffset;
+ float scrollTo = GetItemScrollToPosition(itemID) + layoutPositionOffset;
return scrollTo;
}
return currentLayoutPosition;
unsigned int GridLayout::GetReserveItemCount(Vector3 layoutSize) const
{
- float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height;
+ float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height;
Vector3 itemSize;
- GetItemSize( 0, layoutSize, itemSize );
+ GetItemSize(0, layoutSize, itemSize);
int itemsPerPage = mImpl->mNumberOfColumns * ceil(layoutHeight / (itemSize.y + mImpl->mRowSpacing));
return itemsPerPage;
}
-void GridLayout::GetDefaultItemSize( unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize ) const
+void GridLayout::GetDefaultItemSize(unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize) const
{
- float layoutWidth = IsHorizontal( GetOrientation() ) ? layoutSize.height : layoutSize.width;
- itemSize.width = ( layoutWidth - mImpl->mSideMargin * 2.0f - mImpl->mColumnSpacing * static_cast<float>( mImpl->mNumberOfColumns - 1 ) ) / static_cast<float>( mImpl->mNumberOfColumns );
+ float layoutWidth = IsHorizontal(GetOrientation()) ? layoutSize.height : layoutSize.width;
+ itemSize.width = (layoutWidth - mImpl->mSideMargin * 2.0f - mImpl->mColumnSpacing * static_cast<float>(mImpl->mNumberOfColumns - 1)) / static_cast<float>(mImpl->mNumberOfColumns);
// 4x3 aspect ratio
itemSize.height = itemSize.depth = itemSize.width * 0.75f;
Degree GridLayout::GetScrollDirection() const
{
- Degree scrollDirection(0.0f);
+ Degree scrollDirection(0.0f);
ControlOrientation::Type orientation = GetOrientation();
- if ( orientation == ControlOrientation::Up )
+ if(orientation == ControlOrientation::Up)
{
- scrollDirection = Degree( 0.0f );
+ scrollDirection = Degree(0.0f);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- scrollDirection = Degree( 90.0f );
+ scrollDirection = Degree(90.0f);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- scrollDirection = Degree( 180.0f );
+ scrollDirection = Degree(180.0f);
}
else // orientation == ControlOrientation::Right
{
- scrollDirection = Degree( 270.0f );
+ scrollDirection = Degree(270.0f);
}
return scrollDirection;
}
-void GridLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor )
+void GridLayout::ApplyConstraints(Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor)
{
// This just implements the default behaviour of constraint application.
// Custom layouts can override this function to apply their custom constraints.
- Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast( itemViewActor );
- if( itemView )
+ Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(itemViewActor);
+ if(itemView)
{
Vector3 itemSize;
- GetItemSize( itemId, layoutSize, itemSize );
- const unsigned int columnIndex = itemId % mImpl->mNumberOfColumns;
+ GetItemSize(itemId, layoutSize, itemSize);
+ const unsigned int columnIndex = itemId % mImpl->mNumberOfColumns;
const ControlOrientation::Type orientation = GetOrientation();
// Position constraint
- GridPositionConstraint positionConstraint( itemId,
- columnIndex,
- mImpl->mNumberOfColumns,
- mImpl->mRowSpacing,
- mImpl->mColumnSpacing,
- mImpl->mTopMargin,
- mImpl->mSideMargin,
- itemSize,
- mImpl->mZGap );
- Constraint constraint;
- if ( orientation == ControlOrientation::Up )
+ GridPositionConstraint positionConstraint(itemId,
+ columnIndex,
+ mImpl->mNumberOfColumns,
+ mImpl->mRowSpacing,
+ mImpl->mColumnSpacing,
+ mImpl->mTopMargin,
+ mImpl->mSideMargin,
+ itemSize,
+ mImpl->mZGap);
+ Constraint constraint;
+ if(orientation == ControlOrientation::Up)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation0 );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation0);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation90 );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation90);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation180 );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation180);
}
else // orientation == ControlOrientation::Right
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation270 );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation270);
}
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
- constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
+ constraint.AddSource(ParentSource(Actor::Property::SIZE));
constraint.Apply();
// Rotation constraint
- if ( orientation == ControlOrientation::Up )
+ if(orientation == ControlOrientation::Up)
{
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, &GridRotationConstraint0 );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, &GridRotationConstraint0);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, &GridRotationConstraint90 );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, &GridRotationConstraint90);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, &GridRotationConstraint180 );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, &GridRotationConstraint180);
}
else // orientation == ControlOrientation::Right
{
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, &GridRotationConstraint270 );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, &GridRotationConstraint270);
}
constraint.Apply();
// Color constraint
- constraint = Constraint::New< Vector4 >( actor, Actor::Property::COLOR, &GridColorConstraint );
- constraint.SetRemoveAction( Dali::Constraint::DISCARD );
+ constraint = Constraint::New<Vector4>(actor, Actor::Property::COLOR, &GridColorConstraint);
+ constraint.SetRemoveAction(Dali::Constraint::DISCARD);
constraint.Apply();
// Visibility constraint
- GridVisibilityConstraint visibilityConstraint( itemId,
- columnIndex,
- mImpl->mNumberOfColumns,
- mImpl->mRowSpacing,
- mImpl->mColumnSpacing,
- mImpl->mSideMargin,
- itemSize );
- if ( IsVertical( orientation ) )
+ GridVisibilityConstraint visibilityConstraint(itemId,
+ columnIndex,
+ mImpl->mNumberOfColumns,
+ mImpl->mRowSpacing,
+ mImpl->mColumnSpacing,
+ mImpl->mSideMargin,
+ itemSize);
+ if(IsVertical(orientation))
{
- constraint = Constraint::New<bool>( actor, Actor::Property::VISIBLE, visibilityConstraint, &GridVisibilityConstraint::Portrait );
+ constraint = Constraint::New<bool>(actor, Actor::Property::VISIBLE, visibilityConstraint, &GridVisibilityConstraint::Portrait);
}
else // horizontal
{
- constraint = Constraint::New<bool>( actor, Actor::Property::VISIBLE, visibilityConstraint, &GridVisibilityConstraint::Landscape );
+ constraint = Constraint::New<bool>(actor, Actor::Property::VISIBLE, visibilityConstraint, &GridVisibilityConstraint::Landscape);
}
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
- constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
- constraint.SetRemoveAction( Dali::Constraint::DISCARD );
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
+ constraint.AddSource(ParentSource(Actor::Property::SIZE));
+ constraint.SetRemoveAction(Dali::Constraint::DISCARD);
constraint.Apply();
}
}
void GridLayout::SetGridLayoutProperties(const Property::Map& properties)
{
// Set any properties specified for gridLayout.
- for( unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx )
+ for(unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx)
{
- KeyValuePair propertyPair = properties.GetKeyValue( idx );
+ KeyValuePair propertyPair = properties.GetKeyValue(idx);
switch(DefaultItemLayoutProperty::Property(propertyPair.first.indexKey))
{
case DefaultItemLayoutProperty::GRID_COLUMN_NUMBER:
Vector3 GridLayout::GetItemPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) const
{
- Vector3 itemPosition = Vector3::ZERO;
- const unsigned int columnIndex = itemID % mImpl->mNumberOfColumns;
- const ControlOrientation::Type orientation = GetOrientation();
- Vector3 itemSize;
- GetItemSize( itemID, layoutSize, itemSize );
-
- GridPositionConstraint positionConstraintStruct( itemID,
- columnIndex,
- mImpl->mNumberOfColumns,
- mImpl->mRowSpacing,
- mImpl->mColumnSpacing,
- mImpl->mTopMargin,
- mImpl->mSideMargin,
- itemSize,
- mImpl->mZGap );
-
- if ( orientation == ControlOrientation::Up )
+ Vector3 itemPosition = Vector3::ZERO;
+ const unsigned int columnIndex = itemID % mImpl->mNumberOfColumns;
+ const ControlOrientation::Type orientation = GetOrientation();
+ Vector3 itemSize;
+ GetItemSize(itemID, layoutSize, itemSize);
+
+ GridPositionConstraint positionConstraintStruct(itemID,
+ columnIndex,
+ mImpl->mNumberOfColumns,
+ mImpl->mRowSpacing,
+ mImpl->mColumnSpacing,
+ mImpl->mTopMargin,
+ mImpl->mSideMargin,
+ itemSize,
+ mImpl->mZGap);
+
+ if(orientation == ControlOrientation::Up)
{
- positionConstraintStruct.Orientation0( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionConstraintStruct.Orientation0(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- positionConstraintStruct.Orientation90( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionConstraintStruct.Orientation90(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- positionConstraintStruct.Orientation180( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionConstraintStruct.Orientation180(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
else // orientation == ControlOrientation::Right
{
- positionConstraintStruct.Orientation270( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionConstraintStruct.Orientation270(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
return itemPosition;
int GridLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
{
- switch( direction )
+ switch(direction)
{
case Toolkit::Control::KeyboardFocus::LEFT:
{
itemID--;
- if( itemID < 0 )
+ if(itemID < 0)
{
itemID = loopEnabled ? maxItems - 1 : 0;
}
case Toolkit::Control::KeyboardFocus::UP:
{
itemID -= mImpl->mNumberOfColumns;
- if( itemID < 0 )
+ if(itemID < 0)
{
itemID = loopEnabled ? itemID + maxItems : itemID + mImpl->mNumberOfColumns;
}
case Toolkit::Control::KeyboardFocus::RIGHT:
{
itemID++;
- if( itemID >= maxItems )
+ if(itemID >= maxItems)
{
itemID = loopEnabled ? 0 : maxItems - 1;
}
case Toolkit::Control::KeyboardFocus::DOWN:
{
itemID += mImpl->mNumberOfColumns;
- if( itemID >= maxItems )
+ if(itemID >= maxItems)
{
itemID = loopEnabled ? 0 : itemID - mImpl->mNumberOfColumns;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/scrollable/item-view/item-view-impl.h>
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
-#include <algorithm>
-#include <dali/public-api/actors/layer.h>
#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/devel-api/common/stage.h>
+#include <dali/devel-api/object/property-helper-devel.h>
+#include <dali/public-api/actors/layer.h>
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/animation/constraints.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/public-api/events/wheel-event.h>
#include <dali/public-api/events/touch-event.h>
-#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/events/wheel-event.h>
#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/devel-api/object/property-helper-devel.h>
+#include <dali/public-api/object/type-registry.h>
+#include <algorithm>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/scroll-bar/scroll-bar.h>
-#include <dali-toolkit/public-api/controls/scrollable/item-view/item-factory.h>
-#include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout.h>
-#include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h>
-#include <dali-toolkit/internal/controls/scrollable/item-view/grid-layout.h>
+#include <dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.h>
#include <dali-toolkit/internal/controls/scrollable/item-view/depth-layout.h>
+#include <dali-toolkit/internal/controls/scrollable/item-view/grid-layout.h>
#include <dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.h>
-#include <dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.h>
+#include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h>
+#include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout.h>
+#include <dali-toolkit/public-api/controls/scrollable/item-view/item-factory.h>
using std::string;
using namespace Dali;
namespace // Unnamed namespace
{
-
-const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f;
-const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f;
+const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f;
+const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f;
const float DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = 0.1f;
const float DEFAULT_MINIMUM_SWIPE_DURATION = 0.45f;
const float DEFAULT_MAXIMUM_SWIPE_DURATION = 2.6f;
const float DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS = 20.0f; // 1 updates per 20 items
-const int WHEEL_EVENT_FINISHED_TIME_OUT = 500; // 0.5 second
+const int WHEEL_EVENT_FINISHED_TIME_OUT = 500; // 0.5 second
-const float DEFAULT_ANCHORING_DURATION = 1.0f; // 1 second
+const float DEFAULT_ANCHORING_DURATION = 1.0f; // 1 second
const float MILLISECONDS_PER_SECONDS = 1000.0f;
-const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f;
+const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f;
const Vector4 OVERSHOOT_OVERLAY_NINE_PATCH_BORDER(0.0f, 0.0f, 1.0f, 12.0f);
-const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f;
+const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f;
const unsigned int OVERSHOOT_SIZE_CONSTRAINT_TAG(42);
// Overshoot overlay constraints
struct OvershootOverlaySizeConstraint
{
- OvershootOverlaySizeConstraint( float height )
- : mOvershootHeight( height )
+ OvershootOverlaySizeConstraint(float height)
+ : mOvershootHeight(height)
{
}
- void operator()( Vector3& current, const PropertyInputContainer& inputs )
+ void operator()(Vector3& current, const PropertyInputContainer& inputs)
{
- const Vector2& parentScrollDirection = inputs[0]->GetVector2();
- const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
- const Vector3& parentSize = inputs[2]->GetVector3();
+ const Vector2& parentScrollDirection = inputs[0]->GetVector2();
+ const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
+ const Vector3& parentSize = inputs[2]->GetVector3();
if(Toolkit::IsVertical(layoutOrientation))
{
current.width = fabsf(parentScrollDirection.x) > Math::MACHINE_EPSILON_1 ? parentSize.y : parentSize.x;
}
- current.height = ( current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD ) ? mOvershootHeight : mOvershootHeight*0.5f;
+ current.height = (current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD) ? mOvershootHeight : mOvershootHeight * 0.5f;
}
float mOvershootHeight;
};
-void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInputContainer& inputs )
+void OvershootOverlayRotationConstraint(Quaternion& current, const PropertyInputContainer& inputs)
{
- const Vector2& parentScrollDirection = inputs[0]->GetVector2();
- const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
- const float parentOvershoot = inputs[2]->GetFloat();
+ const Vector2& parentScrollDirection = inputs[0]->GetVector2();
+ const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
+ const float parentOvershoot = inputs[2]->GetFloat();
float multiplier = 0;
if(Toolkit::IsVertical(layoutOrientation))
{
if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
{
- if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
- || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
+ if((layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0) || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0))
{
multiplier = 0.5f;
}
multiplier = 1.5f;
}
}
- else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
- || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
+ else if((parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0) || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0))
{
multiplier = 0.0f;
}
{
if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
{
- if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0)
- ||(layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0) )
+ if((layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0) || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0))
{
multiplier = 1.0f;
}
multiplier = 0.0f;
}
}
- else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
- || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
+ else if((parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0) || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0))
{
multiplier = 1.5f;
}
}
}
- current = Quaternion( Radian( multiplier * Math::PI ), Vector3::ZAXIS );
+ current = Quaternion(Radian(multiplier * Math::PI), Vector3::ZAXIS);
}
-void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputContainer& inputs )
+void OvershootOverlayPositionConstraint(Vector3& current, const PropertyInputContainer& inputs)
{
- const Vector3& parentSize = inputs[0]->GetVector3();
- const Vector2& parentScrollDirection = inputs[1]->GetVector2();
- const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[2]->GetInteger());
- const float parentOvershoot = inputs[3]->GetFloat();
+ const Vector3& parentSize = inputs[0]->GetVector3();
+ const Vector2& parentScrollDirection = inputs[1]->GetVector2();
+ const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[2]->GetInteger());
+ const float parentOvershoot = inputs[3]->GetFloat();
Vector3 relativeOffset;
{
if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
{
- if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
- || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
+ if((layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0) || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0))
{
relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
}
else
{
- relativeOffset =Vector3(0.0f, 1.0f, 0.0f);
+ relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
}
}
- else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
- || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
+ else if((parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0) || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0))
{
relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
}
{
if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
{
- if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0)
- || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0) )
+ if((layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0) || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0))
{
relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
}
relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
}
}
- else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
- || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
+ else if((parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0) || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0))
{
relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
}
current = relativeOffset * parentSize;
}
-void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputContainer& inputs )
+void OvershootOverlayVisibilityConstraint(bool& current, const PropertyInputContainer& inputs)
{
current = inputs[0]->GetBoolean();
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace // unnamed namespace
{
-
//Type registration
+// clang-format off
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ItemView, Toolkit::Scrollable, nullptr)
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ItemView, Toolkit::Scrollable, NULL)
+DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED )
+DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE )
+DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP)
+DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED )
+DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "layout", ARRAY, LAYOUT )
-DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED )
-DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE )
-DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP )
-DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED )
-DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout", ARRAY, LAYOUT )
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION )
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED )
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT )
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION )
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION )
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE)
+DALI_SIGNAL_REGISTRATION(Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL)
-DALI_SIGNAL_REGISTRATION( Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL )
+DALI_ACTION_REGISTRATION(Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING)
-DALI_ACTION_REGISTRATION( Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING )
-
-DALI_ACTION_REGISTRATION( Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH )
-DALI_ACTION_REGISTRATION( Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH )
+DALI_ACTION_REGISTRATION(Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH )
+DALI_ACTION_REGISTRATION(Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH)
DALI_TYPE_REGISTRATION_END()
+// clang-format on
-const ItemIter FindItemById( ItemContainer& items, ItemId id )
+const ItemIter FindItemById(ItemContainer& items, ItemId id)
{
- for( ItemIter iter = items.begin(); items.end() != iter; ++iter )
+ for(ItemIter iter = items.begin(); items.end() != iter; ++iter)
{
- if( iter->first == id )
+ if(iter->first == id)
{
return iter;
}
return items.end();
}
-void InsertToItemContainer( ItemContainer& items, Item item )
+void InsertToItemContainer(ItemContainer& items, Item item)
{
- if( items.end() == FindItemById( items, item.first ) )
+ if(items.end() == FindItemById(items, item.first))
{
- ItemIter iterToInsert = std::lower_bound( items.begin(), items.end(), item );
- items.insert( iterToInsert, item );
+ ItemIter iterToInsert = std::lower_bound(items.begin(), items.end(), item);
+ items.insert(iterToInsert, item);
}
}
-
/**
* Helper to apply size constraint to mOvershootOverlay
* @param[in] overshootOverlay The overshootOverlay actor
* @param[in] The required height
*/
-void ApplyOvershootSizeConstraint( Actor overshootOverlay, float height )
+void ApplyOvershootSizeConstraint(Actor overshootOverlay, float height)
{
- Constraint constraint = Constraint::New<Vector3>( overshootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint( height ) );
- constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
- constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
- constraint.AddSource( ParentSource( Dali::Actor::Property::SIZE ) );
- constraint.SetTag( OVERSHOOT_SIZE_CONSTRAINT_TAG );
+ Constraint constraint = Constraint::New<Vector3>(overshootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint(height));
+ constraint.AddSource(ParentSource(Dali::Toolkit::ItemView::Property::SCROLL_DIRECTION));
+ constraint.AddSource(ParentSource(Dali::Toolkit::ItemView::Property::LAYOUT_ORIENTATION));
+ constraint.AddSource(ParentSource(Dali::Actor::Property::SIZE));
+ constraint.SetTag(OVERSHOOT_SIZE_CONSTRAINT_TAG);
constraint.Apply();
}
}
ItemView::ItemView(ItemFactory& factory)
-: Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ),
+: Scrollable(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT)),
mItemFactory(factory),
mItemsParentOrigin(ParentOrigin::CENTER),
mItemsAnchorPoint(AnchorPoint::CENTER),
mAnimatingOvershootOn(false),
mAnimateOvershootOff(false),
mAnchoringEnabled(false),
- mRefreshOrderHint(true/*Refresh item 0 first*/),
+ mRefreshOrderHint(true /*Refresh item 0 first*/),
mIsFlicking(false),
mAddingItems(false),
mRefreshEnabled(true),
Actor self = Self();
- Vector2 stageSize = Stage::GetCurrent().GetSize();
+ Vector2 stageSize = Stage::GetCurrent().GetSize();
mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
- self.TouchedSignal().Connect( this, &ItemView::OnTouch );
+ self.TouchedSignal().Connect(this, &ItemView::OnTouch);
EnableGestureDetection(GestureType::Value(GestureType::PAN));
- mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
- mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
+ mWheelEventFinishedTimer = Timer::New(WHEEL_EVENT_FINISHED_TIME_OUT);
+ mWheelEventFinishedTimer.TickSignal().Connect(this, &ItemView::OnWheelEventFinished);
SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
// Connect wheel event
- self.WheelEventSignal().Connect( this, &ItemView::OnWheelEvent );
+ self.WheelEventSignal().Connect(this, &ItemView::OnWheelEvent);
- DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor)
- {
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
return std::unique_ptr<Dali::Accessibility::Accessible>(new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE));
});
}
{
DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
- if (mActiveLayout == mLayouts[layoutIndex].Get())
+ if(mActiveLayout == mLayouts[layoutIndex].Get())
{
mActiveLayout = NULL;
}
float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
{
- return Self().GetCurrentProperty< float >( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
+ return Self().GetCurrentProperty<float>(Toolkit::ItemView::Property::LAYOUT_POSITION) + static_cast<float>(itemId);
}
void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
Actor self = Self();
// The ItemView size should match the active layout size
- self.SetProperty( Actor::Property::SIZE, targetSize);
+ self.SetProperty(Actor::Property::SIZE, targetSize);
mActiveLayoutTargetSize = targetSize;
// Switch to the new layout
// Move the items to the new layout positions...
- for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
+ for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
unsigned int itemId = iter->first;
- Actor actor = iter->second;
+ Actor actor = iter->second;
// Remove constraints from previous layout
actor.RemoveConstraints();
- mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
+ mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self());
Vector3 size;
- mActiveLayout->GetItemSize( itemId, targetSize, size );
- actor.SetProperty( Actor::Property::SIZE, size.GetVectorXY() );
+ mActiveLayout->GetItemSize(itemId, targetSize, size);
+ actor.SetProperty(Actor::Property::SIZE, size.GetVectorXY());
}
// Refresh the new layout
- ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
- AddActorsWithinRange( range, targetSize );
+ ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false /* don't reserve extra*/);
+ AddActorsWithinRange(range, targetSize);
// Scroll to an appropriate layout position
- bool scrollAnimationNeeded(false);
+ bool scrollAnimationNeeded(false);
float firstItemScrollPosition(0.0f);
float current = GetCurrentLayoutPosition(0);
float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
- if (current < minimum)
+ if(current < minimum)
{
- scrollAnimationNeeded = true;
+ scrollAnimationNeeded = true;
firstItemScrollPosition = minimum;
}
- else if (mAnchoringEnabled)
+ else if(mAnchoringEnabled)
{
- scrollAnimationNeeded = true;
+ scrollAnimationNeeded = true;
firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
}
- if (scrollAnimationNeeded)
+ if(scrollAnimationNeeded)
{
RemoveAnimation(mScrollAnimation);
mScrollAnimation = Animation::New(durationSeconds);
- mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
+ mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT);
mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
mScrollAnimation.Play();
}
void ItemView::DeactivateCurrentLayout()
{
- if (mActiveLayout)
+ if(mActiveLayout)
{
- for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
+ for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
Actor actor = iter->second;
actor.RemoveConstraints();
void ItemView::OnRefreshNotification(PropertyNotification& source)
{
- if( mRefreshNotificationEnabled )
+ if(mRefreshNotificationEnabled)
{
// Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
if(!mRefreshEnabled && mScrollAnimation)
void ItemView::Refresh()
{
- for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
+ for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
- ReleaseActor( iter->first, iter->second );
+ ReleaseActor(iter->first, iter->second);
}
mItemPool.clear();
void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
{
- if (mActiveLayout)
+ if(mActiveLayout)
{
- ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
- RemoveActorsOutsideRange( range );
- AddActorsWithinRange( range, Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) );
+ ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra /*reserve extra*/);
+ RemoveActorsOutsideRange(range);
+ AddActorsWithinRange(range, Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE));
- mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
+ mScrollUpdatedSignal.Emit(Vector2(0.0f, currentLayoutPosition));
}
}
void ItemView::SetRefreshInterval(float intervalLayoutPositions)
{
- if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
+ if(!Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions))
{
mRefreshIntervalLayoutPositions = intervalLayoutPositions;
{
self.RemovePropertyNotification(mRefreshNotification);
}
- mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
- mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
+ mRefreshNotification = self.AddPropertyNotification(Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f));
+ mRefreshNotification.NotifySignal().Connect(this, &ItemView::OnRefreshNotification);
}
}
{
Actor actor;
- for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
+ for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
- if( iter->first == itemId )
+ if(iter->first == itemId)
{
actor = iter->second;
break;
return actor;
}
-unsigned int ItemView::GetItemId( Actor actor ) const
+unsigned int ItemView::GetItemId(Actor actor) const
{
- unsigned int itemId( 0 );
+ unsigned int itemId(0);
- for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
+ for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
- if( iter->second == actor )
+ if(iter->second == actor)
{
itemId = iter->first;
break;
return itemId;
}
-void ItemView::InsertItem( Item newItem, float durationSeconds )
+void ItemView::InsertItem(Item newItem, float durationSeconds)
{
- mAddingItems = true;
- Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ mAddingItems = true;
+ Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
- Actor displacedActor;
+ Actor displacedActor;
ItemIter afterDisplacedIter = mItemPool.end();
- ItemIter foundIter = FindItemById( mItemPool, newItem.first );
- if( mItemPool.end() != foundIter )
+ ItemIter foundIter = FindItemById(mItemPool, newItem.first);
+ if(mItemPool.end() != foundIter)
{
- SetupActor( newItem, layoutSize );
- Self().Add( newItem.second );
+ SetupActor(newItem, layoutSize);
+ Self().Add(newItem.second);
- displacedActor = foundIter->second;
+ displacedActor = foundIter->second;
foundIter->second = newItem.second;
afterDisplacedIter = ++foundIter;
{
// Inserting before the existing item range?
ItemIter iter = mItemPool.begin();
- if( iter != mItemPool.end() &&
- iter->first > newItem.first )
+ if(iter != mItemPool.end() &&
+ iter->first > newItem.first)
{
displacedActor = iter->second;
- iter = mItemPool.erase( iter ); // iter is still valid after the erase
+ iter = mItemPool.erase(iter); // iter is still valid after the erase
afterDisplacedIter = iter;
}
}
- if( displacedActor )
+ if(displacedActor)
{
// Move the existing actors to make room
- for( ItemIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
+ for(ItemIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter)
{
- Actor temp = iter->second;
- iter->second = displacedActor;
+ Actor temp = iter->second;
+ iter->second = displacedActor;
displacedActor = temp;
iter->second.RemoveConstraints();
- mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
+ mActiveLayout->ApplyConstraints(iter->second, iter->first, layoutSize, Self());
}
// Create last item
ItemContainer::reverse_iterator lastIter = mItemPool.rbegin();
- if ( lastIter != mItemPool.rend() )
+ if(lastIter != mItemPool.rend())
{
ItemId lastId = lastIter->first;
- Item lastItem( lastId + 1, displacedActor );
- InsertToItemContainer( mItemPool, lastItem );
+ Item lastItem(lastId + 1, displacedActor);
+ InsertToItemContainer(mItemPool, lastItem);
lastItem.second.RemoveConstraints();
- mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
+ mActiveLayout->ApplyConstraints(lastItem.second, lastItem.first, layoutSize, Self());
}
}
- CalculateDomainSize( layoutSize );
+ CalculateDomainSize(layoutSize);
mAddingItems = false;
}
-void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
+void ItemView::InsertItems(const ItemContainer& newItems, float durationSeconds)
{
- mAddingItems = true;
- Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ mAddingItems = true;
+ Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
// Insert from lowest id to highest
ItemContainer sortedItems(newItems);
- std::sort( sortedItems.begin(), sortedItems.end() );
+ std::sort(sortedItems.begin(), sortedItems.end());
- for( ItemIter iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
+ for(ItemIter iter = sortedItems.begin(); sortedItems.end() != iter; ++iter)
{
- Self().Add( iter->second );
+ Self().Add(iter->second);
- ItemIter foundIter = FindItemById( mItemPool, iter->first );
- if( mItemPool.end() != foundIter )
+ ItemIter foundIter = FindItemById(mItemPool, iter->first);
+ if(mItemPool.end() != foundIter)
{
- Actor moveMe = foundIter->second;
+ Actor moveMe = foundIter->second;
foundIter->second = iter->second;
// Move the existing actors to make room
- for( ItemIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
+ for(ItemIter iter = ++foundIter; mItemPool.end() != iter; ++iter)
{
- Actor temp = iter->second;
+ Actor temp = iter->second;
iter->second = moveMe;
- moveMe = temp;
+ moveMe = temp;
}
// Create last item
ItemId lastId = mItemPool.rbegin()->first;
- Item lastItem( lastId + 1, moveMe );
- InsertToItemContainer( mItemPool, lastItem );
+ Item lastItem(lastId + 1, moveMe);
+ InsertToItemContainer(mItemPool, lastItem);
}
else
{
- InsertToItemContainer( mItemPool, *iter );
+ InsertToItemContainer(mItemPool, *iter);
}
}
// Relayout everything
- for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
+ for(ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
// If newly inserted
- if( std::binary_search( sortedItems.begin(), sortedItems.end(), *iter ) )
+ if(std::binary_search(sortedItems.begin(), sortedItems.end(), *iter))
{
- SetupActor( *iter, layoutSize );
+ SetupActor(*iter, layoutSize);
}
else
{
iter->second.RemoveConstraints();
- mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
+ mActiveLayout->ApplyConstraints(iter->second, iter->first, layoutSize, Self());
}
}
- CalculateDomainSize( layoutSize );
+ CalculateDomainSize(layoutSize);
mAddingItems = false;
}
-void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
+void ItemView::RemoveItem(unsigned int itemId, float durationSeconds)
{
- bool actorsReordered = RemoveActor( itemId );
- if( actorsReordered )
+ bool actorsReordered = RemoveActor(itemId);
+ if(actorsReordered)
{
ReapplyAllConstraints();
}
}
-void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
+void ItemView::RemoveItems(const ItemIdContainer& itemIds, float durationSeconds)
{
- bool actorsReordered( false );
+ bool actorsReordered(false);
// Remove from highest id to lowest
ItemIdContainer sortedItems(itemIds);
- std::sort( sortedItems.begin(), sortedItems.end() );
+ std::sort(sortedItems.begin(), sortedItems.end());
- for( ItemIdContainer::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
+ for(ItemIdContainer::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter)
{
- if( RemoveActor( *iter ) )
+ if(RemoveActor(*iter))
{
actorsReordered = true;
}
}
- if( actorsReordered )
+ if(actorsReordered)
{
ReapplyAllConstraints();
bool ItemView::RemoveActor(unsigned int itemId)
{
- bool reordered( false );
+ bool reordered(false);
- ItemIter removeIter = FindItemById( mItemPool, itemId );
- if( removeIter != mItemPool.end() )
+ ItemIter removeIter = FindItemById(mItemPool, itemId);
+ if(removeIter != mItemPool.end())
{
ReleaseActor(itemId, removeIter->second);
}
{
// Removing before the existing item range?
ItemIter iter = mItemPool.begin();
- if( iter != mItemPool.end() &&
- iter->first > itemId )
+ if(iter != mItemPool.end() &&
+ iter->first > itemId)
{
// In order to decrement the first visible item ID
- InsertToItemContainer( mItemPool, Item(iter->first - 1, Actor()) );
+ InsertToItemContainer(mItemPool, Item(iter->first - 1, Actor()));
removeIter = mItemPool.begin();
}
}
- if( removeIter != mItemPool.end() )
+ if(removeIter != mItemPool.end())
{
reordered = true;
// ID 2 - ActorB ID 2 - ActorC (previously ID 3)
// ID 3 - ActorC ID 3 - ActorB (previously ID 4)
// ID 4 - ActorD
- for (ItemIter iter = removeIter; iter != mItemPool.end(); ++iter)
+ for(ItemIter iter = removeIter; iter != mItemPool.end(); ++iter)
{
- if( iter->first < mItemPool.rbegin()->first )
+ if(iter->first < mItemPool.rbegin()->first)
{
- iter->second = ( iter + 1 )->second;
+ iter->second = (iter + 1)->second;
}
else
{
- mItemPool.erase( iter );
+ mItemPool.erase(iter);
break;
}
}
return reordered;
}
-void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
+void ItemView::ReplaceItem(Item replacementItem, float durationSeconds)
{
- mAddingItems = true;
- Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ mAddingItems = true;
+ Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
- SetupActor( replacementItem, layoutSize );
- Self().Add( replacementItem.second );
+ SetupActor(replacementItem, layoutSize);
+ Self().Add(replacementItem.second);
- const ItemIter iter = FindItemById( mItemPool, replacementItem.first );
- if( mItemPool.end() != iter )
+ const ItemIter iter = FindItemById(mItemPool, replacementItem.first);
+ if(mItemPool.end() != iter)
{
ReleaseActor(iter->first, iter->second);
iter->second = replacementItem.second;
}
else
{
- InsertToItemContainer( mItemPool, replacementItem );
+ InsertToItemContainer(mItemPool, replacementItem);
}
- CalculateDomainSize( layoutSize );
+ CalculateDomainSize(layoutSize);
mAddingItems = false;
}
-void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
+void ItemView::ReplaceItems(const ItemContainer& replacementItems, float durationSeconds)
{
- for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
+ for(ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter)
{
- ReplaceItem( *iter, durationSeconds );
+ ReplaceItem(*iter, durationSeconds);
}
}
-void ItemView::RemoveActorsOutsideRange( ItemRange range )
+void ItemView::RemoveActorsOutsideRange(ItemRange range)
{
// Remove unwanted actors from the ItemView & ItemPool
- for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); )
+ for(ItemIter iter = mItemPool.begin(); iter != mItemPool.end();)
{
unsigned int current = iter->first;
- if( ! range.Within( current ) )
+ if(!range.Within(current))
{
ReleaseActor(iter->first, iter->second);
- iter = mItemPool.erase( iter ); // iter is still valid after the erase
+ iter = mItemPool.erase(iter); // iter is still valid after the erase
}
else
{
}
}
-void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
+void ItemView::AddActorsWithinRange(ItemRange range, const Vector3& layoutSize)
{
range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
// The order of addition depends on the scroll direction.
- if (mRefreshOrderHint)
+ if(mRefreshOrderHint)
{
- for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
+ for(unsigned int itemId = range.begin; itemId < range.end; ++itemId)
{
- AddNewActor( itemId, layoutSize );
+ AddNewActor(itemId, layoutSize);
}
}
else
{
- for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
+ for(unsigned int itemId = range.end; itemId > range.begin; --itemId)
{
- AddNewActor( itemId-1, layoutSize );
+ AddNewActor(itemId - 1, layoutSize);
}
}
// Total number of items may change dynamically.
// Always recalculate the domain size to reflect that.
- CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
+ CalculateDomainSize(Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE));
}
-void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
+void ItemView::AddNewActor(unsigned int itemId, const Vector3& layoutSize)
{
mAddingItems = true;
- if( mItemPool.end() == FindItemById( mItemPool, itemId ) )
+ if(mItemPool.end() == FindItemById(mItemPool, itemId))
{
- Actor actor = mItemFactory.NewItem( itemId );
+ Actor actor = mItemFactory.NewItem(itemId);
- if( actor )
+ if(actor)
{
- Item newItem( itemId, actor );
+ Item newItem(itemId, actor);
- InsertToItemContainer( mItemPool, newItem );
+ InsertToItemContainer(mItemPool, newItem);
- SetupActor( newItem, layoutSize );
- Self().Add( actor );
+ SetupActor(newItem, layoutSize);
+ Self().Add(actor);
}
}
mAddingItems = false;
}
-void ItemView::SetupActor( Item item, const Vector3& layoutSize )
+void ItemView::SetupActor(Item item, const Vector3& layoutSize)
{
- item.second.SetProperty( Actor::Property::PARENT_ORIGIN, mItemsParentOrigin );
- item.second.SetProperty( Actor::Property::ANCHOR_POINT, mItemsAnchorPoint );
+ item.second.SetProperty(Actor::Property::PARENT_ORIGIN, mItemsParentOrigin);
+ item.second.SetProperty(Actor::Property::ANCHOR_POINT, mItemsAnchorPoint);
- if( mActiveLayout )
+ if(mActiveLayout)
{
Vector3 size;
- mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
- item.second.SetProperty( Actor::Property::SIZE, size.GetVectorXY() );
+ mActiveLayout->GetItemSize(item.first, mActiveLayoutTargetSize, size);
+ item.second.SetProperty(Actor::Property::SIZE, size.GetVectorXY());
- mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
+ mActiveLayout->ApplyConstraints(item.second, item.first, layoutSize, Self());
}
}
-void ItemView::ReleaseActor( ItemId item, Actor actor )
+void ItemView::ReleaseActor(ItemId item, Actor actor)
{
- Self().Remove( actor );
+ Self().Remove(actor);
mItemFactory.ItemReleased(item, actor);
}
ItemRange available(0u, itemCount);
- ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
+ ItemRange range = layout.GetItemsWithinArea(layoutPosition, layoutSize);
- if (reserveExtra)
+ if(reserveExtra)
{
// Add the reserve items for scrolling
unsigned int extra = layout.GetReserveItemCount(layoutSize);
- range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
+ range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
range.end += extra;
}
}
}
- Scrollable::OnChildAdd( child );
+ Scrollable::OnChildAdd(child);
}
bool ItemView::OnWheelEvent(Actor actor, const WheelEvent& event)
{
// Respond the wheel event to scroll
- if (mActiveLayout)
+ if(mActiveLayout)
{
- Actor self = Self();
- const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
- float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.GetDelta() * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
- float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
+ Actor self = Self();
+ const Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
+ float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.GetDelta() * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
+ float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
- self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
+ self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition);
mScrollStartedSignal.Emit(GetCurrentScrollPosition());
mRefreshEnabled = true;
}
- if (mWheelEventFinishedTimer.IsRunning())
+ if(mWheelEventFinishedTimer.IsRunning())
{
mWheelEventFinishedTimer.Stop();
}
bool ItemView::OnWheelEventFinished()
{
- if (mActiveLayout)
+ if(mActiveLayout)
{
RemoveAnimation(mScrollAnimation);
// No more wheel events coming. Do the anchoring if enabled.
mScrollAnimation = DoAnchoring();
- if (mScrollAnimation)
+ if(mScrollAnimation)
{
mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
mScrollAnimation.Play();
void ItemView::ReapplyAllConstraints()
{
- Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
- for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
+ for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
- unsigned int id = iter->first;
- Actor actor = iter->second;
+ unsigned int id = iter->first;
+ Actor actor = iter->second;
actor.RemoveConstraints();
mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
void ItemView::OnItemsRemoved()
{
- CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
+ CalculateDomainSize(Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE));
// Adjust scroll-position after an item is removed
- if( mActiveLayout )
+ if(mActiveLayout)
{
- float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ), *mActiveLayout);
- Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
+ float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE), *mActiveLayout);
+ Self().SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition);
}
}
-float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
+float ItemView::ClampFirstItemPosition(float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot)
{
- Actor self = Self();
+ Actor self = Self();
float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
- float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
+ float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
- if( updateOvershoot )
+ if(updateOvershoot)
{
mScrollOvershoot = targetPosition - clamppedPosition;
}
return clamppedPosition;
}
-bool ItemView::OnTouch( Actor actor, const TouchEvent& touch )
+bool ItemView::OnTouch(Actor actor, const TouchEvent& touch)
{
// Ignore events with multiple-touch points
- if (touch.GetPointCount() != 1)
+ if(touch.GetPointCount() != 1)
{
return false;
}
- if ( touch.GetState( 0 ) == PointState::DOWN )
+ if(touch.GetState(0) == PointState::DOWN)
{
// Cancel ongoing scrolling etc.
mGestureState = GestureState::CLEAR;
mScrollDistance = 0.0f;
- mScrollSpeed = 0.0f;
+ mScrollSpeed = 0.0f;
Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
mScrollOvershoot = 0.0f;
return false; // Do not consume as we're potentially scrolling (detecting pan gestures)
}
-void ItemView::OnPan( const PanGesture& gesture )
+void ItemView::OnPan(const PanGesture& gesture)
{
- Actor self = Self();
- const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Actor self = Self();
+ const Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
RemoveAnimation(mScrollAnimation);
// Short-circuit if there is no active layout
- if (!mActiveLayout)
+ if(!mActiveLayout)
{
mGestureState = GestureState::CLEAR;
return;
mGestureState = gesture.GetState();
- switch (mGestureState)
+ switch(mGestureState)
{
case GestureState::FINISHED:
{
// Swipe Detection
- if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
- mScrollSpeed > mMinimumSwipeSpeed)
+ if(fabsf(mScrollDistance) > mMinimumSwipeDistance &&
+ mScrollSpeed > mMinimumSwipeSpeed)
{
float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
mRefreshOrderHint = true;
- float currentLayoutPosition = GetCurrentLayoutPosition(0);
+ float currentLayoutPosition = GetCurrentLayoutPosition(0);
float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
layoutSize,
*mActiveLayout);
- if (mAnchoringEnabled)
+ if(mAnchoringEnabled)
{
firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
}
RemoveAnimation(mScrollAnimation);
- float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
- , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
+ float flickAnimationDuration = Clamp(mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0))), DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
mScrollAnimation = Animation::New(flickAnimationDuration);
- mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
- mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
+ mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT);
+ mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT);
mIsFlicking = true;
// Check whether it has already scrolled to the end
- if( fabs(currentLayoutPosition - firstItemScrollPosition) < Math::MACHINE_EPSILON_0 )
+ if(fabs(currentLayoutPosition - firstItemScrollPosition) < Math::MACHINE_EPSILON_0)
{
- AnimateScrollOvershoot( 0.0f );
- RemoveAnimation( mScrollAnimation );
+ AnimateScrollOvershoot(0.0f);
+ RemoveAnimation(mScrollAnimation);
}
}
// Anchoring may be triggered when there was no swipe
- if (!mScrollAnimation)
+ if(!mScrollAnimation)
{
mScrollAnimation = DoAnchoring();
}
// Reset the overshoot if no scroll animation.
- if (!mScrollAnimation)
+ if(!mScrollAnimation)
{
mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
case GestureState::CONTINUING:
{
const Vector2& displacement = gesture.GetDisplacement();
- mScrollDistance = CalculateScrollDistance(displacement, *mActiveLayout);
- mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
+ mScrollDistance = CalculateScrollDistance(displacement, *mActiveLayout);
+ mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
// Refresh order depends on the direction of the scroll; negative is towards the last item.
mRefreshOrderHint = mScrollDistance < 0.0f;
float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
- float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT );
+ float currentOvershoot = self.GetCurrentProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
- self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
+ self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition);
- if( ( firstItemScrollPosition >= 0.0f &&
- currentOvershoot < 1.0f ) ||
- ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
- currentOvershoot > -1.0f ) )
+ if((firstItemScrollPosition >= 0.0f &&
+ currentOvershoot < 1.0f) ||
+ (firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
+ currentOvershoot > -1.0f))
{
mTotalPanDisplacement += displacement;
}
// If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
// First make sure we are not in an animation, otherwise a previously started
// off-animation will be overwritten as the user continues scrolling.
- if( !mInAnimation )
+ if(!mInAnimation)
{
// Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
- if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
- ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
+ if(((mScrollOvershoot > Math::MACHINE_EPSILON_0) && (mScrollDistance < -Math::MACHINE_EPSILON_0)) ||
+ ((mScrollOvershoot < Math::MACHINE_EPSILON_0) && (mScrollDistance > Math::MACHINE_EPSILON_0)))
{
// The user has moved against the indicator direction.
// First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
// and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
mTotalPanDisplacement = Vector2::ZERO;
// Animate the overshoot indicator off.
- AnimateScrollOvershoot( 0.0f, false );
+ AnimateScrollOvershoot(0.0f, false);
}
else
{
// Only set the property directly if we are not animating the overshoot away,
// as otherwise this will overwrite the animation generated value.
- self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
+ self.SetProperty(Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot);
}
}
}
break;
}
- if (mScrollAnimation)
+ if(mScrollAnimation)
{
mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
mScrollAnimation.Play();
}
else if(actor && actor.GetParent() == this->Self())
{
- int itemID = GetItemId(actor);
- nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
+ int itemID = GetItemId(actor);
+ nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
nextFocusActor = GetItem(nextItemID);
if(nextFocusActor == actor)
{
return nextFocusActor;
}
}
- float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
- Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ float layoutPosition = mActiveLayout->GetClosestAnchorPosition(GetCurrentLayoutPosition(0));
+ Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
if(!nextFocusActor)
{
// likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
- nextItemID = viewableItems.begin;
- nextFocusActor = GetItem(nextItemID);
+ nextItemID = viewableItems.begin;
+ nextFocusActor = GetItem(nextItemID);
}
}
return nextFocusActor;
// only in this function if our chosen focus actor was actually used
if(commitedFocusableActor)
{
- int nextItemID = GetItemId(commitedFocusableActor);
- float layoutPosition = GetCurrentLayoutPosition(0);
- Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ int nextItemID = GetItemId(commitedFocusableActor);
+ float layoutPosition = GetCurrentLayoutPosition(0);
+ Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
Animation ItemView::DoAnchoring()
{
Animation anchoringAnimation;
- Actor self = Self();
+ Actor self = Self();
- if (mActiveLayout && mAnchoringEnabled)
+ if(mActiveLayout && mAnchoringEnabled)
{
- float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
+ float anchorPosition = mActiveLayout->GetClosestAnchorPosition(GetCurrentLayoutPosition(0));
anchoringAnimation = Animation::New(mAnchoringDuration);
- anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
- anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
+ anchoringAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT);
+ anchoringAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT);
if(!mIsFlicking)
{
AnimateScrollOvershoot(0.0f);
if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
{
- AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
+ AnimateScrollOvershoot(mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
}
else
{
// Reset the overshoot
- AnimateScrollOvershoot( 0.0f );
+ AnimateScrollOvershoot(0.0f);
}
mIsFlicking = false;
void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
{
- Actor self = Self();
- const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
- float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
+ Actor self = Self();
+ const Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
+ float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
if(durationSeconds > 0.0f)
{
RemoveAnimation(mScrollAnimation);
mScrollAnimation = Animation::New(durationSeconds);
- mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
+ mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction);
mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
mScrollAnimation.Play();
}
else
{
- self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
+ self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition);
AnimateScrollOvershoot(0.0f);
}
if(mActiveLayout)
{
- firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
+ firstItemPosition = mActiveLayout->GetItemPosition(0, 0, layoutSize);
float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
- lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
+ lastItemPosition = mActiveLayout->GetItemPosition(fabs(minLayoutPosition), fabs(minLayoutPosition), layoutSize);
float domainSize;
{
Actor self = Self();
- float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false );
- float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false );
- float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false );
+ float currentLayoutPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false);
+ float forwardClampedPosition = ClampFirstItemPosition(currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false);
+ float backwardClampedPosition = ClampFirstItemPosition(currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false);
return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
}
float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
{
- Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
- return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
+ Vector3 firstItemPosition(mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize));
+ return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x : firstItemPosition.y;
}
Vector2 ItemView::GetCurrentScrollPosition() const
{
- return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE )));
+ return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE)));
}
void ItemView::AddOverlay(Actor actor)
{
- actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
+ actor.SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D);
Self().Add(actor);
}
void ItemView::ScrollTo(const Vector2& position, float duration)
{
- Actor self = Self();
- const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Actor self = Self();
+ const Vector3 layoutSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
{
RemoveAnimation(mScrollAnimation);
mScrollAnimation = Animation::New(duration);
- mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
+ mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction);
mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
mScrollAnimation.Play();
}
else
{
- self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
+ self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition);
AnimateScrollOvershoot(0.0f);
}
mRefreshEnabled = true;
}
-void ItemView::SetOvershootSize( const Vector2& size )
+void ItemView::SetOvershootSize(const Vector2& size)
{
mOvershootSize = size;
- if( mOvershootOverlay )
+ if(mOvershootOverlay)
{
// Remove old & add new size constraint
- mOvershootOverlay.RemoveConstraints( OVERSHOOT_SIZE_CONSTRAINT_TAG );
- ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
+ mOvershootOverlay.RemoveConstraints(OVERSHOOT_SIZE_CONSTRAINT_TAG);
+ ApplyOvershootSizeConstraint(mOvershootOverlay, mOvershootSize.height);
}
}
-void ItemView::SetOvershootEffectColor( const Vector4& color )
+void ItemView::SetOvershootEffectColor(const Vector4& color)
{
mOvershootEffectColor = color;
- if( mOvershootOverlay )
+ if(mOvershootOverlay)
{
- mOvershootOverlay.SetProperty( Actor::Property::COLOR, color );
+ mOvershootOverlay.SetProperty(Actor::Property::COLOR, color);
}
}
-void ItemView::EnableScrollOvershoot( bool enable )
+void ItemView::EnableScrollOvershoot(bool enable)
{
Actor self = Self();
- if( enable )
+ if(enable)
{
- if( !mOvershootOverlay )
+ if(!mOvershootOverlay)
{
Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
- mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
- mOvershootOverlay.SetProperty( Actor::Property::COLOR,mOvershootEffectColor);
- mOvershootOverlay.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT );
- mOvershootOverlay.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::TOP_LEFT);
- mOvershootOverlay.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
+ mOvershootOverlay = CreateBouncingEffectActor(effectOvershootPropertyIndex);
+ mOvershootOverlay.SetProperty(Actor::Property::COLOR, mOvershootEffectColor);
+ mOvershootOverlay.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ mOvershootOverlay.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ mOvershootOverlay.SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D);
self.Add(mOvershootOverlay);
- ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
+ ApplyOvershootSizeConstraint(mOvershootOverlay, mOvershootSize.height);
- Constraint constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
+ Constraint constraint = Constraint::New<Quaternion>(mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint);
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::SCROLL_DIRECTION));
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_ORIENTATION));
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::OVERSHOOT));
constraint.Apply();
- constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
- constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
+ constraint = Constraint::New<Vector3>(mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint);
+ constraint.AddSource(ParentSource(Actor::Property::SIZE));
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::SCROLL_DIRECTION));
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_ORIENTATION));
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::OVERSHOOT));
constraint.Apply();
- constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
- constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
+ constraint = Constraint::New<bool>(mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint);
+ constraint.AddSource(ParentSource(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL));
constraint.Apply();
- constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
+ constraint = Constraint::New<float>(mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint());
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::OVERSHOOT));
constraint.Apply();
}
}
else
{
- if( mOvershootOverlay )
+ if(mOvershootOverlay)
{
self.Remove(mOvershootOverlay);
mOvershootOverlay.Reset();
{
// The overshoot must be calculated from the accumulated pan gesture displacement
// since the pan gesture starts.
- Actor self = Self();
- float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
- float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
- float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
+ Actor self = Self();
+ float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
+ float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
+ float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE));
self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
- overshoot = positionDelta - clamppedPosition;
+ overshoot = positionDelta - clamppedPosition;
}
return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
// make sure we animate back if needed
mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
- if( mAnimatingOvershootOn )
+ if(mAnimatingOvershootOn)
{
// animating on, do not allow animate off
return;
if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
{
- float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT );
- float duration = 0.0f;
+ float currentOvershoot = self.GetCurrentProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
+ float duration = 0.0f;
- if (mOvershootOverlay)
+ if(mOvershootOverlay)
{
- duration = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
+ duration = mOvershootOverlay.GetCurrentProperty<Vector3>(Actor::Property::SIZE).height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
}
// Mark the animation as in progress to prevent manual property sets overwriting it.
- mInAnimation = true;
+ mInAnimation = true;
mAnimatingOvershootOn = animatingOn;
RemoveAnimation(mScrollOvershootAnimation);
mScrollOvershootAnimation = Animation::New(duration);
mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
- mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
+ mScrollOvershootAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration));
mScrollOvershootAnimation.Play();
}
else
{
- self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
+ self.SetProperty(Toolkit::ItemView::Property::OVERSHOOT, overshootAmount);
}
}
-void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
+void ItemView::SetItemsParentOrigin(const Vector3& parentOrigin)
{
- if( parentOrigin != mItemsParentOrigin )
+ if(parentOrigin != mItemsParentOrigin)
{
mItemsParentOrigin = parentOrigin;
- for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
+ for(ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
- iter->second.SetProperty( Actor::Property::PARENT_ORIGIN,parentOrigin );
+ iter->second.SetProperty(Actor::Property::PARENT_ORIGIN, parentOrigin);
}
}
}
return mItemsParentOrigin;
}
-void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
+void ItemView::SetItemsAnchorPoint(const Vector3& anchorPoint)
{
- if( anchorPoint != mItemsAnchorPoint )
+ if(anchorPoint != mItemsAnchorPoint)
{
mItemsAnchorPoint = anchorPoint;
- for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
+ for(ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
{
- iter->second.SetProperty( Actor::Property::ANCHOR_POINT,anchorPoint);
+ iter->second.SetProperty(Actor::Property::ANCHOR_POINT, anchorPoint);
}
}
}
void ItemView::GetItemsRange(ItemRange& range)
{
- if( !mItemPool.empty() )
+ if(!mItemPool.empty())
{
range.begin = mItemPool.begin()->first;
- range.end = mItemPool.rbegin()->first + 1;
+ range.end = mItemPool.rbegin()->first + 1;
}
else
{
range.begin = 0;
- range.end = 0;
+ range.end = 0;
}
}
-bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool ItemView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
+ bool connected(true);
+ Toolkit::ItemView itemView = Toolkit::ItemView::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
+ if(0 == strcmp(signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL))
{
- itemView.LayoutActivatedSignal().Connect( tracker, functor );
+ itemView.LayoutActivatedSignal().Connect(tracker, functor);
}
else
{
return connected;
}
-void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void ItemView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ItemView itemView = Toolkit::ItemView::DownCast(Dali::BaseHandle(object));
- if( itemView )
+ if(itemView)
{
- ItemView& itemViewImpl( GetImpl( itemView ) );
- switch( index )
+ ItemView& itemViewImpl(GetImpl(itemView));
+ switch(index)
{
case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
{
- itemViewImpl.SetMinimumSwipeSpeed( value.Get<float>() );
+ itemViewImpl.SetMinimumSwipeSpeed(value.Get<float>());
break;
}
case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
{
- itemViewImpl.SetMinimumSwipeDistance( value.Get<float>() );
+ itemViewImpl.SetMinimumSwipeDistance(value.Get<float>());
break;
}
case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
{
- itemViewImpl.SetWheelScrollDistanceStep( value.Get<float>() );
+ itemViewImpl.SetWheelScrollDistanceStep(value.Get<float>());
break;
}
case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
{
- itemViewImpl.SetAnchoring( value.Get<bool>() );
+ itemViewImpl.SetAnchoring(value.Get<bool>());
break;
}
case Toolkit::ItemView::Property::REFRESH_INTERVAL:
{
- itemViewImpl.SetRefreshInterval( value.Get<float>() );
+ itemViewImpl.SetRefreshInterval(value.Get<float>());
break;
}
{
// Get a Property::Array from the property if possible.
Property::Array layoutArray;
- if( value.Get( layoutArray ) )
+ if(value.Get(layoutArray))
{
- itemViewImpl.SetLayoutArray( layoutArray );
+ itemViewImpl.SetLayoutArray(layoutArray);
}
break;
}
return mlayoutArray;
}
-void ItemView::SetLayoutArray( const Property::Array& layouts )
+void ItemView::SetLayoutArray(const Property::Array& layouts)
{
- mlayoutArray = layouts;
+ mlayoutArray = layouts;
const int layoutCount = GetLayoutCount();
- if( layoutCount > 0 )
+ if(layoutCount > 0)
{
for(int index = layoutCount - 1; index >= 0; --index)
{
}
}
- for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx )
+ for(unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx)
{
- const Property::Value& element = layouts.GetElementAt( arrayIdx );
+ const Property::Value& element = layouts.GetElementAt(arrayIdx);
const Property::Map* layout = element.GetMap();
- if( layout != NULL )
+ if(layout != NULL)
{
- for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx )
+ for(unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx)
{
- KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) );
+ KeyValuePair propertyPair((*layout).GetKeyValue(mapIdx));
if(propertyPair.first == DefaultItemLayoutProperty::TYPE)
{
case DefaultItemLayout::LIST:
{
Internal::GridLayoutPtr listLayout = Internal::GridLayout::New();
- listLayout->SetNumberOfColumns( 1 );
+ listLayout->SetNumberOfColumns(1);
(*listLayout).SetLayoutProperties(*layout);
(*listLayout).SetGridLayoutProperties(*layout);
AddLayout(*listLayout);
}
}
-Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index )
+Property::Value ItemView::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ItemView itemView = Toolkit::ItemView::DownCast(Dali::BaseHandle(object));
- if( itemView )
+ if(itemView)
{
- ItemView& itemViewImpl( GetImpl( itemView ) );
- switch( index )
+ ItemView& itemViewImpl(GetImpl(itemView));
+ switch(index)
{
case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
{
case Toolkit::ItemView::Property::LAYOUT:
{
- Property::Array layouts= itemViewImpl.GetLayoutArray();
- value = layouts;
+ Property::Array layouts = itemViewImpl.GetLayoutArray();
+ value = layouts;
break;
}
}
return value;
}
-bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
+bool ItemView::DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
+ Toolkit::ItemView itemView = Toolkit::ItemView::DownCast(handle);
- DALI_ASSERT_ALWAYS( itemView );
+ DALI_ASSERT_ALWAYS(itemView);
- if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
+ if(0 == strcmp(actionName.c_str(), ACTION_STOP_SCROLLING))
{
- GetImpl( itemView ).DoStopScrolling();
+ GetImpl(itemView).DoStopScrolling();
}
- else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_ENABLE_REFRESH))
{
- GetImpl( itemView ).SetRefreshNotificationEnabled( true );
+ GetImpl(itemView).SetRefreshNotificationEnabled(true);
}
- else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
+ else if(0 == strcmp(actionName.c_str(), ACTION_DISABLE_REFRESH))
{
- GetImpl( itemView ).SetRefreshNotificationEnabled( false );
+ GetImpl(itemView).SetRefreshNotificationEnabled(false);
}
return true;
void ItemView::DoStopScrolling()
{
- if( mScrollAnimation )
+ if(mScrollAnimation)
{
mScrollAnimation.Stop();
mScrollAnimation.Reset();
}
}
-void ItemView::SetRefreshNotificationEnabled( bool enabled )
+void ItemView::SetRefreshNotificationEnabled(bool enabled)
{
mRefreshNotificationEnabled = enabled;
}
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.h>
// EXTERNAL INCLUDES
-#include <algorithm>
#include <dali/public-api/animation/animation.h>
#include <dali/public-api/animation/constraint.h>
+#include <algorithm>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h>
#include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h>
+#include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h>
using namespace Dali;
using namespace Dali::Toolkit;
namespace // unnamed namespace
{
-
const float DEFAULT_ITEMS_PER_SPIRAL_TURN = 9.5f;
-const float DEFAULT_ITEM_SPACING_RADIANS = Math::PI*2.0f/DEFAULT_ITEMS_PER_SPIRAL_TURN;
+const float DEFAULT_ITEM_SPACING_RADIANS = Math::PI * 2.0f / DEFAULT_ITEMS_PER_SPIRAL_TURN;
const float DEFAULT_REVOLUTION_DISTANCE = 190.0f;
-const float DEFAULT_ITEM_DESCENT = DEFAULT_REVOLUTION_DISTANCE / DEFAULT_ITEMS_PER_SPIRAL_TURN;
+const float DEFAULT_ITEM_DESCENT = DEFAULT_REVOLUTION_DISTANCE / DEFAULT_ITEMS_PER_SPIRAL_TURN;
const float DEFAULT_TOP_ITEM_ALIGNMENT = -0.125f;
-const float DEFAULT_SCROLL_SPEED_FACTOR = 0.01f;
-const float DEFAULT_MAXIMUM_SWIPE_SPEED = 30.0f;
+const float DEFAULT_SCROLL_SPEED_FACTOR = 0.01f;
+const float DEFAULT_MAXIMUM_SWIPE_SPEED = 30.0f;
const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.1f;
float GetDefaultSpiralRadiusFunction(const Vector3& layoutSize)
{
- return layoutSize.width*0.4f;
+ return layoutSize.width * 0.4f;
}
struct SpiralPositionConstraint
{
- SpiralPositionConstraint( unsigned int itemId, float spiralRadius, float itemSpacingRadians, float itemDescent, float topItemAlignment )
- : mItemId( itemId ),
- mSpiralRadius( spiralRadius ),
- mItemSpacingRadians( itemSpacingRadians ),
- mItemDescent( itemDescent ),
- mTopItemAlignment( topItemAlignment )
+ SpiralPositionConstraint(unsigned int itemId, float spiralRadius, float itemSpacingRadians, float itemDescent, float topItemAlignment)
+ : mItemId(itemId),
+ mSpiralRadius(spiralRadius),
+ mItemSpacingRadians(itemSpacingRadians),
+ mItemDescent(itemDescent),
+ mTopItemAlignment(topItemAlignment)
{
}
- inline void OrientationUp( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void OrientationUp(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
float angle = -Math::PI * 0.5f + mItemSpacingRadians * layoutPosition;
- current.x = -mSpiralRadius * cosf( angle );
- current.y = ( mItemDescent * layoutPosition ) + layoutSize.height * mTopItemAlignment;
- current.z = -mSpiralRadius * sinf( angle );
+ current.x = -mSpiralRadius * cosf(angle);
+ current.y = (mItemDescent * layoutPosition) + layoutSize.height * mTopItemAlignment;
+ current.z = -mSpiralRadius * sinf(angle);
}
- inline void OrientationLeft( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void OrientationLeft(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
float angle = Math::PI * 0.5f + mItemSpacingRadians * layoutPosition;
- current.x = ( mItemDescent * layoutPosition ) + layoutSize.width * mTopItemAlignment;
- current.y = -mSpiralRadius * cosf( angle );
- current.z = mSpiralRadius * sinf( angle );
+ current.x = (mItemDescent * layoutPosition) + layoutSize.width * mTopItemAlignment;
+ current.y = -mSpiralRadius * cosf(angle);
+ current.z = mSpiralRadius * sinf(angle);
}
- inline void OrientationDown( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void OrientationDown(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
float angle = Math::PI * 0.5f + mItemSpacingRadians * layoutPosition;
- current.x = -mSpiralRadius * cosf( angle );
- current.y = ( -mItemDescent * layoutPosition ) - layoutSize.height * mTopItemAlignment;
+ current.x = -mSpiralRadius * cosf(angle);
+ current.y = (-mItemDescent * layoutPosition) - layoutSize.height * mTopItemAlignment;
current.z = mSpiralRadius * sinf(angle);
}
- inline void OrientationRight( Vector3& current, float layoutPosition, const Vector3& layoutSize )
+ inline void OrientationRight(Vector3& current, float layoutPosition, const Vector3& layoutSize)
{
- float angle = -Math::PI*0.5f + mItemSpacingRadians * layoutPosition;
+ float angle = -Math::PI * 0.5f + mItemSpacingRadians * layoutPosition;
current.x = (-mItemDescent * layoutPosition) - layoutSize.width * mTopItemAlignment;
- current.y = -mSpiralRadius * cosf( angle );
- current.z = -mSpiralRadius * sinf( angle );
+ current.y = -mSpiralRadius * cosf(angle);
+ current.z = -mSpiralRadius * sinf(angle);
}
- void OrientationUp( Vector3& current, const PropertyInputContainer& inputs )
+ void OrientationUp(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- OrientationUp( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ OrientationUp(current, layoutPosition, layoutSize);
}
- void OrientationLeft( Vector3& current, const PropertyInputContainer& inputs )
+ void OrientationLeft(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- OrientationLeft( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ OrientationLeft(current, layoutPosition, layoutSize);
}
- void OrientationDown( Vector3& current, const PropertyInputContainer& inputs )
+ void OrientationDown(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- OrientationDown( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ OrientationDown(current, layoutPosition, layoutSize);
}
- void OrientationRight( Vector3& current, const PropertyInputContainer& inputs )
+ void OrientationRight(Vector3& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- OrientationRight( current, layoutPosition, layoutSize );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ OrientationRight(current, layoutPosition, layoutSize);
}
unsigned int mItemId;
- float mSpiralRadius;
- float mItemSpacingRadians;
- float mItemDescent;
- float mTopItemAlignment;
+ float mSpiralRadius;
+ float mItemSpacingRadians;
+ float mItemDescent;
+ float mTopItemAlignment;
};
struct SpiralRotationConstraint
{
- SpiralRotationConstraint( unsigned int itemId, float itemSpacingRadians )
- : mItemId( itemId ),
- mItemSpacingRadians( itemSpacingRadians )
+ SpiralRotationConstraint(unsigned int itemId, float itemSpacingRadians)
+ : mItemId(itemId),
+ mItemSpacingRadians(itemSpacingRadians)
{
}
- void OrientationUp( Quaternion& current, const PropertyInputContainer& inputs )
+ void OrientationUp(Quaternion& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- float angle = -mItemSpacingRadians * layoutPosition;
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ float angle = -mItemSpacingRadians * layoutPosition;
- current = Quaternion( Radian( angle ), Vector3::YAXIS);
+ current = Quaternion(Radian(angle), Vector3::YAXIS);
}
- void OrientationLeft( Quaternion& current, const PropertyInputContainer& inputs )
+ void OrientationLeft(Quaternion& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- float angle = -mItemSpacingRadians * layoutPosition;
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ float angle = -mItemSpacingRadians * layoutPosition;
- current = Quaternion( Radian( -Math::PI * 0.5f ), Vector3::ZAXIS ) * Quaternion( Radian( angle ), Vector3::YAXIS );
+ current = Quaternion(Radian(-Math::PI * 0.5f), Vector3::ZAXIS) * Quaternion(Radian(angle), Vector3::YAXIS);
}
- void OrientationDown( Quaternion& current, const PropertyInputContainer& inputs )
+ void OrientationDown(Quaternion& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- float angle = -mItemSpacingRadians * layoutPosition;
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ float angle = -mItemSpacingRadians * layoutPosition;
- current = Quaternion( Radian( -Math::PI ), Vector3::ZAXIS) * Quaternion( Radian( angle ), Vector3::YAXIS );
+ current = Quaternion(Radian(-Math::PI), Vector3::ZAXIS) * Quaternion(Radian(angle), Vector3::YAXIS);
}
- void OrientationRight( Quaternion& current, const PropertyInputContainer& inputs )
+ void OrientationRight(Quaternion& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- float angle = -mItemSpacingRadians * layoutPosition;
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ float angle = -mItemSpacingRadians * layoutPosition;
- current = Quaternion( Radian( -Math::PI * 1.5f ), Vector3::ZAXIS) * Quaternion( Radian( angle ), Vector3::YAXIS );
+ current = Quaternion(Radian(-Math::PI * 1.5f), Vector3::ZAXIS) * Quaternion(Radian(angle), Vector3::YAXIS);
}
unsigned int mItemId;
- float mItemSpacingRadians;
+ float mItemSpacingRadians;
};
struct SpiralColorConstraint
{
- SpiralColorConstraint( unsigned int itemId, float itemSpacingRadians )
- : mItemId( itemId ),
- mItemSpacingRadians( itemSpacingRadians )
+ SpiralColorConstraint(unsigned int itemId, float itemSpacingRadians)
+ : mItemId(itemId),
+ mItemSpacingRadians(itemSpacingRadians)
{
}
- void operator()( Vector4& current, const PropertyInputContainer& inputs )
+ void operator()(Vector4& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- Radian angle( mItemSpacingRadians * fabsf( layoutPosition ) / Dali::ANGLE_360 );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ Radian angle(mItemSpacingRadians * fabsf(layoutPosition) / Dali::ANGLE_360);
- float progress = angle - floorf( angle ); // take fractional bit only to get between 0.0 - 1.0
- progress = (progress > 0.5f) ? 2.0f*(1.0f - progress) : progress*2.0f;
+ float progress = angle - floorf(angle); // take fractional bit only to get between 0.0 - 1.0
+ progress = (progress > 0.5f) ? 2.0f * (1.0f - progress) : progress * 2.0f;
float darkness(1.0f);
{
const float endMarker = 0.35f; // The progress at which darkening ends
const float minDarkness = 0.15f; // The darkness at end marker
- if (progress > endMarker)
+ if(progress > endMarker)
{
darkness = minDarkness;
}
- else if (progress > startMarker)
+ else if(progress > startMarker)
{
- darkness = 1.0f - ( (1.0f - minDarkness) * ((progress-startMarker) / (endMarker-startMarker)) );
+ darkness = 1.0f - ((1.0f - minDarkness) * ((progress - startMarker) / (endMarker - startMarker)));
}
}
}
unsigned int mItemId;
- float mItemSpacingRadians;
+ float mItemSpacingRadians;
};
struct SpiralVisibilityConstraint
{
- SpiralVisibilityConstraint( unsigned int itemId, float itemSpacingRadians, float itemDescent, float topItemAlignment )
- : mItemId( itemId ),
- mItemSpacingRadians( itemSpacingRadians ),
- mItemDescent( itemDescent ),
- mTopItemAlignment( topItemAlignment )
+ SpiralVisibilityConstraint(unsigned int itemId, float itemSpacingRadians, float itemDescent, float topItemAlignment)
+ : mItemId(itemId),
+ mItemSpacingRadians(itemSpacingRadians),
+ mItemDescent(itemDescent),
+ mTopItemAlignment(topItemAlignment)
{
}
- void Portrait( bool& current, const PropertyInputContainer& inputs )
+ void Portrait(bool& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- float itemsCachedBeforeTopItem = layoutSize.height*(mTopItemAlignment+0.5f) / mItemDescent;
- current = ( layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= ( layoutSize.height / mItemDescent ) + 1.0f );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ float itemsCachedBeforeTopItem = layoutSize.height * (mTopItemAlignment + 0.5f) / mItemDescent;
+ current = (layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= (layoutSize.height / mItemDescent) + 1.0f);
}
- void Landscape( bool& current, const PropertyInputContainer& inputs )
+ void Landscape(bool& current, const PropertyInputContainer& inputs)
{
- float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId );
- const Vector3& layoutSize = inputs[1]->GetVector3();
- float itemsCachedBeforeTopItem = layoutSize.width*(mTopItemAlignment+0.5f) / mItemDescent;
- current = ( layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= ( layoutSize.width / mItemDescent ) + 1.0f );
+ float layoutPosition = inputs[0]->GetFloat() + static_cast<float>(mItemId);
+ const Vector3& layoutSize = inputs[1]->GetVector3();
+ float itemsCachedBeforeTopItem = layoutSize.width * (mTopItemAlignment + 0.5f) / mItemDescent;
+ current = (layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= (layoutSize.width / mItemDescent) + 1.0f);
}
unsigned int mItemId;
- float mItemSpacingRadians;
- float mItemDescent;
- float mTopItemAlignment;
+ float mItemSpacingRadians;
+ float mItemDescent;
+ float mTopItemAlignment;
};
} // unnamed namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
struct SpiralLayout::Impl
{
Impl()
{
mImpl->mItemSpacingRadians = itemSpacing;
- float itemsPerSpiral = std::max(1.0f, (2.0f*(float)Math::PI) / mImpl->mItemSpacingRadians);
- mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral;
+ float itemsPerSpiral = std::max(1.0f, (2.0f * (float)Math::PI) / mImpl->mItemSpacingRadians);
+ mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral;
}
Radian SpiralLayout::GetItemSpacing() const
{
- return Radian( mImpl->mItemSpacingRadians );
+ return Radian(mImpl->mItemSpacingRadians);
}
void SpiralLayout::SetRevolutionDistance(float distance)
{
mImpl->mRevolutionDistance = distance;
- float itemsPerSpiral = std::max(1.0f, (2.0f*(float)Math::PI) / mImpl->mItemSpacingRadians);
- mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral;
+ float itemsPerSpiral = std::max(1.0f, (2.0f * (float)Math::PI) / mImpl->mItemSpacingRadians);
+ mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral;
}
float SpiralLayout::GetRevolutionDistance() const
ItemRange SpiralLayout::GetItemsWithinArea(float firstItemPosition, Vector3 layoutSize) const
{
- float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height;
- float itemsPerSpiral = layoutHeight / mImpl->mItemDescent;
+ float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height;
+ float itemsPerSpiral = layoutHeight / mImpl->mItemDescent;
float itemsCachedBeforeTopItem = layoutHeight * (mImpl->mTopItemAlignment + 0.5f) / mImpl->mItemDescent;
- float itemsViewable = std::min(itemsPerSpiral, itemsPerSpiral - itemsCachedBeforeTopItem - firstItemPosition + 1.0f);
+ float itemsViewable = std::min(itemsPerSpiral, itemsPerSpiral - itemsCachedBeforeTopItem - firstItemPosition + 1.0f);
unsigned int firstItem = static_cast<unsigned int>(std::max(0.0f, -firstItemPosition - itemsCachedBeforeTopItem - 1.0f));
unsigned int lastItem = static_cast<unsigned int>(std::max(0.0f, firstItem + itemsViewable));
- return ItemRange(firstItem, lastItem+1);
+ return ItemRange(firstItem, lastItem + 1);
}
unsigned int SpiralLayout::GetReserveItemCount(Vector3 layoutSize) const
{
- float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height;
+ float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height;
return static_cast<unsigned int>(layoutHeight / mImpl->mItemDescent);
}
-void SpiralLayout::GetDefaultItemSize( unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize ) const
+void SpiralLayout::GetDefaultItemSize(unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize) const
{
itemSize.width = layoutSize.width * 0.25f;
// 4x3 aspect ratio
- itemSize.height = itemSize.depth = ( itemSize.width / 4.0f ) * 3.0f;
+ itemSize.height = itemSize.depth = (itemSize.width / 4.0f) * 3.0f;
}
Degree SpiralLayout::GetScrollDirection() const
{
- Degree scrollDirection(0);
+ Degree scrollDirection(0);
const ControlOrientation::Type orientation = GetOrientation();
- if ( orientation == ControlOrientation::Up )
+ if(orientation == ControlOrientation::Up)
{
- scrollDirection = Degree( -45.0f ); // Allow swiping horizontally & vertically
+ scrollDirection = Degree(-45.0f); // Allow swiping horizontally & vertically
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- scrollDirection = Degree( 45.0f );
+ scrollDirection = Degree(45.0f);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- scrollDirection = Degree( 180.0f - 45.0f );
+ scrollDirection = Degree(180.0f - 45.0f);
}
else // orientation == ControlOrientation::Right
{
- scrollDirection = Degree( 270.0f - 45.0f );
+ scrollDirection = Degree(270.0f - 45.0f);
}
return scrollDirection;
}
-void SpiralLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor )
+void SpiralLayout::ApplyConstraints(Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor)
{
-
// This just implements the default behaviour of constraint application.
// Custom layouts can override this function to apply their custom constraints.
- Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast( itemViewActor );
- if( itemView )
+ Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(itemViewActor);
+ if(itemView)
{
const ControlOrientation::Type orientation = GetOrientation();
// Position constraint
- SpiralPositionConstraint positionConstraint( itemId, GetDefaultSpiralRadiusFunction( layoutSize ), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment );
- Constraint constraint;
- if ( orientation == ControlOrientation::Up )
+ SpiralPositionConstraint positionConstraint(itemId, GetDefaultSpiralRadiusFunction(layoutSize), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment);
+ Constraint constraint;
+ if(orientation == ControlOrientation::Up)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationUp );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationUp);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationLeft );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationLeft);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationDown );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationDown);
}
else // orientation == ControlOrientation::Right
{
- constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationRight );
+ constraint = Constraint::New<Vector3>(actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationRight);
}
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
- constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
+ constraint.AddSource(ParentSource(Actor::Property::SIZE));
constraint.Apply();
// Rotation constraint
- SpiralRotationConstraint rotationConstraint( itemId, mImpl->mItemSpacingRadians );
- if ( orientation == ControlOrientation::Up )
+ SpiralRotationConstraint rotationConstraint(itemId, mImpl->mItemSpacingRadians);
+ if(orientation == ControlOrientation::Up)
{
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationUp );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationUp);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationLeft );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationLeft);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationDown );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationDown);
}
else // orientation == ControlOrientation::Right
{
- constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationRight );
+ constraint = Constraint::New<Quaternion>(actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationRight);
}
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
constraint.Apply();
// Color constraint
- constraint = Constraint::New< Vector4 >( actor, Actor::Property::COLOR, SpiralColorConstraint( itemId, mImpl->mItemSpacingRadians ) );
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
+ constraint = Constraint::New<Vector4>(actor, Actor::Property::COLOR, SpiralColorConstraint(itemId, mImpl->mItemSpacingRadians));
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
constraint.SetRemoveAction(Dali::Constraint::DISCARD);
constraint.Apply();
// Visibility constraint
- SpiralVisibilityConstraint visibilityConstraint( itemId, mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment );
- if (IsVertical( orientation ) )
+ SpiralVisibilityConstraint visibilityConstraint(itemId, mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment);
+ if(IsVertical(orientation))
{
- constraint = Constraint::New< bool >( actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Portrait );
+ constraint = Constraint::New<bool>(actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Portrait);
}
else // horizontal
{
- constraint = Constraint::New< bool >( actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Landscape );
+ constraint = Constraint::New<bool>(actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Landscape);
}
- constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) );
- constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
+ constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION));
+ constraint.AddSource(ParentSource(Actor::Property::SIZE));
constraint.SetRemoveAction(Dali::Constraint::DISCARD);
constraint.Apply();
}
void SpiralLayout::SetSpiralLayoutProperties(const Property::Map& properties)
{
// Set any properties specified for SpiralLayout.
- for( unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx )
+ for(unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx)
{
- KeyValuePair propertyPair = properties.GetKeyValue( idx );
+ KeyValuePair propertyPair = properties.GetKeyValue(idx);
switch(DefaultItemLayoutProperty::Property(propertyPair.first.indexKey))
{
case DefaultItemLayoutProperty::SPIRAL_ITEM_SPACING:
Vector3 SpiralLayout::GetItemPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) const
{
- Vector3 itemPosition = Vector3::ZERO;
- const ControlOrientation::Type orientation = GetOrientation();
+ Vector3 itemPosition = Vector3::ZERO;
+ const ControlOrientation::Type orientation = GetOrientation();
- SpiralPositionConstraint positionConstraint( itemID, GetDefaultSpiralRadiusFunction( layoutSize ), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment );
+ SpiralPositionConstraint positionConstraint(itemID, GetDefaultSpiralRadiusFunction(layoutSize), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment);
- if ( orientation == ControlOrientation::Up )
+ if(orientation == ControlOrientation::Up)
{
- positionConstraint.OrientationUp( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionConstraint.OrientationUp(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
- else if ( orientation == ControlOrientation::Left )
+ else if(orientation == ControlOrientation::Left)
{
- positionConstraint.OrientationLeft( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionConstraint.OrientationLeft(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
- else if ( orientation == ControlOrientation::Down )
+ else if(orientation == ControlOrientation::Down)
{
- positionConstraint.OrientationDown( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionConstraint.OrientationDown(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
else //orientation == ControlOrientation::Right
{
- positionConstraint.OrientationRight( itemPosition, currentLayoutPosition + itemID, layoutSize );
+ positionConstraint.OrientationRight(itemPosition, currentLayoutPosition + itemID, layoutSize);
}
return itemPosition;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
///////////////////////////////////////////////////////////////////////////////////////////////////
// ScrollBase
///////////////////////////////////////////////////////////////////////////////////////////////////
-ScrollBase::ScrollBase( ControlBehaviour behaviourFlags )
-: Scrollable( behaviourFlags ),
+ScrollBase::ScrollBase(ControlBehaviour behaviourFlags)
+: Scrollable(behaviourFlags),
mParent(NULL),
mDelay(0.0f)
{
}
-void ScrollBase::SetParent(ScrollBase *parent)
+void ScrollBase::SetParent(ScrollBase* parent)
{
mParent = parent;
}
// Apply all our constraints to this new child.
ConstraintStack::iterator i;
- for(i = mConstraintStack.begin();i!=mConstraintStack.end();i++)
+ for(i = mConstraintStack.begin(); i != mConstraintStack.end(); i++)
{
actorInfo->ApplyConstraint(*i);
}
void ScrollBase::UnbindActor(Actor child)
{
// Find the child in mBoundActors, and unparent it
- for (ActorInfoIter iter = mBoundActors.begin(); iter != mBoundActors.end(); ++iter)
+ for(ActorInfoIter iter = mBoundActors.begin(); iter != mBoundActors.end(); ++iter)
{
ActorInfoPtr actorInfo = *iter;
- if( actorInfo->mActor == child )
+ if(actorInfo->mActor == child)
{
mBoundActors.erase(iter);
break;
{
mConstraintStack.push_back(constraint);
- for(ActorInfoIter i = mBoundActors.begin();i != mBoundActors.end(); ++i)
+ for(ActorInfoIter i = mBoundActors.begin(); i != mBoundActors.end(); ++i)
{
(*i)->ApplyConstraint(constraint);
}
{
mConstraintStack.clear();
- for(ActorInfoIter i = mBoundActors.begin();i != mBoundActors.end(); ++i)
+ for(ActorInfoIter i = mBoundActors.begin(); i != mBoundActors.end(); ++i)
{
(*i)->RemoveConstraints();
}
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/controls/scrollable/scrollable-impl.h>
#include <dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.h>
+#include <dali-toolkit/internal/controls/scrollable/scrollable-impl.h>
#include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h>
using namespace Dali;
namespace
{
-
const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f;
// local helper function to resize the height of the bounce actor
-float GetBounceActorHeight( float width, float defaultHeight )
+float GetBounceActorHeight(float width, float defaultHeight)
{
return (width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD) ? defaultHeight : defaultHeight * 0.5f;
}
-const float MAX_OVERSHOOT_NOTIFY_AMOUNT = 0.99f; // maximum amount to set notification for increased overshoot, beyond this we just wait for it to reduce again
-const float MIN_OVERSHOOT_NOTIFY_AMOUNT = Math::MACHINE_EPSILON_0; // minimum amount to set notification for reduced overshoot, beyond this we just wait for it to increase again
-const float OVERSHOOT_NOTIFY_STEP = 0.01f; // amount to set notifications beyond current overshoot value
+const float MAX_OVERSHOOT_NOTIFY_AMOUNT = 0.99f; // maximum amount to set notification for increased overshoot, beyond this we just wait for it to reduce again
+const float MIN_OVERSHOOT_NOTIFY_AMOUNT = Math::MACHINE_EPSILON_0; // minimum amount to set notification for reduced overshoot, beyond this we just wait for it to increase again
+const float OVERSHOOT_NOTIFY_STEP = 0.01f; // amount to set notifications beyond current overshoot value
-}
+} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-ScrollOvershootIndicator::ScrollOvershootIndicator() :
- mEffectX(NULL),
+ScrollOvershootIndicator::ScrollOvershootIndicator()
+: mEffectX(NULL),
mEffectY(NULL)
{
}
ScrollOvershootIndicator::~ScrollOvershootIndicator()
{
-
}
ScrollOvershootIndicator* ScrollOvershootIndicator::New()
mEffectY->Reset();
}
-void ScrollOvershootIndicator::SetOvershootEffectColor( const Vector4& color )
+void ScrollOvershootIndicator::SetOvershootEffectColor(const Vector4& color)
{
if(mEffectX)
{
}
}
-ScrollOvershootEffect::ScrollOvershootEffect( bool vertical ) :
- mVertical(vertical)
+ScrollOvershootEffect::ScrollOvershootEffect(bool vertical)
+: mVertical(vertical)
{
-
}
bool ScrollOvershootEffect::IsVertical() const
return mVertical;
}
-ScrollOvershootEffectRipple::ScrollOvershootEffectRipple( bool vertical, Scrollable& scrollable ) :
- ScrollOvershootEffect( vertical ),
- mAttachedScrollView(scrollable),
- mOvershootProperty(Property::INVALID_INDEX),
- mEffectOvershootProperty(Property::INVALID_INDEX),
- mOvershoot(0.0f),
- mOvershootSize( scrollable.GetOvershootSize() ),
- mAnimationStateFlags(0)
+ScrollOvershootEffectRipple::ScrollOvershootEffectRipple(bool vertical, Scrollable& scrollable)
+: ScrollOvershootEffect(vertical),
+ mAttachedScrollView(scrollable),
+ mOvershootProperty(Property::INVALID_INDEX),
+ mEffectOvershootProperty(Property::INVALID_INDEX),
+ mOvershoot(0.0f),
+ mOvershootSize(scrollable.GetOvershootSize()),
+ mAnimationStateFlags(0)
{
mOvershootOverlay = CreateBouncingEffectActor(mEffectOvershootProperty);
- mOvershootOverlay.SetProperty( Actor::Property::COLOR,mAttachedScrollView.GetOvershootEffectColor());
- mOvershootOverlay.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT );
- mOvershootOverlay.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::TOP_LEFT);
- mOvershootOverlay.SetProperty( Actor::Property::VISIBLE,false);
-
+ mOvershootOverlay.SetProperty(Actor::Property::COLOR, mAttachedScrollView.GetOvershootEffectColor());
+ mOvershootOverlay.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ mOvershootOverlay.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ mOvershootOverlay.SetProperty(Actor::Property::VISIBLE, false);
}
void ScrollOvershootEffectRipple::Apply()
{
- Actor self = mAttachedScrollView.Self();
+ Actor self = mAttachedScrollView.Self();
mOvershootProperty = IsVertical() ? Toolkit::ScrollView::Property::OVERSHOOT_Y : Toolkit::ScrollView::Property::OVERSHOOT_X;
// make sure height is set, since we only create a constraint for image width
mOvershootSize = mAttachedScrollView.GetOvershootSize();
- mOvershootOverlay.SetProperty( Actor::Property::SIZE, mOvershootSize );
+ mOvershootOverlay.SetProperty(Actor::Property::SIZE, mOvershootSize);
mAttachedScrollView.AddOverlay(mOvershootOverlay);
UpdatePropertyNotifications();
}
-void ScrollOvershootEffectRipple::Remove( Scrollable& scrollable )
+void ScrollOvershootEffectRipple::Remove(Scrollable& scrollable)
{
if(mOvershootOverlay)
{
void ScrollOvershootEffectRipple::Reset()
{
- mOvershootOverlay.SetProperty( Actor::Property::VISIBLE,false);
- mOvershootOverlay.SetProperty( mEffectOvershootProperty, 0.f);
+ mOvershootOverlay.SetProperty(Actor::Property::VISIBLE, false);
+ mOvershootOverlay.SetProperty(mEffectOvershootProperty, 0.f);
}
void ScrollOvershootEffectRipple::UpdatePropertyNotifications()
Actor self = mAttachedScrollView.Self();
// update overshoot increase notify
- if( mOvershootIncreaseNotification )
+ if(mOvershootIncreaseNotification)
{
- self.RemovePropertyNotification( mOvershootIncreaseNotification );
+ self.RemovePropertyNotification(mOvershootIncreaseNotification);
mOvershootIncreaseNotification.Reset();
}
- if( absOvershoot < MAX_OVERSHOOT_NOTIFY_AMOUNT )
+ if(absOvershoot < MAX_OVERSHOOT_NOTIFY_AMOUNT)
{
float increaseStep = absOvershoot + OVERSHOOT_NOTIFY_STEP;
- if( increaseStep > MAX_OVERSHOOT_NOTIFY_AMOUNT )
+ if(increaseStep > MAX_OVERSHOOT_NOTIFY_AMOUNT)
{
increaseStep = MAX_OVERSHOOT_NOTIFY_AMOUNT;
}
- mOvershootIncreaseNotification = self.AddPropertyNotification( mOvershootProperty, OutsideCondition(-increaseStep, increaseStep) );
+ mOvershootIncreaseNotification = self.AddPropertyNotification(mOvershootProperty, OutsideCondition(-increaseStep, increaseStep));
mOvershootIncreaseNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_TRUE);
mOvershootIncreaseNotification.NotifySignal().Connect(this, &ScrollOvershootEffectRipple::OnOvershootNotification);
}
// update overshoot decrease notify
- if( mOvershootDecreaseNotification )
+ if(mOvershootDecreaseNotification)
{
- self.RemovePropertyNotification( mOvershootDecreaseNotification );
+ self.RemovePropertyNotification(mOvershootDecreaseNotification);
mOvershootDecreaseNotification.Reset();
}
- if( absOvershoot > MIN_OVERSHOOT_NOTIFY_AMOUNT )
+ if(absOvershoot > MIN_OVERSHOOT_NOTIFY_AMOUNT)
{
float reduceStep = absOvershoot - OVERSHOOT_NOTIFY_STEP;
- if( reduceStep < MIN_OVERSHOOT_NOTIFY_AMOUNT )
+ if(reduceStep < MIN_OVERSHOOT_NOTIFY_AMOUNT)
{
reduceStep = MIN_OVERSHOOT_NOTIFY_AMOUNT;
}
- mOvershootDecreaseNotification = self.AddPropertyNotification( mOvershootProperty, InsideCondition(-reduceStep, reduceStep) );
+ mOvershootDecreaseNotification = self.AddPropertyNotification(mOvershootProperty, InsideCondition(-reduceStep, reduceStep));
mOvershootDecreaseNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_TRUE);
mOvershootDecreaseNotification.NotifySignal().Connect(this, &ScrollOvershootEffectRipple::OnOvershootNotification);
}
}
-void ScrollOvershootEffectRipple::SetOvershootEffectColor( const Vector4& color )
+void ScrollOvershootEffectRipple::SetOvershootEffectColor(const Vector4& color)
{
if(mOvershootOverlay)
{
- mOvershootOverlay.SetProperty( Actor::Property::COLOR,color);
+ mOvershootOverlay.SetProperty(Actor::Property::COLOR, color);
}
}
-void ScrollOvershootEffectRipple::UpdateVisibility( bool visible )
+void ScrollOvershootEffectRipple::UpdateVisibility(bool visible)
{
- mOvershootOverlay.SetProperty( Actor::Property::VISIBLE,visible);
+ mOvershootOverlay.SetProperty(Actor::Property::VISIBLE, visible);
// make sure overshoot image is correctly placed
- if( visible )
+ if(visible)
{
Actor self = mAttachedScrollView.Self();
if(mOvershoot > 0.0f)
{
// positive overshoot
- const Vector3 size = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
- Vector3 relativeOffset;
- const Vector3 parentSize = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ const Vector3 size = mOvershootOverlay.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
+ Vector3 relativeOffset;
+ const Vector3 parentSize = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
if(IsVertical())
{
- mOvershootOverlay.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( 0.0f ), Vector3::ZAXIS ) ) );
- mOvershootOverlay.SetProperty( Actor::Property::SIZE, Vector3( parentSize.width, GetBounceActorHeight(parentSize.width, mOvershootSize.height), size.depth ) );
+ mOvershootOverlay.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(0.0f), Vector3::ZAXIS)));
+ mOvershootOverlay.SetProperty(Actor::Property::SIZE, Vector3(parentSize.width, GetBounceActorHeight(parentSize.width, mOvershootSize.height), size.depth));
}
else
{
- mOvershootOverlay.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( 1.5f * Math::PI ), Vector3::ZAXIS ) ) );
- mOvershootOverlay.SetProperty( Actor::Property::SIZE, Vector3( parentSize.height, GetBounceActorHeight(parentSize.height, mOvershootSize.height), size.depth ) );
+ mOvershootOverlay.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(1.5f * Math::PI), Vector3::ZAXIS)));
+ mOvershootOverlay.SetProperty(Actor::Property::SIZE, Vector3(parentSize.height, GetBounceActorHeight(parentSize.height, mOvershootSize.height), size.depth));
relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
}
- mOvershootOverlay.SetProperty( Actor::Property::POSITION, relativeOffset * parentSize );
+ mOvershootOverlay.SetProperty(Actor::Property::POSITION, relativeOffset * parentSize);
}
else
{
// negative overshoot
- const Vector3 size = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
- Vector3 relativeOffset;
- const Vector3 parentSize = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ const Vector3 size = mOvershootOverlay.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
+ Vector3 relativeOffset;
+ const Vector3 parentSize = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
if(IsVertical())
{
- mOvershootOverlay.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( Math::PI ), Vector3::ZAXIS ) ) );
- mOvershootOverlay.SetProperty( Actor::Property::SIZE, Vector3( parentSize.width, GetBounceActorHeight(parentSize.width, mOvershootSize.height), size.depth ) );
+ mOvershootOverlay.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(Math::PI), Vector3::ZAXIS)));
+ mOvershootOverlay.SetProperty(Actor::Property::SIZE, Vector3(parentSize.width, GetBounceActorHeight(parentSize.width, mOvershootSize.height), size.depth));
relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
}
else
{
- mOvershootOverlay.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( 0.5f * Math::PI ), Vector3::ZAXIS ) ) );
- mOvershootOverlay.SetProperty( Actor::Property::SIZE, Vector3( parentSize.height, GetBounceActorHeight(parentSize.height, mOvershootSize.height), size.depth ) );
+ mOvershootOverlay.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(0.5f * Math::PI), Vector3::ZAXIS)));
+ mOvershootOverlay.SetProperty(Actor::Property::SIZE, Vector3(parentSize.height, GetBounceActorHeight(parentSize.height, mOvershootSize.height), size.depth));
relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
}
- mOvershootOverlay.SetProperty( Actor::Property::POSITION, relativeOffset * parentSize );
+ mOvershootOverlay.SetProperty(Actor::Property::POSITION, relativeOffset * parentSize);
}
}
}
void ScrollOvershootEffectRipple::OnOvershootNotification(PropertyNotification& source)
{
Actor self = mAttachedScrollView.Self();
- mOvershoot = self.GetCurrentProperty< float >( mOvershootProperty );
+ mOvershoot = self.GetCurrentProperty<float>(mOvershootProperty);
SetOvershoot(mOvershoot, false);
UpdatePropertyNotifications();
}
void ScrollOvershootEffectRipple::SetOvershoot(float amount, bool animate)
{
- float absAmount = fabsf(amount);
- bool animatingOn = absAmount > Math::MACHINE_EPSILON_0;
- if( (animatingOn && (mAnimationStateFlags & AnimatingIn)) )
+ float absAmount = fabsf(amount);
+ bool animatingOn = absAmount > Math::MACHINE_EPSILON_0;
+ if((animatingOn && (mAnimationStateFlags & AnimatingIn)))
{
// trying to do what we are already doing
- if( mAnimationStateFlags & AnimateBack )
+ if(mAnimationStateFlags & AnimateBack)
{
mAnimationStateFlags &= ~AnimateBack;
}
return;
}
- if( (!animatingOn && (mAnimationStateFlags & AnimatingOut)) )
+ if((!animatingOn && (mAnimationStateFlags & AnimatingOut)))
{
// trying to do what we are already doing
return;
}
- if( !animatingOn && (mAnimationStateFlags & AnimatingIn) )
+ if(!animatingOn && (mAnimationStateFlags & AnimatingIn))
{
// dont interrupt while animating on
mAnimationStateFlags |= AnimateBack;
return;
}
- if( absAmount > Math::MACHINE_EPSILON_1 )
+ if(absAmount > Math::MACHINE_EPSILON_1)
{
UpdateVisibility(true);
}
float overshootAnimationSpeed = mAttachedScrollView.Self().GetProperty<float>(Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED);
- if( animate && overshootAnimationSpeed > Math::MACHINE_EPSILON_0 )
+ if(animate && overshootAnimationSpeed > Math::MACHINE_EPSILON_0)
{
- float currentOvershoot = fabsf( mOvershootOverlay.GetProperty( mEffectOvershootProperty ).Get<float>() );
- float duration = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).height * (animatingOn ? (1.0f - currentOvershoot) : currentOvershoot) / overshootAnimationSpeed;
+ float currentOvershoot = fabsf(mOvershootOverlay.GetProperty(mEffectOvershootProperty).Get<float>());
+ float duration = mOvershootOverlay.GetCurrentProperty<Vector3>(Actor::Property::SIZE).height * (animatingOn ? (1.0f - currentOvershoot) : currentOvershoot) / overshootAnimationSpeed;
- if( duration > Math::MACHINE_EPSILON_0 )
+ if(duration > Math::MACHINE_EPSILON_0)
{
if(mScrollOvershootAnimation)
{
- mScrollOvershootAnimation.FinishedSignal().Disconnect( this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished );
+ mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished);
mScrollOvershootAnimation.Stop();
mScrollOvershootAnimation.Reset();
}
mScrollOvershootAnimation = Animation::New(duration);
- mScrollOvershootAnimation.FinishedSignal().Connect( this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished );
- mScrollOvershootAnimation.AnimateTo( Property(mOvershootOverlay, mEffectOvershootProperty), amount, TimePeriod(duration) );
+ mScrollOvershootAnimation.FinishedSignal().Connect(this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished);
+ mScrollOvershootAnimation.AnimateTo(Property(mOvershootOverlay, mEffectOvershootProperty), amount, TimePeriod(duration));
mScrollOvershootAnimation.Play();
mAnimationStateFlags = animatingOn ? AnimatingIn : AnimatingOut;
}
}
else
{
- mOvershootOverlay.SetProperty( mEffectOvershootProperty, amount);
+ mOvershootOverlay.SetProperty(mEffectOvershootProperty, amount);
}
}
void ScrollOvershootEffectRipple::OnOvershootAnimFinished(Animation& animation)
{
bool animateOff = false;
- if( mAnimationStateFlags & AnimatingOut )
+ if(mAnimationStateFlags & AnimatingOut)
{
// should now be offscreen
- mOvershootOverlay.SetProperty( Actor::Property::VISIBLE,false);
+ mOvershootOverlay.SetProperty(Actor::Property::VISIBLE, false);
}
- if( (mAnimationStateFlags & AnimateBack) )
+ if((mAnimationStateFlags & AnimateBack))
{
animateOff = true;
}
- mScrollOvershootAnimation.FinishedSignal().Disconnect( this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished );
+ mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished);
mScrollOvershootAnimation.Stop();
mScrollOvershootAnimation.Reset();
mAnimationStateFlags = 0;
- if( animateOff )
+ if(animateOff)
{
SetOvershoot(0.0f, true);
}
}
-ScrollOvershootEffectRipplePtr ScrollOvershootEffectRipple::New( bool vertical, Scrollable& scrollable )
+ScrollOvershootEffectRipplePtr ScrollOvershootEffectRipple::New(bool vertical, Scrollable& scrollable)
{
return new ScrollOvershootEffectRipple(vertical, scrollable);
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
ScrollViewEffect::ScrollViewEffect()
: mScrollViewImpl(NULL)
{
void ScrollViewEffect::Attach(Toolkit::ScrollView& scrollView)
{
- DALI_ASSERT_ALWAYS( (!mScrollViewImpl) && "Already attached to a ScrollView" );
+ DALI_ASSERT_ALWAYS((!mScrollViewImpl) && "Already attached to a ScrollView");
mScrollViewImpl = &GetImpl(scrollView);
void ScrollViewEffect::Detach(Toolkit::ScrollView& scrollView)
{
- DALI_ASSERT_ALWAYS( (mScrollViewImpl) && "Already detached from ScrollView" );
- DALI_ASSERT_ALWAYS( (&GetImpl(scrollView) == mScrollViewImpl) && "Effect attached to a different ScrollView");
+ DALI_ASSERT_ALWAYS((mScrollViewImpl) && "Already detached from ScrollView");
+ DALI_ASSERT_ALWAYS((&GetImpl(scrollView) == mScrollViewImpl) && "Effect attached to a different ScrollView");
OnDetach(scrollView);
{
DALI_ASSERT_ALWAYS(mScrollViewImpl);
- return DownCast<Toolkit::ScrollView>( mScrollViewImpl->Self() );
+ return DownCast<Toolkit::ScrollView>(mScrollViewImpl->Self());
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
#include <dali/devel-api/actors/actor-devel.h>
-#include <dali/public-api/animation/constraints.h>
#include <dali/devel-api/common/stage.h>
-#include <dali/public-api/events/wheel-event.h>
-#include <dali/public-api/events/touch-event.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/public-api/object/property-map.h>
-#include <dali/devel-api/object/property-helper-devel.h>
#include <dali/devel-api/events/pan-gesture-devel.h>
+#include <dali/devel-api/object/property-helper-devel.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/animation/constraints.h>
+#include <dali/public-api/events/touch-event.h>
+#include <dali/public-api/events/wheel-event.h>
+#include <dali/public-api/object/property-map.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/scroll-bar/scroll-bar.h>
-#include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h>
-#include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
-#include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-mode.h>
#include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
#include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
+#include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-mode.h>
+#include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
+#include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h>
//#define ENABLED_SCROLL_STATE_LOGGING
#ifdef ENABLED_SCROLL_STATE_LOGGING
-#define DALI_LOG_SCROLL_STATE(format, ...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ## __VA_ARGS__)
+#define DALI_LOG_SCROLL_STATE(format, ...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define DALI_LOG_SCROLL_STATE(format, ...)
#endif
namespace
{
-const float DEFAULT_SLOW_SNAP_ANIMATION_DURATION(0.5f); ///< Default Drag-Release animation time.
-const float DEFAULT_FAST_SNAP_ANIMATION_DURATION(0.25f); ///< Default Drag-Flick animation time.
-const float DEFAULT_SNAP_OVERSHOOT_DURATION(0.5f); ///< Default Overshoot snapping animation time.
-const float DEFAULT_MAX_OVERSHOOT(100.0f); ///< Default maximum allowed overshoot in pixels
+const float DEFAULT_SLOW_SNAP_ANIMATION_DURATION(0.5f); ///< Default Drag-Release animation time.
+const float DEFAULT_FAST_SNAP_ANIMATION_DURATION(0.25f); ///< Default Drag-Flick animation time.
+const float DEFAULT_SNAP_OVERSHOOT_DURATION(0.5f); ///< Default Overshoot snapping animation time.
+const float DEFAULT_MAX_OVERSHOOT(100.0f); ///< Default maximum allowed overshoot in pixels
-const float DEFAULT_AXIS_AUTO_LOCK_GRADIENT(0.36f); ///< Default Axis-AutoLock gradient threshold. default is 0.36:1 (20 degrees)
-const float DEFAULT_FRICTION_COEFFICIENT(1.0f); ///< Default Friction Co-efficient. (in stage diagonals per second)
-const float DEFAULT_FLICK_SPEED_COEFFICIENT(1.0f); ///< Default Flick speed coefficient (multiples input touch velocity)
-const float DEFAULT_MAX_FLICK_SPEED(3.0f); ///< Default Maximum flick speed. (in stage diagonals per second)
+const float DEFAULT_AXIS_AUTO_LOCK_GRADIENT(0.36f); ///< Default Axis-AutoLock gradient threshold. default is 0.36:1 (20 degrees)
+const float DEFAULT_FRICTION_COEFFICIENT(1.0f); ///< Default Friction Co-efficient. (in stage diagonals per second)
+const float DEFAULT_FLICK_SPEED_COEFFICIENT(1.0f); ///< Default Flick speed coefficient (multiples input touch velocity)
+const float DEFAULT_MAX_FLICK_SPEED(3.0f); ///< Default Maximum flick speed. (in stage diagonals per second)
-const Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed
-const float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s
-const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
-const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
-const float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking)
-const Vector2 DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = Vector2(0.17f, 0.1f); ///< The step of horizontal scroll distance in the proportion of stage size for each wheel event received.
-const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
-const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
-const float DEFAULT_SCROLL_UPDATE_DISTANCE( 30.0f ); ///< Default distance to travel in pixels for scroll update signal
+const Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed
+const float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s
+const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
+const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
+const float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking)
+const Vector2 DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = Vector2(0.17f, 0.1f); ///< The step of horizontal scroll distance in the proportion of stage size for each wheel event received.
+const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET(150u);
+const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
+const float DEFAULT_SCROLL_UPDATE_DISTANCE(30.0f); ///< Default distance to travel in pixels for scroll update signal
-const std::string INTERNAL_MAX_POSITION_PROPERTY_NAME( "internalMaxPosition" );
+const std::string INTERNAL_MAX_POSITION_PROPERTY_NAME("internalMaxPosition");
// Helpers ////////////////////////////////////////////////////////////////////////////////////////
{
if(bias == Dali::Toolkit::DIRECTION_BIAS_NONE)
{
- return ShortestDistanceInDomain( a, b, start, end );
+ return ShortestDistanceInDomain(a, b, start, end);
}
// (a-start + end-b)
- float size = end-start;
- float vect = b-a;
+ float size = end - start;
+ float vect = b - a;
if(vect > 0)
{
}
else
{
- float aRight = a+size;
- return b-aRight;
+ float aRight = a + size;
+ return b - aRight;
}
}
else
}
else
{
- float aLeft = a-size;
- return b-aLeft;
+ float aLeft = a - size;
+ return b - aLeft;
}
}
}
* @param anchor The Anchor point of interest.
* @return The position of the Anchor
*/
-Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
+Vector3 GetPositionOfAnchor(Actor& actor, const Vector3& anchor)
{
- Vector3 childPosition = actor.GetCurrentProperty< Vector3 >( Actor::Property::POSITION );
- Vector3 childAnchor = - actor.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) + anchor;
- Vector3 childSize = actor.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Vector3 childPosition = actor.GetCurrentProperty<Vector3>(Actor::Property::POSITION);
+ Vector3 childAnchor = -actor.GetCurrentProperty<Vector3>(Actor::Property::ANCHOR_POINT) + anchor;
+ Vector3 childSize = actor.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
return childPosition + childAnchor * childSize;
}
* scroll domain. This is a value from 0.0f to 1.0f in each
* scroll position axis.
*/
-void InternalRelativePositionConstraint( Vector2& relativePosition, const PropertyInputContainer& inputs)
+void InternalRelativePositionConstraint(Vector2& relativePosition, const PropertyInputContainer& inputs)
{
- Vector2 position = -inputs[0]->GetVector2();
- const Vector2& min = inputs[1]->GetVector2();
- const Vector2& max = inputs[2]->GetVector2();
- const Vector3& size = inputs[3]->GetVector3();
+ Vector2 position = -inputs[0]->GetVector2();
+ const Vector2& min = inputs[1]->GetVector2();
+ const Vector2& max = inputs[2]->GetVector2();
+ const Vector3& size = inputs[3]->GetVector3();
position.x = WrapInDomain(position.x, min.x, max.x);
position.y = WrapInDomain(position.y, min.y, max.y);
* Internal scroll domain Constraint
* Generates the scroll domain of the scroll view.
*/
-void InternalScrollDomainConstraint( Vector2& scrollDomain, const PropertyInputContainer& inputs)
+void InternalScrollDomainConstraint(Vector2& scrollDomain, const PropertyInputContainer& inputs)
{
- const Vector2& min = inputs[0]->GetVector2();
- const Vector2& max = inputs[1]->GetVector2();
+ const Vector2& min = inputs[0]->GetVector2();
+ const Vector2& max = inputs[1]->GetVector2();
const Vector3& size = inputs[2]->GetVector3();
scrollDomain = (max - min) - size.GetVectorXY();
* Internal maximum scroll position Constraint
* Generates the maximum scroll position of the scroll view.
*/
-void InternalPrePositionMaxConstraint( Vector2& scrollMax, const PropertyInputContainer& inputs)
+void InternalPrePositionMaxConstraint(Vector2& scrollMax, const PropertyInputContainer& inputs)
{
- const Vector2& max = inputs[0]->GetVector2();
+ const Vector2& max = inputs[0]->GetVector2();
const Vector3& size = inputs[1]->GetVector3();
scrollMax = max - size.GetVectorXY();
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
return Toolkit::ScrollView::New();
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ScrollView, Toolkit::Scrollable, Create )
-
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wrapEnabled", BOOLEAN, WRAP_ENABLED )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "panningEnabled", BOOLEAN, PANNING_ENABLED )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "axisAutoLockEnabled", BOOLEAN, AXIS_AUTO_LOCK_ENABLED )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wheelScrollDistanceStep", VECTOR2, WHEEL_SCROLL_DISTANCE_STEP )
-DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollMode", MAP, SCROLL_MODE )
-
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPosition", VECTOR2, SCROLL_POSITION)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPrePosition", VECTOR2, SCROLL_PRE_POSITION)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionX", SCROLL_PRE_POSITION_X, SCROLL_PRE_POSITION, 0)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionY", SCROLL_PRE_POSITION_Y, SCROLL_PRE_POSITION, 1)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMax", VECTOR2, SCROLL_PRE_POSITION_MAX)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMaxX", SCROLL_PRE_POSITION_MAX_X, SCROLL_PRE_POSITION_MAX, 0)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMaxY", SCROLL_PRE_POSITION_MAX_Y, SCROLL_PRE_POSITION_MAX, 1)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "overshootX", FLOAT, OVERSHOOT_X)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "overshootY", FLOAT, OVERSHOOT_Y)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollFinal", VECTOR2, SCROLL_FINAL)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollFinalX", SCROLL_FINAL_X, SCROLL_FINAL,0)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollFinalY", SCROLL_FINAL_Y, SCROLL_FINAL,1)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wrap", BOOLEAN, WRAP)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "panning", BOOLEAN, PANNING)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrolling", BOOLEAN, SCROLLING)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollDomainSize", VECTOR2, SCROLL_DOMAIN_SIZE)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollDomainSizeX", SCROLL_DOMAIN_SIZE_X, SCROLL_DOMAIN_SIZE, 0)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollDomainSizeY", SCROLL_DOMAIN_SIZE_Y, SCROLL_DOMAIN_SIZE, 1)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollDomainOffset", VECTOR2, SCROLL_DOMAIN_OFFSET)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPositionDelta", VECTOR2, SCROLL_POSITION_DELTA)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "startPagePosition", VECTOR3, START_PAGE_POSITION)
-
-DALI_SIGNAL_REGISTRATION( Toolkit, ScrollView, "valueChanged", SIGNAL_SNAP_STARTED )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ScrollView, Toolkit::Scrollable, Create)
+
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wrapEnabled", BOOLEAN, WRAP_ENABLED)
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "panningEnabled", BOOLEAN, PANNING_ENABLED)
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "axisAutoLockEnabled", BOOLEAN, AXIS_AUTO_LOCK_ENABLED)
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wheelScrollDistanceStep", VECTOR2, WHEEL_SCROLL_DISTANCE_STEP)
+DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollMode", MAP, SCROLL_MODE)
+
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPosition", VECTOR2, SCROLL_POSITION)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPrePosition", VECTOR2, SCROLL_PRE_POSITION)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionX", SCROLL_PRE_POSITION_X, SCROLL_PRE_POSITION, 0)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionY", SCROLL_PRE_POSITION_Y, SCROLL_PRE_POSITION, 1)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMax", VECTOR2, SCROLL_PRE_POSITION_MAX)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMaxX", SCROLL_PRE_POSITION_MAX_X, SCROLL_PRE_POSITION_MAX, 0)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMaxY", SCROLL_PRE_POSITION_MAX_Y, SCROLL_PRE_POSITION_MAX, 1)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "overshootX", FLOAT, OVERSHOOT_X)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "overshootY", FLOAT, OVERSHOOT_Y)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollFinal", VECTOR2, SCROLL_FINAL)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollFinalX", SCROLL_FINAL_X, SCROLL_FINAL, 0)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollFinalY", SCROLL_FINAL_Y, SCROLL_FINAL, 1)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wrap", BOOLEAN, WRAP)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "panning", BOOLEAN, PANNING)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrolling", BOOLEAN, SCROLLING)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollDomainSize", VECTOR2, SCROLL_DOMAIN_SIZE)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollDomainSizeX", SCROLL_DOMAIN_SIZE_X, SCROLL_DOMAIN_SIZE, 0)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollDomainSizeY", SCROLL_DOMAIN_SIZE_Y, SCROLL_DOMAIN_SIZE, 1)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollDomainOffset", VECTOR2, SCROLL_DOMAIN_OFFSET)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPositionDelta", VECTOR2, SCROLL_POSITION_DELTA)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "startPagePosition", VECTOR3, START_PAGE_POSITION)
+
+DALI_SIGNAL_REGISTRATION(Toolkit, ScrollView, "valueChanged", SIGNAL_SNAP_STARTED)
DALI_TYPE_REGISTRATION_END()
ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
{
if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
- currentLockAxis == ScrollView::LockPossible)
+ currentLockAxis == ScrollView::LockPossible)
{
float dx = fabsf(panDelta.x);
float dy = fabsf(panDelta.y);
*/
struct InternalPrePositionConstraint
{
- InternalPrePositionConstraint( const Vector2& initialPanPosition,
- const Vector2& initialPanMask,
- bool axisAutoLock,
- float axisAutoLockGradient,
- ScrollView::LockAxis initialLockAxis,
- const Vector2& maxOvershoot,
- const RulerPtr& rulerX, const RulerPtr& rulerY )
- : mLocalStart( initialPanPosition ),
- mInitialPanMask( initialPanMask ),
- mMaxOvershoot( maxOvershoot ),
- mAxisAutoLockGradient( axisAutoLockGradient ),
- mLockAxis( initialLockAxis ),
- mAxisAutoLock( axisAutoLock ),
- mWasPanning( false )
+ InternalPrePositionConstraint(const Vector2& initialPanPosition,
+ const Vector2& initialPanMask,
+ bool axisAutoLock,
+ float axisAutoLockGradient,
+ ScrollView::LockAxis initialLockAxis,
+ const Vector2& maxOvershoot,
+ const RulerPtr& rulerX,
+ const RulerPtr& rulerY)
+ : mLocalStart(initialPanPosition),
+ mInitialPanMask(initialPanMask),
+ mMaxOvershoot(maxOvershoot),
+ mAxisAutoLockGradient(axisAutoLockGradient),
+ mLockAxis(initialLockAxis),
+ mAxisAutoLock(axisAutoLock),
+ mWasPanning(false)
{
const RulerDomain& rulerDomainX = rulerX->GetDomain();
const RulerDomain& rulerDomainY = rulerY->GetDomain();
- mDomainMin = Vector2( rulerDomainX.min, -rulerDomainY.min );
- mDomainMax = Vector2( -rulerDomainX.max, -rulerDomainY.max );
- mClampX = rulerDomainX.enabled;
- mClampY = rulerDomainY.enabled;
- mFixedRulerX = rulerX->GetType() == Ruler::FIXED;
- mFixedRulerY = rulerY->GetType() == Ruler::FIXED;
+ mDomainMin = Vector2(rulerDomainX.min, -rulerDomainY.min);
+ mDomainMax = Vector2(-rulerDomainX.max, -rulerDomainY.max);
+ mClampX = rulerDomainX.enabled;
+ mClampY = rulerDomainY.enabled;
+ mFixedRulerX = rulerX->GetType() == Ruler::FIXED;
+ mFixedRulerY = rulerY->GetType() == Ruler::FIXED;
}
- void operator()( Vector2& scrollPostPosition, const PropertyInputContainer& inputs )
+ void operator()(Vector2& scrollPostPosition, const PropertyInputContainer& inputs)
{
const Vector2& panPosition = inputs[0]->GetVector2();
- const bool& inGesture = inputs[1]->GetBoolean();
+ const bool& inGesture = inputs[1]->GetBoolean();
// First check if we are within a gesture.
// The ScrollView may have received a start gesture from ::OnPan()
// This gesture must then be rejected as the value will be "old".
// Typically the last value from the end of the last gesture.
// If we are rejecting the gesture, we simply don't modify the constraint target.
- if( inGesture )
+ if(inGesture)
{
- if( !mWasPanning )
+ if(!mWasPanning)
{
- mPrePosition = scrollPostPosition;
- mStartPosition = mPrePosition;
+ mPrePosition = scrollPostPosition;
+ mStartPosition = mPrePosition;
mCurrentPanMask = mInitialPanMask;
- mWasPanning = true;
+ mWasPanning = true;
}
// Calculate Deltas...
const Vector2& currentPosition = panPosition;
- Vector2 panDelta( currentPosition - mLocalStart );
+ Vector2 panDelta(currentPosition - mLocalStart);
// Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
// appears mostly horizontal or mostly vertical respectively...
- if( mAxisAutoLock )
+ if(mAxisAutoLock)
{
- mLockAxis = GetLockAxis( panDelta, mLockAxis, mAxisAutoLockGradient );
- if( mLockAxis == ScrollView::LockVertical )
+ mLockAxis = GetLockAxis(panDelta, mLockAxis, mAxisAutoLockGradient);
+ if(mLockAxis == ScrollView::LockVertical)
{
mCurrentPanMask.y = 0.0f;
}
- else if( mLockAxis == ScrollView::LockHorizontal )
+ else if(mLockAxis == ScrollView::LockHorizontal)
{
mCurrentPanMask.x = 0.0f;
}
// if no wrapping then clamp preposition to maximum overshoot amount
const Vector3& size = inputs[2]->GetVector3();
- if( mClampX )
+ if(mClampX)
{
- float newXPosition = Clamp( scrollPostPosition.x, ( mDomainMax.x + size.x ) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
- if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
- || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
+ float newXPosition = Clamp(scrollPostPosition.x, (mDomainMax.x + size.x) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x);
+ if((newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1) || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1))
{
mPrePosition.x = newXPosition;
- mLocalStart.x = panPosition.x;
+ mLocalStart.x = panPosition.x;
}
scrollPostPosition.x = newXPosition;
}
- if( mClampY )
+ if(mClampY)
{
- float newYPosition = Clamp( scrollPostPosition.y, ( mDomainMax.y + size.y ) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
- if( ( newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1 )
- || ( newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1 ) )
+ float newYPosition = Clamp(scrollPostPosition.y, (mDomainMax.y + size.y) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y);
+ if((newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1) || (newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1))
{
mPrePosition.y = newYPosition;
- mLocalStart.y = panPosition.y;
+ mLocalStart.y = panPosition.y;
}
scrollPostPosition.y = newYPosition;
}
// If we are using a fixed ruler in a particular axis, limit the maximum pages scrolled on that axis.
- if( mFixedRulerX || mFixedRulerY )
+ if(mFixedRulerX || mFixedRulerY)
{
// Here we limit the maximum amount that can be moved from the starting position of the gesture to one page.
// We do this only if we have a fixed ruler (on that axis) and the mode is enabled.
// Note: A further 1.0f is subtracted to handle a compensation that happens later within the flick handling code in SnapWithVelocity().
// When a flick is completed, an adjustment of 1.0f is sometimes made to allow for the scenario where:
// A flick finishes before the update thread has advanced the scroll position past the previous snap point.
- Vector2 viewPageSizeLimit( size.x - ( 1.0f + 1.0f ), size.y - ( 1.0f - 1.0f ) );
- Vector2 minPosition( mStartPosition.x - viewPageSizeLimit.x, mStartPosition.y - viewPageSizeLimit.y );
- Vector2 maxPosition( mStartPosition.x + viewPageSizeLimit.x, mStartPosition.y + viewPageSizeLimit.y );
+ Vector2 viewPageSizeLimit(size.x - (1.0f + 1.0f), size.y - (1.0f - 1.0f));
+ Vector2 minPosition(mStartPosition.x - viewPageSizeLimit.x, mStartPosition.y - viewPageSizeLimit.y);
+ Vector2 maxPosition(mStartPosition.x + viewPageSizeLimit.x, mStartPosition.y + viewPageSizeLimit.y);
- if( mFixedRulerX )
+ if(mFixedRulerX)
{
- scrollPostPosition.x = Clamp( scrollPostPosition.x, minPosition.x, maxPosition.x );
+ scrollPostPosition.x = Clamp(scrollPostPosition.x, minPosition.x, maxPosition.x);
}
- if( mFixedRulerY )
+ if(mFixedRulerY)
{
- scrollPostPosition.y = Clamp( scrollPostPosition.y, minPosition.y, maxPosition.y );
+ scrollPostPosition.y = Clamp(scrollPostPosition.y, minPosition.y, maxPosition.y);
}
}
}
Vector2 mPrePosition;
Vector2 mLocalStart;
- Vector2 mStartPosition; ///< The start position of the gesture - used to limit scroll amount (not modified by clamping).
- Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings).
- Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
+ Vector2 mStartPosition; ///< The start position of the gesture - used to limit scroll amount (not modified by clamping).
+ Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings).
+ Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
Vector2 mDomainMin;
Vector2 mDomainMax;
Vector2 mMaxOvershoot;
- float mAxisAutoLockGradient; ///< Set by ScrollView
+ float mAxisAutoLockGradient; ///< Set by ScrollView
ScrollView::LockAxis mLockAxis;
- bool mAxisAutoLock:1; ///< Set by ScrollView
- bool mWasPanning:1;
- bool mClampX:1;
- bool mClampY:1;
- bool mFixedRulerX:1;
- bool mFixedRulerY:1;
+ bool mAxisAutoLock : 1; ///< Set by ScrollView
+ bool mWasPanning : 1;
+ bool mClampX : 1;
+ bool mClampY : 1;
+ bool mFixedRulerX : 1;
+ bool mFixedRulerY : 1;
};
/**
struct InternalPositionConstraint
{
InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
- : mDomainMin( -domainX.min, -domainY.min ),
- mDomainMax( -domainX.max, -domainY.max ),
- mClampX( domainX.enabled ),
- mClampY( domainY.enabled ),
- mWrap( wrap )
+ : mDomainMin(-domainX.min, -domainY.min),
+ mDomainMax(-domainX.max, -domainY.max),
+ mClampX(domainX.enabled),
+ mClampY(domainY.enabled),
+ mWrap(wrap)
{
}
- void operator()( Vector2& position, const PropertyInputContainer& inputs )
+ void operator()(Vector2& position, const PropertyInputContainer& inputs)
{
- position = inputs[0]->GetVector2();
+ position = inputs[0]->GetVector2();
const Vector2& size = inputs[3]->GetVector3().GetVectorXY();
- const Vector2& min = inputs[1]->GetVector2();
- const Vector2& max = inputs[2]->GetVector2();
+ const Vector2& min = inputs[1]->GetVector2();
+ const Vector2& max = inputs[2]->GetVector2();
- if( mWrap )
+ if(mWrap)
{
position.x = -WrapInDomain(-position.x, min.x, max.x);
position.y = -WrapInDomain(-position.y, min.y, max.y);
else
{
// clamp post position to domain
- position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
- position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
+ position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x) : position.x;
+ position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y) : position.y;
}
}
Vector2 mDomainMin;
Vector2 mDomainMax;
- bool mClampX;
- bool mClampY;
- bool mWrap;
-
+ bool mClampX;
+ bool mClampY;
+ bool mWrap;
};
/**
*/
struct OvershootXConstraint
{
- OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
+ OvershootXConstraint(float maxOvershoot)
+ : mMaxOvershoot(maxOvershoot)
+ {
+ }
- void operator()( float& current, const PropertyInputContainer& inputs )
+ void operator()(float& current, const PropertyInputContainer& inputs)
{
- if( inputs[2]->GetBoolean() )
+ if(inputs[2]->GetBoolean())
{
- const Vector2& scrollPrePosition = inputs[0]->GetVector2();
+ const Vector2& scrollPrePosition = inputs[0]->GetVector2();
const Vector2& scrollPostPosition = inputs[1]->GetVector2();
- float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
- current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
+ float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
+ current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
}
else
{
*/
struct OvershootYConstraint
{
- OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
+ OvershootYConstraint(float maxOvershoot)
+ : mMaxOvershoot(maxOvershoot)
+ {
+ }
- void operator()( float& current, const PropertyInputContainer& inputs )
+ void operator()(float& current, const PropertyInputContainer& inputs)
{
- if( inputs[2]->GetBoolean() )
+ if(inputs[2]->GetBoolean())
{
- const Vector2& scrollPrePosition = inputs[0]->GetVector2();
+ const Vector2& scrollPrePosition = inputs[0]->GetVector2();
const Vector2& scrollPostPosition = inputs[1]->GetVector2();
- float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
- current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
+ float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
+ current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
}
else
{
*
* Generates position-delta property based on scroll-position + scroll-offset properties.
*/
-void InternalPositionDeltaConstraint( Vector2& current, const PropertyInputContainer& inputs )
+void InternalPositionDeltaConstraint(Vector2& current, const PropertyInputContainer& inputs)
{
const Vector2& scrollPosition = inputs[0]->GetVector2();
- const Vector2& scrollOffset = inputs[1]->GetVector2();
+ const Vector2& scrollOffset = inputs[1]->GetVector2();
current = scrollPosition + scrollOffset;
}
{
}
- void operator()( Vector2& current, const PropertyInputContainer& inputs )
+ void operator()(Vector2& current, const PropertyInputContainer& inputs)
{
const float& overshootx = inputs[1]->GetFloat();
const float& overshooty = inputs[2]->GetFloat();
- Vector2 offset( mFunctionX(overshootx),
- mFunctionY(overshooty) );
+ Vector2 offset(mFunctionX(overshootx),
+ mFunctionY(overshooty));
current = inputs[0]->GetVector2() - offset;
}
AlphaFunctionPrototype mFunctionY;
};
-}
-
+} // namespace
///////////////////////////////////////////////////////////////////////////////////////////////////
// ScrollView
}
ScrollView::ScrollView()
-: ScrollBase( ControlBehaviour( DISABLE_STYLE_CHANGE_SIGNALS ) ), // Enable size negotiation
+: ScrollBase(ControlBehaviour(DISABLE_STYLE_CHANGE_SIGNALS)), // Enable size negotiation
mTouchDownTime(0u),
mGestureStackDepth(0),
mScrollStateFlags(0),
mInternalActor = Actor::New();
self.Add(mInternalActor);
- mInternalActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- mInternalActor.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::CENTER);
- mInternalActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mInternalActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mInternalActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mInternalActor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
mAlterChild = true;
mGestureStackDepth = 0;
- self.TouchedSignal().Connect( this, &ScrollView::OnTouch );
- EnableGestureDetection( GestureType::Value( GestureType::PAN ) );
+ self.TouchedSignal().Connect(this, &ScrollView::OnTouch);
+ EnableGestureDetection(GestureType::Value(GestureType::PAN));
// By default we'll allow the user to freely drag the scroll view,
// while disabling the other rulers.
RulerPtr ruler = new DefaultRuler();
- mRulerX = ruler;
- mRulerY = ruler;
+ mRulerX = ruler;
+ mRulerY = ruler;
self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, mCanScrollVertical);
self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, mCanScrollHorizontal);
SetInternalConstraints();
// Connect wheel event
- self.WheelEventSignal().Connect( this, &ScrollView::OnWheelEvent );
+ self.WheelEventSignal().Connect(this, &ScrollView::OnWheelEvent);
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::SCROLL_PANE ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE));
+ });
}
-void ScrollView::OnSceneConnection( int depth )
+void ScrollView::OnSceneConnection(int depth)
{
DALI_LOG_SCROLL_STATE("[0x%X]", this);
- if ( mSensitive )
+ if(mSensitive)
{
- SetScrollSensitive( false );
- SetScrollSensitive( true );
+ SetScrollSensitive(false);
+ SetScrollSensitive(true);
}
if(IsOvershootEnabled())
EnableScrollOvershoot(true);
}
- ScrollBase::OnSceneConnection( depth );
+ ScrollBase::OnSceneConnection(depth);
}
void ScrollView::OnSceneDisconnection()
// Assertion check to ensure effect doesn't already exist in this scrollview
bool effectAlreadyExistsInScrollView(false);
- for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
+ for(ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
{
- if(*iter==effect)
+ if(*iter == effect)
{
effectAlreadyExistsInScrollView = true;
break;
// remove effect from effects list
bool effectExistedInScrollView(false);
- for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
+ for(ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
{
- if(*iter==effect)
+ if(*iter == effect)
{
mEffects.erase(iter);
effectExistedInScrollView = true;
{
Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
- for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
+ for(ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
{
Toolkit::ScrollViewEffect effect = *effectIter;
void ScrollView::UpdatePropertyDomain()
{
- Actor self = Self();
- Vector3 size = self.GetTargetSize();
- Vector2 min = mMinScroll;
- Vector2 max = mMaxScroll;
- bool scrollPositionChanged = false;
- bool domainChanged = false;
+ Actor self = Self();
+ Vector3 size = self.GetTargetSize();
+ Vector2 min = mMinScroll;
+ Vector2 max = mMaxScroll;
+ bool scrollPositionChanged = false;
+ bool domainChanged = false;
- bool canScrollVertical = false;
+ bool canScrollVertical = false;
bool canScrollHorizontal = false;
UpdateLocalScrollProperties();
if(mRulerX->IsEnabled())
{
const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
- if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100
- || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
+ if(fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100)
{
domainChanged = true;
- min.x = rulerDomain.min;
- max.x = rulerDomain.max;
+ min.x = rulerDomain.min;
+ max.x = rulerDomain.max;
// make sure new scroll value is within new domain
- if( mScrollPrePosition.x < min.x
- || mScrollPrePosition.x > max.x )
+ if(mScrollPrePosition.x < min.x || mScrollPrePosition.x > max.x)
{
scrollPositionChanged = true;
- mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
+ mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
}
}
- if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100 )
+ if((fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100)
{
canScrollHorizontal = true;
}
}
- else if( fabs(min.x) > Math::MACHINE_EPSILON_100
- || fabs(max.x) > Math::MACHINE_EPSILON_100 )
+ else if(fabs(min.x) > Math::MACHINE_EPSILON_100 || fabs(max.x) > Math::MACHINE_EPSILON_100)
{
// need to reset to 0
- domainChanged = true;
- min.x = 0.0f;
- max.x = 0.0f;
+ domainChanged = true;
+ min.x = 0.0f;
+ max.x = 0.0f;
canScrollHorizontal = false;
}
if(mRulerY->IsEnabled())
{
const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
- if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100
- || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
+ if(fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100)
{
domainChanged = true;
- min.y = rulerDomain.min;
- max.y = rulerDomain.max;
+ min.y = rulerDomain.min;
+ max.y = rulerDomain.max;
// make sure new scroll value is within new domain
- if( mScrollPrePosition.y < min.y
- || mScrollPrePosition.y > max.y )
+ if(mScrollPrePosition.y < min.y || mScrollPrePosition.y > max.y)
{
scrollPositionChanged = true;
- mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
+ mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
}
}
- if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100 )
+ if((fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100)
{
canScrollVertical = true;
}
}
- else if( fabs(min.y) > Math::MACHINE_EPSILON_100
- || fabs(max.y) > Math::MACHINE_EPSILON_100 )
+ else if(fabs(min.y) > Math::MACHINE_EPSILON_100 || fabs(max.y) > Math::MACHINE_EPSILON_100)
{
// need to reset to 0
- domainChanged = true;
- min.y = 0.0f;
- max.y = 0.0f;
+ domainChanged = true;
+ min.y = 0.0f;
+ max.y = 0.0f;
canScrollVertical = false;
}
// avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
- if( mCanScrollVertical != canScrollVertical )
+ if(mCanScrollVertical != canScrollVertical)
{
mCanScrollVertical = canScrollVertical;
self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, canScrollVertical);
}
- if( mCanScrollHorizontal != canScrollHorizontal )
+ if(mCanScrollHorizontal != canScrollHorizontal)
{
mCanScrollHorizontal = canScrollHorizontal;
self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, canScrollHorizontal);
}
- if( scrollPositionChanged )
+ if(scrollPositionChanged)
{
- DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
+ DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y);
self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
}
- if( domainChanged )
+ if(domainChanged)
{
mMinScroll = min;
mMaxScroll = max;
- self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll );
- self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll );
+ self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll);
+ self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll);
}
}
void ScrollView::SetScrollSensitive(bool sensitive)
{
- Actor self = Self();
- PanGestureDetector panGesture( GetPanGestureDetector() );
+ Actor self = Self();
+ PanGestureDetector panGesture(GetPanGestureDetector());
DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive));
DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning));
// while the scroll view is panning, the state needs to be reset.
- if ( mPanning )
+ if(mPanning)
{
- PanGesture cancelGesture = DevelPanGesture::New( GestureState::CANCELLED );
- OnPan( cancelGesture );
+ PanGesture cancelGesture = DevelPanGesture::New(GestureState::CANCELLED);
+ OnPan(cancelGesture);
}
panGesture.Detach(self);
void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
{
- mMaxOvershoot.x = overshootX;
- mMaxOvershoot.y = overshootY;
- mUserMaxOvershoot = mMaxOvershoot;
+ mMaxOvershoot.x = overshootX;
+ mMaxOvershoot.y = overshootY;
+ mUserMaxOvershoot = mMaxOvershoot;
mDefaultMaxOvershoot = false;
UpdateMainInternalConstraint();
}
void ScrollView::SetAxisAutoLockGradient(float gradient)
{
- DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
+ DALI_ASSERT_DEBUG(gradient >= 0.0f && gradient <= 1.0f);
mAxisAutoLockGradient = gradient;
UpdateMainInternalConstraint();
}
void ScrollView::SetFrictionCoefficient(float friction)
{
- DALI_ASSERT_DEBUG( friction > 0.0f );
+ DALI_ASSERT_DEBUG(friction > 0.0f);
mFrictionCoefficient = friction;
}
return mMinFlickDistance;
}
-void ScrollView::SetMinimumDistanceForFlick( const Vector2& distance )
+void ScrollView::SetMinimumDistanceForFlick(const Vector2& distance)
{
mMinFlickDistance = distance;
}
return mFlickSpeedThreshold;
}
-void ScrollView::SetMinimumSpeedForFlick( float speed )
+void ScrollView::SetMinimumSpeedForFlick(float speed)
{
mFlickSpeedThreshold = speed;
}
// in case animation is currently taking place.
Vector2 position = GetPropertyPosition();
- Actor self = Self();
- unsigned int page = 0;
+ Actor self = Self();
+ unsigned int page = 0;
unsigned int pagesPerVolume = 1;
- unsigned int volume = 0;
+ unsigned int volume = 0;
// if rulerX is enabled, then get page count (columns)
- page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
- volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
+ page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
+ volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
pagesPerVolume = mRulerX->GetTotalPages();
return volume * pagesPerVolume + page;
}
void ScrollView::TransformTo(const Vector2& position,
- DirectionBias horizontalBias, DirectionBias verticalBias)
+ DirectionBias horizontalBias,
+ DirectionBias verticalBias)
{
TransformTo(position, mSnapDuration, mSnapAlphaFunction, horizontalBias, verticalBias);
}
-void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha,
- DirectionBias horizontalBias, DirectionBias verticalBias)
+void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias)
{
// If this is called while the timer is running, then cancel it
StopTouchDownTimer();
- Actor self( Self() );
+ Actor self(Self());
// Guard against destruction during signal emission
// Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
- Toolkit::ScrollView handle( GetOwner() );
+ Toolkit::ScrollView handle(GetOwner());
DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], duration[%.2f] bias[%d, %d]",
- this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
+ this,
+ position.x,
+ position.y,
+ duration,
+ int(horizontalBias),
+ int(verticalBias));
Vector2 currentScrollPosition = GetCurrentScrollPosition();
- self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition) );
+ self.SetProperty(Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition));
- if( mScrolling ) // are we interrupting a current scroll?
+ if(mScrolling) // are we interrupting a current scroll?
{
// set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
mScrolling = false;
DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
- mScrollCompletedSignal.Emit( currentScrollPosition );
+ mScrollCompletedSignal.Emit(currentScrollPosition);
}
- if( mPanning ) // are we interrupting a current pan?
+ if(mPanning) // are we interrupting a current pan?
{
- DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this );
- mPanning = false;
+ DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this);
+ mPanning = false;
mGestureStackDepth = 0;
- self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
+ self.SetProperty(Toolkit::ScrollView::Property::PANNING, false);
- if( mScrollMainInternalPrePositionConstraint )
+ if(mScrollMainInternalPrePositionConstraint)
{
mScrollMainInternalPrePositionConstraint.Remove();
}
mScrolling = true;
DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
- mScrollStartedSignal.Emit( currentScrollPosition );
+ mScrollStartedSignal.Emit(currentScrollPosition);
bool animating = AnimateTo(-position,
Vector2::ONE * duration,
alpha,
// If we have no duration, then in the next update frame, we will be at the position specified as we just set.
// In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position
- Vector2 completedPosition( currentScrollPosition );
- if( duration <= Math::MACHINE_EPSILON_10 )
+ Vector2 completedPosition(currentScrollPosition);
+ if(duration <= Math::MACHINE_EPSILON_10)
{
completedPosition = position;
}
DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y);
SetScrollUpdateNotification(false);
- mScrollCompletedSignal.Emit( completedPosition );
+ mScrollCompletedSignal.Emit(completedPosition);
}
}
void ScrollView::ScrollTo(const Vector2& position)
{
- ScrollTo(position, mSnapDuration );
+ ScrollTo(position, mSnapDuration);
}
void ScrollView::ScrollTo(const Vector2& position, float duration)
ScrollTo(position, duration, alpha, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE);
}
-void ScrollView::ScrollTo(const Vector2& position, float duration,
- DirectionBias horizontalBias, DirectionBias verticalBias)
+void ScrollView::ScrollTo(const Vector2& position, float duration, DirectionBias horizontalBias, DirectionBias verticalBias)
{
ScrollTo(position, duration, mSnapAlphaFunction, horizontalBias, verticalBias);
}
-void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha,
- DirectionBias horizontalBias, DirectionBias verticalBias)
+void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias)
{
DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f], bias[%d, %d]", this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
TransformTo(position, duration, alpha, horizontalBias, verticalBias);
void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
{
- Vector2 position;
+ Vector2 position;
unsigned int volume;
unsigned int libraries;
ScrollTo(position, duration, bias, bias);
}
-void ScrollView::ScrollTo(Actor &actor)
+void ScrollView::ScrollTo(Actor& actor)
{
ScrollTo(actor, mSnapDuration);
}
-void ScrollView::ScrollTo(Actor &actor, float duration)
+void ScrollView::ScrollTo(Actor& actor, float duration)
{
DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
- Actor self = Self();
- Vector3 size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
- Vector3 position = actor.GetCurrentProperty< Vector3 >( Actor::Property::POSITION );
+ Actor self = Self();
+ Vector3 size = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
+ Vector3 position = actor.GetCurrentProperty<Vector3>(Actor::Property::POSITION);
Vector2 prePosition = GetPropertyPrePosition();
position.GetVectorXY() -= prePosition;
Actor ScrollView::FindClosestActor()
{
- Actor self = Self();
- Vector3 size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Actor self = Self();
+ Vector3 size = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
- return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
+ return FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f));
}
Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
{
- Actor closestChild;
- float closestDistance2 = 0.0f;
- Vector3 actualPosition = position;
+ Actor closestChild;
+ float closestDistance2 = 0.0f;
+ Vector3 actualPosition = position;
unsigned int numChildren = Self().GetChildCount();
if(dirY > All) // != All,None
{
FindDirection deltaV = delta.y > 0 ? Down : Up;
- if(dirY != deltaV)
+ if(dirY != deltaV)
{
continue;
}
if(dirZ > All) // != All,None
{
FindDirection deltaV = delta.y > 0 ? In : Out;
- if(dirZ != deltaV)
+ if(dirZ != deltaV)
{
continue;
}
{
if(distance2 < closestDistance2)
{
- closestChild = child;
+ closestChild = child;
closestDistance2 = distance2;
}
}
else // First time.
{
- closestChild = child;
+ closestChild = child;
closestDistance2 = distance2;
}
}
bool ScrollView::ScrollToSnapPoint()
{
- DALI_LOG_SCROLL_STATE("[0x%X]", this );
+ DALI_LOG_SCROLL_STATE("[0x%X]", this);
Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
- return SnapWithVelocity( stationaryVelocity );
+ return SnapWithVelocity(stationaryVelocity);
}
// TODO: In situations where axes are different (X snap, Y free)
// to current mScroll's properties, and then resume.
// Note: For Flicking this may work a bit different...
- float angle = atan2(velocity.y, velocity.x);
- float speed2 = velocity.LengthSquared();
- AlphaFunction alphaFunction = mSnapAlphaFunction;
- Vector2 positionDuration = Vector2::ONE * mSnapDuration;
- float biasX = 0.5f;
- float biasY = 0.5f;
- FindDirection horizontal = None;
- FindDirection vertical = None;
+ float angle = atan2(velocity.y, velocity.x);
+ float speed2 = velocity.LengthSquared();
+ AlphaFunction alphaFunction = mSnapAlphaFunction;
+ Vector2 positionDuration = Vector2::ONE * mSnapDuration;
+ float biasX = 0.5f;
+ float biasY = 0.5f;
+ FindDirection horizontal = None;
+ FindDirection vertical = None;
// orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
// that will be accepted as a general N,E,S,W flick direction.
- const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
+ const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
const float flickSpeedThreshold2 = mFlickSpeedThreshold * mFlickSpeedThreshold;
Vector2 positionSnap = mScrollPrePosition;
{
horizontal = All;
- if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
- mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
+ if(speed2 > flickSpeedThreshold2 || // exceeds flick threshold
+ mInAccessibilityPan) // With AccessibilityPan its easier to move between snap positions
{
if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
{
// before the update-thread has advanced mScrollPostPosition past the the previous snap point.
positionSnap.x += 1.0f;
}
- else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
+ else if((angle >= M_PI - orthoAngleRange) || (angle < -M_PI + orthoAngleRange)) // Swiping West
{
biasX = 1.0f, horizontal = Right;
{
vertical = All;
- if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
- mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
+ if(speed2 > flickSpeedThreshold2 || // exceeds flick threshold
+ mInAccessibilityPan) // With AccessibilityPan its easier to move between snap positions
{
- if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
+ if((angle >= M_PI_2 - orthoAngleRange) && (angle < M_PI_2 + orthoAngleRange)) // Swiping South
{
biasY = 0.0f, vertical = Up;
}
- else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
+ else if((angle >= -M_PI_2 - orthoAngleRange) && (angle < -M_PI_2 + orthoAngleRange)) // Swiping North
{
biasY = 1.0f, vertical = Down;
}
// isFlick: Whether this gesture is a flick or not.
bool isFlick = (horizontal != All || vertical != All);
// isFreeFlick: Whether this gesture is a flick under free panning criteria.
- bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
+ bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD * FREE_FLICK_SPEED_THRESHOLD);
if(isFlick || isFreeFlick)
{
positionDuration = Vector2::ONE * mFlickDuration;
- alphaFunction = mFlickAlphaFunction;
+ alphaFunction = mFlickAlphaFunction;
}
// Calculate next positionSnap ////////////////////////////////////////////////////////////
if(mActorAutoSnapEnabled)
{
- Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Vector3 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
- Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
+ Actor child = FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f), horizontal, vertical);
- if(!child && isFlick )
+ if(!child && isFlick)
{
// If we conducted a direction limited search and found no actor, then just snap to the closest actor.
- child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
+ child = FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f));
}
if(child)
{
- Vector2 position = Self().GetCurrentProperty<Vector2>( Toolkit::ScrollView::Property::SCROLL_POSITION );
+ Vector2 position = Self().GetCurrentProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_POSITION);
// Get center-point of the Actor.
Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
}
Vector2 startPosition = positionSnap;
- positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
- positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
+ positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
+ positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
Vector2 clampDelta(Vector2::ZERO);
ClampPosition(positionSnap);
- if( (mRulerX->GetType() == Ruler::FREE || mRulerY->GetType() == Ruler::FREE)
- && isFreeFlick && !mActorAutoSnapEnabled)
+ if((mRulerX->GetType() == Ruler::FREE || mRulerY->GetType() == Ruler::FREE) && isFreeFlick && !mActorAutoSnapEnabled)
{
// Calculate target position based on velocity of flick.
// u = Initial Velocity (Flick velocity)
// v = 0 (Final Velocity)
// t = Time (Velocity / Deceleration)
- Vector2 stageSize = Stage::GetCurrent().GetSize();
- float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
- float a = (stageLength * mFrictionCoefficient);
- Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
- float speed = u.Length();
- u/= speed;
+ Vector2 stageSize = Stage::GetCurrent().GetSize();
+ float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
+ float a = (stageLength * mFrictionCoefficient);
+ Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
+ float speed = u.Length();
+ u /= speed;
// TODO: Change this to a decay function. (faster you flick, the slower it should be)
- speed = std::min(speed, stageLength * mMaxFlickSpeed );
- u*= speed;
+ speed = std::min(speed, stageLength * mMaxFlickSpeed);
+ u *= speed;
alphaFunction = ConstantDecelerationAlphaFunction;
float t = speed / a;
if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::FREE)
{
- positionSnap.x += t*u.x*0.5f;
+ positionSnap.x += t * u.x * 0.5f;
}
if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::FREE)
{
- positionSnap.y += t*u.y*0.5f;
+ positionSnap.y += t * u.y * 0.5f;
}
clampDelta = positionSnap;
positionSnap += clampDelta;
}
- bool animating = AnimateTo(positionSnap, positionDuration,
- alphaFunction, false,
- DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE,
- isFlick || isFreeFlick ? FLICK : SNAP);
+ bool animating = AnimateTo(positionSnap, positionDuration, alphaFunction, false, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE, isFlick || isFreeFlick ? FLICK : SNAP);
return animating;
}
}
}
-bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration,
- AlphaFunction alpha, bool findShortcuts,
- DirectionBias horizontalBias, DirectionBias verticalBias,
- SnapType snapType)
+bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration, AlphaFunction alpha, bool findShortcuts, DirectionBias horizontalBias, DirectionBias verticalBias, SnapType snapType)
{
// Here we perform an animation on a number of properties (depending on which have changed)
// The animation is applied to all ScrollBases
- Actor self = Self();
+ Actor self = Self();
mScrollTargetPosition = position;
- float totalDuration = 0.0f;
+ float totalDuration = 0.0f;
bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
else
{
// try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
- totalDuration = 0.01f;
+ totalDuration = 0.01f;
positionChanged = true;
}
if(mRulerX->IsEnabled())
{
- float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
+ float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
mScrollTargetPosition.x = mScrollPrePosition.x + -dir;
}
if(mRulerY->IsEnabled())
{
- float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
+ float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
mScrollTargetPosition.y = mScrollPrePosition.y + -dir;
}
}
AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
- if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
+ if(!(mScrollStateFlags & SCROLL_ANIMATION_FLAGS))
{
- DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y );
+ DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y);
self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollTargetPosition);
- mScrollPrePosition = mScrollTargetPosition;
+ mScrollPrePosition = mScrollTargetPosition;
mScrollPostPosition = mScrollTargetPosition;
WrapPosition(mScrollPostPosition);
}
- DALI_LOG_SCROLL_STATE("[0x%X] position-changed, mScrollTargetPosition[%.2f, %.2f], mScrollPrePosition[%.2f, %.2f], mScrollPostPosition[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y, mScrollPrePosition.x, mScrollPrePosition.y, mScrollPostPosition.x, mScrollPostPosition.y );
- DALI_LOG_SCROLL_STATE("[0x%X] SCROLL_PRE_POSITION[%.2f, %.2f], SCROLL_POSITION[%.2f, %.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get<Vector2>().x, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get<Vector2>().y, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get<Vector2>().x, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get<Vector2>().y );
+ DALI_LOG_SCROLL_STATE("[0x%X] position-changed, mScrollTargetPosition[%.2f, %.2f], mScrollPrePosition[%.2f, %.2f], mScrollPostPosition[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y, mScrollPrePosition.x, mScrollPrePosition.y, mScrollPostPosition.x, mScrollPostPosition.y);
+ DALI_LOG_SCROLL_STATE("[0x%X] SCROLL_PRE_POSITION[%.2f, %.2f], SCROLL_POSITION[%.2f, %.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().x, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().y, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get<Vector2>().x, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get<Vector2>().y);
}
SetScrollUpdateNotification(true);
// Always send a snap event when AnimateTo is called.
Toolkit::ScrollView::SnapEvent snapEvent;
- snapEvent.type = snapType;
+ snapEvent.type = snapType;
snapEvent.position = -mScrollTargetPosition;
snapEvent.duration = totalDuration;
DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignal [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
- mSnapStartedSignal.Emit( snapEvent );
+ mSnapStartedSignal.Emit(snapEvent);
return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
}
void ScrollView::EnableScrollOvershoot(bool enable)
{
- if (enable)
+ if(enable)
{
- if (!mOvershootIndicator)
+ if(!mOvershootIndicator)
{
mOvershootIndicator = ScrollOvershootIndicator::New();
}
{
mMaxOvershoot = mUserMaxOvershoot;
- if (mOvershootIndicator)
+ if(mOvershootIndicator)
{
mOvershootIndicator->DetachFromScrollable(*this);
}
void ScrollView::AddOverlay(Actor actor)
{
- actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
- mInternalActor.Add( actor );
+ actor.SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D);
+ mInternalActor.Add(actor);
}
void ScrollView::RemoveOverlay(Actor actor)
{
- mInternalActor.Remove( actor );
+ mInternalActor.Remove(actor);
}
-void ScrollView::SetOvershootSize( const Vector2& size )
+void ScrollView::SetOvershootSize(const Vector2& size)
{
mOvershootSize = size;
- if( IsOvershootEnabled() && mOvershootIndicator )
+ if(IsOvershootEnabled() && mOvershootIndicator)
{
mOvershootIndicator->AttachToScrollable(*this);
}
}
-void ScrollView::SetOvershootEffectColor( const Vector4& color )
+void ScrollView::SetOvershootEffectColor(const Vector4& color)
{
mOvershootEffectColor = color;
- if( mOvershootIndicator )
+ if(mOvershootIndicator)
{
- mOvershootIndicator->SetOvershootEffectColor( color );
+ mOvershootIndicator->SetOvershootEffectColor(color);
}
}
-void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
+void ScrollView::SetScrollingDirection(Radian direction, Radian threshold)
{
- PanGestureDetector panGesture( GetPanGestureDetector() );
+ PanGestureDetector panGesture(GetPanGestureDetector());
// First remove just in case we have some set, then add.
- panGesture.RemoveDirection( direction );
- panGesture.AddDirection( direction, threshold );
+ panGesture.RemoveDirection(direction);
+ panGesture.AddDirection(direction, threshold);
}
-void ScrollView::RemoveScrollingDirection( Radian direction )
+void ScrollView::RemoveScrollingDirection(Radian direction)
{
- PanGestureDetector panGesture( GetPanGestureDetector() );
- panGesture.RemoveDirection( direction );
+ PanGestureDetector panGesture(GetPanGestureDetector());
+ panGesture.RemoveDirection(direction);
}
Toolkit::ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal()
Vector2 ScrollView::GetPropertyPrePosition() const
{
- Vector2 position = Self().GetCurrentProperty< Vector2 >( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION );
+ Vector2 position = Self().GetCurrentProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION);
WrapPosition(position);
return position;
}
Vector2 ScrollView::GetPropertyPosition() const
{
- Vector2 position = Self().GetCurrentProperty< Vector2 >( Toolkit::ScrollView::Property::SCROLL_POSITION );
+ Vector2 position = Self().GetCurrentProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_POSITION);
WrapPosition(position);
return position;
UpdateLocalScrollProperties();
WrapPosition(mScrollPrePosition);
- DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
+ DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y);
self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
Vector2 currentScrollPosition = GetCurrentScrollPosition();
- DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y );
- mScrollCompletedSignal.Emit( currentScrollPosition );
+ DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y);
+ mScrollCompletedSignal.Emit(currentScrollPosition);
mDomainOffset += deltaPosition - mScrollPostPosition;
self.SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
HandleStoppedAnimation();
}
-void ScrollView::SetScrollUpdateNotification( bool enabled )
+void ScrollView::SetScrollUpdateNotification(bool enabled)
{
Actor self = Self();
- if( mScrollXUpdateNotification )
+ if(mScrollXUpdateNotification)
{
// disconnect now to avoid a notification before removed from update thread
mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
self.RemovePropertyNotification(mScrollXUpdateNotification);
mScrollXUpdateNotification.Reset();
}
- if( enabled && !mScrollUpdatedSignal.Empty())
+ if(enabled && !mScrollUpdatedSignal.Empty())
{
// Only set up the notification when the application has connected to the updated signal
mScrollXUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 0, StepCondition(mScrollUpdateDistance, 0.0f));
- mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
+ mScrollXUpdateNotification.NotifySignal().Connect(this, &ScrollView::OnScrollUpdateNotification);
}
- if( mScrollYUpdateNotification )
+ if(mScrollYUpdateNotification)
{
// disconnect now to avoid a notification before removed from update thread
mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
self.RemovePropertyNotification(mScrollYUpdateNotification);
mScrollYUpdateNotification.Reset();
}
- if( enabled && !mScrollUpdatedSignal.Empty())
+ if(enabled && !mScrollUpdatedSignal.Empty())
{
// Only set up the notification when the application has connected to the updated signal
mScrollYUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 1, StepCondition(mScrollUpdateDistance, 0.0f));
- mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
+ mScrollYUpdateNotification.NotifySignal().Connect(this, &ScrollView::OnScrollUpdateNotification);
}
}
void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
{
// Guard against destruction during signal emission
- Toolkit::ScrollView handle( GetOwner() );
+ Toolkit::ScrollView handle(GetOwner());
Vector2 currentScrollPosition = GetCurrentScrollPosition();
- mScrollUpdatedSignal.Emit( currentScrollPosition );
+ mScrollUpdatedSignal.Emit(currentScrollPosition);
}
-bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool ScrollView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
+ bool connected(true);
+ Toolkit::ScrollView view = Toolkit::ScrollView::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_SNAP_STARTED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_SNAP_STARTED))
{
- view.SnapStartedSignal().Connect( tracker, functor );
+ view.SnapStartedSignal().Connect(tracker, functor);
}
else
{
UpdatePropertyDomain();
}
-void ScrollView::OnSizeSet( const Vector3& size )
+void ScrollView::OnSizeSet(const Vector3& size)
{
// need to update domain properties for new size
- if( mDefaultMaxOvershoot )
+ if(mDefaultMaxOvershoot)
{
mUserMaxOvershoot.x = size.x * 0.5f;
mUserMaxOvershoot.y = size.y * 0.5f;
- if( !IsOvershootEnabled() )
+ if(!IsOvershootEnabled())
{
mMaxOvershoot = mUserMaxOvershoot;
}
}
UpdatePropertyDomain();
UpdateMainInternalConstraint();
- if( IsOvershootEnabled() )
+ if(IsOvershootEnabled())
{
mOvershootIndicator->Reset();
}
- ScrollBase::OnSizeSet( size );
+ ScrollBase::OnSizeSet(size);
}
void ScrollView::OnChildAdd(Actor& child)
{
- ScrollBase::OnChildAdd( child );
+ ScrollBase::OnChildAdd(child);
Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
- if( scrollBar )
+ if(scrollBar)
{
mScrollBar = scrollBar;
- scrollBar.SetProperty( Dali::Actor::Property::NAME,"ScrollBar");
+ scrollBar.SetProperty(Dali::Actor::Property::NAME, "ScrollBar");
- mInternalActor.Add( scrollBar );
- if( scrollBar.GetScrollDirection() == Toolkit::ScrollBar::HORIZONTAL )
+ mInternalActor.Add(scrollBar);
+ if(scrollBar.GetScrollDirection() == Toolkit::ScrollBar::HORIZONTAL)
{
- scrollBar.SetScrollPropertySource( Self(),
- Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X,
- Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X,
- Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X,
- Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X );
+ scrollBar.SetScrollPropertySource(Self(),
+ Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X,
+ Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X,
+ Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X,
+ Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X);
}
else
{
- scrollBar.SetScrollPropertySource( Self(),
- Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y,
- Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
- Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y,
- Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y );
+ scrollBar.SetScrollPropertySource(Self(),
+ Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y,
+ Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
+ Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y,
+ Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y);
}
- if( mTransientScrollBar )
+ if(mTransientScrollBar)
{
// Show the scroll-indicator for a brief period
Property::Map emptyMap;
- scrollBar.DoAction( "ShowTransientIndicator", emptyMap );
+ scrollBar.DoAction("ShowTransientIndicator", emptyMap);
}
}
else if(mAlterChild)
// TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
UnbindActor(child);
- ScrollBase::OnChildRemove( child );
+ ScrollBase::OnChildRemove(child);
}
void ScrollView::StartTouchDownTimer()
{
- if ( !mTouchDownTimer )
+ if(!mTouchDownTimer)
{
- mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
- mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
+ mTouchDownTimer = Timer::New(TOUCH_DOWN_TIMER_INTERVAL);
+ mTouchDownTimer.TickSignal().Connect(this, &ScrollView::OnTouchDownTimeout);
}
mTouchDownTimer.Start();
void ScrollView::StopTouchDownTimer()
{
- if ( mTouchDownTimer )
+ if(mTouchDownTimer)
{
mTouchDownTimer.Stop();
}
mTouchDownTimeoutReached = true;
- unsigned int currentScrollStateFlags( mScrollStateFlags ); // Cleared in StopAnimation so keep local copy for comparison
- if( currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
+ unsigned int currentScrollStateFlags(mScrollStateFlags); // Cleared in StopAnimation so keep local copy for comparison
+ if(currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS))
{
DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this);
StopAnimation();
- if( currentScrollStateFlags & SCROLL_ANIMATION_FLAGS )
+ if(currentScrollStateFlags & SCROLL_ANIMATION_FLAGS)
{
DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this);
UpdateLocalScrollProperties();
Vector2 currentScrollPosition = GetCurrentScrollPosition();
DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
- mScrollCompletedSignal.Emit( currentScrollPosition );
+ mScrollCompletedSignal.Emit(currentScrollPosition);
}
}
return false;
}
-bool ScrollView::OnTouch( Actor actor, const TouchEvent& touch )
+bool ScrollView::OnTouch(Actor actor, const TouchEvent& touch)
{
if(!mSensitive)
{
}
// Ignore events with multiple-touch points
- if (touch.GetPointCount() != 1)
+ if(touch.GetPointCount() != 1)
{
DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this);
return false;
}
- const PointState::Type pointState = touch.GetState( 0 );
- if( pointState == PointState::DOWN )
+ const PointState::Type pointState = touch.GetState(0);
+ if(pointState == PointState::DOWN)
{
DALI_LOG_SCROLL_STATE("[0x%X] Down", this);
- if(mGestureStackDepth==0)
+ if(mGestureStackDepth == 0)
{
mTouchDownTime = touch.GetTime();
// This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
// If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
mTouchDownTimeoutReached = false;
- mScrollInterrupted = false;
+ mScrollInterrupted = false;
StartTouchDownTimer();
}
}
- else if( ( pointState == PointState::UP ) ||
- ( ( pointState == PointState::INTERRUPTED ) && ( touch.GetHitActor( 0 )== Self() ) ) )
+ else if((pointState == PointState::UP) ||
+ ((pointState == PointState::INTERRUPTED) && (touch.GetHitActor(0) == Self())))
{
- DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ( ( pointState == PointState::UP ) ? "Up" : "Interrupted" ) );
+ DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ((pointState == PointState::UP) ? "Up" : "Interrupted"));
StopTouchDownTimer();
// if the user touches and releases without enough movement to go
// into a gesture state, then we should snap to nearest point.
// otherwise our scroll could be stopped (interrupted) half way through an animation.
- if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
+ if(mGestureStackDepth == 0 && mTouchDownTimeoutReached)
{
- if( ( pointState == PointState::INTERRUPTED ) ||
- ( ( touch.GetTime() - mTouchDownTime ) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET ) )
+ if((pointState == PointState::INTERRUPTED) ||
+ ((touch.GetTime() - mTouchDownTime) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET))
{
// Reset the velocity only if down was received a while ago
- mLastVelocity = Vector2( 0.0f, 0.0f );
+ mLastVelocity = Vector2(0.0f, 0.0f);
}
UpdateLocalScrollProperties();
// Only finish the transform if scrolling was interrupted on down or if we are scrolling
- if ( mScrollInterrupted || mScrolling )
+ if(mScrollInterrupted || mScrolling)
{
DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this);
}
}
mTouchDownTimeoutReached = false;
- mScrollInterrupted = false;
+ mScrollInterrupted = false;
}
return false;
}
-bool ScrollView::OnWheelEvent( Actor actor, const WheelEvent& event)
+bool ScrollView::OnWheelEvent(Actor actor, const WheelEvent& event)
{
if(!mSensitive)
{
void ScrollView::ResetScrolling()
{
Actor self = Self();
- self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition );
+ self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get(mScrollPostPosition);
mScrollPrePosition = mScrollPostPosition;
- DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y );
+ DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y);
self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPostPosition);
}
void ScrollView::UpdateLocalScrollProperties()
{
Actor self = Self();
- self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get( mScrollPrePosition );
- self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition );
+ self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get(mScrollPrePosition);
+ self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get(mScrollPostPosition);
}
// private functions
mDomainOffset += deltaPosition - mScrollPostPosition;
Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
- if( mScrollStateFlags & SCROLL_X_STATE_MASK )
+ if(mScrollStateFlags & SCROLL_X_STATE_MASK)
{
// already performing animation on internal x position
StopAnimation(mInternalXAnimation);
}
- if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
+ if(mScrollStateFlags & SCROLL_Y_STATE_MASK)
{
// already performing animation on internal y position
StopAnimation(mInternalYAnimation);
// TODO - common animation finishing code in here
}
-void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
+void ScrollView::AnimateInternalXTo(float position, float duration, AlphaFunction alpha)
{
StopAnimation(mInternalXAnimation);
- if( duration > Math::MACHINE_EPSILON_10 )
+ if(duration > Math::MACHINE_EPSILON_10)
{
Actor self = Self();
- DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().x, position );
+ DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().x, position);
mInternalXAnimation = Animation::New(duration);
- DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr() );
+ DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr());
mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
- mInternalXAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration));
+ mInternalXAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration));
mInternalXAnimation.Play();
// erase current state flags
}
}
-void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
+void ScrollView::AnimateInternalYTo(float position, float duration, AlphaFunction alpha)
{
StopAnimation(mInternalYAnimation);
- if( duration > Math::MACHINE_EPSILON_10 )
+ if(duration > Math::MACHINE_EPSILON_10)
{
Actor self = Self();
- DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().y, position );
+ DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().y, position);
mInternalYAnimation = Animation::New(duration);
- DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr() );
+ DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr());
mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
- mInternalYAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration));
+ mInternalYAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration));
mInternalYAnimation.Play();
// erase current state flags
}
}
-void ScrollView::OnScrollAnimationFinished( Animation& source )
+void ScrollView::OnScrollAnimationFinished(Animation& source)
{
// Guard against destruction during signal emission
// Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
- Toolkit::ScrollView handle( GetOwner() );
+ Toolkit::ScrollView handle(GetOwner());
bool scrollingFinished = false;
// update our local scroll positions
UpdateLocalScrollProperties();
- if( source == mInternalXAnimation )
+ if(source == mInternalXAnimation)
{
- DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, Self().GetCurrentProperty( SCROLL_PRE_POSITION ).Get< Vector2 >().x, mScrollPostPosition.x );
+ DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, Self().GetCurrentProperty(SCROLL_PRE_POSITION).Get<Vector2>().x, mScrollPostPosition.x);
- if( !(mScrollStateFlags & AnimatingInternalY) )
+ if(!(mScrollStateFlags & AnimatingInternalY))
{
scrollingFinished = true;
}
mInternalXAnimation.Reset();
// wrap pre scroll x position and set it
- if( mWrapMode )
+ if(mWrapMode)
{
const RulerDomain rulerDomain = mRulerX->GetDomain();
- mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
- DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
+ mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
+ DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y);
handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
}
SnapInternalXTo(mScrollPostPosition.x);
}
- if( source == mInternalYAnimation )
+ if(source == mInternalYAnimation)
{
- DALI_LOG_SCROLL_STATE("[0x%X] mInternalYAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalYAnimation.GetObjectPtr(), mScrollTargetPosition.y, DevelHandle::GetProperty( Self(), SCROLL_PRE_POSITION ).Get< Vector2 >().y, mScrollPostPosition.y );
+ DALI_LOG_SCROLL_STATE("[0x%X] mInternalYAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalYAnimation.GetObjectPtr(), mScrollTargetPosition.y, DevelHandle::GetProperty(Self(), SCROLL_PRE_POSITION).Get<Vector2>().y, mScrollPostPosition.y);
- if( !(mScrollStateFlags & AnimatingInternalX) )
+ if(!(mScrollStateFlags & AnimatingInternalX))
{
scrollingFinished = true;
}
mInternalYAnimation.Reset();
- if( mWrapMode )
+ if(mWrapMode)
{
// wrap pre scroll y position and set it
const RulerDomain rulerDomain = mRulerY->GetDomain();
- mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
- DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
+ mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
+ DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y);
handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
}
SnapInternalYTo(mScrollPostPosition.y);
}
}
-void ScrollView::OnSnapInternalPositionFinished( Animation& source )
+void ScrollView::OnSnapInternalPositionFinished(Animation& source)
{
Actor self = Self();
UpdateLocalScrollProperties();
- if( source == mInternalXAnimation )
+ if(source == mInternalXAnimation)
{
- DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this );
+ DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this);
// clear internal x animation flags
mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
mInternalXAnimation.Reset();
WrapPosition(mScrollPrePosition);
}
- if( source == mInternalYAnimation )
+ if(source == mInternalYAnimation)
{
- DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this );
+ DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this);
mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
mInternalYAnimation.Reset();
// if internal x not equal to inputed parameter, animate it
float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
- DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
- if( duration > Math::MACHINE_EPSILON_1 )
+ DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration);
+ if(duration > Math::MACHINE_EPSILON_1)
{
- DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position );
+ DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position);
mInternalXAnimation = Animation::New(duration);
mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
// if internal y not equal to inputed parameter, animate it
float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
- DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
- if( duration > Math::MACHINE_EPSILON_1 )
+ DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration);
+ if(duration > Math::MACHINE_EPSILON_1)
{
- DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position );
+ DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position);
mInternalYAnimation = Animation::New(duration);
mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
// we handle the first gesture.
// if we're currently doing a gesture and receive another
// we continue and combine the effects of the gesture instead of reseting.
- if(mGestureStackDepth++==0)
+ if(mGestureStackDepth++ == 0)
{
Actor self = Self();
StopTouchDownTimer();
StopAnimation();
- mPanDelta = Vector2::ZERO;
+ mPanDelta = Vector2::ZERO;
mLastVelocity = Vector2::ZERO;
- if( !mScrolling )
+ if(!mScrolling)
{
mLockAxis = LockPossible;
}
- if( mScrollStateFlags & SCROLL_X_STATE_MASK )
+ if(mScrollStateFlags & SCROLL_X_STATE_MASK)
{
StopAnimation(mInternalXAnimation);
}
- if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
+ if(mScrollStateFlags & SCROLL_Y_STATE_MASK)
{
StopAnimation(mInternalYAnimation);
}
// send negative scroll position since scroll internal scroll position works as an offset for actors,
// give applications the position within the domain from the scroll view's anchor position
DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
- mScrollCompletedSignal.Emit( -mScrollPostPosition );
+ mScrollCompletedSignal.Emit(-mScrollPostPosition);
}
}
}
void ScrollView::GestureContinuing(const Vector2& panDelta)
{
- mPanDelta.x+= panDelta.x;
- mPanDelta.y+= panDelta.y;
+ mPanDelta.x += panDelta.x;
+ mPanDelta.y += panDelta.y;
// Save the velocity, there is a bug in PanGesture
// Whereby the GestureState::FINISHED's velocity is either:
// TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
// BUG: GestureState::FINISHED doesn't always return velocity on release (due to
// timeDelta between last two events being 0 sometimes, or posiiton being the same)
-void ScrollView::OnPan( const PanGesture& gesture )
+void ScrollView::OnPan(const PanGesture& gesture)
{
// Guard against destruction during signal emission
// Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
- Actor self( Self() );
+ Actor self(Self());
if(!mSensitive)
{
{
DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this);
const Vector2& position = gesture.GetPosition();
- mPanStartPosition = position - gesture.GetDisplacement();
+ mPanStartPosition = position - gesture.GetDisplacement();
UpdateLocalScrollProperties();
GestureStarted();
mPanning = true;
- self.SetProperty( Toolkit::ScrollView::Property::PANNING, true );
- self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(position.x, position.y, 0.0f) );
+ self.SetProperty(Toolkit::ScrollView::Property::PANNING, true);
+ self.SetProperty(Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(position.x, position.y, 0.0f));
UpdateMainInternalConstraint();
Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
- if( scrollBar && mTransientScrollBar )
+ if(scrollBar && mTransientScrollBar)
{
- Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Vector3 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
const Toolkit::RulerDomain& rulerDomainX = mRulerX->GetDomain();
const Toolkit::RulerDomain& rulerDomainY = mRulerY->GetDomain();
- if( ( rulerDomainX.max > size.width ) || ( rulerDomainY.max > size.height ) )
+ if((rulerDomainX.max > size.width) || (rulerDomainY.max > size.height))
{
scrollBar.ShowIndicator();
}
case GestureState::CONTINUING:
{
- if ( mPanning )
+ if(mPanning)
{
DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this);
GestureContinuing(gesture.GetScreenDisplacement());
case GestureState::FINISHED:
case GestureState::CANCELLED:
{
- if ( mPanning )
+ if(mPanning)
{
- DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ( ( gesture.GetState() == GestureState::FINISHED ) ? "Finished" : "Cancelled" ) );
+ DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ((gesture.GetState() == GestureState::FINISHED) ? "Finished" : "Cancelled"));
UpdateLocalScrollProperties();
mLastVelocity = gesture.GetVelocity();
- mPanning = false;
- self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
+ mPanning = false;
+ self.SetProperty(Toolkit::ScrollView::Property::PANNING, false);
- if( mScrollMainInternalPrePositionConstraint )
+ if(mScrollMainInternalPrePositionConstraint)
{
mScrollMainInternalPrePositionConstraint.Remove();
}
Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
- if( scrollBar && mTransientScrollBar )
+ if(scrollBar && mTransientScrollBar)
{
scrollBar.HideIndicator();
}
Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
mScrolling = true;
DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
- mScrollStartedSignal.Emit( currentScrollPosition );
+ mScrollStartedSignal.Emit(currentScrollPosition);
}
- else if( (state == GestureState::FINISHED) ||
- (state == GestureState::CANCELLED) ) // Finished/default
+ else if((state == GestureState::FINISHED) ||
+ (state == GestureState::CANCELLED)) // Finished/default
{
// when all the gestures have finished, we finish the transform.
// so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
// then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
// this is the point we end, and perform necessary snapping.
mGestureStackDepth--;
- if(mGestureStackDepth==0)
+ if(mGestureStackDepth == 0)
{
// no flick if we have not exceeded min flick distance
- if( (fabsf(mPanDelta.x) < mMinFlickDistance.x)
- && (fabsf(mPanDelta.y) < mMinFlickDistance.y) )
+ if((fabsf(mPanDelta.x) < mMinFlickDistance.x) && (fabsf(mPanDelta.y) < mMinFlickDistance.y))
{
// reset flick velocity
mLastVelocity = Vector2::ZERO;
mScrolling = false;
Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
- if( fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10 )
+ if(fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10)
{
SnapInternalXTo(mScrollTargetPosition.x);
}
- if( fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10 )
+ if(fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10)
{
SnapInternalYTo(mScrollTargetPosition.y);
}
Vector2 currentScrollPosition = GetCurrentScrollPosition();
DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
- mScrollCompletedSignal.Emit( currentScrollPosition );
+ mScrollCompletedSignal.Emit(currentScrollPosition);
}
}
Vector2 ScrollView::GetOvershoot(Vector2& position) const
{
- Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Vector3 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
Vector2 overshoot;
const RulerDomain rulerDomainX = mRulerX->GetDomain();
if(mRulerX->IsEnabled() && rulerDomainX.enabled)
{
- const float left = rulerDomainX.min - position.x;
+ const float left = rulerDomainX.min - position.x;
const float right = size.width - rulerDomainX.max - position.x;
- if(left<0)
+ if(left < 0)
{
overshoot.x = left;
}
- else if(right>0)
+ else if(right > 0)
{
overshoot.x = right;
}
if(mRulerY->IsEnabled() && rulerDomainY.enabled)
{
- const float top = rulerDomainY.min - position.y;
+ const float top = rulerDomainY.min - position.y;
const float bottom = size.height - rulerDomainY.max - position.y;
- if(top<0)
+ if(top < 0)
{
overshoot.y = top;
}
- else if(bottom>0)
+ else if(bottom > 0)
{
overshoot.y = bottom;
}
ClampPosition(position, clamped);
}
-void ScrollView::ClampPosition(Vector2& position, ClampState2D &clamped) const
+void ScrollView::ClampPosition(Vector2& position, ClampState2D& clamped) const
{
- Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
+ Vector3 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
- position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
- position.y = -mRulerY->Clamp(-position.y, size.height, 1.0f, clamped.y); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
+ position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
+ position.y = -mRulerY->Clamp(-position.y, size.height, 1.0f, clamped.y); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
}
void ScrollView::WrapPosition(Vector2& position) const
{
// TODO: Only update the constraints which have changed, rather than remove all and add all again.
// Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
- Actor self = Self();
- PanGestureDetector detector( GetPanGestureDetector() );
+ Actor self = Self();
+ PanGestureDetector detector(GetPanGestureDetector());
if(mScrollMainInternalPositionConstraint)
{
mScrollMainInternalDomainConstraint.Remove();
mScrollMainInternalPrePositionMaxConstraint.Remove();
}
- if( mScrollMainInternalPrePositionConstraint )
+ if(mScrollMainInternalPrePositionConstraint)
{
mScrollMainInternalPrePositionConstraint.Remove();
}
// 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
- if( mLockAxis == LockVertical )
+ if(mLockAxis == LockVertical)
{
initialPanMask.y = 0.0f;
}
- else if( mLockAxis == LockHorizontal )
+ else if(mLockAxis == LockHorizontal)
{
initialPanMask.x = 0.0f;
}
- if( mPanning )
- {
- mScrollMainInternalPrePositionConstraint = Constraint::New<Vector2>( self,
- Toolkit::ScrollView::Property::SCROLL_PRE_POSITION,
- InternalPrePositionConstraint( mPanStartPosition,
- initialPanMask,
- mAxisAutoLock,
- mAxisAutoLockGradient,
- mLockAxis,
- mMaxOvershoot,
- mRulerX,
- mRulerY ) );
- mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::LOCAL_POSITION ) );
- mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::PANNING ) );
- mScrollMainInternalPrePositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
+ if(mPanning)
+ {
+ mScrollMainInternalPrePositionConstraint = Constraint::New<Vector2>(self,
+ Toolkit::ScrollView::Property::SCROLL_PRE_POSITION,
+ InternalPrePositionConstraint(mPanStartPosition,
+ initialPanMask,
+ mAxisAutoLock,
+ mAxisAutoLockGradient,
+ mLockAxis,
+ mMaxOvershoot,
+ mRulerX,
+ mRulerY));
+ mScrollMainInternalPrePositionConstraint.AddSource(Source(detector, PanGestureDetector::Property::LOCAL_POSITION));
+ mScrollMainInternalPrePositionConstraint.AddSource(Source(detector, PanGestureDetector::Property::PANNING));
+ mScrollMainInternalPrePositionConstraint.AddSource(Source(self, Actor::Property::SIZE));
mScrollMainInternalPrePositionConstraint.Apply();
}
// 2. Second calculate the clamped position (actual position)
- mScrollMainInternalPositionConstraint = Constraint::New<Vector2>( self,
- Toolkit::ScrollView::Property::SCROLL_POSITION,
- InternalPositionConstraint( mRulerX->GetDomain(),
- mRulerY->GetDomain(),
- mWrapMode ) );
- mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
- mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
- mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
- mScrollMainInternalPositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
+ mScrollMainInternalPositionConstraint = Constraint::New<Vector2>(self,
+ Toolkit::ScrollView::Property::SCROLL_POSITION,
+ InternalPositionConstraint(mRulerX->GetDomain(),
+ mRulerY->GetDomain(),
+ mWrapMode));
+ mScrollMainInternalPositionConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION));
+ mScrollMainInternalPositionConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN));
+ mScrollMainInternalPositionConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX));
+ mScrollMainInternalPositionConstraint.AddSource(Source(self, Actor::Property::SIZE));
mScrollMainInternalPositionConstraint.Apply();
- mScrollMainInternalDeltaConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_POSITION_DELTA, InternalPositionDeltaConstraint );
- mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
- mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET ) );
+ mScrollMainInternalDeltaConstraint = Constraint::New<Vector2>(self, Toolkit::ScrollView::Property::SCROLL_POSITION_DELTA, InternalPositionDeltaConstraint);
+ mScrollMainInternalDeltaConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION));
+ mScrollMainInternalDeltaConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET));
mScrollMainInternalDeltaConstraint.Apply();
- mScrollMainInternalFinalConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_FINAL,
- InternalFinalConstraint( FinalDefaultAlphaFunction,
- FinalDefaultAlphaFunction ) );
- mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
- mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_X ) );
- mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_Y ) );
+ mScrollMainInternalFinalConstraint = Constraint::New<Vector2>(self, Toolkit::ScrollView::Property::SCROLL_FINAL, InternalFinalConstraint(FinalDefaultAlphaFunction, FinalDefaultAlphaFunction));
+ mScrollMainInternalFinalConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION));
+ mScrollMainInternalFinalConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::OVERSHOOT_X));
+ mScrollMainInternalFinalConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::OVERSHOOT_Y));
mScrollMainInternalFinalConstraint.Apply();
- mScrollMainInternalRelativeConstraint = Constraint::New<Vector2>( self, Toolkit::Scrollable::Property::SCROLL_RELATIVE_POSITION, InternalRelativePositionConstraint );
- mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
- mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
- mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
- mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
+ mScrollMainInternalRelativeConstraint = Constraint::New<Vector2>(self, Toolkit::Scrollable::Property::SCROLL_RELATIVE_POSITION, InternalRelativePositionConstraint);
+ mScrollMainInternalRelativeConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION));
+ mScrollMainInternalRelativeConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN));
+ mScrollMainInternalRelativeConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX));
+ mScrollMainInternalRelativeConstraint.AddSource(LocalSource(Actor::Property::SIZE));
mScrollMainInternalRelativeConstraint.Apply();
- mScrollMainInternalDomainConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE, InternalScrollDomainConstraint );
- mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
- mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
- mScrollMainInternalDomainConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
+ mScrollMainInternalDomainConstraint = Constraint::New<Vector2>(self, Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE, InternalScrollDomainConstraint);
+ mScrollMainInternalDomainConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN));
+ mScrollMainInternalDomainConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX));
+ mScrollMainInternalDomainConstraint.AddSource(LocalSource(Actor::Property::SIZE));
mScrollMainInternalDomainConstraint.Apply();
- mScrollMainInternalPrePositionMaxConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX, InternalPrePositionMaxConstraint );
- mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
- mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
+ mScrollMainInternalPrePositionMaxConstraint = Constraint::New<Vector2>(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX, InternalPrePositionMaxConstraint);
+ mScrollMainInternalPrePositionMaxConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX));
+ mScrollMainInternalPrePositionMaxConstraint.AddSource(LocalSource(Actor::Property::SIZE));
mScrollMainInternalPrePositionMaxConstraint.Apply();
// When panning we want to make sure overshoot values are affected by pre position and post position
void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
{
- Actor self( Self() );
+ Actor self(Self());
// remove and reset, it may now be in wrong order with the main internal constraints
- if( mScrollMainInternalOvershootXConstraint )
+ if(mScrollMainInternalOvershootXConstraint)
{
mScrollMainInternalOvershootXConstraint.Remove();
mScrollMainInternalOvershootXConstraint.Reset();
mScrollMainInternalOvershootYConstraint.Remove();
mScrollMainInternalOvershootYConstraint.Reset();
}
- if( enabled )
+ if(enabled)
{
- mScrollMainInternalOvershootXConstraint= Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_X, OvershootXConstraint(mMaxOvershoot.x) );
- mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
- mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
- mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL ) );
+ mScrollMainInternalOvershootXConstraint = Constraint::New<float>(self, Toolkit::ScrollView::Property::OVERSHOOT_X, OvershootXConstraint(mMaxOvershoot.x));
+ mScrollMainInternalOvershootXConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION));
+ mScrollMainInternalOvershootXConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION));
+ mScrollMainInternalOvershootXConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL));
mScrollMainInternalOvershootXConstraint.Apply();
- mScrollMainInternalOvershootYConstraint = Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_Y, OvershootYConstraint(mMaxOvershoot.y) );
- mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
- mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
- mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
+ mScrollMainInternalOvershootYConstraint = Constraint::New<float>(self, Toolkit::ScrollView::Property::OVERSHOOT_Y, OvershootYConstraint(mMaxOvershoot.y));
+ mScrollMainInternalOvershootYConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION));
+ mScrollMainInternalOvershootYConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION));
+ mScrollMainInternalOvershootYConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL));
mScrollMainInternalOvershootYConstraint.Apply();
}
else
Constraint constraint;
// MoveActor (scrolling)
- constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, MoveActorConstraint );
- constraint.AddSource( Source( self, Toolkit::ScrollView::Property::SCROLL_POSITION ) );
+ constraint = Constraint::New<Vector3>(self, Actor::Property::POSITION, MoveActorConstraint);
+ constraint.AddSource(Source(self, Toolkit::ScrollView::Property::SCROLL_POSITION));
constraint.SetRemoveAction(Constraint::DISCARD);
ApplyConstraintToBoundActors(constraint);
// WrapActor (wrap functionality)
- constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, WrapActorConstraint );
- constraint.AddSource( LocalSource( Actor::Property::SCALE ) );
- constraint.AddSource( LocalSource( Actor::Property::ANCHOR_POINT ) );
- constraint.AddSource( LocalSource( Actor::Property::SIZE ) );
- constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
- constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
- constraint.AddSource( Source( self, Toolkit::ScrollView::Property::WRAP ) );
+ constraint = Constraint::New<Vector3>(self, Actor::Property::POSITION, WrapActorConstraint);
+ constraint.AddSource(LocalSource(Actor::Property::SCALE));
+ constraint.AddSource(LocalSource(Actor::Property::ANCHOR_POINT));
+ constraint.AddSource(LocalSource(Actor::Property::SIZE));
+ constraint.AddSource(Source(self, Toolkit::Scrollable::Property::SCROLL_POSITION_MIN));
+ constraint.AddSource(Source(self, Toolkit::Scrollable::Property::SCROLL_POSITION_MAX));
+ constraint.AddSource(Source(self, Toolkit::ScrollView::Property::WRAP));
constraint.SetRemoveAction(Constraint::DISCARD);
ApplyConstraintToBoundActors(constraint);
}
-void ScrollView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void ScrollView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast(Dali::BaseHandle(object));
- if( scrollView )
+ if(scrollView)
{
- ScrollView& scrollViewImpl( GetImpl( scrollView ) );
- switch( index )
+ ScrollView& scrollViewImpl(GetImpl(scrollView));
+ switch(index)
{
case Toolkit::ScrollView::Property::WRAP_ENABLED:
{
- scrollViewImpl.SetWrapMode( value.Get<bool>() );
+ scrollViewImpl.SetWrapMode(value.Get<bool>());
break;
}
case Toolkit::ScrollView::Property::PANNING_ENABLED:
{
- scrollViewImpl.SetScrollSensitive( value.Get<bool>() );
+ scrollViewImpl.SetScrollSensitive(value.Get<bool>());
break;
}
case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
{
- scrollViewImpl.SetAxisAutoLock( value.Get<bool>() );
+ scrollViewImpl.SetAxisAutoLock(value.Get<bool>());
break;
}
case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
{
- scrollViewImpl.SetWheelScrollDistanceStep( value.Get<Vector2>() );
+ scrollViewImpl.SetWheelScrollDistanceStep(value.Get<Vector2>());
break;
}
case Toolkit::ScrollView::Property::SCROLL_MODE:
{
const Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
- scrollViewImpl.SetScrollMode( *map );
+ scrollViewImpl.SetScrollMode(*map);
}
}
}
}
}
-Property::Value ScrollView::GetProperty( BaseObject* object, Property::Index index )
+Property::Value ScrollView::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast(Dali::BaseHandle(object));
- if( scrollView )
+ if(scrollView)
{
- ScrollView& scrollViewImpl( GetImpl( scrollView ) );
- switch( index )
+ ScrollView& scrollViewImpl(GetImpl(scrollView));
+ switch(index)
{
case Toolkit::ScrollView::Property::WRAP_ENABLED:
{
return value;
}
-void ScrollView::SetScrollMode( const Property::Map& scrollModeMap )
+void ScrollView::SetScrollMode(const Property::Map& scrollModeMap)
{
Toolkit::RulerPtr rulerX, rulerY;
// Check the scroll mode in the X axis
- bool xAxisScrollEnabled = true;
- Property::Value* valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SCROLL_ENABLED, "xAxisScrollEnabled" );
- if( valuePtr && valuePtr->GetType() == Property::BOOLEAN )
+ bool xAxisScrollEnabled = true;
+ Property::Value* valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SCROLL_ENABLED, "xAxisScrollEnabled");
+ if(valuePtr && valuePtr->GetType() == Property::BOOLEAN)
{
- valuePtr->Get( xAxisScrollEnabled );
+ valuePtr->Get(xAxisScrollEnabled);
}
- if( !xAxisScrollEnabled )
+ if(!xAxisScrollEnabled)
{
// Default ruler and disabled
rulerX = new Toolkit::DefaultRuler();
}
else
{
- valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SNAP_TO_INTERVAL, "xAxisSnapToInterval" );
+ valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SNAP_TO_INTERVAL, "xAxisSnapToInterval");
float xAxisSnapToInterval = 0.0f;
- if( valuePtr && valuePtr->Get( xAxisSnapToInterval ) )
+ if(valuePtr && valuePtr->Get(xAxisSnapToInterval))
{
// Fixed ruler and enabled
- rulerX = new Toolkit::FixedRuler( xAxisSnapToInterval );
+ rulerX = new Toolkit::FixedRuler(xAxisSnapToInterval);
}
else
{
rulerX = new Toolkit::DefaultRuler();
}
- valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SCROLL_BOUNDARY, "xAxisScrollBoundary" );
+ valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SCROLL_BOUNDARY, "xAxisScrollBoundary");
float xAxisScrollBoundary = 0.0f;
- if( valuePtr && valuePtr->Get( xAxisScrollBoundary ) )
+ if(valuePtr && valuePtr->Get(xAxisScrollBoundary))
{
// By default ruler domain is disabled unless set
- rulerX->SetDomain( Toolkit::RulerDomain( 0, xAxisScrollBoundary, true ) );
+ rulerX->SetDomain(Toolkit::RulerDomain(0, xAxisScrollBoundary, true));
}
}
// Check the scroll mode in the Y axis
bool yAxisScrollEnabled = true;
- valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SCROLL_ENABLED, "yAxisScrollEnabled" );
- if( valuePtr && valuePtr->GetType() == Property::BOOLEAN )
+ valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SCROLL_ENABLED, "yAxisScrollEnabled");
+ if(valuePtr && valuePtr->GetType() == Property::BOOLEAN)
{
- valuePtr->Get( yAxisScrollEnabled );
+ valuePtr->Get(yAxisScrollEnabled);
}
- if( !yAxisScrollEnabled )
+ if(!yAxisScrollEnabled)
{
// Default ruler and disabled
rulerY = new Toolkit::DefaultRuler();
}
else
{
- valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SNAP_TO_INTERVAL, "yAxisSnapToInterval" );
+ valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SNAP_TO_INTERVAL, "yAxisSnapToInterval");
float yAxisSnapToInterval = 0.0f;
- if( valuePtr && valuePtr->Get( yAxisSnapToInterval ) )
+ if(valuePtr && valuePtr->Get(yAxisSnapToInterval))
{
// Fixed ruler and enabled
rulerY = new Toolkit::FixedRuler(yAxisSnapToInterval);
rulerY = new Toolkit::DefaultRuler();
}
- valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SCROLL_BOUNDARY, "yAxisScrollBoundary" );
+ valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SCROLL_BOUNDARY, "yAxisScrollBoundary");
float yAxisScrollBoundary = 0.0f;
- if( valuePtr && valuePtr->Get( yAxisScrollBoundary ) )
+ if(valuePtr && valuePtr->Get(yAxisScrollBoundary))
{
// By default ruler domain is disabled unless set
- rulerY->SetDomain( Toolkit::RulerDomain( 0, yAxisScrollBoundary, true ) );
+ rulerY->SetDomain(Toolkit::RulerDomain(0, yAxisScrollBoundary, true));
}
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
ScrollViewPagePathEffect::ScrollViewPagePathEffect(Path path, const Vector3& forward, Dali::Property::Index inputPropertyIndex, const Vector3& viewPageSize, unsigned int pageCount)
-:mPageSize(viewPageSize),
- mInputPropertyIndex(inputPropertyIndex),
- mPageCount(pageCount)
+: mPageSize(viewPageSize),
+ mInputPropertyIndex(inputPropertyIndex),
+ mPageCount(pageCount)
{
//Create path constrainer
mPathConstrainer = Dali::PathConstrainer::New();
- mPathConstrainer.SetProperty( PathConstrainer::Property::FORWARD, forward );
+ mPathConstrainer.SetProperty(PathConstrainer::Property::FORWARD, forward);
Dali::Property::Value pointsProperty = path.GetProperty(Path::Property::POINTS);
- mPathConstrainer.SetProperty( PathConstrainer::Property::POINTS, pointsProperty );
+ mPathConstrainer.SetProperty(PathConstrainer::Property::POINTS, pointsProperty);
pointsProperty = path.GetProperty(Path::Property::CONTROL_POINTS);
- mPathConstrainer.SetProperty( PathConstrainer::Property::CONTROL_POINTS, pointsProperty );
+ mPathConstrainer.SetProperty(PathConstrainer::Property::CONTROL_POINTS, pointsProperty);
//Create linear constrainer
- pointsProperty = Property::Value(Property::ARRAY);
+ pointsProperty = Property::Value(Property::ARRAY);
Property::Array* array = pointsProperty.GetArray();
- if( array )
+ if(array)
{
array->PushBack(0.0f);
array->PushBack(1.0f);
array->PushBack(0.0f);
}
mLinearConstrainer = Dali::LinearConstrainer::New();
- mLinearConstrainer.SetProperty( LinearConstrainer::Property::VALUE, pointsProperty );
+ mLinearConstrainer.SetProperty(LinearConstrainer::Property::VALUE, pointsProperty);
}
ScrollViewPagePathEffect::~ScrollViewPagePathEffect()
{
}
-void ScrollViewPagePathEffect::ApplyToPage( Actor page, unsigned int pageOrder )
+void ScrollViewPagePathEffect::ApplyToPage(Actor page, unsigned int pageOrder)
{
- float pageHalfSize = mPageSize.x * 0.5f;
- Vector2 range = Vector2( pageHalfSize - (pageHalfSize*pageOrder), -pageHalfSize - (pageHalfSize*pageOrder) );
- Vector2 wrap = Vector2( range.x, -pageHalfSize*(mPageCount-2) + range.y);
+ float pageHalfSize = mPageSize.x * 0.5f;
+ Vector2 range = Vector2(pageHalfSize - (pageHalfSize * pageOrder), -pageHalfSize - (pageHalfSize * pageOrder));
+ Vector2 wrap = Vector2(range.x, -pageHalfSize * (mPageCount - 2) + range.y);
Toolkit::ScrollView scrollView = GetScrollView();
//Position
- mPathConstrainer.Apply( Dali::Property( page, Dali::Actor::Property::POSITION ),
- Dali::Property( scrollView, mInputPropertyIndex),
- range, wrap
- );
+ mPathConstrainer.Apply(Dali::Property(page, Dali::Actor::Property::POSITION),
+ Dali::Property(scrollView, mInputPropertyIndex),
+ range,
+ wrap);
//Rotation
- mPathConstrainer.Apply( Dali::Property( page, Dali::Actor::Property::ORIENTATION ),
- Dali::Property( scrollView, mInputPropertyIndex ),
- range, wrap
- );
+ mPathConstrainer.Apply(Dali::Property(page, Dali::Actor::Property::ORIENTATION),
+ Dali::Property(scrollView, mInputPropertyIndex),
+ range,
+ wrap);
//Alpha
- mLinearConstrainer.Apply( Dali::Property( page, Dali::Actor::Property::COLOR_ALPHA ),
- Dali::Property( scrollView, mInputPropertyIndex ),
- range, wrap
- );
-
+ mLinearConstrainer.Apply(Dali::Property(page, Dali::Actor::Property::COLOR_ALPHA),
+ Dali::Property(scrollView, mInputPropertyIndex),
+ range,
+ wrap);
}
void ScrollViewPagePathEffect::OnAttach(Toolkit::ScrollView& scrollView)
*/
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/controls/scrollable/scrollable-impl.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/controls/scrollable/scrollable-impl.h>
using namespace Dali;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
// empty handle as we cannot create Scrollable (but type registered for scroll signal)
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Scrollable, Toolkit::Control, Create );
-
-DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "overshootEffectColor", VECTOR4, OVERSHOOT_EFFECT_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "overshootAnimationSpeed", FLOAT, OVERSHOOT_ANIMATION_SPEED )
-DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "overshootEnabled", BOOLEAN, OVERSHOOT_ENABLED )
-DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "overshootSize", VECTOR2, OVERSHOOT_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "scrollToAlphaFunction", INTEGER, SCROLL_TO_ALPHA_FUNCTION )
-
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "scrollRelativePosition", VECTOR2, SCROLL_RELATIVE_POSITION)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "scrollPositionMin", VECTOR2, SCROLL_POSITION_MIN)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, Scrollable, "scrollPositionMinX", SCROLL_POSITION_MIN_X, SCROLL_POSITION_MIN, 0)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, Scrollable, "scrollPositionMinY", SCROLL_POSITION_MIN_Y, SCROLL_POSITION_MIN, 1)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "scrollPositionMax", VECTOR2, SCROLL_POSITION_MAX)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, Scrollable, "scrollPositionMaxX", SCROLL_POSITION_MAX_X, SCROLL_POSITION_MAX, 0)
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, Scrollable, "scrollPositionMaxY", SCROLL_POSITION_MAX_Y, SCROLL_POSITION_MAX, 1)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "canScrollVertical", BOOLEAN, CAN_SCROLL_VERTICAL)
-DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "canScrollHorizontal", BOOLEAN, CAN_SCROLL_HORIZONTAL)
-
-DALI_SIGNAL_REGISTRATION( Toolkit, Scrollable, "scrollStarted", SIGNAL_SCROLL_STARTED )
-DALI_SIGNAL_REGISTRATION( Toolkit, Scrollable, "scrollCompleted", SIGNAL_SCROLL_COMPLETED )
-DALI_SIGNAL_REGISTRATION( Toolkit, Scrollable, "scrollUpdated", SIGNAL_SCROLL_UPDATED )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Scrollable, Toolkit::Control, Create);
+
+DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEffectColor", VECTOR4, OVERSHOOT_EFFECT_COLOR)
+DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootAnimationSpeed", FLOAT, OVERSHOOT_ANIMATION_SPEED)
+DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEnabled", BOOLEAN, OVERSHOOT_ENABLED)
+DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootSize", VECTOR2, OVERSHOOT_SIZE)
+DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollToAlphaFunction", INTEGER, SCROLL_TO_ALPHA_FUNCTION)
+
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollRelativePosition", VECTOR2, SCROLL_RELATIVE_POSITION)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMin", VECTOR2, SCROLL_POSITION_MIN)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinX", SCROLL_POSITION_MIN_X, SCROLL_POSITION_MIN, 0)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinY", SCROLL_POSITION_MIN_Y, SCROLL_POSITION_MIN, 1)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMax", VECTOR2, SCROLL_POSITION_MAX)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxX", SCROLL_POSITION_MAX_X, SCROLL_POSITION_MAX, 0)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxY", SCROLL_POSITION_MAX_Y, SCROLL_POSITION_MAX, 1)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollVertical", BOOLEAN, CAN_SCROLL_VERTICAL)
+DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollHorizontal", BOOLEAN, CAN_SCROLL_HORIZONTAL)
+
+DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollStarted", SIGNAL_SCROLL_STARTED)
+DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollCompleted", SIGNAL_SCROLL_COMPLETED)
+DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollUpdated", SIGNAL_SCROLL_UPDATED)
DALI_TYPE_REGISTRATION_END()
const Vector4 DEFAULT_OVERSHOOT_COLOUR(0.0f, 0.64f, 0.85f, 0.25f);
-const float DEFAULT_OVERSHOOT_ANIMATION_SPEED(120.0f); // 120 pixels per second
-const Vector2 OVERSHOOT_DEFAULT_SIZE( 720.0f, 42.0f );
+const float DEFAULT_OVERSHOOT_ANIMATION_SPEED(120.0f); // 120 pixels per second
+const Vector2 OVERSHOOT_DEFAULT_SIZE(720.0f, 42.0f);
-}
+} // namespace
///////////////////////////////////////////////////////////////////////////////////////////////////
// Scrollable
///////////////////////////////////////////////////////////////////////////////////////////////////
-Scrollable::Scrollable( ControlBehaviour behaviourFlags )
-: Control( ControlBehaviour( behaviourFlags ) ),
- mOvershootEffectColor( DEFAULT_OVERSHOOT_COLOUR ),
- mOvershootAnimationSpeed ( DEFAULT_OVERSHOOT_ANIMATION_SPEED ),
- mOvershootSize( OVERSHOOT_DEFAULT_SIZE ),
- mScrollToAlphaFunction( AlphaFunction::EASE_OUT ),
+Scrollable::Scrollable(ControlBehaviour behaviourFlags)
+: Control(ControlBehaviour(behaviourFlags)),
+ mOvershootEffectColor(DEFAULT_OVERSHOOT_COLOUR),
+ mOvershootAnimationSpeed(DEFAULT_OVERSHOOT_ANIMATION_SPEED),
+ mOvershootSize(OVERSHOOT_DEFAULT_SIZE),
+ mScrollToAlphaFunction(AlphaFunction::EASE_OUT),
mScrollStartedSignal(),
mScrollUpdatedSignal(),
mScrollCompletedSignal(),
void Scrollable::OnInitialize()
{
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::SCROLL_PANE ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE));
+ });
}
bool Scrollable::IsOvershootEnabled() const
return mOvershootEffectColor;
};
-void Scrollable::SetOvershootAnimationSpeed( float pixelsPerSecond )
+void Scrollable::SetOvershootAnimationSpeed(float pixelsPerSecond)
{
mOvershootAnimationSpeed = pixelsPerSecond;
}
return mScrollCompletedSignal;
}
-bool Scrollable::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool Scrollable::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast( handle );
+ bool connected(true);
+ Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_SCROLL_STARTED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_STARTED))
{
- scrollable.ScrollStartedSignal().Connect( tracker, functor );
+ scrollable.ScrollStartedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_SCROLL_UPDATED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_UPDATED))
{
- scrollable.ScrollUpdatedSignal().Connect( tracker, functor );
+ scrollable.ScrollUpdatedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_SCROLL_COMPLETED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_COMPLETED))
{
- scrollable.ScrollCompletedSignal().Connect( tracker, functor );
+ scrollable.ScrollCompletedSignal().Connect(tracker, functor);
}
else
{
return connected;
}
-void Scrollable::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void Scrollable::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object));
- if( scrollable )
+ if(scrollable)
{
- Scrollable& scrollableImpl( GetImpl( scrollable ) );
- switch( index )
+ Scrollable& scrollableImpl(GetImpl(scrollable));
+ switch(index)
{
case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR:
{
- scrollableImpl.SetOvershootEffectColor( value.Get<Vector4>() );
+ scrollableImpl.SetOvershootEffectColor(value.Get<Vector4>());
break;
}
case Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED:
{
- scrollableImpl.SetOvershootAnimationSpeed( value.Get<float>() );
+ scrollableImpl.SetOvershootAnimationSpeed(value.Get<float>());
break;
}
case Toolkit::Scrollable::Property::OVERSHOOT_ENABLED:
{
- scrollableImpl.SetOvershootEnabled( value.Get<bool>() );
+ scrollableImpl.SetOvershootEnabled(value.Get<bool>());
break;
}
case Toolkit::Scrollable::Property::OVERSHOOT_SIZE:
{
- scrollableImpl.SetOvershootSize( value.Get<Vector2>() );
+ scrollableImpl.SetOvershootSize(value.Get<Vector2>());
break;
}
case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION:
{
int alphaFunction = value.Get<int>();
- if( alphaFunction >= AlphaFunction::DEFAULT &&
- alphaFunction < AlphaFunction::COUNT )
+ if(alphaFunction >= AlphaFunction::DEFAULT &&
+ alphaFunction < AlphaFunction::COUNT)
{
- scrollableImpl.mScrollToAlphaFunction = static_cast< AlphaFunction::BuiltinFunction >( alphaFunction );
+ scrollableImpl.mScrollToAlphaFunction = static_cast<AlphaFunction::BuiltinFunction>(alphaFunction);
}
break;
}
}
}
-Property::Value Scrollable::GetProperty( BaseObject* object, Property::Index index )
+Property::Value Scrollable::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object));
- if( scrollable )
+ if(scrollable)
{
- Scrollable& scrollableImpl( GetImpl( scrollable ) );
- switch( index )
+ Scrollable& scrollableImpl(GetImpl(scrollable));
+ switch(index)
{
case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR:
{
}
case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION:
{
- value = static_cast<int>( scrollableImpl.mScrollToAlphaFunction );
+ value = static_cast<int>(scrollableImpl.mScrollToAlphaFunction);
break;
}
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "shadow-view-impl.h"
// EXTERNAL INCLUDES
-#include <sstream>
-#include <iomanip>
-#include <dali/public-api/animation/constraint.h>
#include <dali/devel-api/common/stage.h>
-#include <dali/public-api/object/type-registry.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/render-tasks/render-task-list.h>
#include <dali/public-api/rendering/shader.h>
-#include <dali/integration-api/debug.h>
+#include <iomanip>
+#include <sstream>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/controls/control/control-data-impl.h>
#include <dali-toolkit/internal/controls/control/control-renderers.h>
#include <dali-toolkit/internal/controls/shadow-view/shadow-view-impl.h>
#include <dali-toolkit/internal/filters/blur-two-pass-filter.h>
-#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
// TODO:
// pixel format / size - set from JSON
// aspect ratio property needs to be able to be constrained also for cameras. (now do-able)
// default near clip value
-
/////////////////////////////////////////////////////////
// IMPLEMENTATION NOTES
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
using namespace Dali;
BaseHandle Create()
return Toolkit::ShadowView::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ShadowView, Toolkit::Control, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ShadowView, Toolkit::Control, Create)
DALI_TYPE_REGISTRATION_END()
const float BLUR_STRENGTH_DEFAULT = 1.0f;
const Vector3 DEFAULT_LIGHT_POSITION(300.0f, 250.0f, 600.0f);
-const float DEFAULT_FIELD_OF_VIEW_RADIANS = Math::PI / 4.0f; // 45 degrees
+const float DEFAULT_FIELD_OF_VIEW_RADIANS = Math::PI / 4.0f; // 45 degrees
const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.8f);
const char* const SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME = "uLightCameraProjectionMatrix";
-const char* const SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME = "uLightCameraViewMatrix";
-const char* const SHADER_SHADOW_COLOR_PROPERTY_NAME = "uShadowColor";
-const char* const BLUR_STRENGTH_PROPERTY_NAME = "BlurStrengthProperty";
-const char* const SHADOW_COLOR_PROPERTY_NAME = "ShadowColorProperty";
+const char* const SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME = "uLightCameraViewMatrix";
+const char* const SHADER_SHADOW_COLOR_PROPERTY_NAME = "uShadowColor";
+const char* const BLUR_STRENGTH_PROPERTY_NAME = "BlurStrengthProperty";
+const char* const SHADOW_COLOR_PROPERTY_NAME = "ShadowColorProperty";
} // namespace
-ShadowView::ShadowView( float downsampleWidthScale, float downsampleHeightScale )
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+ShadowView::ShadowView(float downsampleWidthScale, float downsampleHeightScale)
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mChildrenRoot(Actor::New()),
mCachedShadowColor(DEFAULT_SHADOW_COLOR),
mCachedBackgroundColor(DEFAULT_SHADOW_COLOR.r, DEFAULT_SHADOW_COLOR.g, DEFAULT_SHADOW_COLOR.b, 0.0f),
{
ShadowView* impl = new ShadowView(downsampleWidthScale, downsampleHeightScale);
- Dali::Toolkit::ShadowView handle = Dali::Toolkit::ShadowView( *impl );
+ Dali::Toolkit::ShadowView handle = Dali::Toolkit::ShadowView(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
mShadowPlaneBg = shadowPlaneBackground;
mShadowPlane = Actor::New();
- mShadowPlane.SetProperty( Actor::Property::NAME, "SHADOW_PLANE" );
- mShadowPlane.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mShadowPlane.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- Renderer shadowRenderer = CreateRenderer( SHADER_SHADOW_VIEW_RENDER_SHADER_VERT, SHADER_SHADOW_VIEW_RENDER_SHADER_FRAG,
- Shader::Hint::OUTPUT_IS_TRANSPARENT,
- Uint16Pair(20,20) );
- TextureSet textureSet = shadowRenderer.GetTextures();
- textureSet.SetTexture( 0u, mOutputFrameBuffer.GetColorTexture() );
- mShadowPlane.AddRenderer( shadowRenderer );
+ mShadowPlane.SetProperty(Actor::Property::NAME, "SHADOW_PLANE");
+ mShadowPlane.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mShadowPlane.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ Renderer shadowRenderer = CreateRenderer(SHADER_SHADOW_VIEW_RENDER_SHADER_VERT, SHADER_SHADOW_VIEW_RENDER_SHADER_FRAG, Shader::Hint::OUTPUT_IS_TRANSPARENT, Uint16Pair(20, 20));
+ TextureSet textureSet = shadowRenderer.GetTextures();
+ textureSet.SetTexture(0u, mOutputFrameBuffer.GetColorTexture());
+ mShadowPlane.AddRenderer(shadowRenderer);
SetShaderConstants();
// Rather than parent the shadow plane drawable and have constraints to move it to the same
// position, instead parent the shadow plane drawable on the shadow plane passed in.
- mShadowPlaneBg.Add( mShadowPlane );
- mShadowPlane.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mShadowPlane.SetProperty( Actor::Property::POSITION_Z, 1.0f );
+ mShadowPlaneBg.Add(mShadowPlane);
+ mShadowPlane.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mShadowPlane.SetProperty(Actor::Property::POSITION_Z, 1.0f);
ConstrainCamera();
- mShadowPlane.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mShadowPlane.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
- mBlurRootActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mBlurRootActor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
}
void ShadowView::SetPointLight(Actor pointLight)
void ShadowView::SetShadowColor(Vector4 color)
{
- mCachedShadowColor = color;
+ mCachedShadowColor = color;
mCachedBackgroundColor.r = color.r;
mCachedBackgroundColor.g = color.g;
mCachedBackgroundColor.b = color.b;
- if( mShadowPlane )
+ if(mShadowPlane)
{
- mShadowPlane.SetProperty( mShadowColorPropertyIndex, mCachedShadowColor );
+ mShadowPlane.SetProperty(mShadowColorPropertyIndex, mCachedShadowColor);
}
if(mRenderSceneTask)
{
- mRenderSceneTask.SetClearColor( mCachedBackgroundColor );
+ mRenderSceneTask.SetClearColor(mCachedBackgroundColor);
}
}
void ShadowView::Activate()
{
- DALI_ASSERT_ALWAYS( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) && "ShadowView should be on stage before calling Activate()\n" );
+ DALI_ASSERT_ALWAYS(Self().GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE) && "ShadowView should be on stage before calling Activate()\n");
// make sure resources are allocated and start the render tasks processing
CreateRenderTasks();
void ShadowView::Deactivate()
{
- DALI_ASSERT_ALWAYS( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) && "ShadowView should be on stage before calling Deactivate()\n" )
+ DALI_ASSERT_ALWAYS(Self().GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE) && "ShadowView should be on stage before calling Deactivate()\n")
// stop render tasks processing
// Note: render target resources are automatically freed since we set the Image::Unused flag
void ShadowView::OnInitialize()
{
// root actor to parent all user added actors. Used as source actor for shadow render task.
- mChildrenRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mChildrenRoot.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mChildrenRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mChildrenRoot.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
Vector2 stageSize = Stage::GetCurrent().GetSize();
- mCameraActor = CameraActor::New(stageSize);
+ mCameraActor = CameraActor::New(stageSize);
- mCameraActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
// Target is constrained to point at the shadow plane origin
- mCameraActor.SetNearClippingPlane( 1.0f );
- mCameraActor.SetType( Dali::Camera::FREE_LOOK ); // Camera orientation constrained to point at shadow plane world position
- mCameraActor.SetProperty( Actor::Property::ORIENTATION, Quaternion(Radian(Degree(180)), Vector3::YAXIS) );
- mCameraActor.SetProperty( Actor::Property::POSITION, DEFAULT_LIGHT_POSITION );
+ mCameraActor.SetNearClippingPlane(1.0f);
+ mCameraActor.SetType(Dali::Camera::FREE_LOOK); // Camera orientation constrained to point at shadow plane world position
+ mCameraActor.SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(Degree(180)), Vector3::YAXIS));
+ mCameraActor.SetProperty(Actor::Property::POSITION, DEFAULT_LIGHT_POSITION);
// Create render targets needed for rendering from light's point of view
- mSceneFromLightRenderTarget = FrameBuffer::New( stageSize.width, stageSize.height, FrameBuffer::Attachment::NONE );
- Texture textureFromLight = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, unsigned(stageSize.width), unsigned(stageSize.height) );
- mSceneFromLightRenderTarget.AttachColorTexture( textureFromLight );
+ mSceneFromLightRenderTarget = FrameBuffer::New(stageSize.width, stageSize.height, FrameBuffer::Attachment::NONE);
+ Texture textureFromLight = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, unsigned(stageSize.width), unsigned(stageSize.height));
+ mSceneFromLightRenderTarget.AttachColorTexture(textureFromLight);
- mOutputFrameBuffer = FrameBuffer::New( stageSize.width * 0.5f, stageSize.height * 0.5f, FrameBuffer::Attachment::NONE );
- Texture outputTexture = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, unsigned(stageSize.width * 0.5f), unsigned(stageSize.height * 0.5f) );
- mOutputFrameBuffer.AttachColorTexture( outputTexture );
+ mOutputFrameBuffer = FrameBuffer::New(stageSize.width * 0.5f, stageSize.height * 0.5f, FrameBuffer::Attachment::NONE);
+ Texture outputTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, unsigned(stageSize.width * 0.5f), unsigned(stageSize.height * 0.5f));
+ mOutputFrameBuffer.AttachColorTexture(outputTexture);
//////////////////////////////////////////////////////
// Connect to actor tree
- Self().Add( mChildrenRoot );
- Stage::GetCurrent().Add( mCameraActor );
+ Self().Add(mChildrenRoot);
+ Stage::GetCurrent().Add(mCameraActor);
- mBlurFilter.SetRefreshOnDemand( false );
- mBlurFilter.SetInputTexture( mSceneFromLightRenderTarget.GetColorTexture() );
- mBlurFilter.SetOutputFrameBuffer( mOutputFrameBuffer );
- mBlurFilter.SetSize( stageSize * 0.5f );
- mBlurFilter.SetPixelFormat( Pixel::RGBA8888 );
+ mBlurFilter.SetRefreshOnDemand(false);
+ mBlurFilter.SetInputTexture(mSceneFromLightRenderTarget.GetColorTexture());
+ mBlurFilter.SetOutputFrameBuffer(mOutputFrameBuffer);
+ mBlurFilter.SetSize(stageSize * 0.5f);
+ mBlurFilter.SetPixelFormat(Pixel::RGBA8888);
mBlurRootActor = Actor::New();
- mBlurRootActor.SetProperty( Actor::Property::NAME, "BLUR_ROOT_ACTOR" );
+ mBlurRootActor.SetProperty(Actor::Property::NAME, "BLUR_ROOT_ACTOR");
// Turn off inheritance to ensure filter renders properly
- mBlurRootActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mBlurRootActor.SetProperty( Actor::Property::INHERIT_POSITION, false );
- mBlurRootActor.SetProperty( Actor::Property::INHERIT_ORIENTATION, false );
- mBlurRootActor.SetProperty( Actor::Property::INHERIT_SCALE, false );
- mBlurRootActor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_COLOR );
+ mBlurRootActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mBlurRootActor.SetProperty(Actor::Property::INHERIT_POSITION, false);
+ mBlurRootActor.SetProperty(Actor::Property::INHERIT_ORIENTATION, false);
+ mBlurRootActor.SetProperty(Actor::Property::INHERIT_SCALE, false);
+ mBlurRootActor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_COLOR);
- Self().Add( mBlurRootActor );
+ Self().Add(mBlurRootActor);
mBlurFilter.SetRootActor(mBlurRootActor);
mBlurFilter.SetBackgroundColor(Vector4::ZERO);
// Register a property that the user can use to control the blur in the internal object
mBlurStrengthPropertyIndex = self.RegisterProperty(BLUR_STRENGTH_PROPERTY_NAME, BLUR_STRENGTH_DEFAULT);
- Constraint blurStrengthConstraint = Constraint::New<float>( mBlurFilter.GetHandleForAnimateBlurStrength(), mBlurFilter.GetBlurStrengthPropertyIndex(), EqualToConstraint() );
- blurStrengthConstraint.AddSource( Source( self, mBlurStrengthPropertyIndex) );
+ Constraint blurStrengthConstraint = Constraint::New<float>(mBlurFilter.GetHandleForAnimateBlurStrength(), mBlurFilter.GetBlurStrengthPropertyIndex(), EqualToConstraint());
+ blurStrengthConstraint.AddSource(Source(self, mBlurStrengthPropertyIndex));
blurStrengthConstraint.Apply();
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER));
+ });
}
-void ShadowView::OnChildAdd( Actor& child )
+void ShadowView::OnChildAdd(Actor& child)
{
- if( child != mChildrenRoot && child != mBlurRootActor)
+ if(child != mChildrenRoot && child != mBlurRootActor)
{
- mChildrenRoot.Add( child );
+ mChildrenRoot.Add(child);
}
- Control::OnChildAdd( child );
+ Control::OnChildAdd(child);
}
-void ShadowView::OnChildRemove( Actor& child )
+void ShadowView::OnChildRemove(Actor& child)
{
- mChildrenRoot.Remove( child );
+ mChildrenRoot.Remove(child);
- Control::OnChildRemove( child );
+ Control::OnChildRemove(child);
}
void ShadowView::ConstrainCamera()
{
- if( mPointLight && mShadowPlane )
+ if(mPointLight && mShadowPlane)
{
// Constrain camera to look directly at center of shadow plane. (mPointLight position
// is under control of application, can't use transform inheritance)
- Constraint cameraOrientationConstraint = Constraint::New<Quaternion> ( mCameraActor, Actor::Property::ORIENTATION, &LookAt );
- cameraOrientationConstraint.AddSource( Source( mShadowPlane, Actor::Property::WORLD_POSITION ) );
- cameraOrientationConstraint.AddSource( Source( mPointLight, Actor::Property::WORLD_POSITION ) );
- cameraOrientationConstraint.AddSource( Source( mShadowPlane, Actor::Property::WORLD_ORIENTATION ) );
+ Constraint cameraOrientationConstraint = Constraint::New<Quaternion>(mCameraActor, Actor::Property::ORIENTATION, &LookAt);
+ cameraOrientationConstraint.AddSource(Source(mShadowPlane, Actor::Property::WORLD_POSITION));
+ cameraOrientationConstraint.AddSource(Source(mPointLight, Actor::Property::WORLD_POSITION));
+ cameraOrientationConstraint.AddSource(Source(mShadowPlane, Actor::Property::WORLD_ORIENTATION));
cameraOrientationConstraint.Apply();
- Constraint pointLightPositionConstraint = Constraint::New<Vector3>( mCameraActor, Actor::Property::POSITION, EqualToConstraint() );
- pointLightPositionConstraint.AddSource( Source( mPointLight, Actor::Property::WORLD_POSITION ) );
+ Constraint pointLightPositionConstraint = Constraint::New<Vector3>(mCameraActor, Actor::Property::POSITION, EqualToConstraint());
+ pointLightPositionConstraint.AddSource(Source(mPointLight, Actor::Property::WORLD_POSITION));
pointLightPositionConstraint.Apply();
}
}
// We want the first task to render the scene from the light
mRenderSceneTask = taskList.CreateTask();
- mRenderSceneTask.SetCameraActor( mCameraActor );
- mRenderSceneTask.SetSourceActor( mChildrenRoot );
- mRenderSceneTask.SetFrameBuffer( mSceneFromLightRenderTarget );
- mRenderSceneTask.SetInputEnabled( false );
- mRenderSceneTask.SetClearEnabled( true );
+ mRenderSceneTask.SetCameraActor(mCameraActor);
+ mRenderSceneTask.SetSourceActor(mChildrenRoot);
+ mRenderSceneTask.SetFrameBuffer(mSceneFromLightRenderTarget);
+ mRenderSceneTask.SetInputEnabled(false);
+ mRenderSceneTask.SetClearEnabled(true);
// background color for render task should be the shadow color, but with alpha 0
// we don't want to blend the edges of the content with a BLACK at alpha 0, but
// the same shadow color at alpha 0.
- mRenderSceneTask.SetClearColor( mCachedBackgroundColor );
+ mRenderSceneTask.SetClearColor(mCachedBackgroundColor);
mBlurFilter.Enable();
}
void ShadowView::SetShaderConstants()
{
- Property::Index lightCameraProjectionMatrixPropertyIndex = mShadowPlane.RegisterProperty( SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME, Matrix::IDENTITY );
- Constraint projectionMatrixConstraint = Constraint::New<Dali::Matrix>( mShadowPlane, lightCameraProjectionMatrixPropertyIndex, EqualToConstraint() );
- projectionMatrixConstraint.AddSource( Source( mCameraActor, CameraActor::Property::PROJECTION_MATRIX ) );
+ Property::Index lightCameraProjectionMatrixPropertyIndex = mShadowPlane.RegisterProperty(SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME, Matrix::IDENTITY);
+ Constraint projectionMatrixConstraint = Constraint::New<Dali::Matrix>(mShadowPlane, lightCameraProjectionMatrixPropertyIndex, EqualToConstraint());
+ projectionMatrixConstraint.AddSource(Source(mCameraActor, CameraActor::Property::PROJECTION_MATRIX));
projectionMatrixConstraint.Apply();
- Property::Index lightCameraViewMatrixPropertyIndex = mShadowPlane.RegisterProperty( SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME, Matrix::IDENTITY );
- Constraint viewMatrixConstraint = Constraint::New<Dali::Matrix>( mShadowPlane, lightCameraViewMatrixPropertyIndex, EqualToConstraint() );
- viewMatrixConstraint.AddSource( Source( mCameraActor, CameraActor::Property::VIEW_MATRIX ) );
+ Property::Index lightCameraViewMatrixPropertyIndex = mShadowPlane.RegisterProperty(SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME, Matrix::IDENTITY);
+ Constraint viewMatrixConstraint = Constraint::New<Dali::Matrix>(mShadowPlane, lightCameraViewMatrixPropertyIndex, EqualToConstraint());
+ viewMatrixConstraint.AddSource(Source(mCameraActor, CameraActor::Property::VIEW_MATRIX));
viewMatrixConstraint.Apply();
- mShadowColorPropertyIndex = mShadowPlane.RegisterProperty( SHADER_SHADOW_COLOR_PROPERTY_NAME, mCachedShadowColor );
+ mShadowColorPropertyIndex = mShadowPlane.RegisterProperty(SHADER_SHADOW_COLOR_PROPERTY_NAME, mCachedShadowColor);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/slider/slider-impl.h>
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
-#include <sstream>
-#include <limits>
#include <dali/public-api/events/touch-event.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring> // for strcmp
+#include <limits>
+#include <sstream>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
-#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
#include <dali-toolkit/public-api/controls/control-impl.h>
#include <dali-toolkit/public-api/controls/image-view/image-view.h>
+#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
using namespace Dali;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace // Unnamed namespace
{
-
BaseHandle Create()
{
return Dali::Toolkit::Slider::New();
}
+// clang-format off
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Slider, Toolkit::Control, Create )
-
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "lowerBound", FLOAT, LOWER_BOUND )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "upperBound", FLOAT, UPPER_BOUND )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "value", FLOAT, VALUE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "trackVisual", MAP, TRACK_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "handleVisual", MAP, HANDLE_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "progressVisual", MAP, PROGRESS_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "popupVisual", MAP, POPUP_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "popupArrowVisual", MAP, POPUP_ARROW_VISUAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "disabledColor", VECTOR4, DISABLED_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "valuePrecision", INTEGER, VALUE_PRECISION )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "showPopup", BOOLEAN, SHOW_POPUP )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "showValue", BOOLEAN, SHOW_VALUE )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "marks", ARRAY, MARKS )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "snapToMarks", BOOLEAN, SNAP_TO_MARKS )
-DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "markTolerance", FLOAT, MARK_TOLERANCE )
-
-DALI_SIGNAL_REGISTRATION( Toolkit, Slider, "valueChanged", SIGNAL_VALUE_CHANGED )
-DALI_SIGNAL_REGISTRATION( Toolkit, Slider, "mark", SIGNAL_MARK )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Slider, Toolkit::Control, Create )
+
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "lowerBound", FLOAT, LOWER_BOUND )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "upperBound", FLOAT, UPPER_BOUND )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "value", FLOAT, VALUE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "trackVisual", MAP, TRACK_VISUAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "handleVisual", MAP, HANDLE_VISUAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "progressVisual", MAP, PROGRESS_VISUAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "popupVisual", MAP, POPUP_VISUAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "popupArrowVisual", MAP, POPUP_ARROW_VISUAL)
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "disabledColor", VECTOR4, DISABLED_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "valuePrecision", INTEGER, VALUE_PRECISION )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "showPopup", BOOLEAN, SHOW_POPUP )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "showValue", BOOLEAN, SHOW_VALUE )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "marks", ARRAY, MARKS )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "snapToMarks", BOOLEAN, SNAP_TO_MARKS )
+DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "markTolerance", FLOAT, MARK_TOLERANCE )
+
+DALI_SIGNAL_REGISTRATION(Toolkit, Slider, "valueChanged", SIGNAL_VALUE_CHANGED)
+DALI_SIGNAL_REGISTRATION(Toolkit, Slider, "mark", SIGNAL_MARK )
DALI_TYPE_REGISTRATION_END()
+// clang-format on
const float MARK_SNAP_TOLERANCE = 0.05f; // 5% of slider width
-const int VALUE_VIEW_SHOW_DURATION = 1000; // millisec
-const int VALUE_VIEW_SHOW_DURATION_LONG = 2000; // millisec
+const int VALUE_VIEW_SHOW_DURATION = 1000; // millisec
+const int VALUE_VIEW_SHOW_DURATION_LONG = 2000; // millisec
const float VALUE_VERTICAL_OFFSET = 48.0f;
-const float DEFAULT_WIDTH = 0.0f;
-const float DEFAULT_HEIGHT = 27.0f;
-const float DEFAULT_HIT_HEIGHT = 72.0f;
+const float DEFAULT_WIDTH = 0.0f;
+const float DEFAULT_HEIGHT = 27.0f;
+const float DEFAULT_HIT_HEIGHT = 72.0f;
const float DEFAULT_HANDLE_HEIGHT = DEFAULT_HIT_HEIGHT;
-const float POPUP_TEXT_PADDING = 10.0f;
+const float POPUP_TEXT_PADDING = 10.0f;
-const char* SKINNED_TRACK_VISUAL_FILE_NAME = "slider-skin.9.png";
-const char* SKINNED_HANDLE_VISUAL_FILE_NAME = "slider-skin-handle.png";
-const char* SKINNED_PROGRESS_VISUAL_FILE_NAME = "slider-skin-progress.9.png";
-const char* SKINNED_POPUP_VISUAL_FILE_NAME = "slider-popup.9.png";
+const char* SKINNED_TRACK_VISUAL_FILE_NAME = "slider-skin.9.png";
+const char* SKINNED_HANDLE_VISUAL_FILE_NAME = "slider-skin-handle.png";
+const char* SKINNED_PROGRESS_VISUAL_FILE_NAME = "slider-skin-progress.9.png";
+const char* SKINNED_POPUP_VISUAL_FILE_NAME = "slider-popup.9.png";
const char* SKINNED_POPUP_ARROW_VISUAL_FILE_NAME = "slider-popup-arrow.png";
-const Vector2 DEFAULT_HIT_REGION( DEFAULT_WIDTH, DEFAULT_HIT_HEIGHT );
-const Vector2 DEFAULT_TRACK_REGION( DEFAULT_WIDTH, DEFAULT_HEIGHT );
-const Vector2 DEFAULT_HANDLE_SIZE( DEFAULT_HANDLE_HEIGHT, DEFAULT_HANDLE_HEIGHT );
+const Vector2 DEFAULT_HIT_REGION(DEFAULT_WIDTH, DEFAULT_HIT_HEIGHT);
+const Vector2 DEFAULT_TRACK_REGION(DEFAULT_WIDTH, DEFAULT_HEIGHT);
+const Vector2 DEFAULT_HANDLE_SIZE(DEFAULT_HANDLE_HEIGHT, DEFAULT_HANDLE_HEIGHT);
-const Vector4 DEFAULT_DISABLED_COLOR( 0.5f, 0.5f, 0.5f, 1.0f );
+const Vector4 DEFAULT_DISABLED_COLOR(0.5f, 0.5f, 0.5f, 1.0f);
-const float VALUE_POPUP_MARGIN = 10.0f;
-const float VALUE_POPUP_HEIGHT = 81.0f;
+const float VALUE_POPUP_MARGIN = 10.0f;
+const float VALUE_POPUP_HEIGHT = 81.0f;
const float VALUE_POPUP_MIN_WIDTH = 54.0f;
-const float DEFAULT_LOWER_BOUND = 0.0f;
-const float DEFAULT_UPPER_BOUND = 1.0f;
-const float DEFAULT_VALUE = 0.0f;
-const int DEFAULT_VALUE_PRECISION = 0;
-const bool DEFAULT_SHOW_POPUP = false;
-const bool DEFAULT_SHOW_VALUE = true;
-const bool DEFAULT_ENABLED = true;
-const bool DEFAULT_SNAP_TO_MARKS = false;
+const float DEFAULT_LOWER_BOUND = 0.0f;
+const float DEFAULT_UPPER_BOUND = 1.0f;
+const float DEFAULT_VALUE = 0.0f;
+const int DEFAULT_VALUE_PRECISION = 0;
+const bool DEFAULT_SHOW_POPUP = false;
+const bool DEFAULT_SHOW_VALUE = true;
+const bool DEFAULT_ENABLED = true;
+const bool DEFAULT_SNAP_TO_MARKS = false;
} // Unnamed namespace
Dali::Toolkit::Slider Slider::New()
{
// Create the implementation
- SliderPtr slider( new Slider() );
+ SliderPtr slider(new Slider());
// Pass ownership to CustomActor via derived handle
- Dali::Toolkit::Slider handle( *slider );
+ Dali::Toolkit::Slider handle(*slider);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
}
Slider::Slider()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mState( NORMAL ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mState(NORMAL),
mPopupVisual(""),
mPopupArrowVisual(""),
mTrackVisual(""),
mTrackMap(),
mHandleMap(),
mPopupArrowMap(),
- mDisabledColor( 0.0f, 0.0f, 0.0f, 0.0f ),
- mHitRegion( 0.0f, 0.0f ),
- mTrackRegion( 0.0f, 0.0f ),
- mHandleSize( 0.0f, 0.0f ),
- mLowerBound( 0.0f ),
- mUpperBound( 0.0f ),
- mValue( 0.0f ),
- mMarkTolerance( 0.0f ),
- mValuePrecision( 0 ),
- mShowPopup( false ),
- mShowValue( false ),
- mSnapToMarks( false )
+ mDisabledColor(0.0f, 0.0f, 0.0f, 0.0f),
+ mHitRegion(0.0f, 0.0f),
+ mTrackRegion(0.0f, 0.0f),
+ mHandleSize(0.0f, 0.0f),
+ mLowerBound(0.0f),
+ mUpperBound(0.0f),
+ mValue(0.0f),
+ mMarkTolerance(0.0f),
+ mValuePrecision(0),
+ mShowPopup(false),
+ mShowValue(false),
+ mSnapToMarks(false)
{
}
// Properties
Actor self = Self();
- SetHitRegion( DEFAULT_HIT_REGION );
- SetTrackRegion( DEFAULT_TRACK_REGION );
- SetHandleSize( DEFAULT_HANDLE_SIZE );
+ SetHitRegion(DEFAULT_HIT_REGION);
+ SetTrackRegion(DEFAULT_TRACK_REGION);
+ SetHandleSize(DEFAULT_HANDLE_SIZE);
const std::string imageDirPath = AssetManager::GetDaliImagePath();
- SetTrackVisual( imageDirPath + SKINNED_TRACK_VISUAL_FILE_NAME );
- SetHandleVisual( imageDirPath + SKINNED_HANDLE_VISUAL_FILE_NAME );
- SetProgressVisual( imageDirPath + SKINNED_PROGRESS_VISUAL_FILE_NAME );
- SetPopupVisual( imageDirPath + SKINNED_POPUP_VISUAL_FILE_NAME );
- SetPopupArrowVisual( imageDirPath + SKINNED_POPUP_ARROW_VISUAL_FILE_NAME );
+ SetTrackVisual(imageDirPath + SKINNED_TRACK_VISUAL_FILE_NAME);
+ SetHandleVisual(imageDirPath + SKINNED_HANDLE_VISUAL_FILE_NAME);
+ SetProgressVisual(imageDirPath + SKINNED_PROGRESS_VISUAL_FILE_NAME);
+ SetPopupVisual(imageDirPath + SKINNED_POPUP_VISUAL_FILE_NAME);
+ SetPopupArrowVisual(imageDirPath + SKINNED_POPUP_ARROW_VISUAL_FILE_NAME);
- SetShowPopup( DEFAULT_SHOW_POPUP );
- SetShowValue( DEFAULT_SHOW_VALUE );
+ SetShowPopup(DEFAULT_SHOW_POPUP);
+ SetShowValue(DEFAULT_SHOW_VALUE);
- SetEnabled( DEFAULT_ENABLED );
- SetDisabledColor( DEFAULT_DISABLED_COLOR );
+ SetEnabled(DEFAULT_ENABLED);
+ SetDisabledColor(DEFAULT_DISABLED_COLOR);
- SetSnapToMarks( DEFAULT_SNAP_TO_MARKS );
- SetMarkTolerance( MARK_SNAP_TOLERANCE );
+ SetSnapToMarks(DEFAULT_SNAP_TO_MARKS);
+ SetMarkTolerance(MARK_SNAP_TOLERANCE);
- SetLowerBound( DEFAULT_LOWER_BOUND );
- SetUpperBound( DEFAULT_UPPER_BOUND );
+ SetLowerBound(DEFAULT_LOWER_BOUND);
+ SetUpperBound(DEFAULT_UPPER_BOUND);
UpdateSkin();
- SetValuePrecision( DEFAULT_VALUE_PRECISION );
+ SetValuePrecision(DEFAULT_VALUE_PRECISION);
mValue = DEFAULT_VALUE;
- DisplayValue( mValue, false ); // Run this last to display the correct value
+ DisplayValue(mValue, false); // Run this last to display the correct value
// Size the Slider actor to a default
- self.SetProperty( Actor::Property::SIZE, Vector2( DEFAULT_HIT_REGION.x, DEFAULT_HIT_REGION.y ) );
+ self.SetProperty(Actor::Property::SIZE, Vector2(DEFAULT_HIT_REGION.x, DEFAULT_HIT_REGION.y));
// Set the Slider to be highlightable in Screen Reader mode
- self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true );
+ self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
// Connect to the touch signal
- self.TouchedSignal().Connect( this, &Slider::OnTouch );
+ self.TouchedSignal().Connect(this, &Slider::OnTouch);
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::SLIDER ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::SLIDER));
+ });
}
-void Slider::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void Slider::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- SetHitRegion( Vector2( size.x, GetHitRegion().y ) );
+ SetHitRegion(Vector2(size.x, GetHitRegion().y));
// Factor in handle overshoot into size of backing
- SetTrackRegion( Vector2( size.x - GetHandleSize().x, GetTrackRegion().y ) );
- Control::OnRelayout( size, container );
+ SetTrackRegion(Vector2(size.x - GetHandleSize().x, GetTrackRegion().y));
+ Control::OnRelayout(size, container);
}
bool Slider::OnTouch(Actor actor, const TouchEvent& touch)
{
- if( mState != DISABLED )
+ if(mState != DISABLED)
{
const PointState::Type touchState = touch.GetState(0);
- if( touchState == PointState::DOWN )
+ if(touchState == PointState::DOWN)
{
mState = PRESSED;
- float percentage = MapPercentage( touch.GetLocalPosition( 0 ) );
- float value = MapBounds( ( GetSnapToMarks() ) ? SnapToMark( percentage ) : MarkFilter( percentage ), GetLowerBound(), GetUpperBound() );
- SetValue( value );
- DisplayPopup( value );
+ float percentage = MapPercentage(touch.GetLocalPosition(0));
+ float value = MapBounds((GetSnapToMarks()) ? SnapToMark(percentage) : MarkFilter(percentage), GetLowerBound(), GetUpperBound());
+ SetValue(value);
+ DisplayPopup(value);
}
- else if( touchState == PointState::UP )
+ else if(touchState == PointState::UP)
{
- if( mState == PRESSED )
+ if(mState == PRESSED)
{
mState = NORMAL;
- mSlidingFinishedSignal.Emit( Toolkit::Slider::DownCast( Self() ), GetValue() );
+ mSlidingFinishedSignal.Emit(Toolkit::Slider::DownCast(Self()), GetValue());
}
}
}
return false;
}
-void Slider::OnPan( Actor actor, const PanGesture& gesture )
+void Slider::OnPan(Actor actor, const PanGesture& gesture)
{
// gesture.position is in local actor coordinates
- if( mState != DISABLED )
+ if(mState != DISABLED)
{
- switch( gesture.GetState() )
+ switch(gesture.GetState())
{
case GestureState::CONTINUING:
{
- if( mState == PRESSED )
+ if(mState == PRESSED)
{
- float value = MapBounds( MarkFilter ( MapPercentage( gesture.GetPosition() ) ), GetLowerBound(), GetUpperBound() );
- SetValue( value );
- DisplayPopup( value );
+ float value = MapBounds(MarkFilter(MapPercentage(gesture.GetPosition())), GetLowerBound(), GetUpperBound());
+ SetValue(value);
+ DisplayPopup(value);
}
break;
}
case GestureState::FINISHED:
{
- if( mState == PRESSED )
+ if(mState == PRESSED)
{
- if( GetSnapToMarks() )
+ if(GetSnapToMarks())
{
- float value = MapBounds( SnapToMark( MapPercentage( gesture.GetPosition() ) ), GetLowerBound(), GetUpperBound() );
- SetValue( value );
- DisplayPopup( value );
+ float value = MapBounds(SnapToMark(MapPercentage(gesture.GetPosition())), GetLowerBound(), GetUpperBound());
+ SetValue(value);
+ DisplayPopup(value);
}
- mSlidingFinishedSignal.Emit( Toolkit::Slider::DownCast( Self() ), GetValue() );
+ mSlidingFinishedSignal.Emit(Toolkit::Slider::DownCast(Self()), GetValue());
}
mState = NORMAL;
}
}
-float Slider::HitSpaceToDomain( float x )
+float Slider::HitSpaceToDomain(float x)
{
float halfRegionWidth = GetHitRegion().x * 0.5f;
- float halfDomainWidth = ( mDomain.to.x - mDomain.from.x ) * 0.5f;
- float endDiff = halfRegionWidth - halfDomainWidth;
+ float halfDomainWidth = (mDomain.to.x - mDomain.from.x) * 0.5f;
+ float endDiff = halfRegionWidth - halfDomainWidth;
return x - endDiff;
}
-float Slider::MapPercentage( const Vector2& point )
+float Slider::MapPercentage(const Vector2& point)
{
- return Clamp( ( HitSpaceToDomain( point.x ) - mDomain.from.x ) / ( mDomain.to.x - mDomain.from.x ), 0.0f, 1.0f );
+ return Clamp((HitSpaceToDomain(point.x) - mDomain.from.x) / (mDomain.to.x - mDomain.from.x), 0.0f, 1.0f);
}
-float Slider::MapValuePercentage( float value )
+float Slider::MapValuePercentage(float value)
{
- return ( value - GetLowerBound() ) / ( GetUpperBound() - GetLowerBound() );
+ return (value - GetLowerBound()) / (GetUpperBound() - GetLowerBound());
}
-float Slider::MapBounds( float percent, float lowerBound, float upperBound )
+float Slider::MapBounds(float percent, float lowerBound, float upperBound)
{
- return lowerBound + percent * ( upperBound - lowerBound );
+ return lowerBound + percent * (upperBound - lowerBound);
}
-Slider::Domain Slider::CalcDomain( const Vector2& currentSize )
+Slider::Domain Slider::CalcDomain(const Vector2& currentSize)
{
- return Domain( Vector2( 0.0f, 0.0f ), currentSize );
+ return Domain(Vector2(0.0f, 0.0f), currentSize);
}
-void Slider::DisplayValue( float value, bool raiseSignals )
+void Slider::DisplayValue(float value, bool raiseSignals)
{
- float clampedValue = Clamp( value, GetLowerBound(), GetUpperBound() );
+ float clampedValue = Clamp(value, GetLowerBound(), GetUpperBound());
- float percent = MapValuePercentage( clampedValue );
+ float percent = MapValuePercentage(clampedValue);
- float x = mDomain.from.x + percent * ( mDomain.to.x - mDomain.from.x );
+ float x = mDomain.from.x + percent * (mDomain.to.x - mDomain.from.x);
- mHandle.SetProperty( Actor::Property::POSITION_X, x );
+ mHandle.SetProperty(Actor::Property::POSITION_X, x);
// Progress bar
- if( mProgress )
+ if(mProgress)
{
- mProgress.SetProperty( Actor::Property::SIZE, Vector2( x, GetTrackRegion().y ) );
+ mProgress.SetProperty(Actor::Property::SIZE, Vector2(x, GetTrackRegion().y));
}
// Signals
- if( raiseSignals )
+ if(raiseSignals)
{
- Toolkit::Slider self = Toolkit::Slider::DownCast( Self() );
- mValueChangedSignal.Emit( self, clampedValue );
+ Toolkit::Slider self = Toolkit::Slider::DownCast(Self());
+ mValueChangedSignal.Emit(self, clampedValue);
int markIndex;
- if( MarkReached( percent, markIndex ) )
+ if(MarkReached(percent, markIndex))
{
- mMarkReachedSignal.Emit( self, markIndex );
+ mMarkReachedSignal.Emit(self, markIndex);
}
}
- if( mHandleValueTextLabel )
+ if(mHandleValueTextLabel)
{
std::stringstream ss;
- ss.precision( GetValuePrecision() );
+ ss.precision(GetValuePrecision());
ss << std::fixed << clampedValue;
- std::string label = mHandleValueTextLabel.GetProperty<std::string>( Toolkit::TextLabel::Property::TEXT );
- if( label.compare(ss.str()) )
+ std::string label = mHandleValueTextLabel.GetProperty<std::string>(Toolkit::TextLabel::Property::TEXT);
+ if(label.compare(ss.str()))
{
- mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::TEXT, ss.str() );
+ mHandleValueTextLabel.SetProperty(Toolkit::TextLabel::Property::TEXT, ss.str());
}
}
}
-void Slider::SetMarks( const MarkList& marks )
+void Slider::SetMarks(const MarkList& marks)
{
mMarks = marks;
}
return mMarks;
}
-void Slider::SetSnapToMarks( bool snap )
+void Slider::SetSnapToMarks(bool snap)
{
mSnapToMarks = snap;
}
Actor Slider::CreateHitRegion()
{
Actor hitRegion = Actor::New();
- hitRegion.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- hitRegion.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- hitRegion.TouchedSignal().Connect( this, &Slider::OnTouch );
+ hitRegion.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ hitRegion.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ hitRegion.TouchedSignal().Connect(this, &Slider::OnTouch);
return hitRegion;
}
Toolkit::ImageView Slider::CreateTrack()
{
Toolkit::ImageView track = Toolkit::ImageView::New();
- track.SetProperty( Dali::Actor::Property::NAME,"SliderTrack");
- track.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- track.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ track.SetProperty(Dali::Actor::Property::NAME, "SliderTrack");
+ track.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ track.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
return track;
}
-void Slider::SetTrackVisual( const std::string& filename )
+void Slider::SetTrackVisual(const std::string& filename)
{
- if( mHandle && ( filename.size() > 0 ) )
+ if(mHandle && (filename.size() > 0))
{
- mTrack.SetImage( filename );
+ mTrack.SetImage(filename);
mTrackVisual = filename;
}
}
-void Slider::SetTrackVisual( Property::Map map )
+void Slider::SetTrackVisual(Property::Map map)
{
- Property::Value* imageValue = map.Find( "url" );
- if( imageValue )
+ Property::Value* imageValue = map.Find("url");
+ if(imageValue)
{
mTrackVisual.clear();
std::string filename;
- if( imageValue->Get( filename ) )
+ if(imageValue->Get(filename))
{
- if( mTrack && ( filename.size() > 0 ) )
+ if(mTrack && (filename.size() > 0))
{
- mTrack.SetImage( filename );
+ mTrack.SetImage(filename);
mTrackMap = map;
}
}
}
- Property::Value* sizeValue = map.Find( "size" );
- if( sizeValue )
+ Property::Value* sizeValue = map.Find("size");
+ if(sizeValue)
{
Vector2 size;
- if( sizeValue->Get( size ) )
+ if(sizeValue->Get(size))
{
mTrackRegion = size;
- if( mTrack )
+ if(mTrack)
{
- mTrack.SetProperty( Actor::Property::SIZE, mTrackRegion );
+ mTrack.SetProperty(Actor::Property::SIZE, mTrackRegion);
}
- ResizeProgressRegion( Vector2( 0.0f, mTrackRegion.y ) );
+ ResizeProgressRegion(Vector2(0.0f, mTrackRegion.y));
- mDomain = CalcDomain( mTrackRegion );
+ mDomain = CalcDomain(mTrackRegion);
- // Set the progress bar to correct width
- DisplayValue( GetValue(), false );
+ // Set the progress bar to correct width
+ DisplayValue(GetValue(), false);
}
}
}
Toolkit::ImageView Slider::CreateProgress()
{
Toolkit::ImageView progress = Toolkit::ImageView::New();
- progress.SetProperty( Dali::Actor::Property::NAME,"SliderProgress");
- progress.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT );
- progress.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT );
+ progress.SetProperty(Dali::Actor::Property::NAME, "SliderProgress");
+ progress.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT);
+ progress.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT);
return progress;
}
-void Slider::SetProgressVisual( const std::string& filename )
+void Slider::SetProgressVisual(const std::string& filename)
{
- if( mProgress && ( filename.size() > 0 ) )
+ if(mProgress && (filename.size() > 0))
{
- mProgress.SetImage( filename );
+ mProgress.SetImage(filename);
mProgressVisual = filename;
}
}
-void Slider::SetProgressVisual( Property::Map map )
+void Slider::SetProgressVisual(Property::Map map)
{
- Property::Value* imageValue = map.Find( "url" );
- if( imageValue )
+ Property::Value* imageValue = map.Find("url");
+ if(imageValue)
{
mProgressVisual.clear();
std::string filename;
- if( imageValue->Get( filename ) )
+ if(imageValue->Get(filename))
{
- if( mProgress && ( filename.size() > 0 ) )
+ if(mProgress && (filename.size() > 0))
{
- mProgress.SetImage( filename );
+ mProgress.SetImage(filename);
mProgressMap = map;
}
}
return mProgressVisual;
}
-void Slider::SetPopupVisual( const std::string& filename )
+void Slider::SetPopupVisual(const std::string& filename)
{
mPopupVisual = filename;
}
-void Slider::SetPopupVisual( Property::Map map )
+void Slider::SetPopupVisual(Property::Map map)
{
- Property::Value* imageValue = map.Find( "url" );
- if( imageValue )
+ Property::Value* imageValue = map.Find("url");
+ if(imageValue)
{
mPopupVisual.clear();
std::string filename;
- if( imageValue->Get( filename ) )
+ if(imageValue->Get(filename))
{
- if( mPopup && ( filename.size() > 0 ) )
+ if(mPopup && (filename.size() > 0))
{
- mPopup.SetImage( filename );
+ mPopup.SetImage(filename);
mPopupMap = map;
}
}
return mPopupVisual;
}
-void Slider::CreatePopupImage( const std::string& filename )
+void Slider::CreatePopupImage(const std::string& filename)
{
- if( mPopup && ( filename.size() > 0 ) )
+ if(mPopup && (filename.size() > 0))
{
Property::Map map;
map[Toolkit::ImageVisual::Property::URL] = filename;
- mPopup.SetProperty( Toolkit::ImageView::Property::IMAGE, map );
+ mPopup.SetProperty(Toolkit::ImageView::Property::IMAGE, map);
}
}
-void Slider::SetPopupArrowVisual( const std::string& filename )
+void Slider::SetPopupArrowVisual(const std::string& filename)
{
mPopupArrowVisual = filename;
}
-void Slider::SetPopupArrowVisual( Property::Map map )
+void Slider::SetPopupArrowVisual(Property::Map map)
{
- Property::Value* imageValue = map.Find( "url" );
- if( imageValue )
+ Property::Value* imageValue = map.Find("url");
+ if(imageValue)
{
mPopupArrowVisual.clear();
std::string filename;
- if( imageValue->Get( filename ) )
+ if(imageValue->Get(filename))
{
- if( mPopupArrow && ( filename.size() > 0 ) )
+ if(mPopupArrow && (filename.size() > 0))
{
- mPopupArrow.SetImage( filename );
+ mPopupArrow.SetImage(filename);
mPopupArrowMap = map;
}
}
return mPopupArrowVisual;
}
-void Slider::CreatePopupArrowImage( const std::string& filename )
+void Slider::CreatePopupArrowImage(const std::string& filename)
{
- if( mPopupArrow && ( filename.size() > 0 ) )
+ if(mPopupArrow && (filename.size() > 0))
{
Property::Map map;
map[Toolkit::ImageVisual::Property::URL] = filename;
- mPopupArrow.SetProperty( Toolkit::ImageView::Property::IMAGE, map );
+ mPopupArrow.SetProperty(Toolkit::ImageView::Property::IMAGE, map);
}
}
-void Slider::ResizeProgressRegion( const Vector2& region )
+void Slider::ResizeProgressRegion(const Vector2& region)
{
- if( mProgress )
+ if(mProgress)
{
- mProgress.SetProperty( Actor::Property::SIZE, region );
+ mProgress.SetProperty(Actor::Property::SIZE, region);
}
}
Toolkit::ImageView Slider::CreateHandle()
{
Toolkit::ImageView handle = Toolkit::ImageView::New();
- handle.SetProperty( Dali::Actor::Property::NAME,"SliderHandle");
- handle.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT );
- handle.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ handle.SetProperty(Dali::Actor::Property::NAME, "SliderHandle");
+ handle.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT);
+ handle.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
return handle;
}
{
Toolkit::ImageView arrow = Toolkit::ImageView::New();
arrow.SetStyleName("SliderPopupArrow");
- arrow.SetProperty( Dali::Actor::Property::NAME,"SliderPopupArrow");
- arrow.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER );
- arrow.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER );
+ arrow.SetProperty(Dali::Actor::Property::NAME, "SliderPopupArrow");
+ arrow.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER);
+ arrow.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER);
return arrow;
}
Toolkit::TextLabel Slider::CreatePopupText()
{
Toolkit::TextLabel textLabel = Toolkit::TextLabel::New();
- textLabel.SetProperty( Dali::Actor::Property::NAME, "SliderPopupTextLabel" );
- textLabel.SetStyleName( "SliderPopupTextLabel" );
- textLabel.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- textLabel.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- textLabel.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
- textLabel.SetProperty( Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" );
- textLabel.SetProperty( Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER" );
- textLabel.SetProperty( Actor::Property::PADDING, Padding( POPUP_TEXT_PADDING, POPUP_TEXT_PADDING, 0.0f, 0.0f ) );
- textLabel.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false );
+ textLabel.SetProperty(Dali::Actor::Property::NAME, "SliderPopupTextLabel");
+ textLabel.SetStyleName("SliderPopupTextLabel");
+ textLabel.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ textLabel.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ textLabel.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS);
+ textLabel.SetProperty(Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER");
+ textLabel.SetProperty(Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER");
+ textLabel.SetProperty(Actor::Property::PADDING, Padding(POPUP_TEXT_PADDING, POPUP_TEXT_PADDING, 0.0f, 0.0f));
+ textLabel.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false);
return textLabel;
}
Toolkit::ImageView Slider::CreatePopup()
{
Toolkit::ImageView popup = Toolkit::ImageView::New();
- popup.SetProperty( Dali::Actor::Property::NAME, "SliderPopup" );
- popup.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER );
- popup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER );
- popup.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH );
+ popup.SetProperty(Dali::Actor::Property::NAME, "SliderPopup");
+ popup.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER);
+ popup.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER);
+ popup.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH);
mValueTextLabel = CreatePopupText();
- popup.Add( mValueTextLabel );
+ popup.Add(mValueTextLabel);
return popup;
}
-void Slider::SetHandleVisual( const std::string& filename )
+void Slider::SetHandleVisual(const std::string& filename)
{
- if( mHandle && ( filename.size() > 0 ) )
+ if(mHandle && (filename.size() > 0))
{
- mHandle.SetImage( filename );
+ mHandle.SetImage(filename);
mHandleVisual = filename;
}
}
-void Slider::SetHandleVisual( Property::Map map )
+void Slider::SetHandleVisual(Property::Map map)
{
- Property::Value* imageValue = map.Find( "url" );
- if( imageValue )
+ Property::Value* imageValue = map.Find("url");
+ if(imageValue)
{
mHandleVisual.clear();
std::string filename;
- if( imageValue->Get( filename ) )
+ if(imageValue->Get(filename))
{
- if( mHandle && ( filename.size() > 0 ) )
+ if(mHandle && (filename.size() > 0))
{
- mHandle.SetImage( filename );
+ mHandle.SetImage(filename);
mHandleMap = map;
}
}
}
- Property::Value* sizeValue = map.Find( "size" );
- if( sizeValue )
+ Property::Value* sizeValue = map.Find("size");
+ if(sizeValue)
{
Vector2 size;
- if( sizeValue->Get( size ) )
+ if(sizeValue->Get(size))
{
mHandleSize = size;
- ResizeHandleSize( mHandleSize );
+ ResizeHandleSize(mHandleSize);
Vector2 hitRegion = GetHitRegion();
hitRegion.x += mHandleSize.x;
- SetHitRegion( hitRegion );
+ SetHitRegion(hitRegion);
}
}
}
return mHandleVisual;
}
-void Slider::ResizeHandleSize( const Vector2& size )
+void Slider::ResizeHandleSize(const Vector2& size)
{
- if( mHandle )
+ if(mHandle)
{
- mHandle.SetProperty( Actor::Property::SIZE, size );
+ mHandle.SetProperty(Actor::Property::SIZE, size);
}
}
void Slider::CreateHandleValueDisplay()
{
- if( mHandle && !mHandleValueTextLabel )
+ if(mHandle && !mHandleValueTextLabel)
{
mHandleValueTextLabel = Toolkit::TextLabel::New();
- mHandleValueTextLabel.SetProperty( Dali::Actor::Property::NAME,"SliderHandleTextLabel");
+ mHandleValueTextLabel.SetProperty(Dali::Actor::Property::NAME, "SliderHandleTextLabel");
mHandleValueTextLabel.SetStyleName("SliderHandleTextLabel");
- mHandleValueTextLabel.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mHandleValueTextLabel.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" );
- mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER" );
- mHandleValueTextLabel.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false );
- mHandle.Add( mHandleValueTextLabel );
+ mHandleValueTextLabel.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mHandleValueTextLabel.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mHandleValueTextLabel.SetProperty(Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER");
+ mHandleValueTextLabel.SetProperty(Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER");
+ mHandleValueTextLabel.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false);
+ mHandle.Add(mHandleValueTextLabel);
}
}
Actor Slider::CreateValueDisplay()
{
Actor popup = Actor::New();
- popup.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER );
- popup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER );
+ popup.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER);
+ popup.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER);
mPopupArrow = CreatePopupArrow();
- popup.Add( mPopupArrow );
+ popup.Add(mPopupArrow);
mPopup = CreatePopup();
- mPopup.SetProperty( Actor::Property::SIZE, Vector2( 0.0f, VALUE_POPUP_HEIGHT ) );
- mPopupArrow.Add( mPopup );
+ mPopup.SetProperty(Actor::Property::SIZE, Vector2(0.0f, VALUE_POPUP_HEIGHT));
+ mPopupArrow.Add(mPopup);
return popup;
}
void Slider::UpdateSkin()
{
- switch( mState )
+ switch(mState)
{
case NORMAL:
{
- mTrack.SetProperty( Actor::Property::COLOR, Color::WHITE );
- mHandle.SetProperty( Actor::Property::COLOR, Color::WHITE );
- mProgress.SetProperty( Actor::Property::COLOR, Color::WHITE );
+ mTrack.SetProperty(Actor::Property::COLOR, Color::WHITE);
+ mHandle.SetProperty(Actor::Property::COLOR, Color::WHITE);
+ mProgress.SetProperty(Actor::Property::COLOR, Color::WHITE);
break;
}
case DISABLED:
{
Vector4 disabledColor = GetDisabledColor();
- mTrack.SetProperty( Actor::Property::COLOR, disabledColor );
- mHandle.SetProperty( Actor::Property::COLOR, disabledColor );
- mProgress.SetProperty( Actor::Property::COLOR, disabledColor );
+ mTrack.SetProperty(Actor::Property::COLOR, disabledColor);
+ mHandle.SetProperty(Actor::Property::COLOR, disabledColor);
+ mProgress.SetProperty(Actor::Property::COLOR, disabledColor);
break;
}
case PRESSED:
Actor self = Self();
// Hit region
- mHitArea = CreateHitRegion();
+ mHitArea = CreateHitRegion();
mPanDetector = PanGestureDetector::New();
- mPanDetector.Attach( mHitArea );
- mPanDetector.DetectedSignal().Connect( this, &Slider::OnPan );
- self.Add( mHitArea );
+ mPanDetector.Attach(mHitArea);
+ mPanDetector.DetectedSignal().Connect(this, &Slider::OnPan);
+ self.Add(mHitArea);
// Track
mTrack = CreateTrack();
- self.Add( mTrack );
+ self.Add(mTrack);
// Progress bar
mProgress = CreateProgress();
- mTrack.Add( mProgress );
+ mTrack.Add(mProgress);
// Handle
mHandle = CreateHandle();
- mProgress.Add( mHandle );
+ mProgress.Add(mHandle);
}
-void Slider::SetHitRegion( const Vector2& size )
+void Slider::SetHitRegion(const Vector2& size)
{
mHitRegion = size;
- if( mHitArea )
+ if(mHitArea)
{
- mHitArea.SetProperty( Actor::Property::SIZE, mHitRegion );
+ mHitArea.SetProperty(Actor::Property::SIZE, mHitRegion);
}
}
void Slider::AddPopup()
{
- if( !mValueDisplay )
+ if(!mValueDisplay)
{
mValueDisplay = CreateValueDisplay();
- mValueDisplay.SetProperty( Actor::Property::VISIBLE, false );
- mHandle.Add( mValueDisplay );
+ mValueDisplay.SetProperty(Actor::Property::VISIBLE, false);
+ mHandle.Add(mValueDisplay);
- CreatePopupImage( GetPopupVisual() );
- CreatePopupArrowImage( GetPopupArrowVisual() );
+ CreatePopupImage(GetPopupVisual());
+ CreatePopupArrowImage(GetPopupArrowVisual());
- mValueTimer = Timer::New( VALUE_VIEW_SHOW_DURATION );
- mValueTimer.TickSignal().Connect( this, &Slider::HideValueView );
+ mValueTimer = Timer::New(VALUE_VIEW_SHOW_DURATION);
+ mValueTimer.TickSignal().Connect(this, &Slider::HideValueView);
}
}
void Slider::RemovePopup()
{
- if( mValueDisplay )
+ if(mValueDisplay)
{
mPopup.Unparent();
mPopup.Reset();
mValueDisplay.Unparent();
mValueDisplay.Reset();
- mValueTimer.TickSignal().Disconnect( this, &Slider::HideValueView );
+ mValueTimer.TickSignal().Disconnect(this, &Slider::HideValueView);
mValueTimer.Reset();
}
}
-
-float Slider::MarkFilter( float value )
+float Slider::MarkFilter(float value)
{
const float MARK_TOLERANCE = GetMarkTolerance();
float mark = SnapToMark(value);
- if (fabsf(mark - value) < MARK_TOLERANCE)
+ if(fabsf(mark - value) < MARK_TOLERANCE)
return mark;
return value;
}
-float Slider::SnapToMark( float value )
+float Slider::SnapToMark(float value)
{
float closestMark = value;
float closestDist = std::numeric_limits<float>::max();
float mark;
- for( MarkList::SizeType i = 0; i < mMarks.Count(); ++i)
+ for(MarkList::SizeType i = 0; i < mMarks.Count(); ++i)
{
const Property::Value& propertyValue = mMarks[i];
- propertyValue.Get( mark );
- mark = MapValuePercentage( mark );
+ propertyValue.Get(mark);
+ mark = MapValuePercentage(mark);
- float dist = fabsf( mark - value );
- if( dist < closestDist )
+ float dist = fabsf(mark - value);
+ if(dist < closestDist)
{
closestDist = dist;
closestMark = mark;
return closestMark;
}
-bool Slider::MarkReached( float value, int& outIndex )
+bool Slider::MarkReached(float value, int& outIndex)
{
const float MARK_TOLERANCE = GetMarkTolerance();
// Binary search
int head = 0,
tail = mMarks.Size() - 1;
- int current;
+ int current;
float mark;
- while( head <= tail )
+ while(head <= tail)
{
- current = head + ( tail - head ) / 2;
+ current = head + (tail - head) / 2;
- const Property::Value& propertyValue = mMarks[ current ];
- propertyValue.Get( mark );
- mark = MapValuePercentage( mark );
+ const Property::Value& propertyValue = mMarks[current];
+ propertyValue.Get(mark);
+ mark = MapValuePercentage(mark);
- if( fabsf( mark - value ) < MARK_TOLERANCE )
+ if(fabsf(mark - value) < MARK_TOLERANCE)
{
outIndex = current;
return true;
}
- if( value < mark )
+ if(value < mark)
{
tail = current - 1;
}
bool Slider::HideValueView()
{
- if( mValueDisplay )
+ if(mValueDisplay)
{
- mValueDisplay.SetProperty( Actor::Property::VISIBLE, false );
+ mValueDisplay.SetProperty(Actor::Property::VISIBLE, false);
}
return false;
}
-void Slider::SetLowerBound( float bound )
+void Slider::SetLowerBound(float bound)
{
mLowerBound = bound;
- DisplayValue( GetValue(), false );
+ DisplayValue(GetValue(), false);
}
float Slider::GetLowerBound() const
return mLowerBound;
}
-void Slider::SetUpperBound( float bound )
+void Slider::SetUpperBound(float bound)
{
mUpperBound = bound;
- DisplayValue( GetValue(), false );
+ DisplayValue(GetValue(), false);
}
float Slider::GetUpperBound() const
return mUpperBound;
}
-void Slider::SetValue( float value )
+void Slider::SetValue(float value)
{
mValue = value;
- DisplayValue( mValue, true );
- if (Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
+ DisplayValue(mValue, true);
+ if(Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor())
{
Control::Impl::GetAccessibilityObject(Self())->Emit(Dali::Accessibility::ObjectPropertyChangeEvent::VALUE);
}
return mValue;
}
-void Slider::SetTrackRegion( const Vector2& region )
+void Slider::SetTrackRegion(const Vector2& region)
{
mTrackRegion = region;
- if( mTrack )
+ if(mTrack)
{
- mTrack.SetProperty( Actor::Property::SIZE, mTrackRegion );
+ mTrack.SetProperty(Actor::Property::SIZE, mTrackRegion);
}
- ResizeProgressRegion( Vector2( 0.0f, mTrackRegion.y ) );
+ ResizeProgressRegion(Vector2(0.0f, mTrackRegion.y));
- mDomain = CalcDomain( mTrackRegion );
+ mDomain = CalcDomain(mTrackRegion);
- DisplayValue( GetValue(), false ); // Set the progress bar to correct width
+ DisplayValue(GetValue(), false); // Set the progress bar to correct width
}
const Vector2& Slider::GetTrackRegion() const
return mTrackRegion;
}
-void Slider::SetHandleSize( const Vector2& size )
+void Slider::SetHandleSize(const Vector2& size)
{
mHandleSize = size;
- ResizeHandleSize( mHandleSize );
+ ResizeHandleSize(mHandleSize);
Vector2 hitRegion = GetHitRegion();
hitRegion.x += mHandleSize.x;
- SetHitRegion( hitRegion );
+ SetHitRegion(hitRegion);
}
const Vector2& Slider::GetHandleSize() const
return mHandleSize;
}
-void Slider::SetDisabledColor( const Vector4& color )
+void Slider::SetDisabledColor(const Vector4& color)
{
mDisabledColor = color;
return mDisabledColor;
}
-void Slider::SetValuePrecision( int precision )
+void Slider::SetValuePrecision(int precision)
{
mValuePrecision = precision;
}
return mValuePrecision;
}
-void Slider::SetShowPopup( bool showPopup )
+void Slider::SetShowPopup(bool showPopup)
{
mShowPopup = showPopup;
// Value display
- if( mShowPopup )
+ if(mShowPopup)
{
AddPopup();
}
return mShowPopup;
}
-void Slider::SetShowValue( bool showValue )
+void Slider::SetShowValue(bool showValue)
{
mShowValue = showValue;
- if( mShowValue )
+ if(mShowValue)
{
CreateHandleValueDisplay();
}
return mShowValue;
}
-void Slider::SetEnabled( bool enabled )
+void Slider::SetEnabled(bool enabled)
{
- if( enabled )
+ if(enabled)
{
mState = NORMAL;
}
return mState != DISABLED;
}
-void Slider::SetMarkTolerance( float tolerance )
+void Slider::SetMarkTolerance(float tolerance)
{
mMarkTolerance = tolerance;
}
}
// Static class method to support script connecting signals
-bool Slider::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool Slider::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected = true;
- Toolkit::Slider slider = Toolkit::Slider::DownCast( handle );
+ bool connected = true;
+ Toolkit::Slider slider = Toolkit::Slider::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_VALUE_CHANGED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_VALUE_CHANGED))
{
- slider.ValueChangedSignal().Connect( tracker, functor );
+ slider.ValueChangedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_MARK ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_MARK))
{
- slider.MarkReachedSignal().Connect( tracker, functor );
+ slider.MarkReachedSignal().Connect(tracker, functor);
}
else
{
return connected;
}
-void Slider::DisplayPopup( float value )
+void Slider::DisplayPopup(float value)
{
// Value displayDoConnectSignal
- if( mValueTextLabel )
+ if(mValueTextLabel)
{
std::stringstream ss;
- ss.precision( GetValuePrecision() );
+ ss.precision(GetValuePrecision());
ss << std::fixed << value;
- mValueTextLabel.SetProperty( Toolkit::TextLabel::Property::TEXT, ss.str() );
+ mValueTextLabel.SetProperty(Toolkit::TextLabel::Property::TEXT, ss.str());
- if( mValueDisplay )
+ if(mValueDisplay)
{
- mValueDisplay.SetProperty( Actor::Property::VISIBLE, true );
+ mValueDisplay.SetProperty(Actor::Property::VISIBLE, true);
- mValueTimer.SetInterval( VALUE_VIEW_SHOW_DURATION );
+ mValueTimer.SetInterval(VALUE_VIEW_SHOW_DURATION);
}
}
}
-void Slider::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
+void Slider::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value)
{
- Toolkit::Slider slider = Toolkit::Slider::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Slider slider = Toolkit::Slider::DownCast(Dali::BaseHandle(object));
- if ( slider )
+ if(slider)
{
- Slider& sliderImpl( GetImpl( slider ) );
+ Slider& sliderImpl(GetImpl(slider));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::Slider::Property::LOWER_BOUND:
{
- sliderImpl.SetLowerBound( value.Get< float >() );
+ sliderImpl.SetLowerBound(value.Get<float>());
break;
}
case Toolkit::Slider::Property::UPPER_BOUND:
{
- sliderImpl.SetUpperBound( value.Get< float >() );
+ sliderImpl.SetUpperBound(value.Get<float>());
break;
}
case Toolkit::Slider::Property::VALUE:
{
- sliderImpl.SetValue( value.Get< float >() );
+ sliderImpl.SetValue(value.Get<float>());
break;
}
case Toolkit::Slider::Property::TRACK_VISUAL:
{
Property::Map map;
- if( value.Get( map ) )
+ if(value.Get(map))
{
- sliderImpl.SetTrackVisual( map );
+ sliderImpl.SetTrackVisual(map);
}
break;
}
case Toolkit::Slider::Property::HANDLE_VISUAL:
{
Property::Map map;
- if( value.Get( map ) )
+ if(value.Get(map))
{
- sliderImpl.SetHandleVisual( map );
+ sliderImpl.SetHandleVisual(map);
}
break;
}
case Toolkit::Slider::Property::PROGRESS_VISUAL:
{
Property::Map map;
- if( value.Get( map ) )
+ if(value.Get(map))
{
- sliderImpl.SetProgressVisual( map );
+ sliderImpl.SetProgressVisual(map);
}
break;
}
case Toolkit::Slider::Property::POPUP_VISUAL:
{
std::string imageUrl;
- if( value.Get( imageUrl ) )
+ if(value.Get(imageUrl))
{
- sliderImpl.SetPopupVisual( imageUrl );
+ sliderImpl.SetPopupVisual(imageUrl);
}
// If it is not a string, then get a Property::Map from the property if possible.
Property::Map map;
- if( value.Get( map ) )
+ if(value.Get(map))
{
- sliderImpl.SetPopupVisual( map );
+ sliderImpl.SetPopupVisual(map);
}
break;
case Toolkit::Slider::Property::POPUP_ARROW_VISUAL:
{
Property::Map map;
- if( value.Get( map ) )
+ if(value.Get(map))
{
- sliderImpl.SetPopupArrowVisual( map );
+ sliderImpl.SetPopupArrowVisual(map);
}
break;
}
case Toolkit::Slider::Property::DISABLED_COLOR:
{
- sliderImpl.SetDisabledColor( value.Get< Vector4 >() );
+ sliderImpl.SetDisabledColor(value.Get<Vector4>());
break;
}
case Toolkit::Slider::Property::VALUE_PRECISION:
{
- sliderImpl.SetValuePrecision( value.Get< int >() );
+ sliderImpl.SetValuePrecision(value.Get<int>());
break;
}
case Toolkit::Slider::Property::SHOW_POPUP:
{
- sliderImpl.SetShowPopup( value.Get< bool >() );
+ sliderImpl.SetShowPopup(value.Get<bool>());
break;
}
case Toolkit::Slider::Property::SHOW_VALUE:
{
- sliderImpl.SetShowValue( value.Get< bool >() );
+ sliderImpl.SetShowValue(value.Get<bool>());
break;
}
case Toolkit::Slider::Property::MARKS:
{
- sliderImpl.SetMarks( value.Get< Property::Array >() );
+ sliderImpl.SetMarks(value.Get<Property::Array>());
break;
}
case Toolkit::Slider::Property::SNAP_TO_MARKS:
{
- sliderImpl.SetSnapToMarks( value.Get< bool >() );
+ sliderImpl.SetSnapToMarks(value.Get<bool>());
break;
}
case Toolkit::Slider::Property::MARK_TOLERANCE:
{
- sliderImpl.SetMarkTolerance( value.Get< float >() );
+ sliderImpl.SetMarkTolerance(value.Get<float>());
break;
}
}
}
}
-Property::Value Slider::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value Slider::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::Slider slider = Toolkit::Slider::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::Slider slider = Toolkit::Slider::DownCast(Dali::BaseHandle(object));
- if ( slider )
+ if(slider)
{
- Slider& sliderImpl( GetImpl( slider ) );
+ Slider& sliderImpl(GetImpl(slider));
- switch ( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::Slider::Property::LOWER_BOUND:
{
case Toolkit::Slider::Property::TRACK_VISUAL:
{
- if( !sliderImpl.mTrackVisual.empty() )
+ if(!sliderImpl.mTrackVisual.empty())
{
value = sliderImpl.GetTrackVisual();
}
- else if( !sliderImpl.mTrackMap.Empty() )
+ else if(!sliderImpl.mTrackMap.Empty())
{
value = sliderImpl.mTrackMap;
}
case Toolkit::Slider::Property::HANDLE_VISUAL:
{
- if( !sliderImpl.mHandleVisual.empty() )
+ if(!sliderImpl.mHandleVisual.empty())
{
value = sliderImpl.GetHandleVisual();
}
- else if( !sliderImpl.mHandleMap.Empty() )
+ else if(!sliderImpl.mHandleMap.Empty())
{
value = sliderImpl.mHandleMap;
}
case Toolkit::Slider::Property::PROGRESS_VISUAL:
{
- if( !sliderImpl.mProgressVisual.empty() )
+ if(!sliderImpl.mProgressVisual.empty())
{
value = sliderImpl.GetProgressVisual();
}
- else if( !sliderImpl.mProgressMap.Empty() )
+ else if(!sliderImpl.mProgressMap.Empty())
{
value = sliderImpl.mProgressMap;
}
case Toolkit::Slider::Property::POPUP_VISUAL:
{
- if( !sliderImpl.mPopupVisual.empty() )
+ if(!sliderImpl.mPopupVisual.empty())
{
value = sliderImpl.GetPopupVisual();
}
- else if( !sliderImpl.mPopupMap.Empty() )
+ else if(!sliderImpl.mPopupMap.Empty())
{
value = sliderImpl.mPopupMap;
}
case Toolkit::Slider::Property::POPUP_ARROW_VISUAL:
{
- if( !sliderImpl.mPopupArrowVisual.empty() )
+ if(!sliderImpl.mPopupArrowVisual.empty())
{
value = sliderImpl.GetPopupArrowVisual();
}
- else if( !sliderImpl.mPopupArrowMap.Empty() )
+ else if(!sliderImpl.mPopupArrowMap.Empty())
{
value = sliderImpl.mPopupArrowMap;
}
case Toolkit::Slider::Property::MARKS:
{
- Property::Value value1( Property::ARRAY );
+ Property::Value value1(Property::ARRAY);
Property::Array* markArray = value1.GetArray();
- if( markArray )
+ if(markArray)
{
*markArray = sliderImpl.GetMarks();
}
double Slider::AccessibleImpl::GetMinimum()
{
- auto p = Toolkit::Slider::DownCast( self );
- return p.GetProperty( Toolkit::Slider::Property::LOWER_BOUND ).Get< float >();
+ auto p = Toolkit::Slider::DownCast(self);
+ return p.GetProperty(Toolkit::Slider::Property::LOWER_BOUND).Get<float>();
}
double Slider::AccessibleImpl::GetCurrent()
{
- auto p = Toolkit::Slider::DownCast( self );
- return p.GetProperty( Toolkit::Slider::Property::VALUE ).Get< float >();
+ auto p = Toolkit::Slider::DownCast(self);
+ return p.GetProperty(Toolkit::Slider::Property::VALUE).Get<float>();
}
double Slider::AccessibleImpl::GetMaximum()
{
- auto p = Toolkit::Slider::DownCast( self );
- return p.GetProperty( Toolkit::Slider::Property::UPPER_BOUND ).Get< float >();
+ auto p = Toolkit::Slider::DownCast(self);
+ return p.GetProperty(Toolkit::Slider::Property::UPPER_BOUND).Get<float>();
}
-bool Slider::AccessibleImpl::SetCurrent( double current )
+bool Slider::AccessibleImpl::SetCurrent(double current)
{
- if (current < GetMinimum() || current > GetMaximum())
+ if(current < GetMinimum() || current > GetMaximum())
return false;
- auto p = Toolkit::Slider::DownCast( self );
- auto &impl = Toolkit::GetImpl(p);
+ auto p = Toolkit::Slider::DownCast(self);
+ auto& impl = Toolkit::GetImpl(p);
const float prev = p.GetProperty<float>(Toolkit::Slider::Property::VALUE);
- float next = static_cast<float>(current);
+ float next = static_cast<float>(current);
- if (fabsf(next - prev) < Math::MACHINE_EPSILON_0)
+ if(fabsf(next - prev) < Math::MACHINE_EPSILON_0)
{
// do nothing
}
- else if (p.GetProperty<bool>(Toolkit::Slider::Property::SNAP_TO_MARKS))
+ else if(p.GetProperty<bool>(Toolkit::Slider::Property::SNAP_TO_MARKS))
{
auto marks = p.GetProperty<Property::Array>(Toolkit::Slider::Property::MARKS);
int prevIdx;
- if (impl.MarkReached(impl.MapValuePercentage(prev), prevIdx))
+ if(impl.MarkReached(impl.MapValuePercentage(prev), prevIdx))
{
int nextIdx = prevIdx;
nextIdx += (next > prev) ? 1 : -1;
- if (nextIdx < 0 || nextIdx >= static_cast<int>(marks.Count()))
+ if(nextIdx < 0 || nextIdx >= static_cast<int>(marks.Count()))
return false;
next = marks[nextIdx].Get<float>();
double Slider::AccessibleImpl::GetMinimumIncrement()
{
- auto p = Toolkit::Slider::DownCast( self );
+ auto p = Toolkit::Slider::DownCast(self);
- bool hasMarks = !p.GetProperty<Property::Array>(Toolkit::Slider::Property::MARKS).Empty();
+ bool hasMarks = !p.GetProperty<Property::Array>(Toolkit::Slider::Property::MARKS).Empty();
float tolerance = p.GetProperty<float>(Toolkit::Slider::Property::MARK_TOLERANCE);
- if (!hasMarks || fabsf(tolerance) < 0.01)
+ if(!hasMarks || fabsf(tolerance) < 0.01)
return 0.0; // let screen-reader choose the increment
return Math::MACHINE_EPSILON_10000 + tolerance * (GetMaximum() - GetMinimum());
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "super-blur-view-impl.h"
// EXTERNAL INCLUDES
-#include <cmath>
-#include <dali/public-api/animation/constraint.h>
#include <dali/devel-api/common/stage.h>
+#include <dali/devel-api/scripting/scripting.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/object/property-map.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/rendering/renderer.h>
-#include <dali/devel-api/scripting/scripting.h>
-#include <dali/integration-api/debug.h>
+#include <cmath>
// INTERNAL_INCLUDES
-#include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/controls/control/control-data-impl.h>
#include <dali-toolkit/internal/controls/control/control-renderers.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
#include <dali-toolkit/internal/visuals/visual-base-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
-#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
namespace //Unnamed namespace
{
-
using namespace Dali;
//Todo: make these properties instead of constants
-const unsigned int GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES = 11;
-const unsigned int GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION = 10;
-const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH = 4.5f;
-const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION = 5.f;
-const Pixel::Format GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888;
-const float GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
-const float GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
+const unsigned int GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES = 11;
+const unsigned int GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION = 10;
+const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH = 4.5f;
+const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION = 5.f;
+const Pixel::Format GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888;
+const float GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
+const float GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
-const char* ALPHA_UNIFORM_NAME( "uAlpha" );
+const char* ALPHA_UNIFORM_NAME("uAlpha");
/**
* The constraint is used to blend the group of blurred images continuously with a unified blur strength property value which ranges from zero to one.
{
ActorOpacityConstraint(int totalImageNum, int currentImageIdx)
{
- float rangeLength = 1.f / static_cast<float>( totalImageNum );
- float index = static_cast<float>( currentImageIdx );
- mRange = Vector2( index*rangeLength, (index+1.f)*rangeLength );
+ float rangeLength = 1.f / static_cast<float>(totalImageNum);
+ float index = static_cast<float>(currentImageIdx);
+ mRange = Vector2(index * rangeLength, (index + 1.f) * rangeLength);
}
- void operator()( float& current, const PropertyInputContainer& inputs )
+ void operator()(float& current, const PropertyInputContainer& inputs)
{
float blurStrength = inputs[0]->GetFloat();
if(blurStrength < mRange.x)
}
else
{
- current = ( blurStrength - mRange.x) / ( mRange.y - mRange.x );
+ current = (blurStrength - mRange.x) / (mRange.y - mRange.x);
}
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
const unsigned int DEFAULT_BLUR_LEVEL(5u); ///< The default blur level when creating SuperBlurView from the type registry
BaseHandle Create()
{
- return Toolkit::SuperBlurView::New( DEFAULT_BLUR_LEVEL );
+ return Toolkit::SuperBlurView::New(DEFAULT_BLUR_LEVEL);
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::SuperBlurView, Toolkit::Control, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::SuperBlurView, Toolkit::Control, Create)
-DALI_PROPERTY_REGISTRATION( Toolkit, SuperBlurView, "imageUrl", STRING, IMAGE_URL )
+DALI_PROPERTY_REGISTRATION(Toolkit, SuperBlurView, "imageUrl", STRING, IMAGE_URL)
DALI_TYPE_REGISTRATION_END()
} // unnamed namespace
-SuperBlurView::SuperBlurView( unsigned int blurLevels )
-: Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS ) ),
- mTargetSize( Vector2::ZERO ),
+SuperBlurView::SuperBlurView(unsigned int blurLevels)
+: Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
+ mTargetSize(Vector2::ZERO),
mBlurStrengthPropertyIndex(Property::INVALID_INDEX),
- mBlurLevels( blurLevels ),
- mResourcesCleared( true )
+ mBlurLevels(blurLevels),
+ mResourcesCleared(true)
{
- DALI_ASSERT_ALWAYS( mBlurLevels > 0 && " Minimal blur level is one, otherwise no blur is needed" );
- mGaussianBlurView.assign( blurLevels, Toolkit::GaussianBlurView() );
- mBlurredImage.assign( blurLevels, FrameBuffer() );
- mRenderers.assign( blurLevels+1, Dali::Renderer() );
+ DALI_ASSERT_ALWAYS(mBlurLevels > 0 && " Minimal blur level is one, otherwise no blur is needed");
+ mGaussianBlurView.assign(blurLevels, Toolkit::GaussianBlurView());
+ mBlurredImage.assign(blurLevels, FrameBuffer());
+ mRenderers.assign(blurLevels + 1, Dali::Renderer());
}
SuperBlurView::~SuperBlurView()
{
}
-Toolkit::SuperBlurView SuperBlurView::New( unsigned int blurLevels )
+Toolkit::SuperBlurView SuperBlurView::New(unsigned int blurLevels)
{
//Create the implementation
- IntrusivePtr<SuperBlurView> superBlurView( new SuperBlurView( blurLevels ) );
+ IntrusivePtr<SuperBlurView> superBlurView(new SuperBlurView(blurLevels));
//Pass ownership to CustomActor via derived handle
- Toolkit::SuperBlurView handle( *superBlurView );
+ Toolkit::SuperBlurView handle(*superBlurView);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
void SuperBlurView::OnInitialize()
{
- Actor self( Self() );
+ Actor self(Self());
- mBlurStrengthPropertyIndex = self.RegisterProperty( "blurStrength", 0.f );
+ mBlurStrengthPropertyIndex = self.RegisterProperty("blurStrength", 0.f);
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER));
+ });
}
-void SuperBlurView::SetTexture( Texture texture )
+void SuperBlurView::SetTexture(Texture texture)
{
mInputTexture = texture;
- if( mTargetSize == Vector2::ZERO )
+ if(mTargetSize == Vector2::ZERO)
{
return;
}
ClearBlurResource();
- Actor self( Self() );
+ Actor self(Self());
- BlurTexture( 0, mInputTexture );
- SetRendererTexture( mRenderers[0], texture );
+ BlurTexture(0, mInputTexture);
+ SetRendererTexture(mRenderers[0], texture);
unsigned int i = 1;
- for(; i<mBlurLevels; i++)
+ for(; i < mBlurLevels; i++)
{
- BlurTexture( i, mBlurredImage[i-1].GetColorTexture() );
- SetRendererTexture( mRenderers[i], mBlurredImage[i-1] );
+ BlurTexture(i, mBlurredImage[i - 1].GetColorTexture());
+ SetRendererTexture(mRenderers[i], mBlurredImage[i - 1]);
}
- SetRendererTexture( mRenderers[i], mBlurredImage[i-1] );
+ SetRendererTexture(mRenderers[i], mBlurredImage[i - 1]);
mResourcesCleared = false;
}
return mBlurStrengthPropertyIndex;
}
-void SuperBlurView::SetBlurStrength( float blurStrength )
+void SuperBlurView::SetBlurStrength(float blurStrength)
{
Self().SetProperty(mBlurStrengthPropertyIndex, blurStrength);
}
float SuperBlurView::GetCurrentBlurStrength() const
{
float blurStrength;
- (Self().GetProperty( mBlurStrengthPropertyIndex )).Get(blurStrength);
+ (Self().GetProperty(mBlurStrengthPropertyIndex)).Get(blurStrength);
return blurStrength;
}
return mBlurFinishedSignal;
}
-Texture SuperBlurView::GetBlurredTexture( unsigned int level )
+Texture SuperBlurView::GetBlurredTexture(unsigned int level)
{
- DALI_ASSERT_ALWAYS( level>0 && level<=mBlurLevels );
+ DALI_ASSERT_ALWAYS(level > 0 && level <= mBlurLevels);
- FrameBuffer frameBuffer = mBlurredImage[level-1];
+ FrameBuffer frameBuffer = mBlurredImage[level - 1];
return frameBuffer.GetColorTexture();
}
-void SuperBlurView::BlurTexture( unsigned int idx, Texture texture )
+void SuperBlurView::BlurTexture(unsigned int idx, Texture texture)
{
- DALI_ASSERT_ALWAYS( mGaussianBlurView.size()>idx );
- mGaussianBlurView[idx] = Toolkit::GaussianBlurView::New( GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES+GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION*idx,
- GAUSSIAN_BLUR_BELL_CURVE_WIDTH + GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION*static_cast<float>(idx),
- GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT,
- GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE, GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE, true );
- mGaussianBlurView[idx].SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
- mGaussianBlurView[idx].SetProperty( Actor::Property::SIZE, mTargetSize );
- Stage::GetCurrent().Add( mGaussianBlurView[idx] );
-
- mGaussianBlurView[idx].SetUserImageAndOutputRenderTarget( texture, mBlurredImage[idx] );
+ DALI_ASSERT_ALWAYS(mGaussianBlurView.size() > idx);
+ mGaussianBlurView[idx] = Toolkit::GaussianBlurView::New(GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES + GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION * idx,
+ GAUSSIAN_BLUR_BELL_CURVE_WIDTH + GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION * static_cast<float>(idx),
+ GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT,
+ GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE,
+ GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE,
+ true);
+ mGaussianBlurView[idx].SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mGaussianBlurView[idx].SetProperty(Actor::Property::SIZE, mTargetSize);
+ Stage::GetCurrent().Add(mGaussianBlurView[idx]);
+
+ mGaussianBlurView[idx].SetUserImageAndOutputRenderTarget(texture, mBlurredImage[idx]);
mGaussianBlurView[idx].ActivateOnce();
- if( idx == mBlurLevels-1 )
+ if(idx == mBlurLevels - 1)
{
- mGaussianBlurView[idx].FinishedSignal().Connect( this, &SuperBlurView::OnBlurViewFinished );
+ mGaussianBlurView[idx].FinishedSignal().Connect(this, &SuperBlurView::OnBlurViewFinished);
}
}
-void SuperBlurView::OnBlurViewFinished( Toolkit::GaussianBlurView blurView )
+void SuperBlurView::OnBlurViewFinished(Toolkit::GaussianBlurView blurView)
{
ClearBlurResource();
- Toolkit::SuperBlurView handle( GetOwner() );
- mBlurFinishedSignal.Emit( handle );
+ Toolkit::SuperBlurView handle(GetOwner());
+ mBlurFinishedSignal.Emit(handle);
}
void SuperBlurView::ClearBlurResource()
{
- if( !mResourcesCleared )
+ if(!mResourcesCleared)
{
- DALI_ASSERT_ALWAYS( mGaussianBlurView.size() == mBlurLevels && "must synchronize the GaussianBlurView group if blur levels got changed " );
- for(unsigned int i=0; i<mBlurLevels;i++)
+ DALI_ASSERT_ALWAYS(mGaussianBlurView.size() == mBlurLevels && "must synchronize the GaussianBlurView group if blur levels got changed ");
+ for(unsigned int i = 0; i < mBlurLevels; i++)
{
- Stage::GetCurrent().Remove( mGaussianBlurView[i] );
+ Stage::GetCurrent().Remove(mGaussianBlurView[i]);
mGaussianBlurView[i].Deactivate();
}
mResourcesCleared = true;
}
}
-void SuperBlurView::OnSizeSet( const Vector3& targetSize )
+void SuperBlurView::OnSizeSet(const Vector3& targetSize)
{
- if( mTargetSize != Vector2(targetSize) )
+ if(mTargetSize != Vector2(targetSize))
{
mTargetSize = Vector2(targetSize);
Actor self = Self();
- for( unsigned int i = 1; i <= mBlurLevels; i++ )
+ for(unsigned int i = 1; i <= mBlurLevels; i++)
{
float exponent = static_cast<float>(i);
- unsigned int width = mTargetSize.width/std::pow(2.f,exponent);
- unsigned int height = mTargetSize.height/std::pow(2.f,exponent);
+ unsigned int width = mTargetSize.width / std::pow(2.f, exponent);
+ unsigned int height = mTargetSize.height / std::pow(2.f, exponent);
- mBlurredImage[i-1] = FrameBuffer::New( width, height, FrameBuffer::Attachment::NONE );
- Texture texture = Texture::New( TextureType::TEXTURE_2D, GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, unsigned(width), unsigned(height) );
- mBlurredImage[i-1].AttachColorTexture( texture );
+ mBlurredImage[i - 1] = FrameBuffer::New(width, height, FrameBuffer::Attachment::NONE);
+ Texture texture = Texture::New(TextureType::TEXTURE_2D, GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, unsigned(width), unsigned(height));
+ mBlurredImage[i - 1].AttachColorTexture(texture);
}
- if( mInputTexture )
+ if(mInputTexture)
{
- SetTexture( mInputTexture );
+ SetTexture(mInputTexture);
}
}
- Control::OnSizeSet( targetSize );
+ Control::OnSizeSet(targetSize);
}
-void SuperBlurView::OnSceneConnection( int depth )
+void SuperBlurView::OnSceneConnection(int depth)
{
- if( mTargetSize == Vector2::ZERO )
+ if(mTargetSize == Vector2::ZERO)
{
return;
}
// Exception to the rule, chaining up first ensures visuals have SetOnScene called to create their renderers
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
Actor self = Self();
- for(unsigned int i=0; i<mBlurLevels+1;i++)
+ for(unsigned int i = 0; i < mBlurLevels + 1; i++)
{
- mRenderers[i] = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_SUPER_BLUR_VIEW_FRAG );
- mRenderers[i].SetProperty( Dali::Renderer::Property::DEPTH_INDEX, (int)i );
- self.AddRenderer( mRenderers[i] );
+ mRenderers[i] = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_SUPER_BLUR_VIEW_FRAG);
+ mRenderers[i].SetProperty(Dali::Renderer::Property::DEPTH_INDEX, (int)i);
+ self.AddRenderer(mRenderers[i]);
- if( i > 0 )
+ if(i > 0)
{
- Renderer renderer = mRenderers[i];
- Property::Index index = renderer.RegisterProperty( ALPHA_UNIFORM_NAME, 0.f );
- Constraint constraint = Constraint::New<float>( renderer, index, ActorOpacityConstraint(mBlurLevels, i-1) );
- constraint.AddSource( Source( self, mBlurStrengthPropertyIndex ) );
+ Renderer renderer = mRenderers[i];
+ Property::Index index = renderer.RegisterProperty(ALPHA_UNIFORM_NAME, 0.f);
+ Constraint constraint = Constraint::New<float>(renderer, index, ActorOpacityConstraint(mBlurLevels, i - 1));
+ constraint.AddSource(Source(self, mBlurStrengthPropertyIndex));
constraint.Apply();
}
}
- if( mInputTexture )
+ if(mInputTexture)
{
- SetRendererTexture( mRenderers[0], mInputTexture );
+ SetRendererTexture(mRenderers[0], mInputTexture);
unsigned int i = 1;
- for(; i<mBlurLevels; i++)
+ for(; i < mBlurLevels; i++)
{
- SetRendererTexture( mRenderers[i], mBlurredImage[i-1] );
+ SetRendererTexture(mRenderers[i], mBlurredImage[i - 1]);
}
- SetRendererTexture( mRenderers[i], mBlurredImage[i-1] );
+ SetRendererTexture(mRenderers[i], mBlurredImage[i - 1]);
}
}
void SuperBlurView::OnSceneDisconnection()
{
- for(unsigned int i=0; i<mBlurLevels+1;i++)
+ for(unsigned int i = 0; i < mBlurLevels + 1; i++)
{
- Self().RemoveRenderer( mRenderers[i] );
+ Self().RemoveRenderer(mRenderers[i]);
mRenderers[i].Reset();
}
Vector3 SuperBlurView::GetNaturalSize()
{
- if( mInputTexture )
+ if(mInputTexture)
{
- return Vector3( mInputTexture.GetWidth(), mInputTexture.GetHeight(), 0.f );
+ return Vector3(mInputTexture.GetWidth(), mInputTexture.GetHeight(), 0.f);
}
return Vector3::ZERO;
}
-void SuperBlurView::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value )
+void SuperBlurView::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value)
{
- Toolkit::SuperBlurView superBlurView = Toolkit::SuperBlurView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::SuperBlurView superBlurView = Toolkit::SuperBlurView::DownCast(Dali::BaseHandle(object));
- if( superBlurView )
+ if(superBlurView)
{
- SuperBlurView& superBlurViewImpl( GetImpl( superBlurView ) );
+ SuperBlurView& superBlurViewImpl(GetImpl(superBlurView));
- if( propertyIndex == Toolkit::SuperBlurView::Property::IMAGE_URL )
+ if(propertyIndex == Toolkit::SuperBlurView::Property::IMAGE_URL)
{
- value.Get( superBlurViewImpl.mUrl );
+ value.Get(superBlurViewImpl.mUrl);
- PixelData pixels = SyncImageLoader::Load( superBlurViewImpl.mUrl );
+ PixelData pixels = SyncImageLoader::Load(superBlurViewImpl.mUrl);
- if ( pixels )
+ if(pixels)
{
- Texture texture = Texture::New( TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight() );
- texture.Upload( pixels, 0, 0, 0, 0, pixels.GetWidth(), pixels.GetHeight() );
+ Texture texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight());
+ texture.Upload(pixels, 0, 0, 0, 0, pixels.GetWidth(), pixels.GetHeight());
- superBlurViewImpl.SetTexture( texture );
+ superBlurViewImpl.SetTexture(texture);
}
else
{
- DALI_LOG_ERROR( "Cannot create image from property value\n" );
+ DALI_LOG_ERROR("Cannot create image from property value\n");
}
}
}
}
-Property::Value SuperBlurView::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value SuperBlurView::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::SuperBlurView blurView = Toolkit::SuperBlurView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::SuperBlurView blurView = Toolkit::SuperBlurView::DownCast(Dali::BaseHandle(object));
- if( blurView )
+ if(blurView)
{
- SuperBlurView& superBlurViewImpl( GetImpl( blurView ) );
+ SuperBlurView& superBlurViewImpl(GetImpl(blurView));
- if( propertyIndex == Toolkit::SuperBlurView::Property::IMAGE_URL )
+ if(propertyIndex == Toolkit::SuperBlurView::Property::IMAGE_URL)
{
value = superBlurViewImpl.mUrl;
}
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/table-view/table-view-impl.h>
// EXTERNAL INCLUDES
-#include <sstream>
-#include <dali/public-api/object/ref-object.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/devel-api/actors/actor-devel.h>
#include <dali/devel-api/scripting/scripting.h>
-#include <dali/public-api/size-negotiation/relayout-container.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/ref-object.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <dali/public-api/size-negotiation/relayout-container.h>
+#include <sstream>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
* @param[in] actor The child actor to test against
* @param[dimension] The dimension to test against
*/
-bool FitToChild( Actor actor, Dimension::Type dimension )
+bool FitToChild(Actor actor, Dimension::Type dimension)
{
- return actor.GetResizePolicy( dimension ) != ResizePolicy::FILL_TO_PARENT && actor.GetRelayoutSize( dimension ) > 0.0f;
+ return actor.GetResizePolicy(dimension) != ResizePolicy::FILL_TO_PARENT && actor.GetRelayoutSize(dimension) > 0.0f;
}
#if defined(DEBUG_ENABLED)
// currently not called from code so compiler will optimize these away, kept here for future debugging
#define TABLEVIEW_TAG "DALI Toolkit::TableView "
-#define TV_LOG(fmt, args,...) Debug::LogMessage(Debug::DebugInfo, TABLEVIEW_TAG fmt, ## args)
+#define TV_LOG(fmt, args, ...) Debug::LogMessage(Debug::DebugInfo, TABLEVIEW_TAG fmt, ##args)
//#define TABLEVIEW_DEBUG 1
#if defined(TABLEVIEW_DEBUG)
-void PrintArray( Array2d<Dali::Toolkit::Internal::TableView::CellData>& array )
+void PrintArray(Array2d<Dali::Toolkit::Internal::TableView::CellData>& array)
{
- TV_LOG( "Array2d<CellData> size [%d,%d] \n", array.GetRows(), array.GetColumns() );
+ TV_LOG("Array2d<CellData> size [%d,%d] \n", array.GetRows(), array.GetColumns());
// print values
- for( unsigned int i = 0; i < array.GetRows(); ++i )
+ for(unsigned int i = 0; i < array.GetRows(); ++i)
{
- for( unsigned int j = 0; j < array.GetColumns(); ++j )
+ for(unsigned int j = 0; j < array.GetColumns(); ++j)
{
- Dali::Toolkit::Internal::TableView::CellData data = array[i][j];
- char actor = ' ';
- std::string actorName;
- if( data.actor )
+ Dali::Toolkit::Internal::TableView::CellData data = array[i][j];
+ char actor = ' ';
+ std::string actorName;
+ if(data.actor)
{
- actor = 'A';
- actorName = data.actor.GetProperty< std::string >( Dali::Actor::Property::NAME );
+ actor = 'A';
+ actorName = data.actor.GetProperty<std::string>(Dali::Actor::Property::NAME);
}
- TV_LOG("Array[%d,%d]=%c %s %d,%d,%d,%d ", i, j, actor, actorName.c_str(),
- data.position.rowIndex, data.position.columnIndex,
- data.position.rowSpan, data.position.columnSpan );
+ TV_LOG("Array[%d,%d]=%c %s %d,%d,%d,%d ", i, j, actor, actorName.c_str(), data.position.rowIndex, data.position.columnIndex, data.position.rowSpan, data.position.columnSpan);
}
- TV_LOG( "\n" );
+ TV_LOG("\n");
}
}
// debugging support, very useful when new features are added or bugs are hunted down
// currently not called from code so compiler will optimize these away, kept here for future debugging
-void PrintArray( Array2d<Size>& array )
+void PrintArray(Array2d<Size>& array)
{
- TV_LOG( "Array2d<Size> size [%d,%d] \n", array.GetRows(), array.GetColumns() );
+ TV_LOG("Array2d<Size> size [%d,%d] \n", array.GetRows(), array.GetColumns());
// print values
- for( unsigned int i = 0; i < array.GetRows(); ++i )
+ for(unsigned int i = 0; i < array.GetRows(); ++i)
{
- for( unsigned int j = 0; j < array.GetColumns(); ++j )
+ for(unsigned int j = 0; j < array.GetColumns(); ++j)
{
- TV_LOG( "Array[%d,%d]=%.2f,%.2f ", i, j, array[i][j].width, array[i][j].height );
+ TV_LOG("Array[%d,%d]=%.2f,%.2f ", i, j, array[i][j].width, array[i][j].height);
}
- TV_LOG( "\n" );
+ TV_LOG("\n");
}
}
// debugging support, very useful when new features are added or bugs are hunted down
// currently not called from code so compiler will optimize these away, kept here for future debugging
-void PrintVector( std::vector<float>& array )
+void PrintVector(std::vector<float>& array)
{
- TV_LOG( "vector, size [%d]\n", array.size() );
+ TV_LOG("vector, size [%d]\n", array.size());
// print values
- for( unsigned int i = 0; i < array.size(); ++i )
+ for(unsigned int i = 0; i < array.size(); ++i)
{
- TV_LOG( "vector[%d]=%.2f ", i, array[i] );
+ TV_LOG("vector[%d]=%.2f ", i, array[i]);
}
- TV_LOG( "\n" );
+ TV_LOG("\n");
}
#endif // defined(TABLEVIEW_DEBUG)
#endif // defined(DEBUG_ENABLED)
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// Type registration
BaseHandle Create()
{
- return Toolkit::TableView::New( 0, 0 );
+ return Toolkit::TableView::New(0, 0);
}
+// clang-format off
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TableView, Toolkit::Control, Create );
-
-DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "rows", INTEGER, ROWS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "columns", INTEGER, COLUMNS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "cellPadding", VECTOR2, CELL_PADDING )
-DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "layoutRows", MAP, LAYOUT_ROWS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "layoutColumns", MAP, LAYOUT_COLUMNS )
-DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellIndex", VECTOR2, CELL_INDEX )
-DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "rowSpan", INTEGER, ROW_SPAN )
-DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "columnSpan", INTEGER, COLUMN_SPAN )
-DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellHorizontalAlignment", STRING, CELL_HORIZONTAL_ALIGNMENT )
-DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellVerticalAlignment", STRING, CELL_VERTICAL_ALIGNMENT )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TableView, Toolkit::Control, Create);
+
+DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "rows", INTEGER, ROWS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "columns", INTEGER, COLUMNS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "cellPadding", VECTOR2, CELL_PADDING )
+DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "layoutRows", MAP, LAYOUT_ROWS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "layoutColumns", MAP, LAYOUT_COLUMNS)
+
+DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "cellIndex", VECTOR2, CELL_INDEX )
+DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "rowSpan", INTEGER, ROW_SPAN )
+DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "columnSpan", INTEGER, COLUMN_SPAN )
+DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "cellHorizontalAlignment", STRING, CELL_HORIZONTAL_ALIGNMENT)
+DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "cellVerticalAlignment", STRING, CELL_VERTICAL_ALIGNMENT )
DALI_TYPE_REGISTRATION_END()
const Scripting::StringEnum LAYOUT_POLICY_STRING_TABLE[] =
{
- { "fixed", Toolkit::TableView::FIXED },
- { "relative", Toolkit::TableView::RELATIVE },
- { "fill", Toolkit::TableView::FILL },
- { "fit", Toolkit::TableView::FIT }
+ {"fixed", Toolkit::TableView::FIXED },
+ {"relative", Toolkit::TableView::RELATIVE},
+ {"fill", Toolkit::TableView::FILL },
+ {"fit", Toolkit::TableView::FIT }
};
-const unsigned int LAYOUT_POLICY_STRING_TABLE_COUNT = sizeof(LAYOUT_POLICY_STRING_TABLE) / sizeof( LAYOUT_POLICY_STRING_TABLE[0] );
+const unsigned int LAYOUT_POLICY_STRING_TABLE_COUNT = sizeof(LAYOUT_POLICY_STRING_TABLE) / sizeof(LAYOUT_POLICY_STRING_TABLE[0]);
const Scripting::StringEnum HORIZONTAL_ALIGNMENT_STRING_TABLE[] =
{
- {"left", HorizontalAlignment::LEFT},
+ {"left", HorizontalAlignment::LEFT },
{"center", HorizontalAlignment::CENTER},
- {"right", HorizontalAlignment::RIGHT}
+ {"right", HorizontalAlignment::RIGHT }
};
-const unsigned int HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(HORIZONTAL_ALIGNMENT_STRING_TABLE) / sizeof( HORIZONTAL_ALIGNMENT_STRING_TABLE[0] );
+const unsigned int HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(HORIZONTAL_ALIGNMENT_STRING_TABLE) / sizeof(HORIZONTAL_ALIGNMENT_STRING_TABLE[0]);
const Scripting::StringEnum VERTICAL_ALIGNMENT_STRING_TABLE[] =
{
- {"top", VerticalAlignment::TOP},
+ {"top", VerticalAlignment::TOP },
{"center", VerticalAlignment::CENTER},
{"bottom", VerticalAlignment::BOTTOM}
};
-const unsigned int VERTICAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(VERTICAL_ALIGNMENT_STRING_TABLE) / sizeof( VERTICAL_ALIGNMENT_STRING_TABLE[0] );
-
+const unsigned int VERTICAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(VERTICAL_ALIGNMENT_STRING_TABLE) / sizeof(VERTICAL_ALIGNMENT_STRING_TABLE[0]);
+// clang-format on
} // Unnamed namespace
-Toolkit::TableView TableView::New( unsigned int initialRows, unsigned int initialColumns )
+Toolkit::TableView TableView::New(unsigned int initialRows, unsigned int initialColumns)
{
// Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< TableView > impl = new TableView( initialRows, initialColumns );
+ IntrusivePtr<TableView> impl = new TableView(initialRows, initialColumns);
// Pass ownership to CustomActor handle
- Toolkit::TableView handle( *impl );
+ Toolkit::TableView handle(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-bool TableView::AddChild( Actor& child, const Toolkit::TableView::CellPosition& position )
+bool TableView::AddChild(Actor& child, const Toolkit::TableView::CellPosition& position)
{
// check that the child is valid
- DALI_ASSERT_ALWAYS( child );
+ DALI_ASSERT_ALWAYS(child);
// if child is already parented, we adopt it
child.Unparent();
// check if we need to expand our data array
- if( position.rowIndex >= mCellData.GetRows() )
+ if(position.rowIndex >= mCellData.GetRows())
{
// only adding new rows
- ResizeContainers( position.rowIndex + 1, mCellData.GetColumns() );
+ ResizeContainers(position.rowIndex + 1, mCellData.GetColumns());
}
- if( position.columnIndex >= mCellData.GetColumns() )
+ if(position.columnIndex >= mCellData.GetColumns())
{
// only adding new columns
- ResizeContainers( mCellData.GetRows(), position.columnIndex + 1 );
+ ResizeContainers(mCellData.GetRows(), position.columnIndex + 1);
}
// check if there already is something in this cell
- if( mCellData[ position.rowIndex ][ position.columnIndex ].actor )
+ if(mCellData[position.rowIndex][position.columnIndex].actor)
{
return false; // cannot share a cell, it would complicate all logic and not bring much benefit
}
- RelayoutingLock lock( *this );
+ RelayoutingLock lock(*this);
// adopt the child
- Self().Add( child );
+ Self().Add(child);
// if child spans multiple rows of columns
- if( ( position.rowSpan > 1 ) && ( position.rowIndex + position.rowSpan > mCellData.GetRows() ) )
+ if((position.rowSpan > 1) && (position.rowIndex + position.rowSpan > mCellData.GetRows()))
{
// increase table size for the full span, only increasing rows
- ResizeContainers( position.rowIndex + position.rowSpan, mCellData.GetColumns() );
+ ResizeContainers(position.rowIndex + position.rowSpan, mCellData.GetColumns());
}
- if( ( position.columnSpan > 1 ) && ( position.columnIndex + position.columnSpan > mCellData.GetColumns() ) )
+ if((position.columnSpan > 1) && (position.columnIndex + position.columnSpan > mCellData.GetColumns()))
{
// increase table size for the full span, only increasing columns
- ResizeContainers( mCellData.GetRows(), position.columnIndex + position.columnSpan );
+ ResizeContainers(mCellData.GetRows(), position.columnIndex + position.columnSpan);
}
// Fill in all cells that need the data
CellData data;
- data.actor = child;
+ data.actor = child;
data.position = position;
- for( unsigned int row = position.rowIndex; row < ( position.rowIndex + position.rowSpan ); ++row )
+ for(unsigned int row = position.rowIndex; row < (position.rowIndex + position.rowSpan); ++row)
{
// store same information to all cells, this way we can identify
// if a cell is the prime location of an actor or a spanned one
- for( unsigned int column = position.columnIndex; column < ( position.columnIndex + position.columnSpan ); ++column )
+ for(unsigned int column = position.columnIndex; column < (position.columnIndex + position.columnSpan); ++column)
{
// store same information to all cells, this way we can identify
// if a cell is the prime location of an actor or a spanned one
- mCellData[ row ][ column ] = data;
+ mCellData[row][column] = data;
}
}
// Relayout the whole table
- if( mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT && position.rowSpan == 1 )
+ if(mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT && position.rowSpan == 1)
{
mRowDirty = true;
}
- if( mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT && position.columnSpan == 1 )
+ if(mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT && position.columnSpan == 1)
{
mColumnDirty = true;
}
RelayoutRequest();
- return true; // Addition successful
+ return true; // Addition successful
}
-Actor TableView::GetChildAt( const Toolkit::TableView::CellPosition& position )
+Actor TableView::GetChildAt(const Toolkit::TableView::CellPosition& position)
{
- if( ( position.rowIndex < mCellData.GetRows() ) && ( position.columnIndex < mCellData.GetColumns() ) )
+ if((position.rowIndex < mCellData.GetRows()) && (position.columnIndex < mCellData.GetColumns()))
{
- return mCellData[ position.rowIndex ][ position.columnIndex ].actor;
+ return mCellData[position.rowIndex][position.columnIndex].actor;
}
// Return an empty handle
return Actor();
}
-Actor TableView::RemoveChildAt( const Toolkit::TableView::CellPosition& position )
+Actor TableView::RemoveChildAt(const Toolkit::TableView::CellPosition& position)
{
// get the child handle
- Actor child = GetChildAt( position );
+ Actor child = GetChildAt(position);
// if no real actor there, nothing else to be done
- if( child )
+ if(child)
{
- RelayoutingLock lock( *this );
+ RelayoutingLock lock(*this);
// Remove the child, this will trigger a call to OnChildRemove
- Self().Remove( child );
+ Self().Remove(child);
// relayout the table only if instances were found
- if( RemoveAllInstances( child ) )
+ if(RemoveAllInstances(child))
{
- if( mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT )
+ if(mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT)
{
mRowDirty = true;
}
- if( mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT )
+ if(mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT)
{
mColumnDirty = true;
}
return child;
}
-bool TableView::FindChildPosition( const Actor& child, Toolkit::TableView::CellPosition& positionOut )
+bool TableView::FindChildPosition(const Actor& child, Toolkit::TableView::CellPosition& positionOut)
{
// Only find valid child actors
- if( child )
+ if(child)
{
// Walk through the layout data
- const unsigned int rowCount = mCellData.GetRows();
+ const unsigned int rowCount = mCellData.GetRows();
const unsigned int columnCount = mCellData.GetColumns();
- for( unsigned int row = 0; row < rowCount; ++row )
+ for(unsigned int row = 0; row < rowCount; ++row)
{
- for( unsigned int column = 0; column < columnCount; ++column )
+ for(unsigned int column = 0; column < columnCount; ++column)
{
- if( mCellData[ row ][ column ].actor == child )
+ if(mCellData[row][column].actor == child)
{
- positionOut = mCellData[ row ][ column ].position;
+ positionOut = mCellData[row][column].position;
return true;
}
}
return false;
}
-void TableView::InsertRow( unsigned int rowIndex )
+void TableView::InsertRow(unsigned int rowIndex)
{
- RelayoutingLock lock( *this );
+ RelayoutingLock lock(*this);
- mCellData.InsertRow( rowIndex );
+ mCellData.InsertRow(rowIndex);
// Need to update the cell infos for the items that moved
- const unsigned int rowCount = mCellData.GetRows();
+ const unsigned int rowCount = mCellData.GetRows();
const unsigned int columnCount = mCellData.GetColumns();
- for( unsigned int row = 0; row < rowCount; ++row )
+ for(unsigned int row = 0; row < rowCount; ++row)
{
- for( unsigned int column = 0; column < columnCount; ++column )
+ for(unsigned int column = 0; column < columnCount; ++column)
{
- Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position;
+ Toolkit::TableView::CellPosition& position = mCellData[row][column].position;
// If cell is spanning and above and spans to inserted row
- if( ( position.rowSpan > 1 ) && ( position.rowIndex <= rowIndex ) &&
- ( position.rowIndex + position.rowSpan > rowIndex ) )
+ if((position.rowSpan > 1) && (position.rowIndex <= rowIndex) &&
+ (position.rowIndex + position.rowSpan > rowIndex))
{
// Increment span
position.rowSpan++;
// Copy cell to occupy the new column
- mCellData[ rowIndex ][ column ] = mCellData[ row ][ column ];
+ mCellData[rowIndex][column] = mCellData[row][column];
}
- else if( row > rowIndex ) // If below of inserted row, increase row index
+ else if(row > rowIndex) // If below of inserted row, increase row index
{
// Increment index
position.rowIndex++;
}
// Expand row data array
- mRowData.Insert( mRowData.Begin() + rowIndex, RowColumnData() );
+ mRowData.Insert(mRowData.Begin() + rowIndex, RowColumnData());
// Sizes may have changed, so relayout
mRowDirty = true;
RelayoutRequest();
}
-void TableView::DeleteRow( unsigned int rowIndex )
+void TableView::DeleteRow(unsigned int rowIndex)
{
- std::vector< Actor > ignored;
- DeleteRow( rowIndex, ignored );
+ std::vector<Actor> ignored;
+ DeleteRow(rowIndex, ignored);
}
-void TableView::DeleteRow( unsigned int rowIndex, std::vector<Actor>& removed )
+void TableView::DeleteRow(unsigned int rowIndex, std::vector<Actor>& removed)
{
- RelayoutingLock lock( *this );
+ RelayoutingLock lock(*this);
// Delete the row
- std::vector< CellData > lost;
- mCellData.DeleteRow( rowIndex, lost );
+ std::vector<CellData> lost;
+ mCellData.DeleteRow(rowIndex, lost);
// Need to update the cell infos for the items that moved
- const unsigned int rowCount = mCellData.GetRows();
+ const unsigned int rowCount = mCellData.GetRows();
const unsigned int columnCount = mCellData.GetColumns();
- for( unsigned int row = 0; row < rowCount; ++row )
+ for(unsigned int row = 0; row < rowCount; ++row)
{
- for( unsigned int column = 0; column < columnCount; ++column )
+ for(unsigned int column = 0; column < columnCount; ++column)
{
- Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position;
+ Toolkit::TableView::CellPosition& position = mCellData[row][column].position;
// If cell is spanning and above and spans to deleted row
- if( ( position.rowSpan > 1 ) && ( position.rowIndex <= rowIndex ) &&
- ( position.rowIndex + position.rowSpan > rowIndex ) )
+ if((position.rowSpan > 1) && (position.rowIndex <= rowIndex) &&
+ (position.rowIndex + position.rowSpan > rowIndex))
{
// Decrement span
- if( position.rowSpan > 1 )
+ if(position.rowSpan > 1)
{
position.rowSpan--;
}
}
- else if( row >= rowIndex ) // If below of or at the inserted row, decrease row index
+ else if(row >= rowIndex) // If below of or at the inserted row, decrease row index
{
// Decrement index
- if( position.rowIndex > 0 )
+ if(position.rowIndex > 0)
{
position.rowIndex--;
}
}
// 1 row removed, 0 columns
- RemoveAndGetLostActors( lost, removed, 1u, 0u );
+ RemoveAndGetLostActors(lost, removed, 1u, 0u);
// Contract row data array
- mRowData.Erase( mRowData.Begin() + rowIndex );
+ mRowData.Erase(mRowData.Begin() + rowIndex);
// Sizes may have changed, so relayout
mRowDirty = true;
RelayoutRequest();
}
-void TableView::InsertColumn( unsigned int columnIndex )
+void TableView::InsertColumn(unsigned int columnIndex)
{
- RelayoutingLock lock( *this );
+ RelayoutingLock lock(*this);
// Insert the new column
- mCellData.InsertColumn( columnIndex );
+ mCellData.InsertColumn(columnIndex);
// Need to update the cell infos for the items that moved
- const unsigned int rowCount = mCellData.GetRows();
+ const unsigned int rowCount = mCellData.GetRows();
const unsigned int columnCount = mCellData.GetColumns();
- for( unsigned int row = 0; row < rowCount; ++row )
+ for(unsigned int row = 0; row < rowCount; ++row)
{
- for( unsigned int column = 0; column < columnCount; ++column )
+ for(unsigned int column = 0; column < columnCount; ++column)
{
- Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position;
+ Toolkit::TableView::CellPosition& position = mCellData[row][column].position;
// If cell is spanning and left side and spans to inserted column
- if( ( position.columnSpan > 1 ) && ( position.columnIndex <= columnIndex ) &&
- ( position.columnIndex + position.columnSpan > columnIndex ) )
+ if((position.columnSpan > 1) && (position.columnIndex <= columnIndex) &&
+ (position.columnIndex + position.columnSpan > columnIndex))
{
// Increment span
position.columnSpan++;
// Copy cell to occupy the new column
- mCellData[ row ][ columnIndex ] = mCellData[ row ][ column ];
+ mCellData[row][columnIndex] = mCellData[row][column];
}
- else if( column > columnIndex ) // If on the right side of inserted column, increase column index
+ else if(column > columnIndex) // If on the right side of inserted column, increase column index
{
// Increment index
position.columnIndex++;
}
// Expand column data array
- mColumnData.Insert( mColumnData.Begin() + columnIndex, RowColumnData() );
+ mColumnData.Insert(mColumnData.Begin() + columnIndex, RowColumnData());
// Sizes may have changed so relayout
mColumnDirty = true;
RelayoutRequest();
}
-void TableView::DeleteColumn( unsigned int columnIndex )
+void TableView::DeleteColumn(unsigned int columnIndex)
{
- std::vector< Actor > ignored;
- DeleteColumn( columnIndex, ignored );
+ std::vector<Actor> ignored;
+ DeleteColumn(columnIndex, ignored);
}
-void TableView::DeleteColumn( unsigned int columnIndex, std::vector<Actor>& removed )
+void TableView::DeleteColumn(unsigned int columnIndex, std::vector<Actor>& removed)
{
- RelayoutingLock lock( *this );
+ RelayoutingLock lock(*this);
// Remove the column
- std::vector< CellData > lost;
- mCellData.DeleteColumn( columnIndex, lost );
+ std::vector<CellData> lost;
+ mCellData.DeleteColumn(columnIndex, lost);
// Need to update the cell infos for the items that moved
- const unsigned int rowCount = mCellData.GetRows();
+ const unsigned int rowCount = mCellData.GetRows();
const unsigned int columnCount = mCellData.GetColumns();
- for( unsigned int row = 0; row < rowCount; ++row )
+ for(unsigned int row = 0; row < rowCount; ++row)
{
- for( unsigned int column = 0; column < columnCount; ++column )
+ for(unsigned int column = 0; column < columnCount; ++column)
{
- Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position;
+ Toolkit::TableView::CellPosition& position = mCellData[row][column].position;
// If cell is spanning and left side and spans to inserted column
- if( ( position.columnSpan > 1 ) && ( position.columnIndex <= columnIndex ) &&
- ( position.columnIndex + position.columnSpan > columnIndex ) )
+ if((position.columnSpan > 1) && (position.columnIndex <= columnIndex) &&
+ (position.columnIndex + position.columnSpan > columnIndex))
{
// Decrement span
- if( position.columnSpan > 1 )
+ if(position.columnSpan > 1)
{
position.columnSpan--;
}
}
- else if( column >= columnIndex ) // If on the right side of or at the inserted column, decrease column index
+ else if(column >= columnIndex) // If on the right side of or at the inserted column, decrease column index
{
// Decrement index
- if( position.columnIndex > 0 )
+ if(position.columnIndex > 0)
{
position.columnIndex--;
}
}
// 0 rows, 1 column removed
- RemoveAndGetLostActors( lost, removed, 0u, 1u );
+ RemoveAndGetLostActors(lost, removed, 0u, 1u);
// Contract column data array
- mColumnData.Erase( mColumnData.Begin() + columnIndex );
+ mColumnData.Erase(mColumnData.Begin() + columnIndex);
// Size may have changed so relayout
mColumnDirty = true;
RelayoutRequest();
}
-void TableView::Resize( unsigned int rows, unsigned int columns )
+void TableView::Resize(unsigned int rows, unsigned int columns)
{
- std::vector< Actor > ignored;
- Resize( rows, columns, ignored );
+ std::vector<Actor> ignored;
+ Resize(rows, columns, ignored);
}
-void TableView::Resize( unsigned int rows, unsigned int columns, std::vector<Actor>& removed )
+void TableView::Resize(unsigned int rows, unsigned int columns, std::vector<Actor>& removed)
{
- RelayoutingLock lock( *this );
+ RelayoutingLock lock(*this);
- unsigned int oldRows = GetRows();
+ unsigned int oldRows = GetRows();
unsigned int oldColumns = GetColumns();
// Resize data array
- std::vector< CellData > lost;
- ResizeContainers( rows, columns, lost );
+ std::vector<CellData> lost;
+ ResizeContainers(rows, columns, lost);
// Calculate if we lost rows
unsigned int rowsRemoved = 0;
- unsigned int newRows = GetRows();
+ unsigned int newRows = GetRows();
- if( oldRows < newRows )
+ if(oldRows < newRows)
{
rowsRemoved = newRows - oldRows;
}
// Calculate if we lost columns
unsigned int columnsRemoved = 0;
- unsigned int newColumns = GetColumns();
- if( oldColumns < newColumns )
+ unsigned int newColumns = GetColumns();
+ if(oldColumns < newColumns)
{
rowsRemoved = newColumns - oldColumns;
}
- RemoveAndGetLostActors( lost, removed, rowsRemoved, columnsRemoved );
+ RemoveAndGetLostActors(lost, removed, rowsRemoved, columnsRemoved);
// Sizes may have changed so request a relayout
- mRowDirty = true;
+ mRowDirty = true;
mColumnDirty = true;
RelayoutRequest();
}
-void TableView::SetCellPadding( Size padding )
+void TableView::SetCellPadding(Size padding)
{
// If padding really changed
- if( padding != mPadding )
+ if(padding != mPadding)
{
mPadding = padding;
return mPadding;
}
-void TableView::SetFitHeight( unsigned int rowIndex )
+void TableView::SetFitHeight(unsigned int rowIndex)
{
- DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() );
+ DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size());
- if( mRowData[ rowIndex ].sizePolicy != Toolkit::TableView::FIT )
+ if(mRowData[rowIndex].sizePolicy != Toolkit::TableView::FIT)
{
- mRowData[ rowIndex ].sizePolicy = Toolkit::TableView::FIT;
+ mRowData[rowIndex].sizePolicy = Toolkit::TableView::FIT;
mRowDirty = true;
RelayoutRequest();
}
}
-bool TableView::IsFitHeight( unsigned int rowIndex ) const
+bool TableView::IsFitHeight(unsigned int rowIndex) const
{
- DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() );
+ DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size());
- return mRowData[ rowIndex ].sizePolicy == Toolkit::TableView::FIT;
+ return mRowData[rowIndex].sizePolicy == Toolkit::TableView::FIT;
}
-void TableView::SetFitWidth( unsigned int columnIndex )
+void TableView::SetFitWidth(unsigned int columnIndex)
{
- DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() );
+ DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size());
- if( mColumnData[ columnIndex ].sizePolicy != Toolkit::TableView::FIT )
+ if(mColumnData[columnIndex].sizePolicy != Toolkit::TableView::FIT)
{
- mColumnData[ columnIndex ].sizePolicy = Toolkit::TableView::FIT;
+ mColumnData[columnIndex].sizePolicy = Toolkit::TableView::FIT;
mColumnDirty = true;
RelayoutRequest();
}
}
-bool TableView::IsFitWidth( unsigned int columnIndex ) const
+bool TableView::IsFitWidth(unsigned int columnIndex) const
{
- DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() );
+ DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size());
- return mColumnData[ columnIndex ].sizePolicy == Toolkit::TableView::FIT;
+ return mColumnData[columnIndex].sizePolicy == Toolkit::TableView::FIT;
}
-void TableView::SetFixedHeight( unsigned int rowIndex, float height )
+void TableView::SetFixedHeight(unsigned int rowIndex, float height)
{
- DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() );
+ DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size());
- RowColumnData& data = mRowData[ rowIndex ];
- data.size = height;
- data.sizePolicy = Toolkit::TableView::FIXED;
+ RowColumnData& data = mRowData[rowIndex];
+ data.size = height;
+ data.sizePolicy = Toolkit::TableView::FIXED;
mRowDirty = true;
RelayoutRequest();
}
-float TableView::GetFixedHeight( unsigned int rowIndex ) const
+float TableView::GetFixedHeight(unsigned int rowIndex) const
{
- DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() );
+ DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size());
- return mRowData[ rowIndex ].size;
+ return mRowData[rowIndex].size;
}
-void TableView::SetFixedWidth( unsigned int columnIndex, float width )
+void TableView::SetFixedWidth(unsigned int columnIndex, float width)
{
- DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() );
+ DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size());
- RowColumnData& data = mColumnData[ columnIndex ];
- data.size = width;
- data.sizePolicy = Toolkit::TableView::FIXED;
+ RowColumnData& data = mColumnData[columnIndex];
+ data.size = width;
+ data.sizePolicy = Toolkit::TableView::FIXED;
mColumnDirty = true;
RelayoutRequest();
}
-float TableView::GetFixedWidth( unsigned int columnIndex ) const
+float TableView::GetFixedWidth(unsigned int columnIndex) const
{
- DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() );
+ DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size());
- return mColumnData[ columnIndex ].size;
+ return mColumnData[columnIndex].size;
}
-void TableView::SetRelativeHeight( unsigned int rowIndex, float heightPercentage )
+void TableView::SetRelativeHeight(unsigned int rowIndex, float heightPercentage)
{
- DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() );
+ DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size());
- RowColumnData& data = mRowData[ rowIndex ];
- data.fillRatio = heightPercentage;
- data.sizePolicy = Toolkit::TableView::RELATIVE;
+ RowColumnData& data = mRowData[rowIndex];
+ data.fillRatio = heightPercentage;
+ data.sizePolicy = Toolkit::TableView::RELATIVE;
mRowDirty = true;
RelayoutRequest();
}
-float TableView::GetRelativeHeight( unsigned int rowIndex ) const
+float TableView::GetRelativeHeight(unsigned int rowIndex) const
{
- DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() );
+ DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size());
- return mRowData[ rowIndex ].fillRatio;
+ return mRowData[rowIndex].fillRatio;
}
-void TableView::SetRelativeWidth( unsigned int columnIndex, float widthPercentage )
+void TableView::SetRelativeWidth(unsigned int columnIndex, float widthPercentage)
{
- DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() );
+ DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size());
- RowColumnData& data = mColumnData[ columnIndex ];
- data.fillRatio = widthPercentage;
- data.sizePolicy = Toolkit::TableView::RELATIVE;
+ RowColumnData& data = mColumnData[columnIndex];
+ data.fillRatio = widthPercentage;
+ data.sizePolicy = Toolkit::TableView::RELATIVE;
mColumnDirty = true;
RelayoutRequest();
}
-float TableView::GetRelativeWidth( unsigned int columnIndex ) const
+float TableView::GetRelativeWidth(unsigned int columnIndex) const
{
- DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() );
+ DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size());
- return mColumnData[ columnIndex ].fillRatio;
+ return mColumnData[columnIndex].fillRatio;
}
-void TableView::OnCalculateRelayoutSize( Dimension::Type dimension )
+void TableView::OnCalculateRelayoutSize(Dimension::Type dimension)
{
- if( (dimension & Dimension::WIDTH) && mColumnDirty )
+ if((dimension & Dimension::WIDTH) && mColumnDirty)
{
/*
* FIXED and FIT have size in pixel
*
* Need to update the size for FIT column here
*/
- CalculateFitSizes( mColumnData, Dimension::WIDTH );
+ CalculateFitSizes(mColumnData, Dimension::WIDTH);
/* RELATIVE and FILL have size in ratio
* Their size in pixel is not available until we get the negotiated size for the whole table
*
* Need to update the ratio for FILL column here
*/
- CalculateFillSizes( mColumnData );
+ CalculateFillSizes(mColumnData);
- mFixedTotals.width = CalculateTotalFixedSize( mColumnData );
+ mFixedTotals.width = CalculateTotalFixedSize(mColumnData);
}
- if( (dimension & Dimension::HEIGHT) && mRowDirty )
+ if((dimension & Dimension::HEIGHT) && mRowDirty)
{
// refer to the comment above
- CalculateFitSizes( mRowData, Dimension::HEIGHT );
+ CalculateFitSizes(mRowData, Dimension::HEIGHT);
// refer to the comment above
- CalculateFillSizes( mRowData );
+ CalculateFillSizes(mRowData);
- mFixedTotals.height = CalculateTotalFixedSize( mRowData );
+ mFixedTotals.height = CalculateTotalFixedSize(mRowData);
}
}
-void TableView::OnLayoutNegotiated( float size, Dimension::Type dimension )
+void TableView::OnLayoutNegotiated(float size, Dimension::Type dimension)
{
// Update the column sizes
- if( (dimension & Dimension::WIDTH) && mColumnDirty )
+ if((dimension & Dimension::WIDTH) && mColumnDirty)
{
float remainingSize = size - mFixedTotals.width;
- if( remainingSize < 0.0f )
+ if(remainingSize < 0.0f)
{
remainingSize = 0.0f;
}
// update every column position in ColumnData array
float cumulatedWidth = 0.0f;
- for( auto&& element : mColumnData )
+ for(auto&& element : mColumnData)
{
- if( element.sizePolicy == Toolkit::TableView::FILL || element.sizePolicy == Toolkit::TableView::RELATIVE )
+ if(element.sizePolicy == Toolkit::TableView::FILL || element.sizePolicy == Toolkit::TableView::RELATIVE)
{
element.size = element.fillRatio * remainingSize;
}
}
// Update the row sizes
- if( (dimension & Dimension::HEIGHT) && mRowDirty )
+ if((dimension & Dimension::HEIGHT) && mRowDirty)
{
float remainingSize = size - mFixedTotals.height;
- if( remainingSize < 0.0f )
+ if(remainingSize < 0.0f)
{
remainingSize = 0.0f;
}
// update every row position in RowData array
float cumulatedHeight = 0.0f;
- for( unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row )
+ for(unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row)
{
- if( mRowData[ row ].sizePolicy == Toolkit::TableView::FILL || mRowData[ row ].sizePolicy == Toolkit::TableView::RELATIVE)
+ if(mRowData[row].sizePolicy == Toolkit::TableView::FILL || mRowData[row].sizePolicy == Toolkit::TableView::RELATIVE)
{
- mRowData[ row ].size = mRowData[ row ].fillRatio * remainingSize;
+ mRowData[row].size = mRowData[row].fillRatio * remainingSize;
}
- cumulatedHeight += mRowData[ row ].size;
+ cumulatedHeight += mRowData[row].size;
mRowData[row].position = cumulatedHeight;
}
}
}
-void TableView::OnSizeSet( const Vector3& size )
+void TableView::OnSizeSet(const Vector3& size)
{
// If this table view is size negotiated by another actor or control, then the
// rows and columns must be recalculated or the new size will not take effect.
mRowDirty = mColumnDirty = true;
RelayoutRequest();
- Control::OnSizeSet( size );
+ Control::OnSizeSet(size);
}
-void TableView::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void TableView::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
// Go through the layout data
float totalWidth = 0.0;
- Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>( Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>() );
+ Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
- if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
+ if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
{
- for (auto&& element : mColumnData)
+ for(auto&& element : mColumnData)
{
totalWidth += element.size;
}
}
- for( unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row )
+ for(unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row)
{
- for( unsigned int column = 0, columnCount = mCellData.GetColumns(); column < columnCount; ++column )
+ for(unsigned int column = 0, columnCount = mCellData.GetColumns(); column < columnCount; ++column)
{
- CellData& cellData= mCellData[ row ][ column ];
- Actor& actor = cellData.actor;
+ CellData& cellData = mCellData[row][column];
+ Actor& actor = cellData.actor;
const Toolkit::TableView::CellPosition position = cellData.position;
// If there is an actor and this is the main cell of the actor.
// An actor can be in multiple cells if its row or column span is more than 1.
// We however must lay out each actor only once.
- if( actor && position.rowIndex == row && position.columnIndex == column )
+ if(actor && position.rowIndex == row && position.columnIndex == column)
{
// Anchor actor to top left of the cell
- if( actor.GetProperty( Actor::Property::POSITION_USES_ANCHOR_POINT ).Get< bool >() )
+ if(actor.GetProperty(Actor::Property::POSITION_USES_ANCHOR_POINT).Get<bool>())
{
- actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
+ actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
}
- actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
+ actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
- Padding padding = actor.GetProperty<Vector4>( Actor::Property::PADDING );
+ Padding padding = actor.GetProperty<Vector4>(Actor::Property::PADDING);
float left = (column > 0) ? mColumnData[column - 1].position : 0.f;
float right;
- if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
+ if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
{
right = totalWidth - left;
- left = right - mColumnData[column].size;
+ left = right - mColumnData[column].size;
}
else
{
right = left + mColumnData[column].size;
}
- float top = row > 0 ? mRowData[row-1].position : 0.f;
- float bottom = mRowData[row+position.rowSpan-1].position;
+ float top = row > 0 ? mRowData[row - 1].position : 0.f;
+ float bottom = mRowData[row + position.rowSpan - 1].position;
- if( cellData.horizontalAlignment == HorizontalAlignment::LEFT )
+ if(cellData.horizontalAlignment == HorizontalAlignment::LEFT)
{
- actor.SetProperty( Actor::Property::POSITION_X, left + mPadding.width + padding.left );
+ actor.SetProperty(Actor::Property::POSITION_X, left + mPadding.width + padding.left);
}
- else if( cellData.horizontalAlignment == HorizontalAlignment::RIGHT )
+ else if(cellData.horizontalAlignment == HorizontalAlignment::RIGHT)
{
- actor.SetProperty( Actor::Property::POSITION_X, right - mPadding.width - padding.right - actor.GetRelayoutSize( Dimension::WIDTH ) );
+ actor.SetProperty(Actor::Property::POSITION_X, right - mPadding.width - padding.right - actor.GetRelayoutSize(Dimension::WIDTH));
}
else //if( cellData.horizontalAlignment == HorizontalAlignment::CENTER )
{
- actor.SetProperty( Actor::Property::POSITION_X, (left + right + padding.left - padding.right - actor.GetRelayoutSize( Dimension::WIDTH )) * 0.5f );
+ actor.SetProperty(Actor::Property::POSITION_X, (left + right + padding.left - padding.right - actor.GetRelayoutSize(Dimension::WIDTH)) * 0.5f);
}
- if( cellData.verticalAlignment == VerticalAlignment::TOP )
+ if(cellData.verticalAlignment == VerticalAlignment::TOP)
{
- actor.SetProperty( Actor::Property::POSITION_Y, top + mPadding.height + padding.top );
+ actor.SetProperty(Actor::Property::POSITION_Y, top + mPadding.height + padding.top);
}
- else if( cellData.verticalAlignment == VerticalAlignment::BOTTOM )
+ else if(cellData.verticalAlignment == VerticalAlignment::BOTTOM)
{
- actor.SetProperty( Actor::Property::POSITION_Y, bottom - mPadding.height - padding.bottom - actor.GetRelayoutSize( Dimension::HEIGHT ) );
+ actor.SetProperty(Actor::Property::POSITION_Y, bottom - mPadding.height - padding.bottom - actor.GetRelayoutSize(Dimension::HEIGHT));
}
else //if( cellData.verticalAlignment = VerticalAlignment::CENTER )
{
- actor.SetProperty( Actor::Property::POSITION_Y, (top + bottom + padding.top - padding.bottom - actor.GetRelayoutSize( Dimension::HEIGHT )) * 0.5f );
+ actor.SetProperty(Actor::Property::POSITION_Y, (top + bottom + padding.top - padding.bottom - actor.GetRelayoutSize(Dimension::HEIGHT)) * 0.5f);
}
}
}
return mCellData.GetColumns();
}
-void TableView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void TableView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::TableView tableView = Toolkit::TableView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TableView tableView = Toolkit::TableView::DownCast(Dali::BaseHandle(object));
- if( tableView )
+ if(tableView)
{
- TableView& tableViewImpl( GetImpl( tableView ) );
- switch( index )
+ TableView& tableViewImpl(GetImpl(tableView));
+ switch(index)
{
case Toolkit::TableView::Property::ROWS:
{
int rows = 0;
- if( value.Get( rows ) && rows >= 0 )
+ if(value.Get(rows) && rows >= 0)
{
- if( static_cast<unsigned int>(rows) != tableViewImpl.GetRows() )
+ if(static_cast<unsigned int>(rows) != tableViewImpl.GetRows())
{
- tableViewImpl.Resize( rows, tableViewImpl.GetColumns() );
+ tableViewImpl.Resize(rows, tableViewImpl.GetColumns());
}
}
break;
case Toolkit::TableView::Property::COLUMNS:
{
int columns = 0;
- if( value.Get( columns ) && columns >= 0 )
+ if(value.Get(columns) && columns >= 0)
{
- if( static_cast<unsigned int>( columns ) != tableViewImpl.GetColumns() )
+ if(static_cast<unsigned int>(columns) != tableViewImpl.GetColumns())
{
- tableViewImpl.Resize( tableViewImpl.GetRows(), value.Get<int>() );
+ tableViewImpl.Resize(tableViewImpl.GetRows(), value.Get<int>());
}
}
break;
}
case Toolkit::TableView::Property::CELL_PADDING:
{
- tableViewImpl.SetCellPadding( value.Get<Vector2>() );
+ tableViewImpl.SetCellPadding(value.Get<Vector2>());
break;
}
case Toolkit::TableView::Property::LAYOUT_ROWS:
{
- SetHeightOrWidthProperty( tableViewImpl, &TableView::SetFixedHeight, &TableView::SetRelativeHeight, &TableView::SetFitHeight, value );
+ SetHeightOrWidthProperty(tableViewImpl, &TableView::SetFixedHeight, &TableView::SetRelativeHeight, &TableView::SetFitHeight, value);
break;
}
case Toolkit::TableView::Property::LAYOUT_COLUMNS:
{
- SetHeightOrWidthProperty( tableViewImpl, &TableView::SetFixedWidth, &TableView::SetRelativeWidth, &TableView::SetFitWidth, value );
+ SetHeightOrWidthProperty(tableViewImpl, &TableView::SetFixedWidth, &TableView::SetRelativeWidth, &TableView::SetFitWidth, value);
break;
}
}
}
}
-Property::Value TableView::GetProperty( BaseObject* object, Property::Index index )
+Property::Value TableView::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::TableView tableView = Toolkit::TableView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TableView tableView = Toolkit::TableView::DownCast(Dali::BaseHandle(object));
- if( tableView )
+ if(tableView)
{
- TableView& tableViewImpl( GetImpl( tableView ) );
- switch( index )
+ TableView& tableViewImpl(GetImpl(tableView));
+ switch(index)
{
case Toolkit::TableView::Property::ROWS:
{
- value = static_cast<int>( tableViewImpl.GetRows() );
+ value = static_cast<int>(tableViewImpl.GetRows());
break;
}
case Toolkit::TableView::Property::COLUMNS:
{
- value = static_cast<int>( tableViewImpl.GetColumns() );
+ value = static_cast<int>(tableViewImpl.GetColumns());
break;
}
case Toolkit::TableView::Property::CELL_PADDING:
return value;
}
-void TableView::OnChildAdd( Actor& child )
+void TableView::OnChildAdd(Actor& child)
{
- if( ! mLayoutingChild )
+ if(!mLayoutingChild)
{
// Ensure we're not in the middle of laying out children
// Check child properties on actor to decide its position inside the table
HorizontalAlignment::Type horizontalAlignment = HorizontalAlignment::LEFT;
- VerticalAlignment::Type verticalAlignment = VerticalAlignment::TOP;
+ VerticalAlignment::Type verticalAlignment = VerticalAlignment::TOP;
- if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT ) != Property::NONE )
+ if(child.GetPropertyType(Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT) != Property::NONE)
{
- std::string value = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT ).Get<std::string >();
- Scripting::GetEnumeration< HorizontalAlignment::Type >( value.c_str(),
- HORIZONTAL_ALIGNMENT_STRING_TABLE,
- HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT,
- horizontalAlignment );
+ std::string value = child.GetProperty(Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT).Get<std::string>();
+ Scripting::GetEnumeration<HorizontalAlignment::Type>(value.c_str(),
+ HORIZONTAL_ALIGNMENT_STRING_TABLE,
+ HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT,
+ horizontalAlignment);
}
- if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT ) != Property::NONE )
+ if(child.GetPropertyType(Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT) != Property::NONE)
{
- std::string value = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT ).Get<std::string >();
- Scripting::GetEnumeration< VerticalAlignment::Type >( value.c_str(),
- VERTICAL_ALIGNMENT_STRING_TABLE,
- VERTICAL_ALIGNMENT_STRING_TABLE_COUNT,
- verticalAlignment );
+ std::string value = child.GetProperty(Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT).Get<std::string>();
+ Scripting::GetEnumeration<VerticalAlignment::Type>(value.c_str(),
+ VERTICAL_ALIGNMENT_STRING_TABLE,
+ VERTICAL_ALIGNMENT_STRING_TABLE_COUNT,
+ verticalAlignment);
}
Toolkit::TableView::CellPosition cellPosition;
- if( child.GetPropertyType( Toolkit::TableView::ChildProperty::ROW_SPAN ) != Property::NONE )
+ if(child.GetPropertyType(Toolkit::TableView::ChildProperty::ROW_SPAN) != Property::NONE)
{
- cellPosition.rowSpan = child.GetProperty( Toolkit::TableView::ChildProperty::ROW_SPAN ).Get< int >();
+ cellPosition.rowSpan = child.GetProperty(Toolkit::TableView::ChildProperty::ROW_SPAN).Get<int>();
}
- if( child.GetPropertyType( Toolkit::TableView::ChildProperty::COLUMN_SPAN ) != Property::NONE )
+ if(child.GetPropertyType(Toolkit::TableView::ChildProperty::COLUMN_SPAN) != Property::NONE)
{
- cellPosition.columnSpan = child.GetProperty( Toolkit::TableView::ChildProperty::COLUMN_SPAN ).Get< int >();
+ cellPosition.columnSpan = child.GetProperty(Toolkit::TableView::ChildProperty::COLUMN_SPAN).Get<int>();
}
- if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_INDEX ) != Property::NONE )
+ if(child.GetPropertyType(Toolkit::TableView::ChildProperty::CELL_INDEX) != Property::NONE)
{
- Vector2 indices = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_INDEX ).Get<Vector2 >();
- cellPosition.rowIndex = static_cast<unsigned int>( indices.x );
- cellPosition.columnIndex = static_cast<unsigned int>( indices.y );
+ Vector2 indices = child.GetProperty(Toolkit::TableView::ChildProperty::CELL_INDEX).Get<Vector2>();
+ cellPosition.rowIndex = static_cast<unsigned int>(indices.x);
+ cellPosition.columnIndex = static_cast<unsigned int>(indices.y);
- AddChild( child, cellPosition );
+ AddChild(child, cellPosition);
SetCellAlignment(cellPosition, horizontalAlignment, verticalAlignment);
}
else
bool availableCellFound = false;
// Find the first available cell to store the actor in
- const unsigned int rowCount = mCellData.GetRows();
+ const unsigned int rowCount = mCellData.GetRows();
const unsigned int columnCount = mCellData.GetColumns();
- for( unsigned int row = 0; row < rowCount && !availableCellFound; ++row )
+ for(unsigned int row = 0; row < rowCount && !availableCellFound; ++row)
{
- for( unsigned int column = 0; column < columnCount && !availableCellFound; ++column )
+ for(unsigned int column = 0; column < columnCount && !availableCellFound; ++column)
{
- if( !(mCellData[ row ][ column ].actor) )
+ if(!(mCellData[row][column].actor))
{
// Put the actor in the cell
CellData data;
- data.actor = child;
+ data.actor = child;
data.position.columnIndex = column;
- data.position.rowIndex = row;
- data.horizontalAlignment = horizontalAlignment;
- data.verticalAlignment = verticalAlignment;
- mCellData[ row ][ column ] = data;
+ data.position.rowIndex = row;
+ data.horizontalAlignment = horizontalAlignment;
+ data.verticalAlignment = verticalAlignment;
+ mCellData[row][column] = data;
availableCellFound = true;
break;
}
}
- if( ! availableCellFound )
+ if(!availableCellFound)
{
// No empty cells, so increase size of the table
- unsigned int newColumnCount = ( columnCount > 0 ) ? columnCount : 1;
- ResizeContainers( rowCount + 1, newColumnCount );
+ unsigned int newColumnCount = (columnCount > 0) ? columnCount : 1;
+ ResizeContainers(rowCount + 1, newColumnCount);
// Put the actor in the first cell of the new row
CellData data;
- data.actor = child;
- data.position.rowIndex = rowCount;
+ data.actor = child;
+ data.position.rowIndex = rowCount;
data.position.columnIndex = 0;
- data.horizontalAlignment = horizontalAlignment;
- data.verticalAlignment = verticalAlignment;
- mCellData[ rowCount ][ 0 ] = data;
+ data.horizontalAlignment = horizontalAlignment;
+ data.verticalAlignment = verticalAlignment;
+ mCellData[rowCount][0] = data;
}
RelayoutRequest();
}
}
- Control::OnChildAdd( child );
+ Control::OnChildAdd(child);
}
-void TableView::OnChildRemove( Actor& child )
+void TableView::OnChildRemove(Actor& child)
{
// dont process if we're in the middle of bigger operation like delete row, column or resize
- if( !mLayoutingChild )
+ if(!mLayoutingChild)
{
// relayout the table only if instances were found
- if( RemoveAllInstances( child ) )
+ if(RemoveAllInstances(child))
{
RelayoutRequest();
}
}
- Control::OnChildRemove( child );
+ Control::OnChildRemove(child);
}
-TableView::TableView( unsigned int initialRows, unsigned int initialColumns )
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mCellData( initialRows, initialColumns ),
+TableView::TableView(unsigned int initialRows, unsigned int initialColumns)
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mCellData(initialRows, initialColumns),
mPreviousFocusedActor(),
- mLayoutingChild( false ),
- mRowDirty( true ), // Force recalculation first time
- mColumnDirty( true )
+ mLayoutingChild(false),
+ mRowDirty(true), // Force recalculation first time
+ mColumnDirty(true)
{
- SetKeyboardNavigationSupport( true );
- ResizeContainers( initialRows, initialColumns );
+ SetKeyboardNavigationSupport(true);
+ ResizeContainers(initialRows, initialColumns);
}
void TableView::OnInitialize()
{
// Make self as keyboard focusable and focus group
Actor self = Self();
- self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE,true);
+ self.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true);
SetAsKeyboardFocusGroup(true);
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::TABLE ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::TABLE));
+ });
}
-void TableView::ResizeContainers( unsigned int rows, unsigned int columns )
+void TableView::ResizeContainers(unsigned int rows, unsigned int columns)
{
std::vector<CellData> ignored;
- ResizeContainers( rows, columns, ignored );
+ ResizeContainers(rows, columns, ignored);
}
-void TableView::ResizeContainers( unsigned int rows, unsigned int columns, std::vector<CellData>& removed )
+void TableView::ResizeContainers(unsigned int rows, unsigned int columns, std::vector<CellData>& removed)
{
// Resize cell data
- mCellData.Resize( rows, columns, removed );
+ mCellData.Resize(rows, columns, removed);
// We don't care if these go smaller, data will be regenerated or is not needed anymore
- mRowData.Resize( rows );
- mColumnData.Resize( columns );
+ mRowData.Resize(rows);
+ mColumnData.Resize(columns);
}
-void TableView::RemoveAndGetLostActors( const std::vector<CellData>& lost, std::vector<Actor>& removed,
- unsigned int rowsRemoved, unsigned int columnsRemoved )
+void TableView::RemoveAndGetLostActors(const std::vector<CellData>& lost, std::vector<Actor>& removed, unsigned int rowsRemoved, unsigned int columnsRemoved)
{
// iterate through all lost cells
- std::vector< CellData >::const_iterator iter = lost.begin();
- for( ; iter != lost.end(); ++iter )
+ std::vector<CellData>::const_iterator iter = lost.begin();
+ for(; iter != lost.end(); ++iter)
{
// if it is a valid actor
- if( (*iter).actor )
+ if((*iter).actor)
{
// is this actor still somewhere else in the table
Toolkit::TableView::CellPosition position;
- if( FindChildPosition( (*iter).actor, position ) )
+ if(FindChildPosition((*iter).actor, position))
{
// it must be spanning multiple cells, position contains the top left most one
// check if position is left of the removed location
- if( position.columnIndex < (*iter).position.columnIndex )
+ if(position.columnIndex < (*iter).position.columnIndex)
{
// if column span is greater than 1
- if( mCellData[ position.rowIndex ][ position.columnIndex ].position.columnSpan > 1 )
+ if(mCellData[position.rowIndex][position.columnIndex].position.columnSpan > 1)
{
// decrease column span
- mCellData[ position.rowIndex ][ position.columnIndex ].position.columnSpan -= columnsRemoved;
+ mCellData[position.rowIndex][position.columnIndex].position.columnSpan -= columnsRemoved;
}
}
// check if position is left of the removed location
- if( position.rowIndex < (*iter).position.rowIndex )
+ if(position.rowIndex < (*iter).position.rowIndex)
{
// if row span is greater than 1
- if( mCellData[ position.rowIndex ][ position.columnIndex ].position.rowSpan > 1 )
+ if(mCellData[position.rowIndex][position.columnIndex].position.rowSpan > 1)
{
// decrease row span
- mCellData[ position.rowIndex ][ position.columnIndex ].position.rowSpan -= rowsRemoved;
+ mCellData[position.rowIndex][position.columnIndex].position.rowSpan -= rowsRemoved;
}
}
}
{
// this actor is gone for good
// add actor to removed container
- removed.push_back( (*iter).actor );
+ removed.push_back((*iter).actor);
// we dont want the child actor anymore
- Self().Remove( (*iter).actor );
+ Self().Remove((*iter).actor);
}
}
}
}
-bool TableView::RemoveAllInstances( const Actor& child )
+bool TableView::RemoveAllInstances(const Actor& child)
{
bool found = false;
// walk through the layout data
- const unsigned int rowCount = mCellData.GetRows();
+ const unsigned int rowCount = mCellData.GetRows();
const unsigned int columnCount = mCellData.GetColumns();
- for( unsigned int row = 0; row < rowCount; ++row )
+ for(unsigned int row = 0; row < rowCount; ++row)
{
- for( unsigned int column = 0; column < columnCount; ++column )
+ for(unsigned int column = 0; column < columnCount; ++column)
{
- if( mCellData[ row ][ column ].actor == child )
+ if(mCellData[row][column].actor == child)
{
// clear the cell, NOTE that the cell might be spanning multiple cells
- mCellData[ row ][ column ] = CellData();
- found = true;
+ mCellData[row][column] = CellData();
+ found = true;
}
}
}
}
void TableView::SetHeightOrWidthProperty(TableView& tableViewImpl,
- void(TableView::*funcFixed)(unsigned int, float),
- void(TableView::*funcRelative)(unsigned int, float),
- void(TableView::*funcFit)(unsigned int),
- const Property::Value& value )
+ void (TableView::*funcFixed)(unsigned int, float),
+ void (TableView::*funcRelative)(unsigned int, float),
+ void (TableView::*funcFit)(unsigned int),
+ const Property::Value& value)
{
const Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
unsigned int index(0);
- for ( unsigned int i = 0, count = map->Count(); i < count; ++i )
+ for(unsigned int i = 0, count = map->Count(); i < count; ++i)
{
- Property::Value& item = map->GetValue(i);
- Property::Map* childMap = item.GetMap();
+ Property::Value& item = map->GetValue(i);
+ Property::Map* childMap = item.GetMap();
- std::istringstream( map->GetKey(i) ) >> index;
- if( childMap )
+ std::istringstream(map->GetKey(i)) >> index;
+ if(childMap)
{
- Property::Value* policy = childMap->Find( "policy" );
- Property::Value* childMapValue = childMap->Find( "value" );
- if( policy && childMapValue )
+ Property::Value* policy = childMap->Find("policy");
+ Property::Value* childMapValue = childMap->Find("value");
+ if(policy && childMapValue)
{
std::string policyValue;
- policy->Get( policyValue );
+ policy->Get(policyValue);
Toolkit::TableView::LayoutPolicy policy;
- if( Scripting::GetEnumeration< Toolkit::TableView::LayoutPolicy >( policyValue.c_str(),
- LAYOUT_POLICY_STRING_TABLE,
- LAYOUT_POLICY_STRING_TABLE_COUNT,
- policy ) )
+ if(Scripting::GetEnumeration<Toolkit::TableView::LayoutPolicy>(policyValue.c_str(),
+ LAYOUT_POLICY_STRING_TABLE,
+ LAYOUT_POLICY_STRING_TABLE_COUNT,
+ policy))
{
- if( policy == Toolkit::TableView::FIXED )
+ if(policy == Toolkit::TableView::FIXED)
{
- (tableViewImpl.*funcFixed)( index, childMapValue->Get<float>() );
+ (tableViewImpl.*funcFixed)(index, childMapValue->Get<float>());
}
- else if( policy == Toolkit::TableView::RELATIVE )
+ else if(policy == Toolkit::TableView::RELATIVE)
{
- (tableViewImpl.*funcRelative)( index, childMapValue->Get<float>() );
+ (tableViewImpl.*funcRelative)(index, childMapValue->Get<float>());
}
- else if( policy == Toolkit::TableView::FIT )
+ else if(policy == Toolkit::TableView::FIT)
{
- (tableViewImpl.*funcFit)( index );
+ (tableViewImpl.*funcFit)(index);
}
// do nothing for FILL policy
}
Property::Value TableView::GetRowHeightsPropertyValue()
{
Property::Map map;
- GetMapPropertyValue( mRowData, map);
+ GetMapPropertyValue(mRowData, map);
return Property::Value(map);
}
Property::Value TableView::GetColumnWidthsPropertyValue()
{
Property::Map map;
- GetMapPropertyValue( mColumnData, map);
+ GetMapPropertyValue(mColumnData, map);
return Property::Value(map);
}
-void TableView::GetMapPropertyValue( const RowColumnArray& data, Property::Map& map )
+void TableView::GetMapPropertyValue(const RowColumnArray& data, Property::Map& map)
{
- const char* fixedPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FIXED,
+ const char* fixedPolicy = Scripting::GetEnumerationName<Toolkit::TableView::LayoutPolicy>(Toolkit::TableView::FIXED,
+ LAYOUT_POLICY_STRING_TABLE,
+ LAYOUT_POLICY_STRING_TABLE_COUNT);
+ const char* relativePolicy = Scripting::GetEnumerationName<Toolkit::TableView::LayoutPolicy>(Toolkit::TableView::RELATIVE,
LAYOUT_POLICY_STRING_TABLE,
- LAYOUT_POLICY_STRING_TABLE_COUNT );
- const char* relativePolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::RELATIVE,
- LAYOUT_POLICY_STRING_TABLE,
- LAYOUT_POLICY_STRING_TABLE_COUNT );
- const char* fillPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FILL,
- LAYOUT_POLICY_STRING_TABLE,
- LAYOUT_POLICY_STRING_TABLE_COUNT );
- const char* fitPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FIT,
- LAYOUT_POLICY_STRING_TABLE,
- LAYOUT_POLICY_STRING_TABLE_COUNT );
+ LAYOUT_POLICY_STRING_TABLE_COUNT);
+ const char* fillPolicy = Scripting::GetEnumerationName<Toolkit::TableView::LayoutPolicy>(Toolkit::TableView::FILL,
+ LAYOUT_POLICY_STRING_TABLE,
+ LAYOUT_POLICY_STRING_TABLE_COUNT);
+ const char* fitPolicy = Scripting::GetEnumerationName<Toolkit::TableView::LayoutPolicy>(Toolkit::TableView::FIT,
+ LAYOUT_POLICY_STRING_TABLE,
+ LAYOUT_POLICY_STRING_TABLE_COUNT);
const RowColumnArray::SizeType count = data.Size();
- for( RowColumnArray::SizeType i = 0; i < count; i++ )
+ for(RowColumnArray::SizeType i = 0; i < count; i++)
{
- const RowColumnData& dataInstance = data[ i ];
+ const RowColumnData& dataInstance = data[i];
Property::Map item;
- switch( dataInstance.sizePolicy )
+ switch(dataInstance.sizePolicy)
{
case Toolkit::TableView::FIXED:
{
- item[ "policy" ] = fixedPolicy;
- item[ "value" ] = dataInstance.size;
+ item["policy"] = fixedPolicy;
+ item["value"] = dataInstance.size;
break;
}
case Toolkit::TableView::RELATIVE:
{
- item[ "policy" ] = relativePolicy;
- item[ "value" ] = dataInstance.fillRatio;
+ item["policy"] = relativePolicy;
+ item["value"] = dataInstance.fillRatio;
break;
}
case Toolkit::TableView::FIT:
{
- item[ "policy" ] = fitPolicy;
- item[ "value" ] = 0.f;
+ item["policy"] = fitPolicy;
+ item["value"] = 0.f;
break;
}
case Toolkit::TableView::FILL:
default:
{
- item[ "policy" ] = fillPolicy;
- item[ "value" ] = 0.f;
+ item["policy"] = fillPolicy;
+ item["value"] = 0.f;
break;
}
}
std::ostringstream ss;
ss << i;
- map[ ss.str() ] = item;
+ map[ss.str()] = item;
}
}
{
Actor nextFocusableActor;
- if ( !currentFocusedActor )
+ if(!currentFocusedActor)
{
// Nothing is currently focused, so the child in the first cell should be focused.
nextFocusableActor = GetChildAt(Toolkit::TableView::CellPosition(0, 0));
else
{
Toolkit::TableView::CellPosition position;
- if( FindChildPosition( currentFocusedActor, position ) )
+ if(FindChildPosition(currentFocusedActor, position))
{
// The current focused actor is a child of TableView
- bool focusLost = false;
- int currentRow = position.rowIndex;
- int currentColumn = position.columnIndex;
- int numberOfColumns = GetColumns();
- int numberOfRows = GetRows();
+ bool focusLost = false;
+ int currentRow = position.rowIndex;
+ int currentColumn = position.columnIndex;
+ int numberOfColumns = GetColumns();
+ int numberOfRows = GetRows();
- bool lastCell = false;
+ bool lastCell = false;
Actor nextValidActor;
- switch ( direction )
+ switch(direction)
{
case Toolkit::Control::KeyboardFocus::LEFT:
{
currentColumn = numberOfColumns - 1;
if(--currentRow < 0)
{
- lastCell = true;
+ lastCell = true;
currentRow = loopEnabled ? numberOfRows - 1 : 0;
- focusLost = (currentRow == 0);
+ focusLost = (currentRow == 0);
}
}
nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn));
- } while ( !nextValidActor && !lastCell );
+ } while(!nextValidActor && !lastCell);
break;
}
case Toolkit::Control::KeyboardFocus::RIGHT:
currentColumn = 0;
if(++currentRow > numberOfRows - 1)
{
- lastCell = true;
+ lastCell = true;
currentRow = loopEnabled ? 0 : numberOfRows - 1;
- focusLost = (currentRow == numberOfRows - 1);
+ focusLost = (currentRow == numberOfRows - 1);
}
}
nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn));
- } while ( !nextValidActor && !lastCell );
+ } while(!nextValidActor && !lastCell);
break;
}
case Toolkit::Control::KeyboardFocus::UP:
{
if(--currentRow < 0)
{
- lastCell = true;
+ lastCell = true;
currentRow = loopEnabled ? numberOfRows - 1 : 0;
- focusLost = (currentRow == 0);
+ focusLost = (currentRow == 0);
}
nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn));
- } while ( !nextValidActor && !lastCell );
+ } while(!nextValidActor && !lastCell);
break;
}
case Toolkit::Control::KeyboardFocus::DOWN:
{
if(++currentRow > numberOfRows - 1)
{
- lastCell = true;
+ lastCell = true;
currentRow = loopEnabled ? 0 : numberOfRows - 1;
- focusLost = (currentRow == numberOfRows - 1);
+ focusLost = (currentRow == numberOfRows - 1);
}
nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn));
- } while ( !nextValidActor && !lastCell );
+ } while(!nextValidActor && !lastCell);
break;
}
default:
// The current focused actor is not within this TableView.
unsigned int numberOfColumns = GetColumns();
- unsigned int numberOfRows = GetRows();
+ unsigned int numberOfRows = GetRows();
// Check whether the previous focused actor is a focus group (i.e. a layout container)
- bool wasFocusedOnLayoutContainer = false;
- Actor previousFocusedActor = mPreviousFocusedActor.GetHandle();
- if( previousFocusedActor )
+ bool wasFocusedOnLayoutContainer = false;
+ Actor previousFocusedActor = mPreviousFocusedActor.GetHandle();
+ if(previousFocusedActor)
{
- Toolkit::Control control = Toolkit::Control::DownCast( previousFocusedActor );
- if( control )
+ Toolkit::Control control = Toolkit::Control::DownCast(previousFocusedActor);
+ if(control)
{
Internal::Control& controlImpl = static_cast<Internal::Control&>(control.GetImplementation());
- wasFocusedOnLayoutContainer = controlImpl.IsKeyboardFocusGroup();
+ wasFocusedOnLayoutContainer = controlImpl.IsKeyboardFocusGroup();
}
}
// Check whether the previous focused actor is a layout container and also a child of this TableView
Toolkit::TableView::CellPosition position;
- if( wasFocusedOnLayoutContainer && FindChildPosition( previousFocusedActor, position ) )
+ if(wasFocusedOnLayoutContainer && FindChildPosition(previousFocusedActor, position))
{
nextFocusableActor = GetNextKeyboardFocusableActor(previousFocusedActor, direction, loopEnabled);
}
Vector3 TableView::GetNaturalSize()
{
// Natural size is the size of all fixed cell widths or heights. This ignores cells with relative heights.
- return Vector3( mFixedTotals.width, mFixedTotals.height, 1.0f );
+ return Vector3(mFixedTotals.width, mFixedTotals.height, 1.0f);
}
-float TableView::CalculateChildSize( const Actor& child, Dimension::Type dimension )
+float TableView::CalculateChildSize(const Actor& child, Dimension::Type dimension)
{
Toolkit::TableView::CellPosition position;
- if( FindChildPosition( child, position) )
+ if(FindChildPosition(child, position))
{
- switch( dimension )
+ switch(dimension)
{
case Dimension::WIDTH:
{
float cellSize = 0.0f;
- cellSize = mColumnData[position.columnIndex+position.columnSpan-1].position
- - (position.columnIndex > 0 ? mColumnData[position.columnIndex-1].position : 0.f)
- - mPadding.width * 2.0f;
+ cellSize = mColumnData[position.columnIndex + position.columnSpan - 1].position - (position.columnIndex > 0 ? mColumnData[position.columnIndex - 1].position : 0.f) - mPadding.width * 2.0f;
- if( cellSize < 0.0f )
+ if(cellSize < 0.0f)
{
cellSize = 0.0f;
}
{
float cellSize = 0.0f;
- cellSize = mRowData[position.rowIndex+position.rowSpan-1].position
- - (position.rowIndex > 0 ? mRowData[position.rowIndex-1].position : 0.f)
- - mPadding.height * 2.0f;
+ cellSize = mRowData[position.rowIndex + position.rowSpan - 1].position - (position.rowIndex > 0 ? mRowData[position.rowIndex - 1].position : 0.f) - mPadding.height * 2.0f;
- if( cellSize < 0.0f )
+ if(cellSize < 0.0f)
{
cellSize = 0.0f;
}
}
}
- return 0.0f; // Child not found
+ return 0.0f; // Child not found
}
-bool TableView::RelayoutDependentOnChildren( Dimension::Type dimension )
+bool TableView::RelayoutDependentOnChildren(Dimension::Type dimension)
{
- if ( Control::RelayoutDependentOnChildren( dimension ) )
+ if(Control::RelayoutDependentOnChildren(dimension))
{
return true;
}
- return FindFit( mRowData ) || FindFit( mColumnData );
+ return FindFit(mRowData) || FindFit(mColumnData);
}
-void TableView::SetCellAlignment( Toolkit::TableView::CellPosition position, HorizontalAlignment::Type horizontal, VerticalAlignment::Type vertical )
+void TableView::SetCellAlignment(Toolkit::TableView::CellPosition position, HorizontalAlignment::Type horizontal, VerticalAlignment::Type vertical)
{
// Check if we need to expand our data array
- if( position.rowIndex >= mCellData.GetRows() )
+ if(position.rowIndex >= mCellData.GetRows())
{
// Only adding new rows
- ResizeContainers( position.rowIndex + 1, mCellData.GetColumns() );
+ ResizeContainers(position.rowIndex + 1, mCellData.GetColumns());
}
- if( position.columnIndex >= mCellData.GetColumns() )
+ if(position.columnIndex >= mCellData.GetColumns())
{
// Only adding new columns
- ResizeContainers( mCellData.GetRows(), position.columnIndex + 1 );
+ ResizeContainers(mCellData.GetRows(), position.columnIndex + 1);
}
// Set the alignment of the cell
- CellData& data = mCellData[ position.rowIndex ][ position.columnIndex ];
+ CellData& data = mCellData[position.rowIndex][position.columnIndex];
data.horizontalAlignment = horizontal;
- data.verticalAlignment = vertical;
+ data.verticalAlignment = vertical;
}
-void TableView::CalculateFillSizes( RowColumnArray& data )
+void TableView::CalculateFillSizes(RowColumnArray& data)
{
// First pass: Count number of fill entries and calculate used relative space
- Dali::Vector< RowColumnData* > fillData;
- float relativeTotal = 0.0f;
+ Dali::Vector<RowColumnData*> fillData;
+ float relativeTotal = 0.0f;
const unsigned int dataCount = data.Size();
- for( unsigned int i = 0; i < dataCount; ++i )
+ for(unsigned int i = 0; i < dataCount; ++i)
{
- RowColumnData& dataInstance = data[ i ];
+ RowColumnData& dataInstance = data[i];
- if( dataInstance.sizePolicy == Toolkit::TableView::RELATIVE )
+ if(dataInstance.sizePolicy == Toolkit::TableView::RELATIVE)
{
relativeTotal += dataInstance.fillRatio;
}
else if(dataInstance.sizePolicy == Toolkit::TableView::FILL)
{
- fillData.PushBack( &dataInstance );
+ fillData.PushBack(&dataInstance);
}
}
// Second pass: Distribute remaining relative space
const unsigned int fillCount = fillData.Size();
- if( fillCount > 0 )
+ if(fillCount > 0)
{
- if( relativeTotal > 1.0f )
+ if(relativeTotal > 1.0f)
{
relativeTotal = 1.0f;
}
- const float evenFillRatio = (1.0f - relativeTotal ) / fillCount;
+ const float evenFillRatio = (1.0f - relativeTotal) / fillCount;
- for( unsigned int i = 0; i < fillCount; ++i )
+ for(unsigned int i = 0; i < fillCount; ++i)
{
- fillData[ i ]->fillRatio = evenFillRatio;
+ fillData[i]->fillRatio = evenFillRatio;
}
}
}
-float TableView::CalculateTotalFixedSize( const RowColumnArray& data )
+float TableView::CalculateTotalFixedSize(const RowColumnArray& data)
{
float totalSize = 0.0f;
const unsigned int dataCount = data.Size();
- for( unsigned int i = 0; i < dataCount; ++i )
+ for(unsigned int i = 0; i < dataCount; ++i)
{
- const RowColumnData& dataInstance = data[ i ];
+ const RowColumnData& dataInstance = data[i];
- switch( dataInstance.sizePolicy )
+ switch(dataInstance.sizePolicy)
{
// we have absolute size to FIXED and FIT column/row and relative size for RELATIVE and FILL column/row
case Toolkit::TableView::FIXED:
return totalSize;
}
-Vector2 TableView::GetCellPadding( Dimension::Type dimension )
+Vector2 TableView::GetCellPadding(Dimension::Type dimension)
{
- switch( dimension )
+ switch(dimension)
{
case Dimension::WIDTH:
{
- return Vector2( mPadding.x, mPadding.x );
+ return Vector2(mPadding.x, mPadding.x);
}
case Dimension::HEIGHT:
{
- return Vector2( mPadding.y, mPadding.y );
+ return Vector2(mPadding.y, mPadding.y);
}
default:
{
return Vector2();
}
-void TableView::CalculateFitSizes( RowColumnArray& data, Dimension::Type dimension )
+void TableView::CalculateFitSizes(RowColumnArray& data, Dimension::Type dimension)
{
- Vector2 cellPadding = GetCellPadding( dimension );
+ Vector2 cellPadding = GetCellPadding(dimension);
const unsigned int dataCount = data.Size();
- for( unsigned int i = 0; i < dataCount; ++i )
+ for(unsigned int i = 0; i < dataCount; ++i)
{
- RowColumnData& dataInstance = data[ i ];
+ RowColumnData& dataInstance = data[i];
- if( dataInstance.sizePolicy == Toolkit::TableView::FIT )
+ if(dataInstance.sizePolicy == Toolkit::TableView::FIT)
{
// Find the size of the biggest actor in the row or column
float maxActorHeight = 0.0f;
- unsigned int fitCount = ( dimension == Dimension::WIDTH ) ? mCellData.GetRows() : mCellData.GetColumns();
+ unsigned int fitCount = (dimension == Dimension::WIDTH) ? mCellData.GetRows() : mCellData.GetColumns();
- for( unsigned int j = 0; j < fitCount; ++j )
+ for(unsigned int j = 0; j < fitCount; ++j)
{
- unsigned int row = ( dimension == Dimension::WIDTH ) ? j : i;
- unsigned int column = ( dimension == Dimension::WIDTH ) ? i : j;
- DALI_ASSERT_DEBUG( row < mCellData.GetRows() );
- DALI_ASSERT_DEBUG( column < mCellData.GetColumns() );
-
- const CellData& cellData = mCellData[ row ][ column ];
- const Actor& actor = cellData.actor;
- if( actor )
+ unsigned int row = (dimension == Dimension::WIDTH) ? j : i;
+ unsigned int column = (dimension == Dimension::WIDTH) ? i : j;
+ DALI_ASSERT_DEBUG(row < mCellData.GetRows());
+ DALI_ASSERT_DEBUG(column < mCellData.GetColumns());
+
+ const CellData& cellData = mCellData[row][column];
+ const Actor& actor = cellData.actor;
+ if(actor)
{
- if( FitToChild( actor, dimension ) && ( dimension == Dimension::WIDTH ) ? ( cellData.position.columnSpan == 1 ) : ( cellData.position.rowSpan == 1 ) )
+ if(FitToChild(actor, dimension) && (dimension == Dimension::WIDTH) ? (cellData.position.columnSpan == 1) : (cellData.position.rowSpan == 1))
{
- maxActorHeight = std::max( maxActorHeight, actor.GetRelayoutSize( dimension ) + cellPadding.x + cellPadding.y );
+ maxActorHeight = std::max(maxActorHeight, actor.GetRelayoutSize(dimension) + cellPadding.x + cellPadding.y);
}
}
}
}
}
-bool TableView::FindFit( const RowColumnArray& data )
+bool TableView::FindFit(const RowColumnArray& data)
{
- for( unsigned int i = 0, count = data.Size(); i < count; ++i )
+ for(unsigned int i = 0, count = data.Size(); i < count; ++i)
{
- if( data[ i ].sizePolicy == Toolkit::TableView::FIT )
+ if(data[i].sizePolicy == Toolkit::TableView::FIT)
{
return true;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/text-controls/text-editor-impl.h>
// EXTERNAL INCLUDES
-#include <cstring>
-#include <limits>
-#include <dali/public-api/adaptor-framework/key.h>
-#include <dali/public-api/common/dali-common.h>
+#include <dali/devel-api/actors/actor-devel.h>
#include <dali/devel-api/adaptor-framework/window-devel.h>
#include <dali/devel-api/common/stage.h>
-#include <dali/devel-api/actors/actor-devel.h>
#include <dali/devel-api/object/property-helper-devel.h>
-#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/integration-api/debug.h>
#include <dali/integration-api/adaptor-framework/adaptor.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/adaptor-framework/key.h>
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <cstring>
+#include <limits>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/text/text-enumerations.h>
-#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
-#include <dali-toolkit/devel-api/text/rendering-backend.h>
-#include <dali-toolkit/devel-api/controls/control-devel.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
+#include <dali-toolkit/devel-api/controls/control-devel.h>
#include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/text/text-enumerations-impl.h>
+#include <dali-toolkit/devel-api/text/rendering-backend.h>
+#include <dali-toolkit/internal/styling/style-manager-impl.h>
#include <dali-toolkit/internal/text/rendering/text-backend.h>
#include <dali-toolkit/internal/text/text-effects-style.h>
+#include <dali-toolkit/internal/text/text-enumerations-impl.h>
#include <dali-toolkit/internal/text/text-font-style.h>
#include <dali-toolkit/internal/text/text-view.h>
-#include <dali-toolkit/internal/styling/style-manager-impl.h>
-#include <dali-toolkit/devel-api/controls/control-devel.h>
+#include <dali-toolkit/public-api/text/text-enumerations.h>
+#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
using namespace Dali::Toolkit::Text;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace // unnamed namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_CONTROLS");
#endif
const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND;
-const float DEFAULT_SCROLL_SPEED = 1200.f; ///< The default scroll speed for the text editor in pixels/second.
+const float DEFAULT_SCROLL_SPEED = 1200.f; ///< The default scroll speed for the text editor in pixels/second.
} // unnamed namespace
namespace
return Toolkit::TextEditor::New();
}
+// clang-format off
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextEditor, Toolkit::Control, Create );
-
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "text", STRING, TEXT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "textColor", VECTOR4, TEXT_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "fontFamily", STRING, FONT_FAMILY )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "fontStyle", MAP, FONT_STYLE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "pointSize", FLOAT, POINT_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "scrollThreshold", FLOAT, SCROLL_THRESHOLD )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "scrollSpeed", FLOAT, SCROLL_SPEED )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "primaryCursorColor", VECTOR4, PRIMARY_CURSOR_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "secondaryCursorColor", VECTOR4, SECONDARY_CURSOR_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableCursorBlink", BOOLEAN, ENABLE_CURSOR_BLINK )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "cursorBlinkInterval", FLOAT, CURSOR_BLINK_INTERVAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "cursorBlinkDuration", FLOAT, CURSOR_BLINK_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "cursorWidth", INTEGER, CURSOR_WIDTH )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "grabHandleImage", STRING, GRAB_HANDLE_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "grabHandlePressedImage", STRING, GRAB_HANDLE_PRESSED_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandleImageLeft", MAP, SELECTION_HANDLE_IMAGE_LEFT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandleImageRight", MAP, SELECTION_HANDLE_IMAGE_RIGHT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandlePressedImageLeft", MAP, SELECTION_HANDLE_PRESSED_IMAGE_LEFT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandlePressedImageRight", MAP, SELECTION_HANDLE_PRESSED_IMAGE_RIGHT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandleMarkerImageLeft", MAP, SELECTION_HANDLE_MARKER_IMAGE_LEFT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandleMarkerImageRight", MAP, SELECTION_HANDLE_MARKER_IMAGE_RIGHT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHighlightColor", VECTOR4, SELECTION_HIGHLIGHT_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "decorationBoundingBox", RECTANGLE, DECORATION_BOUNDING_BOX )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableMarkup", BOOLEAN, ENABLE_MARKUP )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputColor", VECTOR4, INPUT_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputFontFamily", STRING, INPUT_FONT_FAMILY )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputFontStyle", MAP, INPUT_FONT_STYLE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputPointSize", FLOAT, INPUT_POINT_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "lineSpacing", FLOAT, LINE_SPACING )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputLineSpacing", FLOAT, INPUT_LINE_SPACING )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "underline", MAP, UNDERLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputUnderline", MAP, INPUT_UNDERLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "shadow", MAP, SHADOW )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputShadow", MAP, INPUT_SHADOW )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "emboss", MAP, EMBOSS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputEmboss", MAP, INPUT_EMBOSS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "outline", MAP, OUTLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputOutline", MAP, INPUT_OUTLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "smoothScroll", BOOLEAN, SMOOTH_SCROLL )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "smoothScrollDuration", FLOAT, SMOOTH_SCROLL_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableScrollBar", BOOLEAN, ENABLE_SCROLL_BAR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "scrollBarShowDuration", FLOAT, SCROLL_BAR_SHOW_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "scrollBarFadeDuration", FLOAT, SCROLL_BAR_FADE_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "pixelSize", FLOAT, PIXEL_SIZE )
-DALI_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextEditor, "lineCount", INTEGER, LINE_COUNT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableSelection", BOOLEAN, ENABLE_SELECTION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "placeholder", MAP, PLACEHOLDER )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "lineWrapMode", INTEGER, LINE_WRAP_MODE )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "placeholderText", STRING, PLACEHOLDER_TEXT )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "placeholderTextColor", VECTOR4, PLACEHOLDER_TEXT_COLOR )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableShiftSelection", BOOLEAN, ENABLE_SHIFT_SELECTION )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableGrabHandle", BOOLEAN, ENABLE_GRAB_HANDLE )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "renderingBackend", INTEGER, RENDERING_BACKEND )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "maxLength", INTEGER, MAX_LENGTH )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectedTextStart", INTEGER, SELECTED_TEXT_START )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectedTextEnd", INTEGER, SELECTED_TEXT_END )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "horizontalScrollPosition", FLOAT, HORIZONTAL_SCROLL_POSITION )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "verticalScrollPosition", INTEGER, VERTICAL_SCROLL_POSITION )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableEditing", BOOLEAN, ENABLE_EDITING )
-DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextEditor, "selectedText", STRING, SELECTED_TEXT )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "fontSizeScale", FLOAT, FONT_SIZE_SCALE )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "primaryCursorPosition", INTEGER, PRIMARY_CURSOR_POSITION )
-
-DALI_SIGNAL_REGISTRATION( Toolkit, TextEditor, "textChanged", SIGNAL_TEXT_CHANGED )
-DALI_SIGNAL_REGISTRATION( Toolkit, TextEditor, "inputStyleChanged", SIGNAL_INPUT_STYLE_CHANGED )
-DALI_SIGNAL_REGISTRATION( Toolkit, TextEditor, "maxLengthReached", SIGNAL_MAX_LENGTH_REACHED )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextEditor, Toolkit::Control, Create);
+
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "text", STRING, TEXT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "textColor", VECTOR4, TEXT_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "fontFamily", STRING, FONT_FAMILY )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "fontStyle", MAP, FONT_STYLE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "pointSize", FLOAT, POINT_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "scrollThreshold", FLOAT, SCROLL_THRESHOLD )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "scrollSpeed", FLOAT, SCROLL_SPEED )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "primaryCursorColor", VECTOR4, PRIMARY_CURSOR_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "secondaryCursorColor", VECTOR4, SECONDARY_CURSOR_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableCursorBlink", BOOLEAN, ENABLE_CURSOR_BLINK )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "cursorBlinkInterval", FLOAT, CURSOR_BLINK_INTERVAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "cursorBlinkDuration", FLOAT, CURSOR_BLINK_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "cursorWidth", INTEGER, CURSOR_WIDTH )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "grabHandleImage", STRING, GRAB_HANDLE_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "grabHandlePressedImage", STRING, GRAB_HANDLE_PRESSED_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandleImageLeft", MAP, SELECTION_HANDLE_IMAGE_LEFT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandleImageRight", MAP, SELECTION_HANDLE_IMAGE_RIGHT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandlePressedImageLeft", MAP, SELECTION_HANDLE_PRESSED_IMAGE_LEFT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandlePressedImageRight", MAP, SELECTION_HANDLE_PRESSED_IMAGE_RIGHT)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandleMarkerImageLeft", MAP, SELECTION_HANDLE_MARKER_IMAGE_LEFT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandleMarkerImageRight", MAP, SELECTION_HANDLE_MARKER_IMAGE_RIGHT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHighlightColor", VECTOR4, SELECTION_HIGHLIGHT_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "decorationBoundingBox", RECTANGLE, DECORATION_BOUNDING_BOX )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableMarkup", BOOLEAN, ENABLE_MARKUP )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputColor", VECTOR4, INPUT_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputFontFamily", STRING, INPUT_FONT_FAMILY )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputFontStyle", MAP, INPUT_FONT_STYLE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputPointSize", FLOAT, INPUT_POINT_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "lineSpacing", FLOAT, LINE_SPACING )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputLineSpacing", FLOAT, INPUT_LINE_SPACING )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "underline", MAP, UNDERLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputUnderline", MAP, INPUT_UNDERLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "shadow", MAP, SHADOW )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputShadow", MAP, INPUT_SHADOW )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "emboss", MAP, EMBOSS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputEmboss", MAP, INPUT_EMBOSS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "outline", MAP, OUTLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputOutline", MAP, INPUT_OUTLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "smoothScroll", BOOLEAN, SMOOTH_SCROLL )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "smoothScrollDuration", FLOAT, SMOOTH_SCROLL_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableScrollBar", BOOLEAN, ENABLE_SCROLL_BAR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "scrollBarShowDuration", FLOAT, SCROLL_BAR_SHOW_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "scrollBarFadeDuration", FLOAT, SCROLL_BAR_FADE_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "pixelSize", FLOAT, PIXEL_SIZE )
+DALI_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextEditor, "lineCount", INTEGER, LINE_COUNT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableSelection", BOOLEAN, ENABLE_SELECTION )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "placeholder", MAP, PLACEHOLDER )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "lineWrapMode", INTEGER, LINE_WRAP_MODE )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "placeholderText", STRING, PLACEHOLDER_TEXT )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "placeholderTextColor", VECTOR4, PLACEHOLDER_TEXT_COLOR )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableShiftSelection", BOOLEAN, ENABLE_SHIFT_SELECTION )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableGrabHandle", BOOLEAN, ENABLE_GRAB_HANDLE )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "renderingBackend", INTEGER, RENDERING_BACKEND )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "maxLength", INTEGER, MAX_LENGTH )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectedTextStart", INTEGER, SELECTED_TEXT_START )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectedTextEnd", INTEGER, SELECTED_TEXT_END )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "horizontalScrollPosition", FLOAT, HORIZONTAL_SCROLL_POSITION )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "verticalScrollPosition", INTEGER, VERTICAL_SCROLL_POSITION )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableEditing", BOOLEAN, ENABLE_EDITING )
+DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextEditor, "selectedText", STRING, SELECTED_TEXT )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "fontSizeScale", FLOAT, FONT_SIZE_SCALE )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "primaryCursorPosition", INTEGER, PRIMARY_CURSOR_POSITION )
+
+DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "textChanged", SIGNAL_TEXT_CHANGED )
+DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "inputStyleChanged", SIGNAL_INPUT_STYLE_CHANGED)
+DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "maxLengthReached", SIGNAL_MAX_LENGTH_REACHED )
DALI_TYPE_REGISTRATION_END()
+// clang-format on
-const char * const IMAGE_MAP_FILENAME_STRING = "filename";
+const char* const IMAGE_MAP_FILENAME_STRING = "filename";
/// Retrieves a filename from a value that is a Property::Map
-std::string GetImageFileNameFromPropertyValue( const Property::Value& value )
+std::string GetImageFileNameFromPropertyValue(const Property::Value& value)
{
- std::string filename;
+ std::string filename;
const Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
- const Property::Value* filenameValue = map->Find( IMAGE_MAP_FILENAME_STRING );
- if( filenameValue )
+ const Property::Value* filenameValue = map->Find(IMAGE_MAP_FILENAME_STRING);
+ if(filenameValue)
{
- filenameValue->Get( filename );
+ filenameValue->Get(filename);
}
}
return filename;
Toolkit::TextEditor TextEditor::New()
{
// Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< TextEditor > impl = new TextEditor();
+ IntrusivePtr<TextEditor> impl = new TextEditor();
// Pass ownership to CustomActor handle
- Toolkit::TextEditor handle( *impl );
+ Toolkit::TextEditor handle(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-void TextEditor::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void TextEditor::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast(Dali::BaseHandle(object));
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor SetProperty\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor SetProperty\n");
-
- if( textEditor )
+ if(textEditor)
{
- TextEditor& impl( GetImpl( textEditor ) );
- DALI_ASSERT_DEBUG( impl.mController && "No text contoller" );
- DALI_ASSERT_DEBUG( impl.mDecorator && "No text decorator" );
+ TextEditor& impl(GetImpl(textEditor));
+ DALI_ASSERT_DEBUG(impl.mController && "No text contoller");
+ DALI_ASSERT_DEBUG(impl.mDecorator && "No text decorator");
- switch( index )
+ switch(index)
{
case Toolkit::DevelTextEditor::Property::RENDERING_BACKEND:
{
- int backend = value.Get< int >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p RENDERING_BACKEND %d\n", impl.mController.Get(), backend );
+ int backend = value.Get<int>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p RENDERING_BACKEND %d\n", impl.mController.Get(), backend);
- if( impl.mRenderingBackend != backend )
+ if(impl.mRenderingBackend != backend)
{
impl.mRenderingBackend = backend;
impl.mRenderer.Reset();
}
case Toolkit::TextEditor::Property::TEXT:
{
- const std::string& text = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p TEXT %s\n", impl.mController.Get(), text.c_str() );
+ const std::string& text = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p TEXT %s\n", impl.mController.Get(), text.c_str());
- impl.mController->SetText( text );
+ impl.mController->SetText(text);
break;
}
case Toolkit::TextEditor::Property::TEXT_COLOR:
{
- const Vector4& textColor = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a );
+ const Vector4& textColor = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a);
- if( impl.mController->GetDefaultColor() != textColor )
+ if(impl.mController->GetDefaultColor() != textColor)
{
- impl.mController->SetDefaultColor( textColor );
- impl.mController->SetInputColor( textColor );
+ impl.mController->SetDefaultColor(textColor);
+ impl.mController->SetInputColor(textColor);
impl.mRenderer.Reset();
}
break;
}
case Toolkit::TextEditor::Property::FONT_FAMILY:
{
- const std::string& fontFamily = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str() );
- impl.mController->SetDefaultFontFamily( fontFamily );
+ const std::string& fontFamily = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str());
+ impl.mController->SetDefaultFontFamily(fontFamily);
break;
}
case Toolkit::TextEditor::Property::FONT_STYLE:
{
- SetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT );
+ SetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT);
break;
}
case Toolkit::TextEditor::Property::POINT_SIZE:
{
- const float pointSize = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p POINT_SIZE %f\n", impl.mController.Get(), pointSize );
+ const float pointSize = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p POINT_SIZE %f\n", impl.mController.Get(), pointSize);
- if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
+ if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize))
{
- impl.mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE );
+ impl.mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE);
}
break;
}
case Toolkit::TextEditor::Property::HORIZONTAL_ALIGNMENT:
{
- Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( Text::GetHorizontalAlignmentEnumeration( value, alignment ) )
+ Text::HorizontalAlignment::Type alignment(static_cast<Text::HorizontalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(Text::GetHorizontalAlignmentEnumeration(value, alignment))
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p HORIZONTAL_ALIGNMENT %d\n", impl.mController.Get(), alignment );
- impl.mController->SetHorizontalAlignment( alignment );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p HORIZONTAL_ALIGNMENT %d\n", impl.mController.Get(), alignment);
+ impl.mController->SetHorizontalAlignment(alignment);
}
break;
}
case Toolkit::TextEditor::Property::SCROLL_THRESHOLD:
{
- const float threshold = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p SCROLL_THRESHOLD %f\n", impl.mController.Get(), threshold );
+ const float threshold = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p SCROLL_THRESHOLD %f\n", impl.mController.Get(), threshold);
- impl.mDecorator->SetScrollThreshold( threshold );
+ impl.mDecorator->SetScrollThreshold(threshold);
break;
}
case Toolkit::TextEditor::Property::SCROLL_SPEED:
{
- const float speed = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p SCROLL_SPEED %f\n", impl.mController.Get(), speed );
+ const float speed = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p SCROLL_SPEED %f\n", impl.mController.Get(), speed);
- impl.mDecorator->SetScrollSpeed( speed );
+ impl.mDecorator->SetScrollSpeed(speed);
break;
}
case Toolkit::TextEditor::Property::PRIMARY_CURSOR_COLOR:
{
- const Vector4& color = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p PRIMARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a );
+ const Vector4& color = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p PRIMARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a);
- impl.mDecorator->SetCursorColor( PRIMARY_CURSOR, color );
+ impl.mDecorator->SetCursorColor(PRIMARY_CURSOR, color);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextEditor::Property::SECONDARY_CURSOR_COLOR:
{
- const Vector4& color = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p SECONDARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a );
+ const Vector4& color = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p SECONDARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a);
- impl.mDecorator->SetCursorColor( SECONDARY_CURSOR, color );
+ impl.mDecorator->SetCursorColor(SECONDARY_CURSOR, color);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextEditor::Property::ENABLE_CURSOR_BLINK:
{
- const bool enable = value.Get< bool >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p ENABLE_CURSOR_BLINK %d\n", impl.mController.Get(), enable );
+ const bool enable = value.Get<bool>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p ENABLE_CURSOR_BLINK %d\n", impl.mController.Get(), enable);
- impl.mController->SetEnableCursorBlink( enable );
+ impl.mController->SetEnableCursorBlink(enable);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextEditor::Property::CURSOR_BLINK_INTERVAL:
{
- const float interval = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_BLINK_INTERVAL %f\n", impl.mController.Get(), interval );
+ const float interval = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_BLINK_INTERVAL %f\n", impl.mController.Get(), interval);
- impl.mDecorator->SetCursorBlinkInterval( interval );
+ impl.mDecorator->SetCursorBlinkInterval(interval);
break;
}
case Toolkit::TextEditor::Property::CURSOR_BLINK_DURATION:
{
- const float duration = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_BLINK_DURATION %f\n", impl.mController.Get(), duration );
+ const float duration = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_BLINK_DURATION %f\n", impl.mController.Get(), duration);
- impl.mDecorator->SetCursorBlinkDuration( duration );
+ impl.mDecorator->SetCursorBlinkDuration(duration);
break;
}
case Toolkit::TextEditor::Property::CURSOR_WIDTH:
{
- const int width = value.Get< int >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_WIDTH %d\n", impl.mController.Get(), width );
+ const int width = value.Get<int>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_WIDTH %d\n", impl.mController.Get(), width);
- impl.mDecorator->SetCursorWidth( width );
- impl.mController->GetLayoutEngine().SetCursorWidth( width );
+ impl.mDecorator->SetCursorWidth(width);
+ impl.mController->GetLayoutEngine().SetCursorWidth(width);
break;
}
case Toolkit::TextEditor::Property::GRAB_HANDLE_IMAGE:
{
- const std::string imageFileName = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p GRAB_HANDLE_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str() );
+ const std::string imageFileName = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p GRAB_HANDLE_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str());
- if( imageFileName.size() )
+ if(imageFileName.size())
{
- impl.mDecorator->SetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_RELEASED, imageFileName );
+ impl.mDecorator->SetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_RELEASED, imageFileName);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextEditor::Property::GRAB_HANDLE_PRESSED_IMAGE:
{
- const std::string imageFileName = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p GRAB_HANDLE_PRESSED_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str() );
+ const std::string imageFileName = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p GRAB_HANDLE_PRESSED_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str());
- if( imageFileName.size() )
+ if(imageFileName.size())
{
- impl.mDecorator->SetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_PRESSED, imageFileName );
+ impl.mDecorator->SetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_PRESSED, imageFileName);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_IMAGE_LEFT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename );
+ impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_IMAGE_RIGHT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename );
+ impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_PRESSED_IMAGE_LEFT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename );
+ impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_PRESSED_IMAGE_RIGHT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename );
+ impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_MARKER_IMAGE_LEFT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename );
+ impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_MARKER_IMAGE_RIGHT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename );
+ impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextEditor::Property::SELECTION_HIGHLIGHT_COLOR:
{
- const Vector4 color = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p SELECTION_HIGHLIGHT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a );
+ const Vector4 color = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p SELECTION_HIGHLIGHT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a);
- impl.mDecorator->SetHighlightColor( color );
+ impl.mDecorator->SetHighlightColor(color);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextEditor::Property::DECORATION_BOUNDING_BOX:
{
- const Rect<int>& box = value.Get< Rect<int> >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p DECORATION_BOUNDING_BOX %d,%d %dx%d\n", impl.mController.Get(), box.x, box.y, box.width, box.height );
+ const Rect<int>& box = value.Get<Rect<int> >();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p DECORATION_BOUNDING_BOX %d,%d %dx%d\n", impl.mController.Get(), box.x, box.y, box.width, box.height);
- impl.mDecorator->SetBoundingBox( box );
+ impl.mDecorator->SetBoundingBox(box);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextEditor::Property::ENABLE_MARKUP:
{
const bool enableMarkup = value.Get<bool>();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_MARKUP %d\n", impl.mController.Get(), enableMarkup );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_MARKUP %d\n", impl.mController.Get(), enableMarkup);
- impl.mController->SetMarkupProcessorEnabled( enableMarkup );
+ impl.mController->SetMarkupProcessorEnabled(enableMarkup);
break;
}
case Toolkit::TextEditor::Property::INPUT_COLOR:
{
- const Vector4& inputColor = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p INPUT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), inputColor.r, inputColor.g, inputColor.b, inputColor.a );
+ const Vector4& inputColor = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p INPUT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), inputColor.r, inputColor.g, inputColor.b, inputColor.a);
- impl.mController->SetInputColor( inputColor );
+ impl.mController->SetInputColor(inputColor);
break;
}
case Toolkit::TextEditor::Property::INPUT_FONT_FAMILY:
{
- const std::string& fontFamily = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p INPUT_FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str() );
- impl.mController->SetInputFontFamily( fontFamily );
+ const std::string& fontFamily = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p INPUT_FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str());
+ impl.mController->SetInputFontFamily(fontFamily);
break;
}
case Toolkit::TextEditor::Property::INPUT_FONT_STYLE:
{
- SetFontStyleProperty( impl.mController, value, Text::FontStyle::INPUT );
+ SetFontStyleProperty(impl.mController, value, Text::FontStyle::INPUT);
break;
}
case Toolkit::TextEditor::Property::INPUT_POINT_SIZE:
{
- const float pointSize = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p INPUT_POINT_SIZE %f\n", impl.mController.Get(), pointSize );
- impl.mController->SetInputFontPointSize( pointSize );
+ const float pointSize = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p INPUT_POINT_SIZE %f\n", impl.mController.Get(), pointSize);
+ impl.mController->SetInputFontPointSize(pointSize);
break;
}
case Toolkit::TextEditor::Property::LINE_SPACING:
// by the TextLabel for now it must be ignored. The property is being shadowed
// locally so its value isn't affected.
const float lineSpacing = value.Get<float>();
- impl.mLineSpacing = lineSpacing;
+ impl.mLineSpacing = lineSpacing;
// set it to 0.0 due to missing implementation
- impl.mController->SetDefaultLineSpacing( 0.0f );
+ impl.mController->SetDefaultLineSpacing(0.0f);
impl.mRenderer.Reset();
break;
}
case Toolkit::TextEditor::Property::INPUT_LINE_SPACING:
{
const float lineSpacing = value.Get<float>();
- impl.mController->SetInputLineSpacing( lineSpacing );
+ impl.mController->SetInputLineSpacing(lineSpacing);
impl.mRenderer.Reset();
break;
}
case Toolkit::TextEditor::Property::UNDERLINE:
{
- const bool update = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
- if( update )
+ const bool update = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextEditor::Property::INPUT_UNDERLINE:
{
- const bool update = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::INPUT );
- if( update )
+ const bool update = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::INPUT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextEditor::Property::SHADOW:
{
- const bool update = SetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
- if( update )
+ const bool update = SetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextEditor::Property::INPUT_SHADOW:
{
- const bool update = SetShadowProperties( impl.mController, value, Text::EffectStyle::INPUT );
- if( update )
+ const bool update = SetShadowProperties(impl.mController, value, Text::EffectStyle::INPUT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextEditor::Property::EMBOSS:
{
- const bool update = SetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
- if( update )
+ const bool update = SetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextEditor::Property::INPUT_EMBOSS:
{
- const bool update = SetEmbossProperties( impl.mController, value, Text::EffectStyle::INPUT );
- if( update )
+ const bool update = SetEmbossProperties(impl.mController, value, Text::EffectStyle::INPUT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextEditor::Property::OUTLINE:
{
- const bool update = SetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
- if( update )
+ const bool update = SetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextEditor::Property::INPUT_OUTLINE:
{
- const bool update = SetOutlineProperties( impl.mController, value, Text::EffectStyle::INPUT );
- if( update )
+ const bool update = SetOutlineProperties(impl.mController, value, Text::EffectStyle::INPUT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextEditor::Property::SMOOTH_SCROLL:
{
- const bool enable = value.Get< bool >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor SMOOTH_SCROLL %d\n", enable );
+ const bool enable = value.Get<bool>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor SMOOTH_SCROLL %d\n", enable);
impl.mScrollAnimationEnabled = enable;
break;
}
case Toolkit::TextEditor::Property::SMOOTH_SCROLL_DURATION:
{
- const float duration = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor SMOOTH_SCROLL_DURATION %f\n", duration );
+ const float duration = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor SMOOTH_SCROLL_DURATION %f\n", duration);
impl.mScrollAnimationDuration = duration;
- if ( impl.mTextVerticalScroller )
+ if(impl.mTextVerticalScroller)
{
- impl.mTextVerticalScroller->SetDuration( duration );
+ impl.mTextVerticalScroller->SetDuration(duration);
}
break;
}
case Toolkit::TextEditor::Property::ENABLE_SCROLL_BAR:
{
- const bool enable = value.Get< bool >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor SHOW_SCROLL_BAR %d\n", enable );
+ const bool enable = value.Get<bool>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor SHOW_SCROLL_BAR %d\n", enable);
impl.mScrollBarEnabled = enable;
break;
}
case Toolkit::TextEditor::Property::SCROLL_BAR_SHOW_DURATION:
{
- const float duration = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor SCROLL_BAR_SHOW_DURATION %f\n", duration );
+ const float duration = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor SCROLL_BAR_SHOW_DURATION %f\n", duration);
impl.mAnimationPeriod.delaySeconds = duration;
break;
}
case Toolkit::TextEditor::Property::SCROLL_BAR_FADE_DURATION:
{
- const float duration = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor SCROLL_BAR_FADE_DURATION %f\n", duration );
+ const float duration = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor SCROLL_BAR_FADE_DURATION %f\n", duration);
impl.mAnimationPeriod.durationSeconds = duration;
break;
}
case Toolkit::TextEditor::Property::PIXEL_SIZE:
{
- const float pixelSize = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize );
+ const float pixelSize = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize);
- if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) )
+ if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE), pixelSize))
{
- impl.mController->SetDefaultFontSize( pixelSize, Text::Controller::PIXEL_SIZE );
+ impl.mController->SetDefaultFontSize(pixelSize, Text::Controller::PIXEL_SIZE);
}
break;
}
case Toolkit::DevelTextEditor::Property::PLACEHOLDER_TEXT:
{
- const std::string& text = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor::OnPropertySet %p PLACEHOLDER_TEXT %s\n", impl.mController.Get(), text.c_str() );
+ const std::string& text = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor::OnPropertySet %p PLACEHOLDER_TEXT %s\n", impl.mController.Get(), text.c_str());
- impl.mController->SetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text );
+ impl.mController->SetPlaceholderText(Controller::PLACEHOLDER_TYPE_INACTIVE, text);
break;
}
case Toolkit::DevelTextEditor::Property::PLACEHOLDER_TEXT_COLOR:
{
- const Vector4& textColor = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p PLACEHOLDER_TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a );
+ const Vector4& textColor = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p PLACEHOLDER_TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a);
- if( impl.mController->GetPlaceholderTextColor() != textColor )
+ if(impl.mController->GetPlaceholderTextColor() != textColor)
{
- impl.mController->SetPlaceholderTextColor( textColor );
+ impl.mController->SetPlaceholderTextColor(textColor);
impl.mRenderer.Reset();
}
break;
}
case Toolkit::TextEditor::Property::ENABLE_SELECTION:
{
- const bool enableSelection = value.Get< bool >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_SELECTION %d\n", impl.mController.Get(), enableSelection );
- impl.mController->SetSelectionEnabled( enableSelection );
+ const bool enableSelection = value.Get<bool>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_SELECTION %d\n", impl.mController.Get(), enableSelection);
+ impl.mController->SetSelectionEnabled(enableSelection);
break;
}
case Toolkit::TextEditor::Property::PLACEHOLDER:
{
const Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
- impl.mController->SetPlaceholderProperty( *map );
+ impl.mController->SetPlaceholderProperty(*map);
}
break;
}
case Toolkit::TextEditor::Property::LINE_WRAP_MODE:
{
- Text::LineWrap::Mode lineWrapMode( static_cast< Text::LineWrap::Mode >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( GetLineWrapModeEnumeration( value, lineWrapMode ) )
+ Text::LineWrap::Mode lineWrapMode(static_cast<Text::LineWrap::Mode>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(GetLineWrapModeEnumeration(value, lineWrapMode))
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p LineWrap::MODE %d\n", impl.mController.Get(), lineWrapMode );
- impl.mController->SetLineWrapMode( lineWrapMode );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p LineWrap::MODE %d\n", impl.mController.Get(), lineWrapMode);
+ impl.mController->SetLineWrapMode(lineWrapMode);
}
break;
}
case Toolkit::DevelTextEditor::Property::ENABLE_SHIFT_SELECTION:
{
const bool shiftSelection = value.Get<bool>();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_SHIFT_SELECTION %d\n", impl.mController.Get(), shiftSelection );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_SHIFT_SELECTION %d\n", impl.mController.Get(), shiftSelection);
- impl.mController->SetShiftSelectionEnabled( shiftSelection );
+ impl.mController->SetShiftSelectionEnabled(shiftSelection);
break;
}
case Toolkit::DevelTextEditor::Property::ENABLE_GRAB_HANDLE:
{
const bool grabHandleEnabled = value.Get<bool>();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_GRAB_HANDLE %d\n", impl.mController.Get(), grabHandleEnabled );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_GRAB_HANDLE %d\n", impl.mController.Get(), grabHandleEnabled);
- impl.mController->SetGrabHandleEnabled( grabHandleEnabled );
+ impl.mController->SetGrabHandleEnabled(grabHandleEnabled);
break;
}
case Toolkit::DevelTextEditor::Property::MATCH_SYSTEM_LANGUAGE_DIRECTION:
{
- impl.mController->SetMatchSystemLanguageDirection(value.Get< bool >());
+ impl.mController->SetMatchSystemLanguageDirection(value.Get<bool>());
break;
}
case Toolkit::DevelTextEditor::Property::MAX_LENGTH:
{
- const int max = value.Get< int >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p MAX_LENGTH %d\n", impl.mController.Get(), max );
+ const int max = value.Get<int>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p MAX_LENGTH %d\n", impl.mController.Get(), max);
- impl.mController->SetMaximumNumberOfCharacters( max );
+ impl.mController->SetMaximumNumberOfCharacters(max);
break;
}
case Toolkit::DevelTextEditor::Property::SELECTED_TEXT_START:
{
- uint32_t start = static_cast<uint32_t>(value.Get< int >());
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p SELECTED_TEXT_START %d\n", impl.mController.Get(), start );
- impl.SetTextSelectionRange( &start, nullptr );
+ uint32_t start = static_cast<uint32_t>(value.Get<int>());
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p SELECTED_TEXT_START %d\n", impl.mController.Get(), start);
+ impl.SetTextSelectionRange(&start, nullptr);
break;
}
case Toolkit::DevelTextEditor::Property::SELECTED_TEXT_END:
{
- uint32_t end = static_cast<uint32_t>(value.Get< int >());
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p SELECTED_TEXT_END %d\n", impl.mController.Get(), end );
- impl.SetTextSelectionRange( nullptr, &end );
+ uint32_t end = static_cast<uint32_t>(value.Get<int>());
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p SELECTED_TEXT_END %d\n", impl.mController.Get(), end);
+ impl.SetTextSelectionRange(nullptr, &end);
break;
}
case Toolkit::DevelTextEditor::Property::ENABLE_EDITING:
{
- const bool editable = value.Get< bool >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_EDITING %d\n", impl.mController.Get(), editable );
- impl.SetEditable( editable );
+ const bool editable = value.Get<bool>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_EDITING %d\n", impl.mController.Get(), editable);
+ impl.SetEditable(editable);
break;
}
case Toolkit::DevelTextEditor::Property::HORIZONTAL_SCROLL_POSITION:
{
- float horizontalScroll = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p HORIZONTAL_SCROLL_POSITION %d\n", impl.mController.Get(), horizontalScroll );
- if (horizontalScroll >= 0.0f)
+ float horizontalScroll = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p HORIZONTAL_SCROLL_POSITION %d\n", impl.mController.Get(), horizontalScroll);
+ if(horizontalScroll >= 0.0f)
{
- impl.ScrollBy( Vector2(horizontalScroll - impl.GetHorizontalScrollPosition(), 0 ));
+ impl.ScrollBy(Vector2(horizontalScroll - impl.GetHorizontalScrollPosition(), 0));
}
break;
}
case Toolkit::DevelTextEditor::Property::VERTICAL_SCROLL_POSITION:
{
- float verticalScroll = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p VERTICAL_SCROLL_POSITION %d\n", impl.mController.Get(), verticalScroll );
- if (verticalScroll >= 0.0f)
+ float verticalScroll = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p VERTICAL_SCROLL_POSITION %d\n", impl.mController.Get(), verticalScroll);
+ if(verticalScroll >= 0.0f)
{
- impl.ScrollBy( Vector2(0, verticalScroll - impl.GetVerticalScrollPosition() ));
+ impl.ScrollBy(Vector2(0, verticalScroll - impl.GetVerticalScrollPosition()));
}
break;
}
case Toolkit::DevelTextEditor::Property::FONT_SIZE_SCALE:
{
- const float scale = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale );
+ const float scale = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale);
- if( !Equals( impl.mController->GetFontSizeScale(), scale ) )
+ if(!Equals(impl.mController->GetFontSizeScale(), scale))
{
- impl.mController->SetFontSizeScale( scale );
+ impl.mController->SetFontSizeScale(scale);
}
break;
}
case Toolkit::DevelTextEditor::Property::PRIMARY_CURSOR_POSITION:
{
- uint32_t position = static_cast<uint32_t>(value.Get< int >());
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p PRIMARY_CURSOR_POSITION %d\n", impl.mController.Get(), position );
- if (impl.mController->SetPrimaryCursorPosition( position ))
+ uint32_t position = static_cast<uint32_t>(value.Get<int>());
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p PRIMARY_CURSOR_POSITION %d\n", impl.mController.Get(), position);
+ if(impl.mController->SetPrimaryCursorPosition(position))
{
impl.SetKeyInputFocus();
}
break;
}
} // switch
- } // texteditor
+ } // texteditor
}
-Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index index )
+Property::Value TextEditor::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast(Dali::BaseHandle(object));
- if( textEditor )
+ if(textEditor)
{
- TextEditor& impl( GetImpl( textEditor ) );
- DALI_ASSERT_DEBUG( impl.mController && "No text contoller" );
- DALI_ASSERT_DEBUG( impl.mDecorator && "No text decorator" );
+ TextEditor& impl(GetImpl(textEditor));
+ DALI_ASSERT_DEBUG(impl.mController && "No text contoller");
+ DALI_ASSERT_DEBUG(impl.mDecorator && "No text decorator");
- switch( index )
+ switch(index)
{
case Toolkit::DevelTextEditor::Property::RENDERING_BACKEND:
{
case Toolkit::TextEditor::Property::TEXT:
{
std::string text;
- impl.mController->GetText( text );
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p returning text: %s\n", impl.mController.Get(), text.c_str() );
+ impl.mController->GetText(text);
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p returning text: %s\n", impl.mController.Get(), text.c_str());
value = text;
break;
}
}
case Toolkit::TextEditor::Property::FONT_STYLE:
{
- GetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT );
+ GetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT);
break;
}
case Toolkit::TextEditor::Property::POINT_SIZE:
{
- value = impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE );
+ value = impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE);
break;
}
case Toolkit::TextEditor::Property::HORIZONTAL_ALIGNMENT:
{
- const char* name = GetHorizontalAlignmentString( impl.mController->GetHorizontalAlignment() );
- if( name )
+ const char* name = GetHorizontalAlignmentString(impl.mController->GetHorizontalAlignment());
+ if(name)
{
- value = std::string( name );
+ value = std::string(name);
}
break;
}
}
case Toolkit::TextEditor::Property::PRIMARY_CURSOR_COLOR:
{
- value = impl.mDecorator->GetColor( PRIMARY_CURSOR );
+ value = impl.mDecorator->GetColor(PRIMARY_CURSOR);
break;
}
case Toolkit::TextEditor::Property::SECONDARY_CURSOR_COLOR:
{
- value = impl.mDecorator->GetColor( SECONDARY_CURSOR );
+ value = impl.mDecorator->GetColor(SECONDARY_CURSOR);
break;
}
case Toolkit::TextEditor::Property::ENABLE_CURSOR_BLINK:
}
case Toolkit::TextEditor::Property::GRAB_HANDLE_IMAGE:
{
- value = impl.mDecorator->GetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_RELEASED );
+ value = impl.mDecorator->GetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextEditor::Property::GRAB_HANDLE_PRESSED_IMAGE:
{
- value = impl.mDecorator->GetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_PRESSED );
+ value = impl.mDecorator->GetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_PRESSED);
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_IMAGE_LEFT:
{
- impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED );
+ impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_IMAGE_RIGHT:
{
- impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED ) ;
+ impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_PRESSED_IMAGE_LEFT:
{
- impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED );
+ impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED);
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_PRESSED_IMAGE_RIGHT:
{
- impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED );
+ impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED);
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_MARKER_IMAGE_LEFT:
{
- impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED );
+ impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextEditor::Property::SELECTION_HANDLE_MARKER_IMAGE_RIGHT:
{
- impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED );
+ impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextEditor::Property::SELECTION_HIGHLIGHT_COLOR:
case Toolkit::TextEditor::Property::DECORATION_BOUNDING_BOX:
{
Rect<int> boundingBox;
- impl.mDecorator->GetBoundingBox( boundingBox );
+ impl.mDecorator->GetBoundingBox(boundingBox);
value = boundingBox;
break;
}
}
case Toolkit::TextEditor::Property::INPUT_FONT_STYLE:
{
- GetFontStyleProperty( impl.mController, value, Text::FontStyle::INPUT );
+ GetFontStyleProperty(impl.mController, value, Text::FontStyle::INPUT);
break;
}
case Toolkit::TextEditor::Property::INPUT_POINT_SIZE:
}
case Toolkit::TextEditor::Property::UNDERLINE:
{
- GetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextEditor::Property::INPUT_UNDERLINE:
{
- GetUnderlineProperties( impl.mController, value, Text::EffectStyle::INPUT );
+ GetUnderlineProperties(impl.mController, value, Text::EffectStyle::INPUT);
break;
}
case Toolkit::TextEditor::Property::SHADOW:
{
- GetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextEditor::Property::INPUT_SHADOW:
{
- GetShadowProperties( impl.mController, value, Text::EffectStyle::INPUT );
+ GetShadowProperties(impl.mController, value, Text::EffectStyle::INPUT);
break;
}
case Toolkit::TextEditor::Property::EMBOSS:
{
- GetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextEditor::Property::INPUT_EMBOSS:
{
- GetEmbossProperties( impl.mController, value, Text::EffectStyle::INPUT );
+ GetEmbossProperties(impl.mController, value, Text::EffectStyle::INPUT);
break;
}
case Toolkit::TextEditor::Property::OUTLINE:
{
- GetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextEditor::Property::INPUT_OUTLINE:
{
- GetOutlineProperties( impl.mController, value, Text::EffectStyle::INPUT );
+ GetOutlineProperties(impl.mController, value, Text::EffectStyle::INPUT);
break;
}
case Toolkit::TextEditor::Property::SMOOTH_SCROLL:
}
case Toolkit::TextEditor::Property::PIXEL_SIZE:
{
- value = impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE );
+ value = impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE);
break;
}
case Toolkit::TextEditor::Property::LINE_COUNT:
{
- float width = textEditor.GetProperty( Actor::Property::SIZE_WIDTH ).Get<float>();
- value = impl.mController->GetLineCount( width );
+ float width = textEditor.GetProperty(Actor::Property::SIZE_WIDTH).Get<float>();
+ value = impl.mController->GetLineCount(width);
break;
}
case Toolkit::DevelTextEditor::Property::PLACEHOLDER_TEXT:
{
std::string text;
- impl.mController->GetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text );
+ impl.mController->GetPlaceholderText(Controller::PLACEHOLDER_TYPE_INACTIVE, text);
value = text;
break;
}
case Toolkit::TextEditor::Property::PLACEHOLDER:
{
Property::Map map;
- impl.mController->GetPlaceholderProperty( map );
+ impl.mController->GetPlaceholderProperty(map);
value = map;
break;
}
}
case Toolkit::DevelTextEditor::Property::SELECTED_TEXT:
{
- value = impl.mController->GetSelectedText( );
+ value = impl.mController->GetSelectedText();
break;
}
case Toolkit::DevelTextEditor::Property::SELECTED_TEXT_START:
{
Uint32Pair range = impl.GetTextSelectionRange();
- value = static_cast<int>(range.first);
+ value = static_cast<int>(range.first);
break;
}
case Toolkit::DevelTextEditor::Property::SELECTED_TEXT_END:
{
Uint32Pair range = impl.GetTextSelectionRange();
- value = static_cast<int>(range.second);
+ value = static_cast<int>(range.second);
break;
}
case Toolkit::DevelTextEditor::Property::ENABLE_EDITING:
void TextEditor::SelectWholeText()
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
mController->SelectWholeText();
SetKeyInputFocus();
void TextEditor::SelectNone()
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
mController->SelectNone();
}
void TextEditor::ScrollBy(Vector2 scroll)
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
mController->ScrollBy(scroll);
}
float TextEditor::GetHorizontalScrollPosition()
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
return mController->GetHorizontalScrollPosition();
}
float TextEditor::GetVerticalScrollPosition()
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
return mController->GetVerticalScrollPosition();
}
string TextEditor::GetSelectedText() const
{
string selectedText = "";
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
- selectedText = mController->GetSelectedText( );
+ selectedText = mController->GetSelectedText();
}
return selectedText;
}
return mController;
}
-bool TextEditor::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool TextEditor::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::TextEditor editor = Toolkit::TextEditor::DownCast( handle );
+ bool connected(true);
+ Toolkit::TextEditor editor = Toolkit::TextEditor::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_TEXT_CHANGED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_TEXT_CHANGED))
{
- editor.TextChangedSignal().Connect( tracker, functor );
+ editor.TextChangedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED))
{
- editor.InputStyleChangedSignal().Connect( tracker, functor );
+ editor.InputStyleChangedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED))
{
- if( editor )
+ if(editor)
{
- Internal::TextEditor& editorImpl( GetImpl( editor ) );
- editorImpl.MaxLengthReachedSignal().Connect( tracker, functor );
+ Internal::TextEditor& editorImpl(GetImpl(editor));
+ editorImpl.MaxLengthReachedSignal().Connect(tracker, functor);
}
}
else
{
Actor self = Self();
- mController = Text::Controller::New( this, this, this);
+ mController = Text::Controller::New(this, this, this);
- mDecorator = Text::Decorator::New( *mController,
- *mController );
+ mDecorator = Text::Decorator::New(*mController,
+ *mController);
- mInputMethodContext = InputMethodContext::New( self );
+ mInputMethodContext = InputMethodContext::New(self);
- mController->GetLayoutEngine().SetLayout( Layout::Engine::MULTI_LINE_BOX );
+ mController->GetLayoutEngine().SetLayout(Layout::Engine::MULTI_LINE_BOX);
// Enables the text input.
- mController->EnableTextInput( mDecorator, mInputMethodContext );
+ mController->EnableTextInput(mDecorator, mInputMethodContext);
// Enables the vertical scrolling after the text input has been enabled.
- mController->SetVerticalScrollEnabled( true );
+ mController->SetVerticalScrollEnabled(true);
// Disables the horizontal scrolling.
- mController->SetHorizontalScrollEnabled( false );
+ mController->SetHorizontalScrollEnabled(false);
// Sets the maximum number of characters.
- mController->SetMaximumNumberOfCharacters( std::numeric_limits<Length>::max() );
+ mController->SetMaximumNumberOfCharacters(std::numeric_limits<Length>::max());
// Enable the smooth handle panning.
- mController->SetSmoothHandlePanEnabled( true );
+ mController->SetSmoothHandlePanEnabled(true);
- mController->SetNoTextDoubleTapAction( Controller::NoTextTap::HIGHLIGHT );
- mController->SetNoTextLongPressAction( Controller::NoTextTap::HIGHLIGHT );
+ mController->SetNoTextDoubleTapAction(Controller::NoTextTap::HIGHLIGHT);
+ mController->SetNoTextLongPressAction(Controller::NoTextTap::HIGHLIGHT);
// Sets layoutDirection value
- Dali::Stage stage = Dali::Stage::GetCurrent();
- Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>( stage.GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
- mController->SetLayoutDirection( layoutDirection );
+ Dali::Stage stage = Dali::Stage::GetCurrent();
+ Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
+ mController->SetLayoutDirection(layoutDirection);
// Forward input events to controller
- EnableGestureDetection( static_cast<GestureType::Value>( GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS ) );
- GetTapGestureDetector().SetMaximumTapsRequired( 2 );
+ EnableGestureDetection(static_cast<GestureType::Value>(GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS));
+ GetTapGestureDetector().SetMaximumTapsRequired(2);
- self.TouchedSignal().Connect( this, &TextEditor::OnTouched );
+ self.TouchedSignal().Connect(this, &TextEditor::OnTouched);
// Set BoundingBox to stage size if not already set.
Rect<int> boundingBox;
- mDecorator->GetBoundingBox( boundingBox );
+ mDecorator->GetBoundingBox(boundingBox);
- if( boundingBox.IsEmpty() )
+ if(boundingBox.IsEmpty())
{
Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
- mDecorator->SetBoundingBox( Rect<int>( 0.0f, 0.0f, stageSize.width, stageSize.height ) );
+ mDecorator->SetBoundingBox(Rect<int>(0.0f, 0.0f, stageSize.width, stageSize.height));
}
// Whether to flip the selection handles as soon as they cross.
- mDecorator->FlipSelectionHandlesOnCrossEnabled( true );
+ mDecorator->FlipSelectionHandlesOnCrossEnabled(true);
// Set the default scroll speed.
- mDecorator->SetScrollSpeed( DEFAULT_SCROLL_SPEED );
+ mDecorator->SetScrollSpeed(DEFAULT_SCROLL_SPEED);
// Fill-parent area by default
- self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
- self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT );
- self.OnSceneSignal().Connect( this, &TextEditor::OnSceneConnect );
+ self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
+ self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
+ self.OnSceneSignal().Connect(this, &TextEditor::OnSceneConnect);
//Enable highightability
- self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true );
+ self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
- DevelControl::SetInputMethodContext( *this, mInputMethodContext );
+ DevelControl::SetInputMethodContext(*this, mInputMethodContext);
// Creates an extra control to be used as stencil buffer.
mStencil = Control::New();
- mStencil.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- mStencil.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
+ mStencil.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ mStencil.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
// Creates a background visual. Even if the color is transparent it updates the stencil.
- mStencil.SetProperty( Toolkit::Control::Property::BACKGROUND,
- Property::Map().Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR ).
- Add( ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT ) );
+ mStencil.SetProperty(Toolkit::Control::Property::BACKGROUND,
+ Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT));
// Enable the clipping property.
- mStencil.SetProperty( Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX );
- mStencil.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mStencil.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX);
+ mStencil.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
- self.Add( mStencil );
+ self.Add(mStencil);
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::ENTRY ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::ENTRY));
+ });
}
-void TextEditor::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
+void TextEditor::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnStyleChange\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnStyleChange\n");
- switch ( change )
+ switch(change)
{
case StyleChange::DEFAULT_FONT_CHANGE:
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnStyleChange DEFAULT_FONT_CHANGE\n");
- const std::string& newFont = GetImpl( styleManager ).GetDefaultFontFamily();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnStyleChange DEFAULT_FONT_CHANGE\n");
+ const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily();
// Property system did not set the font so should update it.
- mController->UpdateAfterFontChange( newFont );
+ mController->UpdateAfterFontChange(newFont);
RelayoutRequest();
break;
}
case StyleChange::DEFAULT_FONT_SIZE_CHANGE:
{
- GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
+ GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner()));
RelayoutRequest();
break;
}
}
// Up call to Control
- Control::OnStyleChange( styleManager, change );
+ Control::OnStyleChange(styleManager, change);
}
Vector3 TextEditor::GetNaturalSize()
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
Vector3 naturalSize = mController->GetNaturalSize();
- naturalSize.width += ( padding.start + padding.end );
- naturalSize.height += ( padding.top + padding.bottom );
+ naturalSize.width += (padding.start + padding.end);
+ naturalSize.height += (padding.top + padding.bottom);
return naturalSize;
}
-float TextEditor::GetHeightForWidth( float width )
+float TextEditor::GetHeightForWidth(float width)
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
- return mController->GetHeightForWidth( width ) + padding.top + padding.bottom;
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
+ return mController->GetHeightForWidth(width) + padding.top + padding.bottom;
}
-void TextEditor::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void TextEditor::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor OnRelayout\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor OnRelayout\n");
Actor self = Self();
Extents padding;
- padding = self.GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = self.GetProperty<Extents>(Toolkit::Control::Property::PADDING);
- Vector2 contentSize( size.x - ( padding.start + padding.end ), size.y - ( padding.top + padding.bottom ) );
+ Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom));
// Support Right-To-Left of padding
Dali::LayoutDirection::Type layoutDirection;
- if( mController->IsMatchSystemLanguageDirection() )
+ if(mController->IsMatchSystemLanguageDirection())
{
- layoutDirection = static_cast<Dali::LayoutDirection::Type>( DevelWindow::Get( self ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ layoutDirection = static_cast<Dali::LayoutDirection::Type>(DevelWindow::Get(self).GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
}
else
{
- layoutDirection = static_cast<Dali::LayoutDirection::Type>( self.GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ layoutDirection = static_cast<Dali::LayoutDirection::Type>(self.GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
}
- if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
+ if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
{
- std::swap( padding.start, padding.end );
+ std::swap(padding.start, padding.end);
}
- if( mStencil )
+ if(mStencil)
{
- mStencil.SetProperty( Actor::Property::POSITION, Vector2( padding.start, padding.top ));
+ mStencil.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
}
- if( mActiveLayer )
+ if(mActiveLayer)
{
- mActiveLayer.SetProperty( Actor::Property::POSITION, Vector2( padding.start, padding.top ));
+ mActiveLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
}
- const Text::Controller::UpdateTextType updateTextType = mController->Relayout( contentSize, layoutDirection );
+ const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection);
- if( ( Text::Controller::NONE_UPDATED != updateTextType ) ||
- !mRenderer )
+ if((Text::Controller::NONE_UPDATED != updateTextType) ||
+ !mRenderer)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnRelayout %p Displaying new contents\n", mController.Get() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnRelayout %p Displaying new contents\n", mController.Get());
- if( mDecorator &&
- ( Text::Controller::NONE_UPDATED != ( Text::Controller::DECORATOR_UPDATED & updateTextType ) ) )
+ if(mDecorator &&
+ (Text::Controller::NONE_UPDATED != (Text::Controller::DECORATOR_UPDATED & updateTextType)))
{
- mDecorator->Relayout( size );
+ mDecorator->Relayout(size);
}
- if( !mRenderer )
+ if(!mRenderer)
{
- mRenderer = Backend::Get().NewRenderer( mRenderingBackend );
+ mRenderer = Backend::Get().NewRenderer(mRenderingBackend);
}
- RenderText( updateTextType );
-
+ RenderText(updateTextType);
}
// The text-editor emits signals when the input style changes. These changes of style are
// detected during the relayout process (size negotiation), i.e after the cursor has been moved. Signals
// can't be emitted during the size negotiation as the callbacks may update the UI.
// The text-editor adds an idle callback to the adaptor to emit the signals after the size negotiation.
- if( !mController->IsInputStyleChangedSignalsQueueEmpty() )
+ if(!mController->IsInputStyleChangedSignalsQueueEmpty())
{
- if( Adaptor::IsAvailable() )
+ if(Adaptor::IsAvailable())
{
Adaptor& adaptor = Adaptor::Get();
- if( NULL == mIdleCallback )
+ if(NULL == mIdleCallback)
{
// @note: The callback manager takes the ownership of the callback object.
- mIdleCallback = MakeCallback( this, &TextEditor::OnIdleSignal );
- adaptor.AddIdle( mIdleCallback, false );
+ mIdleCallback = MakeCallback(this, &TextEditor::OnIdleSignal);
+ adaptor.AddIdle(mIdleCallback, false);
}
}
}
}
-void TextEditor::RenderText( Text::Controller::UpdateTextType updateTextType )
+void TextEditor::RenderText(Text::Controller::UpdateTextType updateTextType)
{
Actor renderableActor;
- if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) )
+ if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType))
{
- if( mRenderer )
+ if(mRenderer)
{
- Dali::Toolkit::TextEditor handle = Dali::Toolkit::TextEditor( GetOwner() );
+ Dali::Toolkit::TextEditor handle = Dali::Toolkit::TextEditor(GetOwner());
- renderableActor = mRenderer->Render( mController->GetView(),
- handle,
- Property::INVALID_INDEX, // Animatable property not supported
- mAlignmentOffset,
- DepthIndex::CONTENT );
+ renderableActor = mRenderer->Render(mController->GetView(),
+ handle,
+ Property::INVALID_INDEX, // Animatable property not supported
+ mAlignmentOffset,
+ DepthIndex::CONTENT);
}
- if( renderableActor != mRenderableActor )
+ if(renderableActor != mRenderableActor)
{
- UnparentAndReset( mRenderableActor );
+ UnparentAndReset(mRenderableActor);
mRenderableActor = renderableActor;
}
}
- if( mRenderableActor )
+ if(mRenderableActor)
{
// Make sure the actors are parented correctly with/without clipping
Actor self = mStencil ? mStencil : Self();
- for( std::vector<Actor>::iterator it = mClippingDecorationActors.begin(),
- endIt = mClippingDecorationActors.end();
- it != endIt;
- ++it )
+ for(std::vector<Actor>::iterator it = mClippingDecorationActors.begin(),
+ endIt = mClippingDecorationActors.end();
+ it != endIt;
+ ++it)
{
- self.Add( *it );
+ self.Add(*it);
it->LowerToBottom();
}
mClippingDecorationActors.clear();
- self.Add( mRenderableActor );
+ self.Add(mRenderableActor);
ApplyScrollPosition();
}
void TextEditor::OnKeyInputFocusGained()
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnKeyInputFocusGained %p\n", mController.Get() );
- if ( mInputMethodContext && IsEditable() )
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnKeyInputFocusGained %p\n", mController.Get());
+ if(mInputMethodContext && IsEditable())
{
// All input panel properties, such as layout, return key type, and input hint, should be set before input panel activates (or shows).
- mInputMethodContext.NotifyTextInputMultiLine( true );
+ mInputMethodContext.NotifyTextInputMultiLine(true);
- mInputMethodContext.StatusChangedSignal().Connect( this, &TextEditor::KeyboardStatusChanged );
+ mInputMethodContext.StatusChangedSignal().Connect(this, &TextEditor::KeyboardStatusChanged);
- mInputMethodContext.EventReceivedSignal().Connect( this, &TextEditor::OnInputMethodContextEvent );
+ mInputMethodContext.EventReceivedSignal().Connect(this, &TextEditor::OnInputMethodContextEvent);
// Notify that the text editing start.
mInputMethodContext.Activate();
// When window gain lost focus, the InputMethodContext is deactivated. Thus when window gain focus again, the InputMethodContext must be activated.
- mInputMethodContext.SetRestoreAfterFocusLost( true );
+ mInputMethodContext.SetRestoreAfterFocusLost(true);
}
- ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
+ ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
- if ( notifier )
+ if(notifier)
{
- notifier.ContentSelectedSignal().Connect( this, &TextEditor::OnClipboardTextSelected );
+ notifier.ContentSelectedSignal().Connect(this, &TextEditor::OnClipboardTextSelected);
}
mController->KeyboardFocusGainEvent(); // Called in the case of no virtual keyboard to trigger this event
- EmitKeyInputFocusSignal( true ); // Calls back into the Control hence done last.
+ EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last.
}
void TextEditor::OnKeyInputFocusLost()
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor:OnKeyInputFocusLost %p\n", mController.Get() );
- if ( mInputMethodContext )
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor:OnKeyInputFocusLost %p\n", mController.Get());
+ if(mInputMethodContext)
{
- mInputMethodContext.StatusChangedSignal().Disconnect( this, &TextEditor::KeyboardStatusChanged );
+ mInputMethodContext.StatusChangedSignal().Disconnect(this, &TextEditor::KeyboardStatusChanged);
// The text editing is finished. Therefore the InputMethodContext don't have restore activation.
- mInputMethodContext.SetRestoreAfterFocusLost( false );
+ mInputMethodContext.SetRestoreAfterFocusLost(false);
// Notify that the text editing finish.
mInputMethodContext.Deactivate();
- mInputMethodContext.EventReceivedSignal().Disconnect( this, &TextEditor::OnInputMethodContextEvent );
+ mInputMethodContext.EventReceivedSignal().Disconnect(this, &TextEditor::OnInputMethodContextEvent);
}
- ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
+ ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
- if ( notifier )
+ if(notifier)
{
- notifier.ContentSelectedSignal().Disconnect( this, &TextEditor::OnClipboardTextSelected );
+ notifier.ContentSelectedSignal().Disconnect(this, &TextEditor::OnClipboardTextSelected);
}
mController->KeyboardFocusLostEvent();
- EmitKeyInputFocusSignal( false ); // Calls back into the Control hence done last.
+ EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last.
}
bool TextEditor::OnAccessibilityActivated()
return true;
}
-void TextEditor::OnTap( const TapGesture& gesture )
+void TextEditor::OnTap(const TapGesture& gesture)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnTap %p\n", mController.Get() );
- if ( mInputMethodContext && IsEditable() )
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnTap %p\n", mController.Get());
+ if(mInputMethodContext && IsEditable())
{
mInputMethodContext.Activate();
}
// Deliver the tap before the focus event to controller; this allows us to detect when focus is gained due to tap-gestures
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
const Vector2& localPoint = gesture.GetLocalPoint();
- mController->TapEvent( gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top );
+ mController->TapEvent(gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top);
SetKeyInputFocus();
}
-void TextEditor::OnPan( const PanGesture& gesture )
+void TextEditor::OnPan(const PanGesture& gesture)
{
- mController->PanEvent( gesture.GetState(), gesture.GetDisplacement() );
+ mController->PanEvent(gesture.GetState(), gesture.GetDisplacement());
}
-void TextEditor::OnLongPress( const LongPressGesture& gesture )
+void TextEditor::OnLongPress(const LongPressGesture& gesture)
{
- if ( mInputMethodContext && IsEditable() )
+ if(mInputMethodContext && IsEditable())
{
mInputMethodContext.Activate();
}
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
const Vector2& localPoint = gesture.GetLocalPoint();
- mController->LongPressEvent( gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top );
+ mController->LongPressEvent(gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top);
SetKeyInputFocus();
}
-bool TextEditor::OnKeyEvent( const KeyEvent& event )
+bool TextEditor::OnKeyEvent(const KeyEvent& event)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode());
- if( Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape() )
+ if(Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape())
{
// Make sure ClearKeyInputFocus when only key is up
- if( event.GetState() == KeyEvent::UP )
+ if(event.GetState() == KeyEvent::UP)
{
ClearKeyInputFocus();
}
return true;
}
- return mController->KeyEvent( event );
+ return mController->KeyEvent(event);
}
void TextEditor::RequestTextRelayout()
RelayoutRequest();
}
-void TextEditor::TextInserted( unsigned int position, unsigned int length, const std::string &content )
+void TextEditor::TextInserted(unsigned int position, unsigned int length, const std::string& content)
{
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
- Control::Impl::GetAccessibilityObject( Self() )->EmitTextInserted( position, length, content );
+ Control::Impl::GetAccessibilityObject(Self())->EmitTextInserted(position, length, content);
}
}
-void TextEditor::TextDeleted( unsigned int position, unsigned int length, const std::string &content )
+void TextEditor::TextDeleted(unsigned int position, unsigned int length, const std::string& content)
{
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
- Control::Impl::GetAccessibilityObject( Self() )->EmitTextDeleted( position, length, content );
+ Control::Impl::GetAccessibilityObject(Self())->EmitTextDeleted(position, length, content);
}
}
-void TextEditor::CaretMoved( unsigned int position )
+void TextEditor::CaretMoved(unsigned int position)
{
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
- Control::Impl::GetAccessibilityObject( Self() )->EmitTextCaretMoved( position );
+ Control::Impl::GetAccessibilityObject(Self())->EmitTextCaretMoved(position);
}
}
void TextEditor::TextChanged()
{
- Dali::Toolkit::TextEditor handle( GetOwner() );
- mTextChangedSignal.Emit( handle );
+ Dali::Toolkit::TextEditor handle(GetOwner());
+ mTextChangedSignal.Emit(handle);
}
void TextEditor::MaxLengthReached()
{
- Dali::Toolkit::TextEditor handle( GetOwner() );
- mMaxLengthReachedSignal.Emit( handle );
+ Dali::Toolkit::TextEditor handle(GetOwner());
+ mMaxLengthReachedSignal.Emit(handle);
}
-void TextEditor::InputStyleChanged( Text::InputStyle::Mask inputStyleMask )
+void TextEditor::InputStyleChanged(Text::InputStyle::Mask inputStyleMask)
{
- Dali::Toolkit::TextEditor handle( GetOwner() );
+ Dali::Toolkit::TextEditor handle(GetOwner());
Toolkit::TextEditor::InputStyle::Mask editorInputStyleMask = Toolkit::TextEditor::InputStyle::NONE;
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_COLOR ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_COLOR))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::COLOR );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::COLOR);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_FONT_FAMILY ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_FAMILY))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_FAMILY );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_FAMILY);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_POINT_SIZE ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_POINT_SIZE))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::POINT_SIZE );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::POINT_SIZE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_FONT_WEIGHT ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_WEIGHT))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_FONT_WIDTH ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_WIDTH))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_FONT_SLANT ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_SLANT))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_LINE_SPACING ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_LINE_SPACING))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::LINE_SPACING );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::LINE_SPACING);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_UNDERLINE ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_UNDERLINE))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::UNDERLINE );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::UNDERLINE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_SHADOW ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_SHADOW))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::SHADOW );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::SHADOW);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_EMBOSS ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_EMBOSS))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::EMBOSS );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::EMBOSS);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_OUTLINE ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_OUTLINE))
{
- editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>( editorInputStyleMask | Toolkit::TextEditor::InputStyle::OUTLINE );
+ editorInputStyleMask = static_cast<Toolkit::TextEditor::InputStyle::Mask>(editorInputStyleMask | Toolkit::TextEditor::InputStyle::OUTLINE);
}
- mInputStyleChangedSignal.Emit( handle, editorInputStyleMask );
+ mInputStyleChangedSignal.Emit(handle, editorInputStyleMask);
}
-void TextEditor::AddDecoration( Actor& actor, bool needsClipping )
+void TextEditor::AddDecoration(Actor& actor, bool needsClipping)
{
- if( actor )
+ if(actor)
{
- if( needsClipping )
+ if(needsClipping)
{
- mClippingDecorationActors.push_back( actor );
+ mClippingDecorationActors.push_back(actor);
}
else
{
- actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- Self().Add( actor );
+ actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ Self().Add(actor);
mActiveLayer = actor;
}
}
}
-void TextEditor::SetTextSelectionRange(const uint32_t *start, const uint32_t *end)
+void TextEditor::SetTextSelectionRange(const uint32_t* start, const uint32_t* end)
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
- mController->SetTextSelectionRange( start, end );
+ mController->SetTextSelectionRange(start, end);
SetKeyInputFocus();
}
}
Uint32Pair TextEditor::GetTextSelectionRange() const
{
Uint32Pair range(0, 0);
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
range = mController->GetTextSelectionRange();
}
float scrollPosition;
float controlSize;
float layoutSize;
- bool latestScrolled;
+ bool latestScrolled;
- if ( !mScrollBarEnabled )
+ if(!mScrollBarEnabled)
{
return;
}
- latestScrolled = mController->GetTextScrollInfo( scrollPosition, controlSize, layoutSize );
- if ( !latestScrolled || controlSize > layoutSize)
+ latestScrolled = mController->GetTextScrollInfo(scrollPosition, controlSize, layoutSize);
+ if(!latestScrolled || controlSize > layoutSize)
{
return;
}
CustomActor self = Self();
- if( !mScrollBar )
+ if(!mScrollBar)
{
- mScrollBar = Toolkit::ScrollBar::New( Toolkit::ScrollBar::VERTICAL );
- mScrollBar.SetIndicatorHeightPolicy( Toolkit::ScrollBar::VARIABLE );
- mScrollBar.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT );
- mScrollBar.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT );
- mScrollBar.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT );
- mScrollBar.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH );
+ mScrollBar = Toolkit::ScrollBar::New(Toolkit::ScrollBar::VERTICAL);
+ mScrollBar.SetIndicatorHeightPolicy(Toolkit::ScrollBar::VARIABLE);
+ mScrollBar.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT);
+ mScrollBar.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT);
+ mScrollBar.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
+ mScrollBar.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH);
// Register the scroll position property
- Property::Index propertyScrollPosition = self.RegisterProperty( SCROLL_BAR_POSITION, scrollPosition );
+ Property::Index propertyScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION, scrollPosition);
// Register the minimum scroll position property
- Property::Index propertyMinScrollPosition = self.RegisterProperty( SCROLL_BAR_POSITION_MIN, 0.0f );
+ Property::Index propertyMinScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION_MIN, 0.0f);
// Register the maximum scroll position property
- Property::Index propertyMaxScrollPosition = self.RegisterProperty( SCROLL_BAR_POSITION_MAX, (layoutSize - controlSize) );
+ Property::Index propertyMaxScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION_MAX, (layoutSize - controlSize));
// Register the scroll content size property
- Property::Index propertyScrollContentSize = self.RegisterProperty( SCROLL_BAR_CONTENT_SIZE, layoutSize );
+ Property::Index propertyScrollContentSize = self.RegisterProperty(SCROLL_BAR_CONTENT_SIZE, layoutSize);
mScrollBar.SetScrollPropertySource(self, propertyScrollPosition, propertyMinScrollPosition, propertyMaxScrollPosition, propertyScrollContentSize);
// Set style name of ScrollBar for styling
mScrollBar.SetStyleName("TextEditorScrollBar");
- Toolkit::Control scrollIndicator = Toolkit::Control::DownCast( mScrollBar.GetScrollIndicator() );
- if( scrollIndicator )
+ Toolkit::Control scrollIndicator = Toolkit::Control::DownCast(mScrollBar.GetScrollIndicator());
+ if(scrollIndicator)
{
// Set style name of ScrollBarIndicator for styling
scrollIndicator.SetStyleName("TextEditorScrollBarIndicator");
}
- self.Add( mScrollBar );
+ self.Add(mScrollBar);
}
else
{
- Property::Index propertyScrollPosition = self.GetPropertyIndex( SCROLL_BAR_POSITION );
- Property::Index propertyMaxScrollPosition = self.GetPropertyIndex( SCROLL_BAR_POSITION_MAX );
- Property::Index propertyScrollContentSize = self.GetPropertyIndex( SCROLL_BAR_CONTENT_SIZE );
+ Property::Index propertyScrollPosition = self.GetPropertyIndex(SCROLL_BAR_POSITION);
+ Property::Index propertyMaxScrollPosition = self.GetPropertyIndex(SCROLL_BAR_POSITION_MAX);
+ Property::Index propertyScrollContentSize = self.GetPropertyIndex(SCROLL_BAR_CONTENT_SIZE);
- self.SetProperty( propertyScrollPosition, scrollPosition );
- self.SetProperty( propertyMaxScrollPosition, (layoutSize - controlSize) );
- self.SetProperty( propertyScrollContentSize, layoutSize );
+ self.SetProperty(propertyScrollPosition, scrollPosition);
+ self.SetProperty(propertyMaxScrollPosition, (layoutSize - controlSize));
+ self.SetProperty(propertyScrollContentSize, layoutSize);
}
// If scrolling is not started, start scrolling and emit ScrollStateChangedSignal
- if( !mScrollStarted )
+ if(!mScrollStarted)
{
mScrollStarted = true;
- Dali::Toolkit::TextEditor handle( GetOwner() );
- mScrollStateChangedSignal.Emit( handle, Toolkit::TextEditor::Scroll::STARTED );
+ Dali::Toolkit::TextEditor handle(GetOwner());
+ mScrollStateChangedSignal.Emit(handle, Toolkit::TextEditor::Scroll::STARTED);
}
Actor indicator = mScrollBar.GetScrollIndicator();
- if( mAnimation )
+ if(mAnimation)
{
mAnimation.Stop(); // Cancel any animation
}
else
{
- mAnimation = Animation::New( mAnimationPeriod.durationSeconds );
+ mAnimation = Animation::New(mAnimationPeriod.durationSeconds);
}
- indicator.SetProperty( Actor::Property::OPACITY,1.0f);
- mAnimation.AnimateTo( Property( indicator, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN, mAnimationPeriod );
+ indicator.SetProperty(Actor::Property::OPACITY, 1.0f);
+ mAnimation.AnimateTo(Property(indicator, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN, mAnimationPeriod);
mAnimation.Play();
- mAnimation.FinishedSignal().Connect( this, &TextEditor::OnScrollIndicatorAnimationFinished );
+ mAnimation.FinishedSignal().Connect(this, &TextEditor::OnScrollIndicatorAnimationFinished);
}
-void TextEditor::OnScrollIndicatorAnimationFinished( Animation& animation )
+void TextEditor::OnScrollIndicatorAnimationFinished(Animation& animation)
{
// If animation is successfully ended, then emit ScrollStateChangedSignal
- if( animation.GetCurrentProgress() == 0.0f )
+ if(animation.GetCurrentProgress() == 0.0f)
{
mScrollStarted = false;
- Dali::Toolkit::TextEditor handle( GetOwner() );
- mScrollStateChangedSignal.Emit( handle, Toolkit::TextEditor::Scroll::FINISHED );
+ Dali::Toolkit::TextEditor handle(GetOwner());
+ mScrollStateChangedSignal.Emit(handle, Toolkit::TextEditor::Scroll::FINISHED);
}
}
-void TextEditor::OnSceneConnect( Dali::Actor actor )
+void TextEditor::OnSceneConnect(Dali::Actor actor)
{
- if ( mHasBeenStaged )
+ if(mHasBeenStaged)
{
- RenderText( static_cast<Text::Controller::UpdateTextType>( Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED ) );
+ RenderText(static_cast<Text::Controller::UpdateTextType>(Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED));
}
else
{
}
}
-InputMethodContext::CallbackData TextEditor::OnInputMethodContextEvent( Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent )
+InputMethodContext::CallbackData TextEditor::OnInputMethodContextEvent(Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName );
- return mController->OnInputMethodContextEvent( inputMethodContext, inputMethodContextEvent );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName);
+ return mController->OnInputMethodContextEvent(inputMethodContext, inputMethodContextEvent);
}
-void TextEditor::GetHandleImagePropertyValue( Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType )
+void TextEditor::GetHandleImagePropertyValue(Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType)
{
- if( mDecorator )
+ if(mDecorator)
{
Property::Map map;
- map[ IMAGE_MAP_FILENAME_STRING ] = mDecorator->GetHandleImage( handleType, handleImageType );
- value = map;
+ map[IMAGE_MAP_FILENAME_STRING] = mDecorator->GetHandleImage(handleType, handleImageType);
+ value = map;
}
}
-void TextEditor::OnClipboardTextSelected( ClipboardEventNotifier& clipboard )
+void TextEditor::OnClipboardTextSelected(ClipboardEventNotifier& clipboard)
{
mController->PasteClipboardItemEvent();
}
void TextEditor::KeyboardStatusChanged(bool keyboardShown)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown);
// Just hide the grab handle when keyboard is hidden.
- if (!keyboardShown )
+ if(!keyboardShown)
{
mController->KeyboardFocusLostEvent();
}
}
}
-void TextEditor::OnSceneConnection( int depth )
+void TextEditor::OnSceneConnection(int depth)
{
// Sets the depth to the visuals inside the text's decorator.
- mDecorator->SetTextDepth( depth );
+ mDecorator->SetTextDepth(depth);
// The depth of the text renderer is set in the RenderText() called from OnRelayout().
// Call the Control::OnSceneConnection() to set the depth of the background.
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
}
-bool TextEditor::OnTouched( Actor actor, const TouchEvent& touch )
+bool TextEditor::OnTouched(Actor actor, const TouchEvent& touch)
{
return false;
}
void TextEditor::ApplyScrollPosition()
{
const Vector2& scrollOffset = mController->GetTextModel()->GetScrollPosition();
- float scrollAmount = 0.0f;
+ float scrollAmount = 0.0f;
- if ( mScrollAnimationEnabled )
+ if(mScrollAnimationEnabled)
{
scrollAmount = mController->GetScrollAmountByUserInput();
}
- if ( mTextVerticalScroller )
+ if(mTextVerticalScroller)
{
- mTextVerticalScroller->CheckStartAnimation( mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount );
+ mTextVerticalScroller->CheckStartAnimation(mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount);
}
- else if ( Equals( scrollAmount, 0.0f, Math::MACHINE_EPSILON_1 ))
+ else if(Equals(scrollAmount, 0.0f, Math::MACHINE_EPSILON_1))
{
- mRenderableActor.SetProperty( Actor::Property::POSITION, Vector2( scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount ));
+ mRenderableActor.SetProperty(Actor::Property::POSITION, Vector2(scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount));
}
else
{
mTextVerticalScroller = Text::TextVerticalScroller::New();
- if ( !Equals( mScrollAnimationDuration, 0.0f, Math::MACHINE_EPSILON_1 ))
+ if(!Equals(mScrollAnimationDuration, 0.0f, Math::MACHINE_EPSILON_1))
{
- mTextVerticalScroller->SetDuration( mScrollAnimationDuration );
+ mTextVerticalScroller->SetDuration(mScrollAnimationDuration);
}
- mTextVerticalScroller->CheckStartAnimation( mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount );
+ mTextVerticalScroller->CheckStartAnimation(mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount);
}
}
return mController->IsEditable();
}
-void TextEditor::SetEditable( bool editable )
+void TextEditor::SetEditable(bool editable)
{
mController->SetEditable(editable);
- if ( mInputMethodContext && !editable )
+ if(mInputMethodContext && !editable)
{
mInputMethodContext.Deactivate();
}
}
TextEditor::TextEditor()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mAnimationPeriod( 0.0f, 0.0f ),
- mIdleCallback( NULL ),
- mAlignmentOffset( 0.f ),
- mScrollAnimationDuration( 0.f ),
- mLineSpacing( 0.f ),
- mRenderingBackend( DEFAULT_RENDERING_BACKEND ),
- mHasBeenStaged( false ),
- mScrollAnimationEnabled( false ),
- mScrollBarEnabled( false ),
- mScrollStarted( false )
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mAnimationPeriod(0.0f, 0.0f),
+ mIdleCallback(NULL),
+ mAlignmentOffset(0.f),
+ mScrollAnimationDuration(0.f),
+ mLineSpacing(0.f),
+ mRenderingBackend(DEFAULT_RENDERING_BACKEND),
+ mHasBeenStaged(false),
+ mScrollAnimationEnabled(false),
+ mScrollBarEnabled(false),
+ mScrollStarted(false)
{
}
TextEditor::~TextEditor()
{
- UnparentAndReset( mStencil );
+ UnparentAndReset(mStencil);
- if( ( NULL != mIdleCallback ) && Adaptor::IsAvailable() )
+ if((NULL != mIdleCallback) && Adaptor::IsAvailable())
{
// Removes the callback from the callback manager in case the text-editor is destroyed before the callback is executed.
- Adaptor::Get().RemoveIdle( mIdleCallback );
+ Adaptor::Get().RemoveIdle(mIdleCallback);
}
}
std::string TextEditor::AccessibleImpl::GetName()
{
- auto slf = Toolkit::TextEditor::DownCast( self );
- return slf.GetProperty( Toolkit::TextEditor::Property::TEXT )
- .Get< std::string >();
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ return slf.GetProperty(Toolkit::TextEditor::Property::TEXT)
+ .Get<std::string>();
}
-std::string TextEditor::AccessibleImpl::GetText( size_t startOffset,
- size_t endOffset )
+std::string TextEditor::AccessibleImpl::GetText(size_t startOffset,
+ size_t endOffset)
{
- if( endOffset <= startOffset )
+ if(endOffset <= startOffset)
return {};
- auto slf = Toolkit::TextEditor::DownCast( self );
+ auto slf = Toolkit::TextEditor::DownCast(self);
auto txt =
- slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get< std::string >();
+ slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get<std::string>();
- if( startOffset > txt.size() || endOffset > txt.size() )
+ if(startOffset > txt.size() || endOffset > txt.size())
return {};
- return txt.substr( startOffset, endOffset - startOffset );
+ return txt.substr(startOffset, endOffset - startOffset);
}
size_t TextEditor::AccessibleImpl::GetCharacterCount()
{
- auto slf = Toolkit::TextEditor::DownCast( self );
+ auto slf = Toolkit::TextEditor::DownCast(self);
auto txt =
- slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get< std::string >();
+ slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get<std::string>();
return txt.size();
}
size_t TextEditor::AccessibleImpl::GetCaretOffset()
{
- auto slf = Toolkit::TextEditor::DownCast( self );
- return Dali::Toolkit::GetImpl( slf ).getController()->GetCursorPosition();
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ return Dali::Toolkit::GetImpl(slf).getController()->GetCursorPosition();
}
bool TextEditor::AccessibleImpl::SetCaretOffset(size_t offset)
{
- auto slf = Toolkit::TextEditor::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get< std::string >();
- if (offset > txt.size())
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get<std::string>();
+ if(offset > txt.size())
return false;
- auto& slfImpl = Dali::Toolkit::GetImpl( slf );
- slfImpl.getController()->ResetCursorPosition( offset );
+ auto& slfImpl = Dali::Toolkit::GetImpl(slf);
+ slfImpl.getController()->ResetCursorPosition(offset);
slfImpl.RequestTextRelayout();
return true;
}
Dali::Accessibility::Range TextEditor::AccessibleImpl::GetTextAtOffset(
- size_t offset, Dali::Accessibility::TextBoundary boundary )
+ size_t offset, Dali::Accessibility::TextBoundary boundary)
{
- auto slf = Toolkit::TextEditor::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get< std::string >();
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get<std::string>();
auto txt_size = txt.size();
auto range = Dali::Accessibility::Range{};
switch(boundary)
{
case Dali::Accessibility::TextBoundary::CHARACTER:
+ {
+ if(offset < txt_size)
{
- if (offset < txt_size)
- {
- range.content = txt[offset];
- range.startOffset = offset;
- range.endOffset = offset + 1;
- }
+ range.content = txt[offset];
+ range.startOffset = offset;
+ range.endOffset = offset + 1;
}
- break;
+ }
+ break;
case Dali::Accessibility::TextBoundary::WORD:
case Dali::Accessibility::TextBoundary::LINE:
- {
- auto txt_c_string = txt.c_str();
- auto breaks = std::vector< char >( txt_size, 0 );
- if(boundary == Dali::Accessibility::TextBoundary::WORD)
- Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data());
+ {
+ auto txt_c_string = txt.c_str();
+ auto breaks = std::vector<char>(txt_size, 0);
+ if(boundary == Dali::Accessibility::TextBoundary::WORD)
+ Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data());
+ else
+ Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data());
+ auto index = 0u;
+ auto counter = 0u;
+ while(index < txt_size && counter <= offset)
+ {
+ auto start = index;
+ if(breaks[index])
+ {
+ while(breaks[index])
+ index++;
+ counter++;
+ }
else
- Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data());
- auto index = 0u;
- auto counter = 0u;
- while( index < txt_size && counter <= offset )
{
- auto start = index;
- if(breaks[index])
- {
- while(breaks[index])
- index++;
+ if(boundary == Dali::Accessibility::TextBoundary::WORD)
+ index++;
+ if(boundary == Dali::Accessibility::TextBoundary::LINE)
counter++;
- }
- else
- {
- if (boundary == Dali::Accessibility::TextBoundary::WORD)
- index++;
- if (boundary == Dali::Accessibility::TextBoundary::LINE)
- counter++;
- }
- if ((counter > 0) && ((counter - 1) == offset))
- {
- range.content = txt.substr(start, index - start + 1);
- range.startOffset = start;
- range.endOffset = index + 1;
- }
- if (boundary == Dali::Accessibility::TextBoundary::LINE)
- index++;
}
+ if((counter > 0) && ((counter - 1) == offset))
+ {
+ range.content = txt.substr(start, index - start + 1);
+ range.startOffset = start;
+ range.endOffset = index + 1;
+ }
+ if(boundary == Dali::Accessibility::TextBoundary::LINE)
+ index++;
}
- break;
+ }
+ break;
case Dali::Accessibility::TextBoundary::SENTENCE:
- {
- /* not supported by efl */
- }
- break;
+ {
+ /* not supported by efl */
+ }
+ break;
case Dali::Accessibility::TextBoundary::PARAGRAPH:
- {
- /* Paragraph is not supported by libunibreak library */
- }
- break;
+ {
+ /* Paragraph is not supported by libunibreak library */
+ }
+ break;
default:
break;
}
}
Dali::Accessibility::Range
-TextEditor::AccessibleImpl::GetSelection( size_t selectionNum )
+TextEditor::AccessibleImpl::GetSelection(size_t selectionNum)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return {};
- auto slf = Toolkit::TextEditor::DownCast( self );
- auto ctrl = Dali::Toolkit::GetImpl( slf ).getController();
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ auto ctrl = Dali::Toolkit::GetImpl(slf).getController();
std::string ret;
- ctrl->RetrieveSelection( ret );
+ ctrl->RetrieveSelection(ret);
auto r = ctrl->GetSelectionIndexes();
- return { static_cast<size_t>(r.first), static_cast<size_t>(r.second), ret };
+ return {static_cast<size_t>(r.first), static_cast<size_t>(r.second), ret};
}
-bool TextEditor::AccessibleImpl::RemoveSelection( size_t selectionNum )
+bool TextEditor::AccessibleImpl::RemoveSelection(size_t selectionNum)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return false;
- auto slf = Toolkit::TextEditor::DownCast( self );
- Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( 0, 0 );
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ Dali::Toolkit::GetImpl(slf).getController()->SetSelection(0, 0);
return true;
}
-bool TextEditor::AccessibleImpl::SetSelection( size_t selectionNum,
- size_t startOffset,
- size_t endOffset )
+bool TextEditor::AccessibleImpl::SetSelection(size_t selectionNum,
+ size_t startOffset,
+ size_t endOffset)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return false;
- auto slf = Toolkit::TextEditor::DownCast( self );
- Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( startOffset,
- endOffset );
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ Dali::Toolkit::GetImpl(slf).getController()->SetSelection(startOffset,
+ endOffset);
return true;
}
-bool TextEditor::AccessibleImpl::CopyText( size_t startPosition,
- size_t endPosition )
+bool TextEditor::AccessibleImpl::CopyText(size_t startPosition,
+ size_t endPosition)
{
- if( endPosition <= startPosition )
+ if(endPosition <= startPosition)
return false;
- auto slf = Toolkit::TextEditor::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get<std::string>();
- Dali::Toolkit::GetImpl( slf ).getController()->CopyStringToClipboard( txt.substr(startPosition, endPosition - startPosition) );
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get<std::string>();
+ Dali::Toolkit::GetImpl(slf).getController()->CopyStringToClipboard(txt.substr(startPosition, endPosition - startPosition));
return true;
}
-bool TextEditor::AccessibleImpl::CutText( size_t startPosition,
- size_t endPosition )
+bool TextEditor::AccessibleImpl::CutText(size_t startPosition,
+ size_t endPosition)
{
- if( endPosition <= startPosition )
+ if(endPosition <= startPosition)
return false;
- auto slf = Toolkit::TextEditor::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get<std::string>();
- Dali::Toolkit::GetImpl( slf ).getController()->CopyStringToClipboard( txt.substr(startPosition, endPosition - startPosition) );
+ auto slf = Toolkit::TextEditor::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get<std::string>();
+ Dali::Toolkit::GetImpl(slf).getController()->CopyStringToClipboard(txt.substr(startPosition, endPosition - startPosition));
- slf.SetProperty( Toolkit::TextEditor::Property::TEXT,
- txt.substr( 0, startPosition ) + txt.substr( endPosition - startPosition, txt.size()));
+ slf.SetProperty(Toolkit::TextEditor::Property::TEXT,
+ txt.substr(0, startPosition) + txt.substr(endPosition - startPosition, txt.size()));
return true;
}
{
using namespace Dali::Accessibility;
- auto states = Control::Impl::AccessibleImpl::CalculateStates();
- states[State::EDITABLE] = true;
+ auto states = Control::Impl::AccessibleImpl::CalculateStates();
+ states[State::EDITABLE] = true;
states[State::FOCUSABLE] = true;
Toolkit::Control focusControl = Toolkit::KeyInputFocusManager::Get().GetCurrentFocusControl();
- if (self == focusControl)
+ if(self == focusControl)
{
states[State::FOCUSED] = true;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/text-controls/text-field-impl.h>
// EXTERNAL INCLUDES
-#include <cstring>
-#include <dali/public-api/adaptor-framework/key.h>
-#include <dali/public-api/common/dali-common.h>
+#include <dali/devel-api/actors/actor-devel.h>
#include <dali/devel-api/adaptor-framework/key-devel.h>
#include <dali/devel-api/adaptor-framework/window-devel.h>
#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/object/property-helper-devel.h>
-#include <dali/devel-api/actors/actor-devel.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/adaptor-framework/key.h>
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <cstring>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/text/text-enumerations.h>
-#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
-#include <dali-toolkit/devel-api/text/rendering-backend.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
-#include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
+#include <dali-toolkit/devel-api/controls/control-devel.h>
#include <dali-toolkit/devel-api/controls/text-controls/text-field-devel.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/text/text-enumerations-impl.h>
+#include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
+#include <dali-toolkit/devel-api/text/rendering-backend.h>
+#include <dali-toolkit/internal/styling/style-manager-impl.h>
#include <dali-toolkit/internal/text/rendering/text-backend.h>
#include <dali-toolkit/internal/text/text-effects-style.h>
+#include <dali-toolkit/internal/text/text-enumerations-impl.h>
#include <dali-toolkit/internal/text/text-font-style.h>
#include <dali-toolkit/internal/text/text-view.h>
-#include <dali-toolkit/internal/styling/style-manager-impl.h>
-#include <dali-toolkit/devel-api/controls/control-devel.h>
+#include <dali-toolkit/public-api/text/text-enumerations.h>
+#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali/integration-api/adaptor-framework/adaptor.h>
using namespace Dali::Toolkit::Text;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace // unnamed namespace
{
-
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_CONTROLS");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_CONTROLS");
#endif
- const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND;
+const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND;
} // unnamed namespace
namespace
return Toolkit::TextField::New();
}
+// clang-format off
// Setup properties, signals and actions using the type-registry.
DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextField, Toolkit::Control, Create );
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "text", STRING, TEXT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "placeholderText", STRING, PLACEHOLDER_TEXT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "placeholderTextFocused", STRING, PLACEHOLDER_TEXT_FOCUSED )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "fontFamily", STRING, FONT_FAMILY )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "fontStyle", MAP, FONT_STYLE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "pointSize", FLOAT, POINT_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "maxLength", INTEGER, MAX_LENGTH )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "exceedPolicy", INTEGER, EXCEED_POLICY )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "verticalAlignment", STRING, VERTICAL_ALIGNMENT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "textColor", VECTOR4, TEXT_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "placeholderTextColor", VECTOR4, PLACEHOLDER_TEXT_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "primaryCursorColor", VECTOR4, PRIMARY_CURSOR_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "secondaryCursorColor", VECTOR4, SECONDARY_CURSOR_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "enableCursorBlink", BOOLEAN, ENABLE_CURSOR_BLINK )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "cursorBlinkInterval", FLOAT, CURSOR_BLINK_INTERVAL )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "cursorBlinkDuration", FLOAT, CURSOR_BLINK_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "cursorWidth", INTEGER, CURSOR_WIDTH )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "grabHandleImage", STRING, GRAB_HANDLE_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "grabHandlePressedImage", STRING, GRAB_HANDLE_PRESSED_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "scrollThreshold", FLOAT, SCROLL_THRESHOLD )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "scrollSpeed", FLOAT, SCROLL_SPEED )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandleImageLeft", MAP, SELECTION_HANDLE_IMAGE_LEFT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandleImageRight", MAP, SELECTION_HANDLE_IMAGE_RIGHT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandlePressedImageLeft", MAP, SELECTION_HANDLE_PRESSED_IMAGE_LEFT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandlePressedImageRight", MAP, SELECTION_HANDLE_PRESSED_IMAGE_RIGHT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandleMarkerImageLeft", MAP, SELECTION_HANDLE_MARKER_IMAGE_LEFT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandleMarkerImageRight", MAP, SELECTION_HANDLE_MARKER_IMAGE_RIGHT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHighlightColor", VECTOR4, SELECTION_HIGHLIGHT_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "decorationBoundingBox", RECTANGLE, DECORATION_BOUNDING_BOX )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputMethodSettings", MAP, INPUT_METHOD_SETTINGS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputColor", VECTOR4, INPUT_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "enableMarkup", BOOLEAN, ENABLE_MARKUP )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputFontFamily", STRING, INPUT_FONT_FAMILY )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputFontStyle", MAP, INPUT_FONT_STYLE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputPointSize", FLOAT, INPUT_POINT_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "underline", MAP, UNDERLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputUnderline", MAP, INPUT_UNDERLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "shadow", MAP, SHADOW )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputShadow", MAP, INPUT_SHADOW )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "emboss", MAP, EMBOSS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputEmboss", MAP, INPUT_EMBOSS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "outline", MAP, OUTLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputOutline", MAP, INPUT_OUTLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "hiddenInputSettings", MAP, HIDDEN_INPUT_SETTINGS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "pixelSize", FLOAT, PIXEL_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "enableSelection", BOOLEAN, ENABLE_SELECTION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "placeholder", MAP, PLACEHOLDER )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "ellipsis", BOOLEAN, ELLIPSIS )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "enableShiftSelection", BOOLEAN, ENABLE_SHIFT_SELECTION )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "enableGrabHandle", BOOLEAN, ENABLE_GRAB_HANDLE )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "enableGrabHandlePopup", BOOLEAN, ENABLE_GRAB_HANDLE_POPUP )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "textBackground", VECTOR4, BACKGROUND )
-DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextField, "selectedText", STRING, SELECTED_TEXT )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "renderingBackend", INTEGER, RENDERING_BACKEND )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "selectedTextStart", INTEGER, SELECTED_TEXT_START )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "selectedTextEnd", INTEGER, SELECTED_TEXT_END )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "enableEditing", BOOLEAN, ENABLE_EDITING )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "fontSizeScale", FLOAT, FONT_SIZE_SCALE )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "primaryCursorPosition", INTEGER, PRIMARY_CURSOR_POSITION )
-
-DALI_SIGNAL_REGISTRATION( Toolkit, TextField, "textChanged", SIGNAL_TEXT_CHANGED )
-DALI_SIGNAL_REGISTRATION( Toolkit, TextField, "maxLengthReached", SIGNAL_MAX_LENGTH_REACHED )
-DALI_SIGNAL_REGISTRATION( Toolkit, TextField, "inputStyleChanged", SIGNAL_INPUT_STYLE_CHANGED )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "text", STRING, TEXT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "placeholderText", STRING, PLACEHOLDER_TEXT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "placeholderTextFocused", STRING, PLACEHOLDER_TEXT_FOCUSED )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "fontFamily", STRING, FONT_FAMILY )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "fontStyle", MAP, FONT_STYLE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "pointSize", FLOAT, POINT_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "maxLength", INTEGER, MAX_LENGTH )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "exceedPolicy", INTEGER, EXCEED_POLICY )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "verticalAlignment", STRING, VERTICAL_ALIGNMENT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "textColor", VECTOR4, TEXT_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "placeholderTextColor", VECTOR4, PLACEHOLDER_TEXT_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "primaryCursorColor", VECTOR4, PRIMARY_CURSOR_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "secondaryCursorColor", VECTOR4, SECONDARY_CURSOR_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "enableCursorBlink", BOOLEAN, ENABLE_CURSOR_BLINK )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "cursorBlinkInterval", FLOAT, CURSOR_BLINK_INTERVAL )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "cursorBlinkDuration", FLOAT, CURSOR_BLINK_DURATION )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "cursorWidth", INTEGER, CURSOR_WIDTH )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "grabHandleImage", STRING, GRAB_HANDLE_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "grabHandlePressedImage", STRING, GRAB_HANDLE_PRESSED_IMAGE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "scrollThreshold", FLOAT, SCROLL_THRESHOLD )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "scrollSpeed", FLOAT, SCROLL_SPEED )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandleImageLeft", MAP, SELECTION_HANDLE_IMAGE_LEFT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandleImageRight", MAP, SELECTION_HANDLE_IMAGE_RIGHT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandlePressedImageLeft", MAP, SELECTION_HANDLE_PRESSED_IMAGE_LEFT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandlePressedImageRight", MAP, SELECTION_HANDLE_PRESSED_IMAGE_RIGHT)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandleMarkerImageLeft", MAP, SELECTION_HANDLE_MARKER_IMAGE_LEFT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandleMarkerImageRight", MAP, SELECTION_HANDLE_MARKER_IMAGE_RIGHT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHighlightColor", VECTOR4, SELECTION_HIGHLIGHT_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "decorationBoundingBox", RECTANGLE, DECORATION_BOUNDING_BOX )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputMethodSettings", MAP, INPUT_METHOD_SETTINGS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputColor", VECTOR4, INPUT_COLOR )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "enableMarkup", BOOLEAN, ENABLE_MARKUP )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputFontFamily", STRING, INPUT_FONT_FAMILY )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputFontStyle", MAP, INPUT_FONT_STYLE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputPointSize", FLOAT, INPUT_POINT_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "underline", MAP, UNDERLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputUnderline", MAP, INPUT_UNDERLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "shadow", MAP, SHADOW )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputShadow", MAP, INPUT_SHADOW )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "emboss", MAP, EMBOSS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputEmboss", MAP, INPUT_EMBOSS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "outline", MAP, OUTLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputOutline", MAP, INPUT_OUTLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "hiddenInputSettings", MAP, HIDDEN_INPUT_SETTINGS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "pixelSize", FLOAT, PIXEL_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "enableSelection", BOOLEAN, ENABLE_SELECTION )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "placeholder", MAP, PLACEHOLDER )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "ellipsis", BOOLEAN, ELLIPSIS )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "enableShiftSelection", BOOLEAN, ENABLE_SHIFT_SELECTION )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "enableGrabHandle", BOOLEAN, ENABLE_GRAB_HANDLE )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "enableGrabHandlePopup", BOOLEAN, ENABLE_GRAB_HANDLE_POPUP )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "textBackground", VECTOR4, BACKGROUND )
+DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextField, "selectedText", STRING, SELECTED_TEXT )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "renderingBackend", INTEGER, RENDERING_BACKEND )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "selectedTextStart", INTEGER, SELECTED_TEXT_START )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "selectedTextEnd", INTEGER, SELECTED_TEXT_END )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "enableEditing", BOOLEAN, ENABLE_EDITING )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "fontSizeScale", FLOAT, FONT_SIZE_SCALE )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "primaryCursorPosition", INTEGER, PRIMARY_CURSOR_POSITION )
+
+DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "textChanged", SIGNAL_TEXT_CHANGED )
+DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "maxLengthReached", SIGNAL_MAX_LENGTH_REACHED )
+DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "inputStyleChanged", SIGNAL_INPUT_STYLE_CHANGED)
DALI_TYPE_REGISTRATION_END()
+// clang-format on
-const char * const IMAGE_MAP_FILENAME_STRING = "filename";
+const char* const IMAGE_MAP_FILENAME_STRING = "filename";
/// Retrieves a filename from a value that is a Property::Map
-std::string GetImageFileNameFromPropertyValue( const Property::Value& value )
+std::string GetImageFileNameFromPropertyValue(const Property::Value& value)
{
- std::string filename;
+ std::string filename;
const Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
- const Property::Value* filenameValue = map->Find( IMAGE_MAP_FILENAME_STRING );
- if( filenameValue )
+ const Property::Value* filenameValue = map->Find(IMAGE_MAP_FILENAME_STRING);
+ if(filenameValue)
{
- filenameValue->Get( filename );
+ filenameValue->Get(filename);
}
}
return filename;
Toolkit::TextField TextField::New()
{
// Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< TextField > impl = new TextField();
+ IntrusivePtr<TextField> impl = new TextField();
// Pass ownership to CustomActor handle
- Toolkit::TextField handle( *impl );
+ Toolkit::TextField handle(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-void TextField::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void TextField::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::TextField textField = Toolkit::TextField::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextField textField = Toolkit::TextField::DownCast(Dali::BaseHandle(object));
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField SetProperty\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField SetProperty\n");
- if( textField )
+ if(textField)
{
- TextField& impl( GetImpl( textField ) );
- DALI_ASSERT_DEBUG( impl.mController && "No text contoller" );
- DALI_ASSERT_DEBUG( impl.mDecorator && "No text decorator" );
+ TextField& impl(GetImpl(textField));
+ DALI_ASSERT_DEBUG(impl.mController && "No text contoller");
+ DALI_ASSERT_DEBUG(impl.mDecorator && "No text decorator");
- switch( index )
+ switch(index)
{
case Toolkit::DevelTextField::Property::RENDERING_BACKEND:
{
- int backend = value.Get< int >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p RENDERING_BACKEND %d\n", impl.mController.Get(), backend );
+ int backend = value.Get<int>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p RENDERING_BACKEND %d\n", impl.mController.Get(), backend);
#ifndef ENABLE_VECTOR_BASED_TEXT_RENDERING
- if( DevelText::RENDERING_VECTOR_BASED == backend )
+ if(DevelText::RENDERING_VECTOR_BASED == backend)
{
backend = TextAbstraction::BITMAP_GLYPH; // Fallback to bitmap-based rendering
}
#endif
- if( impl.mRenderingBackend != backend )
+ if(impl.mRenderingBackend != backend)
{
impl.mRenderingBackend = backend;
impl.mRenderer.Reset();
// When using the vector-based rendering, the size of the GLyphs are different
TextAbstraction::GlyphType glyphType = (DevelText::RENDERING_VECTOR_BASED == impl.mRenderingBackend) ? TextAbstraction::VECTOR_GLYPH : TextAbstraction::BITMAP_GLYPH;
- impl.mController->SetGlyphType( glyphType );
+ impl.mController->SetGlyphType(glyphType);
}
break;
}
case Toolkit::TextField::Property::TEXT:
{
- const std::string& text = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p TEXT %s\n", impl.mController.Get(), text.c_str() );
+ const std::string& text = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p TEXT %s\n", impl.mController.Get(), text.c_str());
- impl.mController->SetText( text );
+ impl.mController->SetText(text);
break;
}
case Toolkit::TextField::Property::PLACEHOLDER_TEXT:
{
- const std::string& text = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT %s\n", impl.mController.Get(), text.c_str() );
+ const std::string& text = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT %s\n", impl.mController.Get(), text.c_str());
- impl.mController->SetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text );
+ impl.mController->SetPlaceholderText(Controller::PLACEHOLDER_TYPE_INACTIVE, text);
break;
}
case Toolkit::TextField::Property::PLACEHOLDER_TEXT_FOCUSED:
{
- const std::string& text = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT_FOCUSED %s\n", impl.mController.Get(), text.c_str() );
+ const std::string& text = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT_FOCUSED %s\n", impl.mController.Get(), text.c_str());
- impl.mController->SetPlaceholderText( Controller::PLACEHOLDER_TYPE_ACTIVE, text );
+ impl.mController->SetPlaceholderText(Controller::PLACEHOLDER_TYPE_ACTIVE, text);
break;
}
case Toolkit::TextField::Property::FONT_FAMILY:
{
- const std::string& fontFamily = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str() );
- impl.mController->SetDefaultFontFamily( fontFamily );
+ const std::string& fontFamily = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str());
+ impl.mController->SetDefaultFontFamily(fontFamily);
break;
}
case Toolkit::TextField::Property::FONT_STYLE:
{
- SetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT );
+ SetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT);
break;
}
case Toolkit::TextField::Property::POINT_SIZE:
{
- const float pointSize = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p POINT_SIZE %f\n", impl.mController.Get(), pointSize );
+ const float pointSize = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p POINT_SIZE %f\n", impl.mController.Get(), pointSize);
- if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
+ if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize))
{
- impl.mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE );
+ impl.mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE);
}
break;
}
case Toolkit::TextField::Property::MAX_LENGTH:
{
- const int max = value.Get< int >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p MAX_LENGTH %d\n", impl.mController.Get(), max );
+ const int max = value.Get<int>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p MAX_LENGTH %d\n", impl.mController.Get(), max);
- impl.mController->SetMaximumNumberOfCharacters( max );
+ impl.mController->SetMaximumNumberOfCharacters(max);
break;
}
case Toolkit::TextField::Property::EXCEED_POLICY:
{
impl.mExceedPolicy = value.Get<int>();
- if( Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == impl.mExceedPolicy )
+ if(Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == impl.mExceedPolicy)
{
impl.EnableClipping();
}
else
{
- UnparentAndReset( impl.mStencil );
+ UnparentAndReset(impl.mStencil);
}
impl.RequestTextRelayout();
break;
}
case Toolkit::TextField::Property::HORIZONTAL_ALIGNMENT:
{
- Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( GetHorizontalAlignmentEnumeration( value, alignment ) )
+ Text::HorizontalAlignment::Type alignment(static_cast<Text::HorizontalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(GetHorizontalAlignmentEnumeration(value, alignment))
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p HORIZONTAL_ALIGNMENT %d\n", impl.mController.Get(), alignment );
- impl.mController->SetHorizontalAlignment( alignment );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p HORIZONTAL_ALIGNMENT %d\n", impl.mController.Get(), alignment);
+ impl.mController->SetHorizontalAlignment(alignment);
}
break;
}
case Toolkit::TextField::Property::VERTICAL_ALIGNMENT:
{
- Toolkit::Text::VerticalAlignment::Type alignment( static_cast< Text::VerticalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( GetVerticalAlignmentEnumeration( value, alignment ) )
+ Toolkit::Text::VerticalAlignment::Type alignment(static_cast<Text::VerticalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(GetVerticalAlignmentEnumeration(value, alignment))
{
- impl.mController->SetVerticalAlignment( alignment );
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p VERTICAL_ALIGNMENT %d\n", impl.mController.Get(), alignment );
+ impl.mController->SetVerticalAlignment(alignment);
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p VERTICAL_ALIGNMENT %d\n", impl.mController.Get(), alignment);
}
break;
}
case Toolkit::TextField::Property::TEXT_COLOR:
{
- const Vector4& textColor = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a );
+ const Vector4& textColor = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a);
- if( impl.mController->GetDefaultColor() != textColor )
+ if(impl.mController->GetDefaultColor() != textColor)
{
- impl.mController->SetDefaultColor( textColor );
- impl.mController->SetInputColor( textColor );
+ impl.mController->SetDefaultColor(textColor);
+ impl.mController->SetInputColor(textColor);
impl.mRenderer.Reset();
}
break;
}
case Toolkit::TextField::Property::PLACEHOLDER_TEXT_COLOR:
{
- const Vector4& textColor = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a );
+ const Vector4& textColor = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a);
- if( impl.mController->GetPlaceholderTextColor() != textColor )
+ if(impl.mController->GetPlaceholderTextColor() != textColor)
{
- impl.mController->SetPlaceholderTextColor( textColor );
+ impl.mController->SetPlaceholderTextColor(textColor);
impl.mRenderer.Reset();
}
break;
}
case Toolkit::TextField::Property::PRIMARY_CURSOR_COLOR:
{
- const Vector4& color = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PRIMARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a );
+ const Vector4& color = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PRIMARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a);
- impl.mDecorator->SetCursorColor( PRIMARY_CURSOR, color );
+ impl.mDecorator->SetCursorColor(PRIMARY_CURSOR, color);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextField::Property::SECONDARY_CURSOR_COLOR:
{
- const Vector4& color = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p SECONDARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a );
+ const Vector4& color = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p SECONDARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a);
- impl.mDecorator->SetCursorColor( SECONDARY_CURSOR, color );
+ impl.mDecorator->SetCursorColor(SECONDARY_CURSOR, color);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextField::Property::ENABLE_CURSOR_BLINK:
{
- const bool enable = value.Get< bool >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p ENABLE_CURSOR_BLINK %d\n", impl.mController.Get(), enable );
+ const bool enable = value.Get<bool>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p ENABLE_CURSOR_BLINK %d\n", impl.mController.Get(), enable);
- impl.mController->SetEnableCursorBlink( enable );
+ impl.mController->SetEnableCursorBlink(enable);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextField::Property::CURSOR_BLINK_INTERVAL:
{
- const float interval = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p CURSOR_BLINK_INTERVAL %f\n", impl.mController.Get(), interval );
+ const float interval = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p CURSOR_BLINK_INTERVAL %f\n", impl.mController.Get(), interval);
- impl.mDecorator->SetCursorBlinkInterval( interval );
+ impl.mDecorator->SetCursorBlinkInterval(interval);
break;
}
case Toolkit::TextField::Property::CURSOR_BLINK_DURATION:
{
- const float duration = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p CURSOR_BLINK_DURATION %f\n", impl.mController.Get(), duration );
+ const float duration = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p CURSOR_BLINK_DURATION %f\n", impl.mController.Get(), duration);
- impl.mDecorator->SetCursorBlinkDuration( duration );
+ impl.mDecorator->SetCursorBlinkDuration(duration);
break;
}
case Toolkit::TextField::Property::CURSOR_WIDTH:
{
- const int width = value.Get< int >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p CURSOR_WIDTH %d\n", impl.mController.Get(), width );
+ const int width = value.Get<int>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p CURSOR_WIDTH %d\n", impl.mController.Get(), width);
- impl.mDecorator->SetCursorWidth( width );
- impl.mController->GetLayoutEngine().SetCursorWidth( width );
+ impl.mDecorator->SetCursorWidth(width);
+ impl.mController->GetLayoutEngine().SetCursorWidth(width);
break;
}
case Toolkit::TextField::Property::GRAB_HANDLE_IMAGE:
{
- const std::string imageFileName = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p GRAB_HANDLE_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str() );
+ const std::string imageFileName = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p GRAB_HANDLE_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str());
- if( imageFileName.size() )
+ if(imageFileName.size())
{
- impl.mDecorator->SetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_RELEASED, imageFileName );
+ impl.mDecorator->SetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_RELEASED, imageFileName);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextField::Property::GRAB_HANDLE_PRESSED_IMAGE:
{
- const std::string imageFileName = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p GRAB_HANDLE_PRESSED_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str() );
+ const std::string imageFileName = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p GRAB_HANDLE_PRESSED_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str());
- if( imageFileName.size() )
+ if(imageFileName.size())
{
- impl.mDecorator->SetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_PRESSED, imageFileName );
+ impl.mDecorator->SetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_PRESSED, imageFileName);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextField::Property::SCROLL_THRESHOLD:
{
- const float threshold = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p SCROLL_THRESHOLD %f\n", impl.mController.Get(), threshold );
+ const float threshold = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p SCROLL_THRESHOLD %f\n", impl.mController.Get(), threshold);
- impl.mDecorator->SetScrollThreshold( threshold );
+ impl.mDecorator->SetScrollThreshold(threshold);
break;
}
case Toolkit::TextField::Property::SCROLL_SPEED:
{
- const float speed = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p SCROLL_SPEED %f\n", impl.mController.Get(), speed );
+ const float speed = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p SCROLL_SPEED %f\n", impl.mController.Get(), speed);
- impl.mDecorator->SetScrollSpeed( speed );
+ impl.mDecorator->SetScrollSpeed(speed);
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_IMAGE_LEFT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename );
+ impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_IMAGE_RIGHT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename );
+ impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_PRESSED_IMAGE_LEFT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename );
+ impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_PRESSED_IMAGE_RIGHT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename );
+ impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_MARKER_IMAGE_LEFT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename );
+ impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_MARKER_IMAGE_RIGHT:
{
- const std::string filename = GetImageFileNameFromPropertyValue( value );
+ const std::string filename = GetImageFileNameFromPropertyValue(value);
- if( filename.size() )
+ if(filename.size())
{
- impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename );
+ impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename);
impl.RequestTextRelayout();
}
break;
}
case Toolkit::TextField::Property::SELECTION_HIGHLIGHT_COLOR:
{
- const Vector4 color = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p SELECTION_HIGHLIGHT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a );
+ const Vector4 color = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p SELECTION_HIGHLIGHT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a);
- impl.mDecorator->SetHighlightColor( color );
+ impl.mDecorator->SetHighlightColor(color);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextField::Property::DECORATION_BOUNDING_BOX:
{
- const Rect<int> box = value.Get< Rect<int> >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p DECORATION_BOUNDING_BOX %d,%d %dx%d\n", impl.mController.Get(), box.x, box.y, box.width, box.height );
+ const Rect<int> box = value.Get<Rect<int> >();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p DECORATION_BOUNDING_BOX %d,%d %dx%d\n", impl.mController.Get(), box.x, box.y, box.width, box.height);
- impl.mDecorator->SetBoundingBox( box );
+ impl.mDecorator->SetBoundingBox(box);
impl.RequestTextRelayout();
break;
}
case Toolkit::TextField::Property::INPUT_METHOD_SETTINGS:
{
const Property::Map* map = value.GetMap();
- if (map)
+ if(map)
{
- impl.mInputMethodOptions.ApplyProperty( *map );
+ impl.mInputMethodOptions.ApplyProperty(*map);
}
- impl.mController->SetInputModePassword( impl.mInputMethodOptions.IsPassword() );
+ impl.mController->SetInputModePassword(impl.mInputMethodOptions.IsPassword());
Toolkit::Control control = Toolkit::KeyInputFocusManager::Get().GetCurrentFocusControl();
- if (control == textField)
+ if(control == textField)
{
- impl.mInputMethodContext.ApplyOptions( impl.mInputMethodOptions );
+ impl.mInputMethodContext.ApplyOptions(impl.mInputMethodOptions);
}
break;
}
case Toolkit::TextField::Property::INPUT_COLOR:
{
- const Vector4 inputColor = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p INPUT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), inputColor.r, inputColor.g, inputColor.b, inputColor.a );
+ const Vector4 inputColor = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p INPUT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), inputColor.r, inputColor.g, inputColor.b, inputColor.a);
- impl.mController->SetInputColor( inputColor );
+ impl.mController->SetInputColor(inputColor);
break;
}
case Toolkit::TextField::Property::ENABLE_MARKUP:
{
const bool enableMarkup = value.Get<bool>();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_MARKUP %d\n", impl.mController.Get(), enableMarkup );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_MARKUP %d\n", impl.mController.Get(), enableMarkup);
- impl.mController->SetMarkupProcessorEnabled( enableMarkup );
+ impl.mController->SetMarkupProcessorEnabled(enableMarkup);
break;
}
case Toolkit::TextField::Property::INPUT_FONT_FAMILY:
{
- const std::string& fontFamily = value.Get< std::string >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p INPUT_FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str() );
- impl.mController->SetInputFontFamily( fontFamily );
+ const std::string& fontFamily = value.Get<std::string>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p INPUT_FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str());
+ impl.mController->SetInputFontFamily(fontFamily);
break;
}
case Toolkit::TextField::Property::INPUT_FONT_STYLE:
{
- SetFontStyleProperty( impl.mController, value, Text::FontStyle::INPUT );
+ SetFontStyleProperty(impl.mController, value, Text::FontStyle::INPUT);
break;
}
case Toolkit::TextField::Property::INPUT_POINT_SIZE:
{
- const float pointSize = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p INPUT_POINT_SIZE %f\n", impl.mController.Get(), pointSize );
- impl.mController->SetInputFontPointSize( pointSize );
+ const float pointSize = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p INPUT_POINT_SIZE %f\n", impl.mController.Get(), pointSize);
+ impl.mController->SetInputFontPointSize(pointSize);
break;
}
case Toolkit::TextField::Property::UNDERLINE:
{
- const bool update = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
- if( update )
+ const bool update = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextField::Property::INPUT_UNDERLINE:
{
- const bool update = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::INPUT );
- if( update )
+ const bool update = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::INPUT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextField::Property::SHADOW:
{
- const bool update = SetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
- if( update )
+ const bool update = SetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextField::Property::INPUT_SHADOW:
{
- const bool update = SetShadowProperties( impl.mController, value, Text::EffectStyle::INPUT );
- if( update )
+ const bool update = SetShadowProperties(impl.mController, value, Text::EffectStyle::INPUT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextField::Property::EMBOSS:
{
- const bool update = SetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
- if( update )
+ const bool update = SetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextField::Property::INPUT_EMBOSS:
{
- const bool update = SetEmbossProperties( impl.mController, value, Text::EffectStyle::INPUT );
- if( update )
+ const bool update = SetEmbossProperties(impl.mController, value, Text::EffectStyle::INPUT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextField::Property::OUTLINE:
{
- const bool update = SetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
- if( update )
+ const bool update = SetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
+ if(update)
{
impl.mRenderer.Reset();
}
}
case Toolkit::TextField::Property::INPUT_OUTLINE:
{
- const bool update = SetOutlineProperties( impl.mController, value, Text::EffectStyle::INPUT );
- if( update )
+ const bool update = SetOutlineProperties(impl.mController, value, Text::EffectStyle::INPUT);
+ if(update)
{
impl.mRenderer.Reset();
}
case Toolkit::TextField::Property::HIDDEN_INPUT_SETTINGS:
{
const Property::Map* map = value.GetMap();
- if (map)
+ if(map)
{
impl.mController->SetHiddenInputOption(*map);
}
}
case Toolkit::TextField::Property::PIXEL_SIZE:
{
- const float pixelSize = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize );
+ const float pixelSize = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize);
- if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) )
+ if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE), pixelSize))
{
- impl.mController->SetDefaultFontSize( pixelSize, Text::Controller::PIXEL_SIZE );
+ impl.mController->SetDefaultFontSize(pixelSize, Text::Controller::PIXEL_SIZE);
}
break;
}
case Toolkit::TextField::Property::ENABLE_SELECTION:
{
- const bool enableSelection = value.Get< bool >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_SELECTION %d\n", impl.mController.Get(), enableSelection );
- impl.mController->SetSelectionEnabled( enableSelection );
+ const bool enableSelection = value.Get<bool>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_SELECTION %d\n", impl.mController.Get(), enableSelection);
+ impl.mController->SetSelectionEnabled(enableSelection);
break;
}
case Toolkit::TextField::Property::PLACEHOLDER:
{
const Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
- impl.mController->SetPlaceholderProperty( *map );
+ impl.mController->SetPlaceholderProperty(*map);
}
break;
}
case Toolkit::TextField::Property::ELLIPSIS:
{
const bool ellipsis = value.Get<bool>();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ELLIPSIS %d\n", impl.mController.Get(), ellipsis );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ELLIPSIS %d\n", impl.mController.Get(), ellipsis);
- impl.mController->SetTextElideEnabled( ellipsis );
+ impl.mController->SetTextElideEnabled(ellipsis);
break;
}
case Toolkit::DevelTextField::Property::ENABLE_SHIFT_SELECTION:
{
const bool shiftSelection = value.Get<bool>();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_SHIFT_SELECTION %d\n", impl.mController.Get(), shiftSelection );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_SHIFT_SELECTION %d\n", impl.mController.Get(), shiftSelection);
- impl.mController->SetShiftSelectionEnabled( shiftSelection );
+ impl.mController->SetShiftSelectionEnabled(shiftSelection);
break;
}
case Toolkit::DevelTextField::Property::ENABLE_GRAB_HANDLE:
{
const bool grabHandleEnabled = value.Get<bool>();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_GRAB_HANDLE %d\n", impl.mController.Get(), grabHandleEnabled );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_GRAB_HANDLE %d\n", impl.mController.Get(), grabHandleEnabled);
- impl.mController->SetGrabHandleEnabled( grabHandleEnabled );
+ impl.mController->SetGrabHandleEnabled(grabHandleEnabled);
break;
}
case Toolkit::DevelTextField::Property::MATCH_SYSTEM_LANGUAGE_DIRECTION:
{
- impl.mController->SetMatchSystemLanguageDirection(value.Get< bool >());
+ impl.mController->SetMatchSystemLanguageDirection(value.Get<bool>());
break;
}
case Toolkit::DevelTextField::Property::ENABLE_GRAB_HANDLE_POPUP:
}
case Toolkit::DevelTextField::Property::BACKGROUND:
{
- const Vector4 backgroundColor = value.Get< Vector4 >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p BACKGROUND %f,%f,%f,%f\n", impl.mController.Get(), backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a );
+ const Vector4 backgroundColor = value.Get<Vector4>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p BACKGROUND %f,%f,%f,%f\n", impl.mController.Get(), backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a);
- impl.mController->SetBackgroundEnabled( true );
- impl.mController->SetBackgroundColor( backgroundColor );
+ impl.mController->SetBackgroundEnabled(true);
+ impl.mController->SetBackgroundColor(backgroundColor);
break;
}
case Toolkit::DevelTextField::Property::SELECTED_TEXT_START:
{
- uint32_t start = static_cast<uint32_t>(value.Get< int >());
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p SELECTED_TEXT_START %d\n", impl.mController.Get(), start );
- impl.SetTextSelectionRange( &start, nullptr );
+ uint32_t start = static_cast<uint32_t>(value.Get<int>());
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p SELECTED_TEXT_START %d\n", impl.mController.Get(), start);
+ impl.SetTextSelectionRange(&start, nullptr);
break;
}
case Toolkit::DevelTextField::Property::SELECTED_TEXT_END:
{
- uint32_t end = static_cast<uint32_t>(value.Get< int >());
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p SELECTED_TEXT_END %d\n", impl.mController.Get(), end );
- impl.SetTextSelectionRange( nullptr, &end );
+ uint32_t end = static_cast<uint32_t>(value.Get<int>());
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p SELECTED_TEXT_END %d\n", impl.mController.Get(), end);
+ impl.SetTextSelectionRange(nullptr, &end);
break;
}
case Toolkit::DevelTextField::Property::ENABLE_EDITING:
{
- const bool editable = value.Get< bool >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_EDITING %d\n", impl.mController.Get(), editable );
- impl.SetEditable( editable );
+ const bool editable = value.Get<bool>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_EDITING %d\n", impl.mController.Get(), editable);
+ impl.SetEditable(editable);
break;
}
case Toolkit::DevelTextField::Property::FONT_SIZE_SCALE:
{
- const float scale = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale );
+ const float scale = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale);
- if( !Equals( impl.mController->GetFontSizeScale(), scale ) )
+ if(!Equals(impl.mController->GetFontSizeScale(), scale))
{
- impl.mController->SetFontSizeScale( scale );
+ impl.mController->SetFontSizeScale(scale);
}
break;
}
case Toolkit::DevelTextField::Property::PRIMARY_CURSOR_POSITION:
{
- uint32_t position = static_cast<uint32_t>(value.Get< int >());
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PRIMARY_CURSOR_POSITION %d\n", impl.mController.Get(), position );
- if (impl.mController->SetPrimaryCursorPosition( position ))
+ uint32_t position = static_cast<uint32_t>(value.Get<int>());
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PRIMARY_CURSOR_POSITION %d\n", impl.mController.Get(), position);
+ if(impl.mController->SetPrimaryCursorPosition(position))
{
impl.SetKeyInputFocus();
}
break;
}
} // switch
- } // textfield
+ } // textfield
}
-Property::Value TextField::GetProperty( BaseObject* object, Property::Index index )
+Property::Value TextField::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::TextField textField = Toolkit::TextField::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextField textField = Toolkit::TextField::DownCast(Dali::BaseHandle(object));
- if( textField )
+ if(textField)
{
- TextField& impl( GetImpl( textField ) );
- DALI_ASSERT_DEBUG( impl.mController && "No text contoller" );
- DALI_ASSERT_DEBUG( impl.mDecorator && "No text decorator" );
+ TextField& impl(GetImpl(textField));
+ DALI_ASSERT_DEBUG(impl.mController && "No text contoller");
+ DALI_ASSERT_DEBUG(impl.mDecorator && "No text decorator");
- switch( index )
+ switch(index)
{
case Toolkit::DevelTextField::Property::RENDERING_BACKEND:
{
case Toolkit::TextField::Property::TEXT:
{
std::string text;
- impl.mController->GetText( text );
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p returning text: %s\n", impl.mController.Get(), text.c_str() );
+ impl.mController->GetText(text);
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p returning text: %s\n", impl.mController.Get(), text.c_str());
value = text;
break;
}
case Toolkit::TextField::Property::PLACEHOLDER_TEXT:
{
std::string text;
- impl.mController->GetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text );
+ impl.mController->GetPlaceholderText(Controller::PLACEHOLDER_TYPE_INACTIVE, text);
value = text;
break;
}
case Toolkit::TextField::Property::PLACEHOLDER_TEXT_FOCUSED:
{
std::string text;
- impl.mController->GetPlaceholderText( Controller::PLACEHOLDER_TYPE_ACTIVE, text );
+ impl.mController->GetPlaceholderText(Controller::PLACEHOLDER_TYPE_ACTIVE, text);
value = text;
break;
}
}
case Toolkit::TextField::Property::FONT_STYLE:
{
- GetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT );
+ GetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT);
break;
}
case Toolkit::TextField::Property::POINT_SIZE:
{
- value = impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE );
+ value = impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE);
break;
}
case Toolkit::TextField::Property::MAX_LENGTH:
}
case Toolkit::TextField::Property::HORIZONTAL_ALIGNMENT:
{
- const char* name = Text::GetHorizontalAlignmentString( impl.mController->GetHorizontalAlignment() );
+ const char* name = Text::GetHorizontalAlignmentString(impl.mController->GetHorizontalAlignment());
- if ( name )
+ if(name)
{
- value = std::string( name );
+ value = std::string(name);
}
break;
}
case Toolkit::TextField::Property::VERTICAL_ALIGNMENT:
{
- const char* name = Text::GetVerticalAlignmentString( impl.mController->GetVerticalAlignment() );
+ const char* name = Text::GetVerticalAlignmentString(impl.mController->GetVerticalAlignment());
- if( name )
+ if(name)
{
- value = std::string( name );
+ value = std::string(name);
}
break;
}
}
case Toolkit::TextField::Property::PRIMARY_CURSOR_COLOR:
{
- value = impl.mDecorator->GetColor( PRIMARY_CURSOR );
+ value = impl.mDecorator->GetColor(PRIMARY_CURSOR);
break;
}
case Toolkit::TextField::Property::SECONDARY_CURSOR_COLOR:
{
- value = impl.mDecorator->GetColor( SECONDARY_CURSOR );
+ value = impl.mDecorator->GetColor(SECONDARY_CURSOR);
break;
}
case Toolkit::TextField::Property::ENABLE_CURSOR_BLINK:
}
case Toolkit::TextField::Property::GRAB_HANDLE_IMAGE:
{
- value = impl.mDecorator->GetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_RELEASED );
+ value = impl.mDecorator->GetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextField::Property::GRAB_HANDLE_PRESSED_IMAGE:
{
- value = impl.mDecorator->GetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_PRESSED );
+ value = impl.mDecorator->GetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_PRESSED);
break;
}
case Toolkit::TextField::Property::SCROLL_THRESHOLD:
}
case Toolkit::TextField::Property::SELECTION_HANDLE_IMAGE_LEFT:
{
- impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED );
+ impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_IMAGE_RIGHT:
{
- impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED ) ;
+ impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_PRESSED_IMAGE_LEFT:
{
- impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED );
+ impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED);
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_PRESSED_IMAGE_RIGHT:
{
- impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED );
+ impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED);
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_MARKER_IMAGE_LEFT:
{
- impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED );
+ impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextField::Property::SELECTION_HANDLE_MARKER_IMAGE_RIGHT:
{
- impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED );
+ impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED);
break;
}
case Toolkit::TextField::Property::SELECTION_HIGHLIGHT_COLOR:
case Toolkit::TextField::Property::DECORATION_BOUNDING_BOX:
{
Rect<int> boundingBox;
- impl.mDecorator->GetBoundingBox( boundingBox );
+ impl.mDecorator->GetBoundingBox(boundingBox);
value = boundingBox;
break;
}
case Toolkit::TextField::Property::INPUT_METHOD_SETTINGS:
{
Property::Map map;
- impl.mInputMethodOptions.RetrieveProperty( map );
+ impl.mInputMethodOptions.RetrieveProperty(map);
value = map;
break;
}
}
case Toolkit::TextField::Property::INPUT_FONT_STYLE:
{
- GetFontStyleProperty( impl.mController, value, Text::FontStyle::INPUT );
+ GetFontStyleProperty(impl.mController, value, Text::FontStyle::INPUT);
break;
}
case Toolkit::TextField::Property::INPUT_POINT_SIZE:
}
case Toolkit::TextField::Property::UNDERLINE:
{
- GetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextField::Property::INPUT_UNDERLINE:
{
- GetUnderlineProperties( impl.mController, value, Text::EffectStyle::INPUT );
+ GetUnderlineProperties(impl.mController, value, Text::EffectStyle::INPUT);
break;
}
case Toolkit::TextField::Property::SHADOW:
{
- GetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextField::Property::INPUT_SHADOW:
{
- GetShadowProperties( impl.mController, value, Text::EffectStyle::INPUT );
+ GetShadowProperties(impl.mController, value, Text::EffectStyle::INPUT);
break;
}
case Toolkit::TextField::Property::EMBOSS:
{
- GetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextField::Property::INPUT_EMBOSS:
{
- GetEmbossProperties( impl.mController, value, Text::EffectStyle::INPUT );
+ GetEmbossProperties(impl.mController, value, Text::EffectStyle::INPUT);
break;
}
case Toolkit::TextField::Property::OUTLINE:
{
- GetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextField::Property::INPUT_OUTLINE:
{
- GetOutlineProperties( impl.mController, value, Text::EffectStyle::INPUT );
+ GetOutlineProperties(impl.mController, value, Text::EffectStyle::INPUT);
break;
}
case Toolkit::TextField::Property::HIDDEN_INPUT_SETTINGS:
}
case Toolkit::TextField::Property::PIXEL_SIZE:
{
- value = impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE );
+ value = impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE);
break;
}
case Toolkit::TextField::Property::ENABLE_SELECTION:
case Toolkit::TextField::Property::PLACEHOLDER:
{
Property::Map map;
- impl.mController->GetPlaceholderProperty( map );
+ impl.mController->GetPlaceholderProperty(map);
value = map;
break;
}
}
case Toolkit::DevelTextField::Property::SELECTED_TEXT:
{
- value = impl.mController->GetSelectedText( );
+ value = impl.mController->GetSelectedText();
break;
}
case Toolkit::DevelTextField::Property::SELECTED_TEXT_START:
{
- Uint32Pair range = impl.GetTextSelectionRange( );
- value = static_cast<int>(range.first);
+ Uint32Pair range = impl.GetTextSelectionRange();
+ value = static_cast<int>(range.first);
break;
}
case Toolkit::DevelTextField::Property::SELECTED_TEXT_END:
{
- Uint32Pair range = impl.GetTextSelectionRange( );
- value = static_cast<int>(range.second);
+ Uint32Pair range = impl.GetTextSelectionRange();
+ value = static_cast<int>(range.second);
break;
}
case Toolkit::DevelTextField::Property::ENABLE_EDITING:
void TextField::SelectWholeText()
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
mController->SelectWholeText();
SetKeyInputFocus();
void TextField::SelectNone()
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
mController->SelectNone();
}
string TextField::GetSelectedText() const
{
string selectedText = "";
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
- selectedText = mController->GetSelectedText( );
+ selectedText = mController->GetSelectedText();
}
return selectedText;
}
-void TextField::SetTextSelectionRange(const uint32_t *start, const uint32_t *end)
+void TextField::SetTextSelectionRange(const uint32_t* start, const uint32_t* end)
{
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
- mController->SetTextSelectionRange( start, end );
+ mController->SetTextSelectionRange(start, end);
SetKeyInputFocus();
}
}
Uint32Pair TextField::GetTextSelectionRange() const
{
Uint32Pair range;
- if( mController && mController->IsShowingRealText() )
+ if(mController && mController->IsShowingRealText())
{
range = mController->GetTextSelectionRange();
}
return range;
}
-
InputMethodContext TextField::GetInputMethodContext()
{
return mInputMethodContext;
}
-bool TextField::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool TextField::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::TextField field = Toolkit::TextField::DownCast( handle );
+ bool connected(true);
+ Toolkit::TextField field = Toolkit::TextField::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_TEXT_CHANGED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_TEXT_CHANGED))
{
- field.TextChangedSignal().Connect( tracker, functor );
+ field.TextChangedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED))
{
- field.MaxLengthReachedSignal().Connect( tracker, functor );
+ field.MaxLengthReachedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED))
{
- field.InputStyleChangedSignal().Connect( tracker, functor );
+ field.InputStyleChangedSignal().Connect(tracker, functor);
}
else
{
{
Actor self = Self();
- mController = Text::Controller::New( this, this ,this);
+ mController = Text::Controller::New(this, this, this);
// When using the vector-based rendering, the size of the GLyphs are different
TextAbstraction::GlyphType glyphType = (DevelText::RENDERING_VECTOR_BASED == mRenderingBackend) ? TextAbstraction::VECTOR_GLYPH : TextAbstraction::BITMAP_GLYPH;
- mController->SetGlyphType( glyphType );
+ mController->SetGlyphType(glyphType);
- mDecorator = Text::Decorator::New( *mController,
- *mController );
+ mDecorator = Text::Decorator::New(*mController,
+ *mController);
- mInputMethodContext = InputMethodContext::New( self );
+ mInputMethodContext = InputMethodContext::New(self);
- mController->GetLayoutEngine().SetLayout( Layout::Engine::SINGLE_LINE_BOX );
+ mController->GetLayoutEngine().SetLayout(Layout::Engine::SINGLE_LINE_BOX);
// Enables the text input.
- mController->EnableTextInput( mDecorator, mInputMethodContext );
+ mController->EnableTextInput(mDecorator, mInputMethodContext);
// Enables the horizontal scrolling after the text input has been enabled.
- mController->SetHorizontalScrollEnabled( true );
+ mController->SetHorizontalScrollEnabled(true);
// Disables the vertical scrolling.
- mController->SetVerticalScrollEnabled( false );
+ mController->SetVerticalScrollEnabled(false);
// Disable the smooth handle panning.
- mController->SetSmoothHandlePanEnabled( false );
+ mController->SetSmoothHandlePanEnabled(false);
- mController->SetNoTextDoubleTapAction( Controller::NoTextTap::HIGHLIGHT );
- mController->SetNoTextLongPressAction( Controller::NoTextTap::HIGHLIGHT );
+ mController->SetNoTextDoubleTapAction(Controller::NoTextTap::HIGHLIGHT);
+ mController->SetNoTextLongPressAction(Controller::NoTextTap::HIGHLIGHT);
// Sets layoutDirection value
- Dali::Stage stage = Dali::Stage::GetCurrent();
- Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>( stage.GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
- mController->SetLayoutDirection( layoutDirection );
+ Dali::Stage stage = Dali::Stage::GetCurrent();
+ Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
+ mController->SetLayoutDirection(layoutDirection);
// Forward input events to controller
- EnableGestureDetection( static_cast<GestureType::Value>( GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS ) );
- GetTapGestureDetector().SetMaximumTapsRequired( 2 );
+ EnableGestureDetection(static_cast<GestureType::Value>(GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS));
+ GetTapGestureDetector().SetMaximumTapsRequired(2);
- self.TouchedSignal().Connect( this, &TextField::OnTouched );
+ self.TouchedSignal().Connect(this, &TextField::OnTouched);
// Set BoundingBox to stage size if not already set.
Rect<int> boundingBox;
- mDecorator->GetBoundingBox( boundingBox );
+ mDecorator->GetBoundingBox(boundingBox);
- if( boundingBox.IsEmpty() )
+ if(boundingBox.IsEmpty())
{
Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
- mDecorator->SetBoundingBox( Rect<int>( 0.0f, 0.0f, stageSize.width, stageSize.height ) );
+ mDecorator->SetBoundingBox(Rect<int>(0.0f, 0.0f, stageSize.width, stageSize.height));
}
// Flip vertically the 'left' selection handle
- mDecorator->FlipHandleVertically( LEFT_SELECTION_HANDLE, true );
+ mDecorator->FlipHandleVertically(LEFT_SELECTION_HANDLE, true);
// Fill-parent area by default
- self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
- self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT );
- self.OnSceneSignal().Connect( this, &TextField::OnSceneConnect );
+ self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
+ self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
+ self.OnSceneSignal().Connect(this, &TextField::OnSceneConnect);
//Enable highightability
- self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true );
+ self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
- DevelControl::SetInputMethodContext( *this, mInputMethodContext );
+ DevelControl::SetInputMethodContext(*this, mInputMethodContext);
- if( Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == mExceedPolicy )
+ if(Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == mExceedPolicy)
{
EnableClipping();
}
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::ENTRY ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::ENTRY));
+ });
}
-void TextField::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
+void TextField::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnStyleChange\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnStyleChange\n");
- switch ( change )
+ switch(change)
{
case StyleChange::DEFAULT_FONT_CHANGE:
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnStyleChange DEFAULT_FONT_CHANGE\n");
- const std::string& newFont = GetImpl( styleManager ).GetDefaultFontFamily();
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnStyleChange DEFAULT_FONT_CHANGE\n");
+ const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily();
// Property system did not set the font so should update it.
- mController->UpdateAfterFontChange( newFont );
+ mController->UpdateAfterFontChange(newFont);
RelayoutRequest();
break;
}
case StyleChange::DEFAULT_FONT_SIZE_CHANGE:
{
- GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
+ GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner()));
RelayoutRequest();
break;
}
}
// Up call to Control
- Control::OnStyleChange( styleManager, change );
+ Control::OnStyleChange(styleManager, change);
}
Vector3 TextField::GetNaturalSize()
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
Vector3 naturalSize = mController->GetNaturalSize();
- naturalSize.width += ( padding.start + padding.end );
- naturalSize.height += ( padding.top + padding.bottom );
+ naturalSize.width += (padding.start + padding.end);
+ naturalSize.height += (padding.top + padding.bottom);
return naturalSize;
}
-float TextField::GetHeightForWidth( float width )
+float TextField::GetHeightForWidth(float width)
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
- return mController->GetHeightForWidth( width ) + padding.top + padding.bottom;
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
+ return mController->GetHeightForWidth(width) + padding.top + padding.bottom;
}
-void TextField::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void TextField::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField OnRelayout\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField OnRelayout\n");
Actor self = Self();
Extents padding;
- padding = self.GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = self.GetProperty<Extents>(Toolkit::Control::Property::PADDING);
- Vector2 contentSize( size.x - ( padding.start + padding.end ), size.y - ( padding.top + padding.bottom ) );
+ Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom));
// Support Right-To-Left of padding
Dali::LayoutDirection::Type layoutDirection;
- if( mController->IsMatchSystemLanguageDirection() )
+ if(mController->IsMatchSystemLanguageDirection())
{
- layoutDirection = static_cast<Dali::LayoutDirection::Type>( DevelWindow::Get( self ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ layoutDirection = static_cast<Dali::LayoutDirection::Type>(DevelWindow::Get(self).GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
}
else
{
- layoutDirection = static_cast<Dali::LayoutDirection::Type>( self.GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ layoutDirection = static_cast<Dali::LayoutDirection::Type>(self.GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
}
- if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
+ if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
{
- std::swap( padding.start, padding.end );
+ std::swap(padding.start, padding.end);
}
- if( mStencil )
+ if(mStencil)
{
- mStencil.SetProperty( Actor::Property::POSITION, Vector2( padding.start, padding.top ));
+ mStencil.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
}
- if( mActiveLayer )
+ if(mActiveLayer)
{
- mActiveLayer.SetProperty( Actor::Property::POSITION, Vector2( padding.start, padding.top ));
+ mActiveLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top));
}
- const Text::Controller::UpdateTextType updateTextType = mController->Relayout( contentSize, layoutDirection );
+ const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection);
- if( ( Text::Controller::NONE_UPDATED != updateTextType ) ||
- !mRenderer )
+ if((Text::Controller::NONE_UPDATED != updateTextType) ||
+ !mRenderer)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnRelayout %p Displaying new contents\n", mController.Get() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnRelayout %p Displaying new contents\n", mController.Get());
- if( mDecorator &&
- ( Text::Controller::NONE_UPDATED != ( Text::Controller::DECORATOR_UPDATED & updateTextType ) ) )
+ if(mDecorator &&
+ (Text::Controller::NONE_UPDATED != (Text::Controller::DECORATOR_UPDATED & updateTextType)))
{
- mDecorator->Relayout( size );
+ mDecorator->Relayout(size);
}
- if( !mRenderer )
+ if(!mRenderer)
{
- mRenderer = Backend::Get().NewRenderer( mRenderingBackend );
+ mRenderer = Backend::Get().NewRenderer(mRenderingBackend);
}
- RenderText( updateTextType );
-
+ RenderText(updateTextType);
}
// The text-field emits signals when the input style changes. These changes of style are
// detected during the relayout process (size negotiation), i.e after the cursor has been moved. Signals
// can't be emitted during the size negotiation as the callbacks may update the UI.
// The text-field adds an idle callback to the adaptor to emit the signals after the size negotiation.
- if( !mController->IsInputStyleChangedSignalsQueueEmpty() )
+ if(!mController->IsInputStyleChangedSignalsQueueEmpty())
{
- if( Adaptor::IsAvailable() )
+ if(Adaptor::IsAvailable())
{
Adaptor& adaptor = Adaptor::Get();
- if( NULL == mIdleCallback )
+ if(NULL == mIdleCallback)
{
// @note: The callback manager takes the ownership of the callback object.
- mIdleCallback = MakeCallback( this, &TextField::OnIdleSignal );
- adaptor.AddIdle( mIdleCallback, false );
+ mIdleCallback = MakeCallback(this, &TextField::OnIdleSignal);
+ adaptor.AddIdle(mIdleCallback, false);
}
}
}
}
-Text::ControllerPtr TextField::getController() { return mController; }
+Text::ControllerPtr TextField::getController()
+{
+ return mController;
+}
-void TextField::RenderText( Text::Controller::UpdateTextType updateTextType )
+void TextField::RenderText(Text::Controller::UpdateTextType updateTextType)
{
Actor renderableActor;
- if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) )
+ if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType))
{
- if( mRenderer )
+ if(mRenderer)
{
- Dali::Toolkit::TextField handle = Dali::Toolkit::TextField( GetOwner() );
+ Dali::Toolkit::TextField handle = Dali::Toolkit::TextField(GetOwner());
- renderableActor = mRenderer->Render( mController->GetView(),
- handle,
- Property::INVALID_INDEX, // Animatable property not supported
- mAlignmentOffset,
- DepthIndex::CONTENT );
+ renderableActor = mRenderer->Render(mController->GetView(),
+ handle,
+ Property::INVALID_INDEX, // Animatable property not supported
+ mAlignmentOffset,
+ DepthIndex::CONTENT);
}
- if( renderableActor != mRenderableActor )
+ if(renderableActor != mRenderableActor)
{
- UnparentAndReset( mBackgroundActor );
- UnparentAndReset( mRenderableActor );
+ UnparentAndReset(mBackgroundActor);
+ UnparentAndReset(mRenderableActor);
mRenderableActor = renderableActor;
- if ( mRenderableActor )
+ if(mRenderableActor)
{
mBackgroundActor = mController->CreateBackgroundActor();
}
}
}
- if( mRenderableActor )
+ if(mRenderableActor)
{
const Vector2& scrollOffset = mController->GetTextModel()->GetScrollPosition();
float renderableActorPositionX, renderableActorPositionY;
- if( mStencil )
+ if(mStencil)
{
renderableActorPositionX = scrollOffset.x + mAlignmentOffset;
renderableActorPositionY = scrollOffset.y;
else
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
// Support Right-To-Left of padding
- Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>( Self().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
- if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
+ Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
+ if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
{
- std::swap( padding.start, padding.end );
+ std::swap(padding.start, padding.end);
}
renderableActorPositionX = scrollOffset.x + mAlignmentOffset + padding.start;
renderableActorPositionY = scrollOffset.y + padding.top;
}
- mRenderableActor.SetProperty( Actor::Property::POSITION, Vector2( renderableActorPositionX, renderableActorPositionY ));
+ mRenderableActor.SetProperty(Actor::Property::POSITION, Vector2(renderableActorPositionX, renderableActorPositionY));
// Make sure the actors are parented correctly with/without clipping
Actor self = mStencil ? mStencil : Self();
Actor highlightActor;
- for( std::vector<Actor>::iterator it = mClippingDecorationActors.begin(),
- endIt = mClippingDecorationActors.end();
- it != endIt;
- ++it )
+ for(std::vector<Actor>::iterator it = mClippingDecorationActors.begin(),
+ endIt = mClippingDecorationActors.end();
+ it != endIt;
+ ++it)
{
- self.Add( *it );
+ self.Add(*it);
it->LowerToBottom();
- if ( it->GetProperty< std::string >( Dali::Actor::Property::NAME ) == "HighlightActor" )
+ if(it->GetProperty<std::string>(Dali::Actor::Property::NAME) == "HighlightActor")
{
highlightActor = *it;
}
}
mClippingDecorationActors.clear();
- self.Add( mRenderableActor );
+ self.Add(mRenderableActor);
- if ( mBackgroundActor )
+ if(mBackgroundActor)
{
- if ( mDecorator && mDecorator->IsHighlightVisible() )
+ if(mDecorator && mDecorator->IsHighlightVisible())
{
- self.Add( mBackgroundActor );
- mBackgroundActor.SetProperty( Actor::Property::POSITION, Vector2( renderableActorPositionX, renderableActorPositionY) ); // In text field's coords.
- mBackgroundActor.LowerBelow( highlightActor );
+ self.Add(mBackgroundActor);
+ mBackgroundActor.SetProperty(Actor::Property::POSITION, Vector2(renderableActorPositionX, renderableActorPositionY)); // In text field's coords.
+ mBackgroundActor.LowerBelow(highlightActor);
}
else
{
- mRenderableActor.Add( mBackgroundActor );
- mBackgroundActor.SetProperty( Actor::Property::POSITION, Vector2( 0.0f, 0.0f ) ); // In renderable actor's coords.
+ mRenderableActor.Add(mBackgroundActor);
+ mBackgroundActor.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f)); // In renderable actor's coords.
mBackgroundActor.LowerToBottom();
}
}
void TextField::OnKeyInputFocusGained()
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnKeyInputFocusGained %p\n", mController.Get() );
- if ( mInputMethodContext && IsEditable() )
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnKeyInputFocusGained %p\n", mController.Get());
+ if(mInputMethodContext && IsEditable())
{
// All input panel properties, such as layout, return key type, and input hint, should be set before input panel activates (or shows).
- mInputMethodContext.ApplyOptions( mInputMethodOptions );
- mInputMethodContext.NotifyTextInputMultiLine( false );
+ mInputMethodContext.ApplyOptions(mInputMethodOptions);
+ mInputMethodContext.NotifyTextInputMultiLine(false);
- mInputMethodContext.StatusChangedSignal().Connect( this, &TextField::KeyboardStatusChanged );
+ mInputMethodContext.StatusChangedSignal().Connect(this, &TextField::KeyboardStatusChanged);
- mInputMethodContext.EventReceivedSignal().Connect( this, &TextField::OnInputMethodContextEvent );
+ mInputMethodContext.EventReceivedSignal().Connect(this, &TextField::OnInputMethodContextEvent);
// Notify that the text editing start.
mInputMethodContext.Activate();
// When window gain lost focus, the inputMethodContext is deactivated. Thus when window gain focus again, the inputMethodContext must be activated.
- mInputMethodContext.SetRestoreAfterFocusLost( true );
+ mInputMethodContext.SetRestoreAfterFocusLost(true);
}
- ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
+ ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
- if ( notifier )
+ if(notifier)
{
- notifier.ContentSelectedSignal().Connect( this, &TextField::OnClipboardTextSelected );
+ notifier.ContentSelectedSignal().Connect(this, &TextField::OnClipboardTextSelected);
}
mController->KeyboardFocusGainEvent(); // Called in the case of no virtual keyboard to trigger this event
- EmitKeyInputFocusSignal( true ); // Calls back into the Control hence done last.
+ EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last.
}
void TextField::OnKeyInputFocusLost()
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField:OnKeyInputFocusLost %p\n", mController.Get() );
- if ( mInputMethodContext )
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField:OnKeyInputFocusLost %p\n", mController.Get());
+ if(mInputMethodContext)
{
- mInputMethodContext.StatusChangedSignal().Disconnect( this, &TextField::KeyboardStatusChanged );
+ mInputMethodContext.StatusChangedSignal().Disconnect(this, &TextField::KeyboardStatusChanged);
// The text editing is finished. Therefore the inputMethodContext don't have restore activation.
- mInputMethodContext.SetRestoreAfterFocusLost( false );
+ mInputMethodContext.SetRestoreAfterFocusLost(false);
// Notify that the text editing finish.
mInputMethodContext.Deactivate();
- mInputMethodContext.EventReceivedSignal().Disconnect( this, &TextField::OnInputMethodContextEvent );
+ mInputMethodContext.EventReceivedSignal().Disconnect(this, &TextField::OnInputMethodContextEvent);
}
- ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
+ ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
- if ( notifier )
+ if(notifier)
{
- notifier.ContentSelectedSignal().Disconnect( this, &TextField::OnClipboardTextSelected );
+ notifier.ContentSelectedSignal().Disconnect(this, &TextField::OnClipboardTextSelected);
}
mController->KeyboardFocusLostEvent();
- EmitKeyInputFocusSignal( false ); // Calls back into the Control hence done last.
+ EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last.
}
bool TextField::OnAccessibilityActivated()
return true;
}
-void TextField::OnTap( const TapGesture& gesture )
+void TextField::OnTap(const TapGesture& gesture)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnTap %p\n", mController.Get() );
- if ( mInputMethodContext && IsEditable() )
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnTap %p\n", mController.Get());
+ if(mInputMethodContext && IsEditable())
{
mInputMethodContext.Activate();
}
// Deliver the tap before the focus event to controller; this allows us to detect when focus is gained due to tap-gestures
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
const Vector2& localPoint = gesture.GetLocalPoint();
- mController->TapEvent( gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top );
+ mController->TapEvent(gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top);
SetKeyInputFocus();
}
-void TextField::OnPan( const PanGesture& gesture )
+void TextField::OnPan(const PanGesture& gesture)
{
- mController->PanEvent( gesture.GetState(), gesture.GetDisplacement() );
+ mController->PanEvent(gesture.GetState(), gesture.GetDisplacement());
}
-void TextField::OnLongPress( const LongPressGesture& gesture )
+void TextField::OnLongPress(const LongPressGesture& gesture)
{
- if ( mInputMethodContext && IsEditable() )
+ if(mInputMethodContext && IsEditable())
{
mInputMethodContext.Activate();
}
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
const Vector2& localPoint = gesture.GetLocalPoint();
- mController->LongPressEvent( gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top );
+ mController->LongPressEvent(gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top);
SetKeyInputFocus();
}
-bool TextField::OnKeyEvent( const KeyEvent& event )
+bool TextField::OnKeyEvent(const KeyEvent& event)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode());
- if( Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape() )
+ if(Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape())
{
// Make sure ClearKeyInputFocus when only key is up
- if( event.GetState() == KeyEvent::UP )
+ if(event.GetState() == KeyEvent::UP)
{
ClearKeyInputFocus();
}
return true;
}
- else if( Dali::DevelKey::DALI_KEY_RETURN == event.GetKeyCode() )
+ else if(Dali::DevelKey::DALI_KEY_RETURN == event.GetKeyCode())
{
// Do nothing when enter is comming.
return false;
}
- return mController->KeyEvent( event );
+ return mController->KeyEvent(event);
}
void TextField::RequestTextRelayout()
return mController->IsEditable();
}
-void TextField::SetEditable( bool editable )
+void TextField::SetEditable(bool editable)
{
mController->SetEditable(editable);
- if ( mInputMethodContext && !editable )
+ if(mInputMethodContext && !editable)
{
mInputMethodContext.Deactivate();
}
}
-void TextField::TextInserted( unsigned int position, unsigned int length, const std::string &content )
+void TextField::TextInserted(unsigned int position, unsigned int length, const std::string& content)
{
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
- Control::Impl::GetAccessibilityObject( Self() )->EmitTextInserted( position, length, content );
+ Control::Impl::GetAccessibilityObject(Self())->EmitTextInserted(position, length, content);
}
}
-void TextField::TextDeleted( unsigned int position, unsigned int length, const std::string &content )
+void TextField::TextDeleted(unsigned int position, unsigned int length, const std::string& content)
{
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
- Control::Impl::GetAccessibilityObject( Self() )->EmitTextDeleted( position, length, content );
+ Control::Impl::GetAccessibilityObject(Self())->EmitTextDeleted(position, length, content);
}
}
-void TextField::CaretMoved( unsigned int position )
+void TextField::CaretMoved(unsigned int position)
{
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
- Control::Impl::GetAccessibilityObject( Self() )->EmitTextCaretMoved( position );
+ Control::Impl::GetAccessibilityObject(Self())->EmitTextCaretMoved(position);
}
}
void TextField::TextChanged()
{
- Dali::Toolkit::TextField handle( GetOwner() );
- mTextChangedSignal.Emit( handle );
+ Dali::Toolkit::TextField handle(GetOwner());
+ mTextChangedSignal.Emit(handle);
}
void TextField::MaxLengthReached()
{
- Dali::Toolkit::TextField handle( GetOwner() );
- mMaxLengthReachedSignal.Emit( handle );
+ Dali::Toolkit::TextField handle(GetOwner());
+ mMaxLengthReachedSignal.Emit(handle);
}
-void TextField::InputStyleChanged( Text::InputStyle::Mask inputStyleMask )
+void TextField::InputStyleChanged(Text::InputStyle::Mask inputStyleMask)
{
- Dali::Toolkit::TextField handle( GetOwner() );
+ Dali::Toolkit::TextField handle(GetOwner());
Toolkit::TextField::InputStyle::Mask fieldInputStyleMask = Toolkit::TextField::InputStyle::NONE;
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_COLOR ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_COLOR))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::COLOR );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::COLOR);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_FONT_FAMILY ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_FAMILY))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_FAMILY );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_FAMILY);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_POINT_SIZE ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_POINT_SIZE))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::POINT_SIZE );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::POINT_SIZE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_FONT_WEIGHT ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_WEIGHT))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_FONT_WIDTH ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_WIDTH))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_FONT_SLANT ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_FONT_SLANT))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_UNDERLINE ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_UNDERLINE))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::UNDERLINE );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::UNDERLINE);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_SHADOW ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_SHADOW))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::SHADOW );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::SHADOW);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_EMBOSS ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_EMBOSS))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::EMBOSS );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::EMBOSS);
}
- if( InputStyle::NONE != static_cast<InputStyle::Mask>( inputStyleMask & InputStyle::INPUT_OUTLINE ) )
+ if(InputStyle::NONE != static_cast<InputStyle::Mask>(inputStyleMask & InputStyle::INPUT_OUTLINE))
{
- fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>( fieldInputStyleMask | Toolkit::TextField::InputStyle::OUTLINE );
+ fieldInputStyleMask = static_cast<Toolkit::TextField::InputStyle::Mask>(fieldInputStyleMask | Toolkit::TextField::InputStyle::OUTLINE);
}
- mInputStyleChangedSignal.Emit( handle, fieldInputStyleMask );
+ mInputStyleChangedSignal.Emit(handle, fieldInputStyleMask);
}
-void TextField::AddDecoration( Actor& actor, bool needsClipping )
+void TextField::AddDecoration(Actor& actor, bool needsClipping)
{
- if( actor )
+ if(actor)
{
- if( needsClipping )
+ if(needsClipping)
{
- mClippingDecorationActors.push_back( actor );
+ mClippingDecorationActors.push_back(actor);
}
else
{
- actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- Self().Add( actor );
+ actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ Self().Add(actor);
mActiveLayer = actor;
}
}
}
-void TextField::OnSceneConnect( Dali::Actor actor )
+void TextField::OnSceneConnect(Dali::Actor actor)
{
- if ( mHasBeenStaged )
+ if(mHasBeenStaged)
{
- RenderText( static_cast<Text::Controller::UpdateTextType>( Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED ) );
+ RenderText(static_cast<Text::Controller::UpdateTextType>(Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED));
}
else
{
}
}
-InputMethodContext::CallbackData TextField::OnInputMethodContextEvent( Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent )
+InputMethodContext::CallbackData TextField::OnInputMethodContextEvent(Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName );
- return mController->OnInputMethodContextEvent( inputMethodContext, inputMethodContextEvent );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName);
+ return mController->OnInputMethodContextEvent(inputMethodContext, inputMethodContextEvent);
}
-void TextField::GetHandleImagePropertyValue( Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType )
+void TextField::GetHandleImagePropertyValue(Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType)
{
- if( mDecorator )
+ if(mDecorator)
{
Property::Map map;
- map[ IMAGE_MAP_FILENAME_STRING ] = mDecorator->GetHandleImage( handleType, handleImageType );
- value = map;
+ map[IMAGE_MAP_FILENAME_STRING] = mDecorator->GetHandleImage(handleType, handleImageType);
+ value = map;
}
}
void TextField::EnableClipping()
{
- if( !mStencil )
+ if(!mStencil)
{
// Creates an extra control to be used as stencil buffer.
mStencil = Control::New();
- mStencil.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- mStencil.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
+ mStencil.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ mStencil.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
// Creates a background visual. Even if the color is transparent it updates the stencil.
- mStencil.SetProperty( Toolkit::Control::Property::BACKGROUND,
- Property::Map().Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR ).
- Add( ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT ) );
+ mStencil.SetProperty(Toolkit::Control::Property::BACKGROUND,
+ Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT));
// Enable the clipping property.
- mStencil.SetProperty( Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX );
- mStencil.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mStencil.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX);
+ mStencil.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
- Self().Add( mStencil );
+ Self().Add(mStencil);
}
}
-void TextField::OnClipboardTextSelected( ClipboardEventNotifier& clipboard )
+void TextField::OnClipboardTextSelected(ClipboardEventNotifier& clipboard)
{
mController->PasteClipboardItemEvent();
}
void TextField::KeyboardStatusChanged(bool keyboardShown)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown);
// Just hide the grab handle when keyboard is hidden.
- if (!keyboardShown )
+ if(!keyboardShown)
{
mController->KeyboardFocusLostEvent();
}
}
}
-void TextField::OnSceneConnection( int depth )
+void TextField::OnSceneConnection(int depth)
{
// Sets the depth to the visuals inside the text's decorator.
- mDecorator->SetTextDepth( depth );
+ mDecorator->SetTextDepth(depth);
// The depth of the text renderer is set in the RenderText() called from OnRelayout().
// Call the Control::OnSceneConnection() to set the depth of the background.
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
}
-bool TextField::OnTouched( Actor actor, const TouchEvent& touch )
+bool TextField::OnTouched(Actor actor, const TouchEvent& touch)
{
return false;
}
}
TextField::TextField()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mIdleCallback( NULL ),
- mAlignmentOffset( 0.f ),
- mRenderingBackend( DEFAULT_RENDERING_BACKEND ),
- mExceedPolicy( Dali::Toolkit::TextField::EXCEED_POLICY_CLIP ),
- mHasBeenStaged( false )
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mIdleCallback(NULL),
+ mAlignmentOffset(0.f),
+ mRenderingBackend(DEFAULT_RENDERING_BACKEND),
+ mExceedPolicy(Dali::Toolkit::TextField::EXCEED_POLICY_CLIP),
+ mHasBeenStaged(false)
{
}
TextField::~TextField()
{
- UnparentAndReset( mStencil );
+ UnparentAndReset(mStencil);
- if( ( NULL != mIdleCallback ) && Adaptor::IsAvailable() )
+ if((NULL != mIdleCallback) && Adaptor::IsAvailable())
{
- Adaptor::Get().RemoveIdle( mIdleCallback );
+ Adaptor::Get().RemoveIdle(mIdleCallback);
}
}
std::string TextField::AccessibleImpl::GetName()
{
- auto slf = Toolkit::TextField::DownCast( self );
- return slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >();
+ auto slf = Toolkit::TextField::DownCast(self);
+ return slf.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
}
-std::string TextField::AccessibleImpl::GetText( size_t startOffset,
- size_t endOffset )
+std::string TextField::AccessibleImpl::GetText(size_t startOffset,
+ size_t endOffset)
{
- if( endOffset <= startOffset )
+ if(endOffset <= startOffset)
return {};
- auto slf = Toolkit::TextField::DownCast( self );
+ auto slf = Toolkit::TextField::DownCast(self);
auto txt =
- slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >();
+ slf.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
- if( startOffset > txt.size() || endOffset > txt.size() )
+ if(startOffset > txt.size() || endOffset > txt.size())
return {};
- return txt.substr( startOffset, endOffset - startOffset );
+ return txt.substr(startOffset, endOffset - startOffset);
}
size_t TextField::AccessibleImpl::GetCharacterCount()
{
- auto slf = Toolkit::TextField::DownCast( self );
+ auto slf = Toolkit::TextField::DownCast(self);
auto txt =
- slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >();
+ slf.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
return txt.size();
}
size_t TextField::AccessibleImpl::GetCaretOffset()
{
- auto slf = Toolkit::TextField::DownCast( self );
- return Dali::Toolkit::GetImpl( slf ).getController()->GetCursorPosition();
+ auto slf = Toolkit::TextField::DownCast(self);
+ return Dali::Toolkit::GetImpl(slf).getController()->GetCursorPosition();
}
bool TextField::AccessibleImpl::SetCaretOffset(size_t offset)
{
- auto slf = Toolkit::TextField::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >();
- if (offset > txt.size())
+ auto slf = Toolkit::TextField::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
+ if(offset > txt.size())
return false;
- auto& slfImpl = Dali::Toolkit::GetImpl( slf );
- slfImpl.getController()->ResetCursorPosition( offset );
+ auto& slfImpl = Dali::Toolkit::GetImpl(slf);
+ slfImpl.getController()->ResetCursorPosition(offset);
slfImpl.RequestTextRelayout();
return true;
}
Dali::Accessibility::Range TextField::AccessibleImpl::GetTextAtOffset(
- size_t offset, Dali::Accessibility::TextBoundary boundary )
+ size_t offset, Dali::Accessibility::TextBoundary boundary)
{
- auto slf = Toolkit::TextField::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >();
+ auto slf = Toolkit::TextField::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
auto txt_size = txt.size();
auto range = Dali::Accessibility::Range{};
switch(boundary)
{
case Dali::Accessibility::TextBoundary::CHARACTER:
+ {
+ if(offset < txt_size)
{
- if (offset < txt_size)
- {
- range.content = txt[offset];
- range.startOffset = offset;
- range.endOffset = offset + 1;
- }
+ range.content = txt[offset];
+ range.startOffset = offset;
+ range.endOffset = offset + 1;
}
- break;
+ }
+ break;
case Dali::Accessibility::TextBoundary::WORD:
case Dali::Accessibility::TextBoundary::LINE:
+ {
+ auto txt_c_string = txt.c_str();
+ auto breaks = std::vector<char>(txt_size, 0);
+ if(boundary == Dali::Accessibility::TextBoundary::WORD)
+ Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data());
+ else
+ Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data());
+ auto index = 0u;
+ auto counter = 0u;
+ while(index < txt_size && counter <= offset)
{
- auto txt_c_string = txt.c_str();
- auto breaks = std::vector< char >( txt_size, 0 );
- if(boundary == Dali::Accessibility::TextBoundary::WORD)
- Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data());
+ auto start = index;
+ if(breaks[index])
+ {
+ while(breaks[index])
+ index++;
+ counter++;
+ }
else
- Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data());
- auto index = 0u;
- auto counter = 0u;
- while( index < txt_size && counter <= offset )
{
- auto start = index;
- if(breaks[index])
- {
- while(breaks[index])
- index++;
+ if(boundary == Dali::Accessibility::TextBoundary::WORD)
+ index++;
+ if(boundary == Dali::Accessibility::TextBoundary::LINE)
counter++;
- }
- else
- {
- if (boundary == Dali::Accessibility::TextBoundary::WORD)
- index++;
- if (boundary == Dali::Accessibility::TextBoundary::LINE)
- counter++;
- }
- if ((counter > 0) && ((counter - 1) == offset))
- {
- range.content = txt.substr(start, index - start + 1);
- range.startOffset = start;
- range.endOffset = index + 1;
- }
- if (boundary == Dali::Accessibility::TextBoundary::LINE)
- index++;
}
+ if((counter > 0) && ((counter - 1) == offset))
+ {
+ range.content = txt.substr(start, index - start + 1);
+ range.startOffset = start;
+ range.endOffset = index + 1;
+ }
+ if(boundary == Dali::Accessibility::TextBoundary::LINE)
+ index++;
}
- break;
+ }
+ break;
case Dali::Accessibility::TextBoundary::SENTENCE:
- {
- /* not supported by efl */
- }
- break;
+ {
+ /* not supported by efl */
+ }
+ break;
case Dali::Accessibility::TextBoundary::PARAGRAPH:
- {
- /* Paragraph is not supported by libunibreak library */
- }
- break;
+ {
+ /* Paragraph is not supported by libunibreak library */
+ }
+ break;
default:
break;
}
}
Dali::Accessibility::Range
-TextField::AccessibleImpl::GetSelection( size_t selectionNum )
+TextField::AccessibleImpl::GetSelection(size_t selectionNum)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return {};
- auto slf = Toolkit::TextField::DownCast( self );
- auto ctrl = Dali::Toolkit::GetImpl( slf ).getController();
+ auto slf = Toolkit::TextField::DownCast(self);
+ auto ctrl = Dali::Toolkit::GetImpl(slf).getController();
std::string ret;
- ctrl->RetrieveSelection( ret );
+ ctrl->RetrieveSelection(ret);
auto r = ctrl->GetSelectionIndexes();
- return { static_cast<size_t>(r.first), static_cast<size_t>(r.second), ret };
+ return {static_cast<size_t>(r.first), static_cast<size_t>(r.second), ret};
}
-bool TextField::AccessibleImpl::RemoveSelection( size_t selectionNum )
+bool TextField::AccessibleImpl::RemoveSelection(size_t selectionNum)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return false;
- auto slf = Toolkit::TextField::DownCast( self );
- Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( 0, 0 );
+ auto slf = Toolkit::TextField::DownCast(self);
+ Dali::Toolkit::GetImpl(slf).getController()->SetSelection(0, 0);
return true;
}
-bool TextField::AccessibleImpl::SetSelection( size_t selectionNum,
- size_t startOffset,
- size_t endOffset )
+bool TextField::AccessibleImpl::SetSelection(size_t selectionNum,
+ size_t startOffset,
+ size_t endOffset)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return false;
- auto slf = Toolkit::TextField::DownCast( self );
- Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( startOffset,
- endOffset );
+ auto slf = Toolkit::TextField::DownCast(self);
+ Dali::Toolkit::GetImpl(slf).getController()->SetSelection(startOffset,
+ endOffset);
return true;
}
-bool TextField::AccessibleImpl::CopyText( size_t startPosition,
- size_t endPosition )
+bool TextField::AccessibleImpl::CopyText(size_t startPosition,
+ size_t endPosition)
{
- if( endPosition <= startPosition )
+ if(endPosition <= startPosition)
return false;
- auto slf = Toolkit::TextField::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get<std::string>();
- Dali::Toolkit::GetImpl( slf ).getController()->CopyStringToClipboard( txt.substr(startPosition, endPosition - startPosition) );
+ auto slf = Toolkit::TextField::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
+ Dali::Toolkit::GetImpl(slf).getController()->CopyStringToClipboard(txt.substr(startPosition, endPosition - startPosition));
return true;
}
-bool TextField::AccessibleImpl::CutText( size_t startPosition,
- size_t endPosition )
+bool TextField::AccessibleImpl::CutText(size_t startPosition,
+ size_t endPosition)
{
- if( endPosition <= startPosition )
+ if(endPosition <= startPosition)
return false;
- auto slf = Toolkit::TextField::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get<std::string>();
- Dali::Toolkit::GetImpl( slf ).getController()->CopyStringToClipboard( txt.substr(startPosition, endPosition - startPosition) );
+ auto slf = Toolkit::TextField::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextField::Property::TEXT).Get<std::string>();
+ Dali::Toolkit::GetImpl(slf).getController()->CopyStringToClipboard(txt.substr(startPosition, endPosition - startPosition));
- slf.SetProperty( Toolkit::TextField::Property::TEXT,
- txt.substr( 0, startPosition ) + txt.substr( endPosition - startPosition, txt.size()));
+ slf.SetProperty(Toolkit::TextField::Property::TEXT,
+ txt.substr(0, startPosition) + txt.substr(endPosition - startPosition, txt.size()));
return true;
}
auto states = Control::Impl::AccessibleImpl::CalculateStates();
- states[State::EDITABLE] = true;
+ states[State::EDITABLE] = true;
states[State::FOCUSABLE] = true;
Toolkit::Control focusControl = Toolkit::KeyInputFocusManager::Get().GetCurrentFocusControl();
- if (self == focusControl)
+ if(self == focusControl)
{
states[State::FOCUSED] = true;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/text-controls/text-label-impl.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/common/dali-common.h>
-#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/devel-api/object/property-helper-devel.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
#include <dali/devel-api/adaptor-framework/window-devel.h>
+#include <dali/devel-api/common/stage.h>
+#include <dali/devel-api/object/property-helper-devel.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/common/dali-common.h>
+#include <dali/public-api/object/type-registry-helper.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/text/text-enumerations.h>
-#include <dali-toolkit/devel-api/text/rendering-backend.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
+#include <dali-toolkit/devel-api/text/rendering-backend.h>
+#include <dali-toolkit/internal/styling/style-manager-impl.h>
#include <dali-toolkit/internal/text/property-string-parser.h>
#include <dali-toolkit/internal/text/rendering/text-backend.h>
+#include <dali-toolkit/internal/text/text-definitions.h>
#include <dali-toolkit/internal/text/text-effects-style.h>
#include <dali-toolkit/internal/text/text-font-style.h>
#include <dali-toolkit/internal/text/text-view.h>
-#include <dali-toolkit/internal/text/text-definitions.h>
-#include <dali-toolkit/internal/styling/style-manager-impl.h>
+#include <dali-toolkit/public-api/text/text-enumerations.h>
-#include <dali-toolkit/public-api/align-enumerations.h>
-#include <dali-toolkit/internal/text/text-enumerations-impl.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
#include <dali-toolkit/devel-api/visual-factory/visual-base.h>
+#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
+#include <dali-toolkit/internal/text/text-enumerations-impl.h>
+#include <dali-toolkit/public-api/align-enumerations.h>
#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
#include <dali-toolkit/devel-api/controls/text-controls/text-label-devel.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND;
* 0.0f aligns the text to the top, 0.5f aligns the text to the center, 1.0f aligns the text to the bottom.
* The alignment depends on the alignment value of the text label (Use Text::VerticalAlignment enumerations).
*/
-const float VERTICAL_ALIGNMENT_TABLE[ Text::VerticalAlignment::BOTTOM + 1 ] =
-{
- 0.0f, // VerticalAlignment::TOP
- 0.5f, // VerticalAlignment::CENTER
- 1.0f // VerticalAlignment::BOTTOM
+const float VERTICAL_ALIGNMENT_TABLE[Text::VerticalAlignment::BOTTOM + 1] =
+ {
+ 0.0f, // VerticalAlignment::TOP
+ 0.5f, // VerticalAlignment::CENTER
+ 1.0f // VerticalAlignment::BOTTOM
};
-const std::string TEXT_FIT_ENABLE_KEY( "enable" );
-const std::string TEXT_FIT_MIN_SIZE_KEY( "minSize" );
-const std::string TEXT_FIT_MAX_SIZE_KEY( "maxSize" );
-const std::string TEXT_FIT_STEP_SIZE_KEY( "stepSize" );
-const std::string TEXT_FIT_FONT_SIZE_TYPE_KEY( "fontSizeType" );
+const std::string TEXT_FIT_ENABLE_KEY("enable");
+const std::string TEXT_FIT_MIN_SIZE_KEY("minSize");
+const std::string TEXT_FIT_MAX_SIZE_KEY("maxSize");
+const std::string TEXT_FIT_STEP_SIZE_KEY("stepSize");
+const std::string TEXT_FIT_FONT_SIZE_TYPE_KEY("fontSizeType");
-#if defined ( DEBUG_ENABLED )
+#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
const Scripting::StringEnum AUTO_SCROLL_STOP_MODE_TABLE[] =
-{
- { "IMMEDIATE", Toolkit::TextLabel::AutoScrollStopMode::IMMEDIATE },
- { "FINISH_LOOP", Toolkit::TextLabel::AutoScrollStopMode::FINISH_LOOP },
+ {
+ {"IMMEDIATE", Toolkit::TextLabel::AutoScrollStopMode::IMMEDIATE},
+ {"FINISH_LOOP", Toolkit::TextLabel::AutoScrollStopMode::FINISH_LOOP},
};
-const unsigned int AUTO_SCROLL_STOP_MODE_TABLE_COUNT = sizeof( AUTO_SCROLL_STOP_MODE_TABLE ) / sizeof( AUTO_SCROLL_STOP_MODE_TABLE[0] );
+const unsigned int AUTO_SCROLL_STOP_MODE_TABLE_COUNT = sizeof(AUTO_SCROLL_STOP_MODE_TABLE) / sizeof(AUTO_SCROLL_STOP_MODE_TABLE[0]);
// Type registration
BaseHandle Create()
return Toolkit::TextLabel::New();
}
+// clang-format off
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextLabel, Toolkit::Control, Create );
-
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "text", STRING, TEXT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "fontFamily", STRING, FONT_FAMILY )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "fontStyle", MAP, FONT_STYLE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "pointSize", FLOAT, POINT_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "multiLine", BOOLEAN, MULTI_LINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "verticalAlignment", STRING, VERTICAL_ALIGNMENT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "enableMarkup", BOOLEAN, ENABLE_MARKUP )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "enableAutoScroll", BOOLEAN, ENABLE_AUTO_SCROLL )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollSpeed", INTEGER, AUTO_SCROLL_SPEED )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollLoopCount", INTEGER, AUTO_SCROLL_LOOP_COUNT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollGap", FLOAT, AUTO_SCROLL_GAP )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "lineSpacing", FLOAT, LINE_SPACING )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "underline", MAP, UNDERLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "shadow", MAP, SHADOW )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "emboss", MAP, EMBOSS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "outline", MAP, OUTLINE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "pixelSize", FLOAT, PIXEL_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "ellipsis", BOOLEAN, ELLIPSIS )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollLoopDelay", FLOAT, AUTO_SCROLL_LOOP_DELAY )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollStopMode", STRING, AUTO_SCROLL_STOP_MODE )
-DALI_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextLabel, "lineCount", INTEGER, LINE_COUNT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "lineWrapMode", INTEGER, LINE_WRAP_MODE )
-DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextLabel, "textDirection", INTEGER, TEXT_DIRECTION )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "verticalLineAlignment", INTEGER, VERTICAL_LINE_ALIGNMENT )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "textBackground", MAP, BACKGROUND )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "ignoreSpacesAfterText", BOOLEAN, IGNORE_SPACES_AFTER_TEXT )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "textFit", MAP, TEXT_FIT )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "minLineSize", FLOAT, MIN_LINE_SIZE )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "renderingBackend", INTEGER, RENDERING_BACKEND )
-DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "fontSizeScale", FLOAT, FONT_SIZE_SCALE )
-DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT( Toolkit, TextLabel, "textColor", Color::BLACK, TEXT_COLOR )
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, TextLabel, "textColorRed", TEXT_COLOR_RED, TEXT_COLOR, 0 )
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, TextLabel, "textColorGreen", TEXT_COLOR_GREEN, TEXT_COLOR, 1 )
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, TextLabel, "textColorBlue", TEXT_COLOR_BLUE, TEXT_COLOR, 2 )
-DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, TextLabel, "textColorAlpha", TEXT_COLOR_ALPHA, TEXT_COLOR, 3 )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextLabel, Toolkit::Control, Create);
+
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "text", STRING, TEXT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "fontFamily", STRING, FONT_FAMILY )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "fontStyle", MAP, FONT_STYLE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "pointSize", FLOAT, POINT_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "multiLine", BOOLEAN, MULTI_LINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "verticalAlignment", STRING, VERTICAL_ALIGNMENT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "enableMarkup", BOOLEAN, ENABLE_MARKUP )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "enableAutoScroll", BOOLEAN, ENABLE_AUTO_SCROLL )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollSpeed", INTEGER, AUTO_SCROLL_SPEED )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollLoopCount", INTEGER, AUTO_SCROLL_LOOP_COUNT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollGap", FLOAT, AUTO_SCROLL_GAP )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "lineSpacing", FLOAT, LINE_SPACING )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "underline", MAP, UNDERLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "shadow", MAP, SHADOW )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "emboss", MAP, EMBOSS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "outline", MAP, OUTLINE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "pixelSize", FLOAT, PIXEL_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "ellipsis", BOOLEAN, ELLIPSIS )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollLoopDelay", FLOAT, AUTO_SCROLL_LOOP_DELAY )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollStopMode", STRING, AUTO_SCROLL_STOP_MODE )
+DALI_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextLabel, "lineCount", INTEGER, LINE_COUNT )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "lineWrapMode", INTEGER, LINE_WRAP_MODE )
+DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextLabel, "textDirection", INTEGER, TEXT_DIRECTION )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "verticalLineAlignment", INTEGER, VERTICAL_LINE_ALIGNMENT )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "textBackground", MAP, BACKGROUND )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "ignoreSpacesAfterText", BOOLEAN, IGNORE_SPACES_AFTER_TEXT )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION)
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "textFit", MAP, TEXT_FIT )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "minLineSize", FLOAT, MIN_LINE_SIZE )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "renderingBackend", INTEGER, RENDERING_BACKEND )
+DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "fontSizeScale", FLOAT, FONT_SIZE_SCALE )
+
+DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT(Toolkit, TextLabel, "textColor", Color::BLACK, TEXT_COLOR )
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, TextLabel, "textColorRed", TEXT_COLOR_RED, TEXT_COLOR, 0)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, TextLabel, "textColorGreen", TEXT_COLOR_GREEN, TEXT_COLOR, 1)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, TextLabel, "textColorBlue", TEXT_COLOR_BLUE, TEXT_COLOR, 2)
+DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, TextLabel, "textColorAlpha", TEXT_COLOR_ALPHA, TEXT_COLOR, 3)
DALI_TYPE_REGISTRATION_END()
+// clang-format on
/// Parses the property map for the TEXT_FIT property
void ParseTextFitProperty(Text::ControllerPtr& controller, const Property::Map* propertiesMap)
{
- if ( propertiesMap && !propertiesMap->Empty() )
+ if(propertiesMap && !propertiesMap->Empty())
{
- bool enabled = false;
- float minSize = 0.f;
- float maxSize = 0.f;
- float stepSize = 0.f;
- bool isMinSizeSet = false, isMaxSizeSet = false, isStepSizeSet = false;
+ bool enabled = false;
+ float minSize = 0.f;
+ float maxSize = 0.f;
+ float stepSize = 0.f;
+ bool isMinSizeSet = false, isMaxSizeSet = false, isStepSizeSet = false;
Controller::FontSizeType type = Controller::FontSizeType::POINT_SIZE;
const unsigned int numberOfItems = propertiesMap->Count();
// Parses and applies
- for( unsigned int index = 0u; index < numberOfItems; ++index )
+ for(unsigned int index = 0u; index < numberOfItems; ++index)
{
- const KeyValuePair& valueGet = propertiesMap->GetKeyValue( index );
+ const KeyValuePair& valueGet = propertiesMap->GetKeyValue(index);
- if( ( Controller::TextFitInfo::Property::TEXT_FIT_ENABLE == valueGet.first.indexKey ) || ( TEXT_FIT_ENABLE_KEY == valueGet.first.stringKey ) )
+ if((Controller::TextFitInfo::Property::TEXT_FIT_ENABLE == valueGet.first.indexKey) || (TEXT_FIT_ENABLE_KEY == valueGet.first.stringKey))
{
/// Enable key.
- enabled = valueGet.second.Get< bool >();
+ enabled = valueGet.second.Get<bool>();
}
- else if( ( Controller::TextFitInfo::Property::TEXT_FIT_MIN_SIZE == valueGet.first.indexKey ) || ( TEXT_FIT_MIN_SIZE_KEY == valueGet.first.stringKey ) )
+ else if((Controller::TextFitInfo::Property::TEXT_FIT_MIN_SIZE == valueGet.first.indexKey) || (TEXT_FIT_MIN_SIZE_KEY == valueGet.first.stringKey))
{
/// min size.
- minSize = valueGet.second.Get< float >();
+ minSize = valueGet.second.Get<float>();
isMinSizeSet = true;
}
- else if( ( Controller::TextFitInfo::Property::TEXT_FIT_MAX_SIZE == valueGet.first.indexKey ) || ( TEXT_FIT_MAX_SIZE_KEY == valueGet.first.stringKey ) )
+ else if((Controller::TextFitInfo::Property::TEXT_FIT_MAX_SIZE == valueGet.first.indexKey) || (TEXT_FIT_MAX_SIZE_KEY == valueGet.first.stringKey))
{
/// max size.
- maxSize = valueGet.second.Get< float >();
+ maxSize = valueGet.second.Get<float>();
isMaxSizeSet = true;
}
- else if( ( Controller::TextFitInfo::Property::TEXT_FIT_STEP_SIZE == valueGet.first.indexKey ) || ( TEXT_FIT_STEP_SIZE_KEY == valueGet.first.stringKey ) )
+ else if((Controller::TextFitInfo::Property::TEXT_FIT_STEP_SIZE == valueGet.first.indexKey) || (TEXT_FIT_STEP_SIZE_KEY == valueGet.first.stringKey))
{
/// step size.
- stepSize = valueGet.second.Get< float >();
+ stepSize = valueGet.second.Get<float>();
isStepSizeSet = true;
}
- else if( ( Controller::TextFitInfo::Property::TEXT_FIT_FONT_SIZE_TYPE == valueGet.first.indexKey ) || ( TEXT_FIT_FONT_SIZE_TYPE_KEY == valueGet.first.stringKey ) )
+ else if((Controller::TextFitInfo::Property::TEXT_FIT_FONT_SIZE_TYPE == valueGet.first.indexKey) || (TEXT_FIT_FONT_SIZE_TYPE_KEY == valueGet.first.stringKey))
{
- if( "pixelSize" == valueGet.second.Get< std::string >() )
+ if("pixelSize" == valueGet.second.Get<std::string>())
{
type = Controller::FontSizeType::PIXEL_SIZE;
}
}
}
- controller->SetTextFitEnabled( enabled );
- if( isMinSizeSet )
+ controller->SetTextFitEnabled(enabled);
+ if(isMinSizeSet)
{
- controller->SetTextFitMinSize( minSize, type );
+ controller->SetTextFitMinSize(minSize, type);
}
- if( isMaxSizeSet )
+ if(isMaxSizeSet)
{
- controller->SetTextFitMaxSize( maxSize, type );
+ controller->SetTextFitMaxSize(maxSize, type);
}
- if( isStepSizeSet )
+ if(isStepSizeSet)
{
- controller->SetTextFitStepSize( stepSize, type );
+ controller->SetTextFitStepSize(stepSize, type);
}
}
}
Toolkit::TextLabel TextLabel::New()
{
// Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< TextLabel > impl = new TextLabel();
+ IntrusivePtr<TextLabel> impl = new TextLabel();
// Pass ownership to CustomActor handle
- Toolkit::TextLabel handle( *impl );
+ Toolkit::TextLabel handle(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-void TextLabel::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void TextLabel::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::TextLabel label = Toolkit::TextLabel::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextLabel label = Toolkit::TextLabel::DownCast(Dali::BaseHandle(object));
- if( label )
+ if(label)
{
- TextLabel& impl( GetImpl( label ) );
- DALI_ASSERT_ALWAYS( impl.mController && "No text contoller" );
+ TextLabel& impl(GetImpl(label));
+ DALI_ASSERT_ALWAYS(impl.mController && "No text contoller");
- switch( index )
+ switch(index)
{
case Toolkit::DevelTextLabel::Property::RENDERING_BACKEND:
{
- int backend = value.Get< int >();
+ int backend = value.Get<int>();
#ifndef ENABLE_VECTOR_BASED_TEXT_RENDERING
- if( DevelText::RENDERING_VECTOR_BASED == backend )
+ if(DevelText::RENDERING_VECTOR_BASED == backend)
{
backend = TextAbstraction::BITMAP_GLYPH; // Fallback to bitmap-based rendering
}
#endif
- if( impl.mRenderingBackend != backend )
+ if(impl.mRenderingBackend != backend)
{
impl.mRenderingBackend = backend;
impl.mTextUpdateNeeded = true;
// When using the vector-based rendering, the size of the GLyphs are different
TextAbstraction::GlyphType glyphType = (DevelText::RENDERING_VECTOR_BASED == impl.mRenderingBackend) ? TextAbstraction::VECTOR_GLYPH : TextAbstraction::BITMAP_GLYPH;
- impl.mController->SetGlyphType( glyphType );
+ impl.mController->SetGlyphType(glyphType);
}
break;
}
case Toolkit::TextLabel::Property::TEXT:
{
- impl.mController->SetText( value.Get< std::string >() );
+ impl.mController->SetText(value.Get<std::string>());
break;
}
case Toolkit::TextLabel::Property::FONT_FAMILY:
{
- const std::string& fontFamily = value.Get< std::string >();
+ const std::string& fontFamily = value.Get<std::string>();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextLabel::SetProperty Property::FONT_FAMILY newFont(%s)\n", fontFamily.c_str() );
- impl.mController->SetDefaultFontFamily( fontFamily );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextLabel::SetProperty Property::FONT_FAMILY newFont(%s)\n", fontFamily.c_str());
+ impl.mController->SetDefaultFontFamily(fontFamily);
break;
}
case Toolkit::TextLabel::Property::FONT_STYLE:
{
- SetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT );
+ SetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT);
break;
}
case Toolkit::TextLabel::Property::POINT_SIZE:
{
- const float pointSize = value.Get< float >();
+ const float pointSize = value.Get<float>();
- if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
+ if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize))
{
- impl.mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE );
+ impl.mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE);
}
break;
}
case Toolkit::TextLabel::Property::MULTI_LINE:
{
- impl.mController->SetMultiLineEnabled( value.Get< bool >() );
+ impl.mController->SetMultiLineEnabled(value.Get<bool>());
break;
}
case Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT:
{
- Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( Text::GetHorizontalAlignmentEnumeration( value, alignment ) )
+ Text::HorizontalAlignment::Type alignment(static_cast<Text::HorizontalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(Text::GetHorizontalAlignmentEnumeration(value, alignment))
{
- impl.mController->SetHorizontalAlignment( alignment );
+ impl.mController->SetHorizontalAlignment(alignment);
}
break;
}
case Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT:
{
- Toolkit::Text::VerticalAlignment::Type alignment( static_cast< Text::VerticalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( Text::GetVerticalAlignmentEnumeration( value, alignment ) )
+ Toolkit::Text::VerticalAlignment::Type alignment(static_cast<Text::VerticalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(Text::GetVerticalAlignmentEnumeration(value, alignment))
{
- impl.mController->SetVerticalAlignment( alignment );
+ impl.mController->SetVerticalAlignment(alignment);
}
break;
}
case Toolkit::TextLabel::Property::ENABLE_MARKUP:
{
const bool enableMarkup = value.Get<bool>();
- impl.mController->SetMarkupProcessorEnabled( enableMarkup );
+ impl.mController->SetMarkupProcessorEnabled(enableMarkup);
break;
}
case Toolkit::TextLabel::Property::ENABLE_AUTO_SCROLL:
{
const bool enableAutoScroll = value.Get<bool>();
// If request to auto scroll is the same as current state then do nothing.
- if ( enableAutoScroll != impl.mController->IsAutoScrollEnabled() )
+ if(enableAutoScroll != impl.mController->IsAutoScrollEnabled())
{
- // If request is disable (false) and auto scrolling is enabled then need to stop it
- if ( enableAutoScroll == false )
- {
- if( impl.mTextScroller )
- {
- impl.mTextScroller->StopScrolling();
- }
- }
- // If request is enable (true) then start autoscroll as not already running
- else
- {
- impl.mController->SetAutoScrollEnabled( enableAutoScroll );
- }
+ // If request is disable (false) and auto scrolling is enabled then need to stop it
+ if(enableAutoScroll == false)
+ {
+ if(impl.mTextScroller)
+ {
+ impl.mTextScroller->StopScrolling();
+ }
+ }
+ // If request is enable (true) then start autoscroll as not already running
+ else
+ {
+ impl.mController->SetAutoScrollEnabled(enableAutoScroll);
+ }
}
break;
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_STOP_MODE:
{
- Text::TextScrollerPtr textScroller = impl.GetTextScroller();
- Toolkit::TextLabel::AutoScrollStopMode::Type stopMode = textScroller->GetStopMode();
- if( Scripting::GetEnumerationProperty< Toolkit::TextLabel::AutoScrollStopMode::Type >( value,
- AUTO_SCROLL_STOP_MODE_TABLE,
- AUTO_SCROLL_STOP_MODE_TABLE_COUNT,
- stopMode ) )
+ Text::TextScrollerPtr textScroller = impl.GetTextScroller();
+ Toolkit::TextLabel::AutoScrollStopMode::Type stopMode = textScroller->GetStopMode();
+ if(Scripting::GetEnumerationProperty<Toolkit::TextLabel::AutoScrollStopMode::Type>(value,
+ AUTO_SCROLL_STOP_MODE_TABLE,
+ AUTO_SCROLL_STOP_MODE_TABLE_COUNT,
+ stopMode))
{
- textScroller->SetStopMode( stopMode );
+ textScroller->SetStopMode(stopMode);
}
break;
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_SPEED:
{
- impl.GetTextScroller()->SetSpeed( value.Get<int>() );
+ impl.GetTextScroller()->SetSpeed(value.Get<int>());
break;
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_LOOP_COUNT:
{
- impl.GetTextScroller()->SetLoopCount( value.Get<int>() );
+ impl.GetTextScroller()->SetLoopCount(value.Get<int>());
break;
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_LOOP_DELAY:
{
- impl.GetTextScroller()->SetLoopDelay( value.Get<float>() );
+ impl.GetTextScroller()->SetLoopDelay(value.Get<float>());
break;
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_GAP:
{
- impl.GetTextScroller()->SetGap( value.Get<float>() );
+ impl.GetTextScroller()->SetGap(value.Get<float>());
break;
}
case Toolkit::TextLabel::Property::LINE_SPACING:
{
const float lineSpacing = value.Get<float>();
- impl.mTextUpdateNeeded = impl.mController->SetDefaultLineSpacing( lineSpacing ) || impl.mTextUpdateNeeded;
+ impl.mTextUpdateNeeded = impl.mController->SetDefaultLineSpacing(lineSpacing) || impl.mTextUpdateNeeded;
break;
}
case Toolkit::TextLabel::Property::UNDERLINE:
{
- impl.mTextUpdateNeeded = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded;
+ impl.mTextUpdateNeeded = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded;
break;
}
case Toolkit::TextLabel::Property::SHADOW:
{
- impl.mTextUpdateNeeded = SetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded;
+ impl.mTextUpdateNeeded = SetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded;
break;
}
case Toolkit::TextLabel::Property::EMBOSS:
{
- impl.mTextUpdateNeeded = SetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded;
+ impl.mTextUpdateNeeded = SetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded;
break;
}
case Toolkit::TextLabel::Property::OUTLINE:
{
- impl.mTextUpdateNeeded = SetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded;
+ impl.mTextUpdateNeeded = SetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded;
break;
}
case Toolkit::TextLabel::Property::PIXEL_SIZE:
{
- const float pixelSize = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize );
+ const float pixelSize = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize);
- if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) )
+ if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE), pixelSize))
{
- impl.mController->SetDefaultFontSize( pixelSize, Text::Controller::PIXEL_SIZE );
+ impl.mController->SetDefaultFontSize(pixelSize, Text::Controller::PIXEL_SIZE);
}
break;
}
case Toolkit::TextLabel::Property::ELLIPSIS:
{
const bool ellipsis = value.Get<bool>();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel %p ELLIPSIS %d\n", impl.mController.Get(), ellipsis );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel %p ELLIPSIS %d\n", impl.mController.Get(), ellipsis);
- impl.mController->SetTextElideEnabled( ellipsis );
+ impl.mController->SetTextElideEnabled(ellipsis);
break;
}
case Toolkit::TextLabel::Property::LINE_WRAP_MODE:
{
- Text::LineWrap::Mode lineWrapMode( static_cast< Text::LineWrap::Mode >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( GetLineWrapModeEnumeration( value, lineWrapMode ) )
+ Text::LineWrap::Mode lineWrapMode(static_cast<Text::LineWrap::Mode>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(GetLineWrapModeEnumeration(value, lineWrapMode))
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel %p LineWrap::MODE %d\n", impl.mController.Get(), lineWrapMode );
- impl.mController->SetLineWrapMode( lineWrapMode );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel %p LineWrap::MODE %d\n", impl.mController.Get(), lineWrapMode);
+ impl.mController->SetLineWrapMode(lineWrapMode);
}
break;
}
case Toolkit::DevelTextLabel::Property::VERTICAL_LINE_ALIGNMENT:
{
- if( impl.mController->GetTextModel() )
+ if(impl.mController->GetTextModel())
{
- DevelText::VerticalLineAlignment::Type alignment = static_cast<DevelText::VerticalLineAlignment::Type>( value.Get<int>() );
+ DevelText::VerticalLineAlignment::Type alignment = static_cast<DevelText::VerticalLineAlignment::Type>(value.Get<int>());
- impl.mController->SetVerticalLineAlignment( alignment );
+ impl.mController->SetVerticalLineAlignment(alignment);
// Property doesn't affect the layout, only Visual must be updated
- TextVisual::EnableRendererUpdate( impl.mVisual );
+ TextVisual::EnableRendererUpdate(impl.mVisual);
// No need to trigger full re-layout. Instead call UpdateRenderer() directly
- TextVisual::UpdateRenderer( impl.mVisual );
+ TextVisual::UpdateRenderer(impl.mVisual);
}
break;
}
case Toolkit::DevelTextLabel::Property::BACKGROUND:
{
- impl.mTextUpdateNeeded = SetBackgroundProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded;
+ impl.mTextUpdateNeeded = SetBackgroundProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded;
break;
}
case Toolkit::DevelTextLabel::Property::IGNORE_SPACES_AFTER_TEXT:
{
- impl.mController->SetIgnoreSpacesAfterText(value.Get< bool >());
+ impl.mController->SetIgnoreSpacesAfterText(value.Get<bool>());
break;
}
case Toolkit::DevelTextLabel::Property::MATCH_SYSTEM_LANGUAGE_DIRECTION:
{
- impl.mController->SetMatchSystemLanguageDirection(value.Get< bool >());
+ impl.mController->SetMatchSystemLanguageDirection(value.Get<bool>());
break;
}
case Toolkit::DevelTextLabel::Property::TEXT_FIT:
}
case Toolkit::DevelTextLabel::Property::MIN_LINE_SIZE:
{
- const float lineSize = value.Get<float>();
- impl.mTextUpdateNeeded = impl.mController->SetDefaultLineSize( lineSize ) || impl.mTextUpdateNeeded;
+ const float lineSize = value.Get<float>();
+ impl.mTextUpdateNeeded = impl.mController->SetDefaultLineSize(lineSize) || impl.mTextUpdateNeeded;
break;
}
case Toolkit::DevelTextLabel::Property::FONT_SIZE_SCALE:
{
- const float scale = value.Get< float >();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale );
+ const float scale = value.Get<float>();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale);
- if( !Equals( impl.mController->GetFontSizeScale(), scale ) )
+ if(!Equals(impl.mController->GetFontSizeScale(), scale))
{
- impl.mController->SetFontSizeScale( scale );
+ impl.mController->SetFontSizeScale(scale);
}
break;
}
// Request relayout when text update is needed. It's necessary to call it
// as changing the property not via UI interaction brings no effect if only
// the mTextUpdateNeeded is changed.
- if( impl.mTextUpdateNeeded )
+ if(impl.mTextUpdateNeeded)
{
// need to request relayout as size of text may have changed
impl.RequestTextRelayout();
}
}
-Text::ControllerPtr TextLabel::getController() { return mController; }
+Text::ControllerPtr TextLabel::getController()
+{
+ return mController;
+}
-Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index index )
+Property::Value TextLabel::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::TextLabel label = Toolkit::TextLabel::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextLabel label = Toolkit::TextLabel::DownCast(Dali::BaseHandle(object));
- if( label )
+ if(label)
{
- TextLabel& impl( GetImpl( label ) );
- DALI_ASSERT_DEBUG( impl.mController && "No text contoller" );
+ TextLabel& impl(GetImpl(label));
+ DALI_ASSERT_DEBUG(impl.mController && "No text contoller");
- switch( index )
+ switch(index)
{
case Toolkit::DevelTextLabel::Property::RENDERING_BACKEND:
{
case Toolkit::TextLabel::Property::TEXT:
{
std::string text;
- impl.mController->GetText( text );
+ impl.mController->GetText(text);
value = text;
break;
}
}
case Toolkit::TextLabel::Property::FONT_STYLE:
{
- GetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT );
+ GetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT);
break;
}
case Toolkit::TextLabel::Property::POINT_SIZE:
{
- value = impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE );
+ value = impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE);
break;
}
case Toolkit::TextLabel::Property::MULTI_LINE:
}
case Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT:
{
- const char* name = Text::GetHorizontalAlignmentString( impl.mController->GetHorizontalAlignment() );
+ const char* name = Text::GetHorizontalAlignmentString(impl.mController->GetHorizontalAlignment());
- if ( name )
+ if(name)
{
- value = std::string( name );
+ value = std::string(name);
}
break;
}
case Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT:
{
- const char* name = Text::GetVerticalAlignmentString( impl.mController->GetVerticalAlignment() );
- if( name )
+ const char* name = Text::GetVerticalAlignmentString(impl.mController->GetVerticalAlignment());
+ if(name)
{
- value = std::string( name );
+ value = std::string(name);
}
break;
}
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_STOP_MODE:
{
- if( impl.mTextScroller )
+ if(impl.mTextScroller)
{
- const char* mode = Scripting::GetEnumerationName< Toolkit::TextLabel::AutoScrollStopMode::Type >( impl.mTextScroller->GetStopMode(),
- AUTO_SCROLL_STOP_MODE_TABLE,
- AUTO_SCROLL_STOP_MODE_TABLE_COUNT );
- if( mode )
+ const char* mode = Scripting::GetEnumerationName<Toolkit::TextLabel::AutoScrollStopMode::Type>(impl.mTextScroller->GetStopMode(),
+ AUTO_SCROLL_STOP_MODE_TABLE,
+ AUTO_SCROLL_STOP_MODE_TABLE_COUNT);
+ if(mode)
{
- value = std::string( mode );
+ value = std::string(mode);
}
}
break;
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_SPEED:
{
- if ( impl.mTextScroller )
+ if(impl.mTextScroller)
{
value = impl.mTextScroller->GetSpeed();
}
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_LOOP_COUNT:
{
- if ( impl.mTextScroller )
+ if(impl.mTextScroller)
{
value = impl.mTextScroller->GetLoopCount();
}
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_LOOP_DELAY:
{
- if ( impl.mTextScroller )
+ if(impl.mTextScroller)
{
value = impl.mTextScroller->GetLoopDelay();
}
}
case Toolkit::TextLabel::Property::AUTO_SCROLL_GAP:
{
- if ( impl.mTextScroller )
+ if(impl.mTextScroller)
{
value = impl.mTextScroller->GetGap();
}
}
case Toolkit::TextLabel::Property::UNDERLINE:
{
- GetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextLabel::Property::SHADOW:
{
- GetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextLabel::Property::EMBOSS:
{
- GetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextLabel::Property::OUTLINE:
{
- GetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextLabel::Property::PIXEL_SIZE:
{
- value = impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE );
+ value = impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE);
break;
}
case Toolkit::TextLabel::Property::ELLIPSIS:
}
case Toolkit::TextLabel::Property::LINE_COUNT:
{
- float width = label.GetProperty( Actor::Property::SIZE_WIDTH ).Get<float>();
- value = impl.mController->GetLineCount( width );
+ float width = label.GetProperty(Actor::Property::SIZE_WIDTH).Get<float>();
+ value = impl.mController->GetLineCount(width);
break;
}
case Toolkit::DevelTextLabel::Property::TEXT_DIRECTION:
}
case Toolkit::DevelTextLabel::Property::BACKGROUND:
{
- GetBackgroundProperties( impl.mController, value, Text::EffectStyle::DEFAULT );
+ GetBackgroundProperties(impl.mController, value, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::DevelTextLabel::Property::IGNORE_SPACES_AFTER_TEXT:
}
case Toolkit::DevelTextLabel::Property::TEXT_FIT:
{
- const bool enabled = impl.mController->IsTextFitEnabled();
- const float minSize = impl.mController->GetTextFitMinSize();
- const float maxSize = impl.mController->GetTextFitMaxSize();
+ const bool enabled = impl.mController->IsTextFitEnabled();
+ const float minSize = impl.mController->GetTextFitMinSize();
+ const float maxSize = impl.mController->GetTextFitMaxSize();
const float stepSize = impl.mController->GetTextFitStepSize();
Property::Map map;
- map.Insert( TEXT_FIT_ENABLE_KEY, enabled );
- map.Insert( TEXT_FIT_MIN_SIZE_KEY, minSize );
- map.Insert( TEXT_FIT_MAX_SIZE_KEY, maxSize );
- map.Insert( TEXT_FIT_STEP_SIZE_KEY, stepSize );
- map.Insert( TEXT_FIT_FONT_SIZE_TYPE_KEY, "pointSize" );
+ map.Insert(TEXT_FIT_ENABLE_KEY, enabled);
+ map.Insert(TEXT_FIT_MIN_SIZE_KEY, minSize);
+ map.Insert(TEXT_FIT_MAX_SIZE_KEY, maxSize);
+ map.Insert(TEXT_FIT_STEP_SIZE_KEY, stepSize);
+ map.Insert(TEXT_FIT_FONT_SIZE_TYPE_KEY, "pointSize");
value = map;
break;
Actor self = Self();
Property::Map propertyMap;
- propertyMap.Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT );
+ propertyMap.Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT);
- mVisual = Toolkit::VisualFactory::Get().CreateVisual( propertyMap );
- DevelControl::RegisterVisual( *this, Toolkit::TextLabel::Property::TEXT, mVisual );
+ mVisual = Toolkit::VisualFactory::Get().CreateVisual(propertyMap);
+ DevelControl::RegisterVisual(*this, Toolkit::TextLabel::Property::TEXT, mVisual);
- TextVisual::SetAnimatableTextColorProperty( mVisual, Toolkit::TextLabel::Property::TEXT_COLOR );
+ TextVisual::SetAnimatableTextColorProperty(mVisual, Toolkit::TextLabel::Property::TEXT_COLOR);
mController = TextVisual::GetController(mVisual);
- DALI_ASSERT_DEBUG( mController && "Invalid Text Controller")
+ DALI_ASSERT_DEBUG(mController && "Invalid Text Controller")
mController->SetControlInterface(this);
// Use height-for-width negotiation by default
- self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH );
- self.SetResizePolicy( ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT );
+ self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH);
+ self.SetResizePolicy(ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT);
// Enable highlightability
- self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true );
+ self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
// Enable the text ellipsis.
- mController->SetTextElideEnabled( true ); // If false then text larger than control will overflow
+ mController->SetTextElideEnabled(true); // If false then text larger than control will overflow
// Sets layoutDirection value
- Dali::Stage stage = Dali::Stage::GetCurrent();
- Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>( stage.GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
- mController->SetLayoutDirection( layoutDirection );
+ Dali::Stage stage = Dali::Stage::GetCurrent();
+ Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
+ mController->SetLayoutDirection(layoutDirection);
Layout::Engine& engine = mController->GetLayoutEngine();
- engine.SetCursorWidth( 0u ); // Do not layout space for the cursor.
+ engine.SetCursorWidth(0u); // Do not layout space for the cursor.
- DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new AccessibleImpl( actor, Dali::Accessibility::Role::LABEL ) );
- } );
+ DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new AccessibleImpl(actor, Dali::Accessibility::Role::LABEL));
+ });
}
-void TextLabel::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
+void TextLabel::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextLabel::OnStyleChange\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextLabel::OnStyleChange\n");
- switch ( change )
+ switch(change)
{
case StyleChange::DEFAULT_FONT_CHANGE:
{
// Property system did not set the font so should update it.
- const std::string& newFont = GetImpl( styleManager ).GetDefaultFontFamily();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::OnStyleChange StyleChange::DEFAULT_FONT_CHANGE newFont(%s)\n", newFont.c_str() );
- mController->UpdateAfterFontChange( newFont );
+ const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily();
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::OnStyleChange StyleChange::DEFAULT_FONT_CHANGE newFont(%s)\n", newFont.c_str());
+ mController->UpdateAfterFontChange(newFont);
RelayoutRequest();
break;
}
case StyleChange::DEFAULT_FONT_SIZE_CHANGE:
{
- GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
+ GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner()));
RelayoutRequest();
break;
}
}
// Up call to Control
- Control::OnStyleChange( styleManager, change );
+ Control::OnStyleChange(styleManager, change);
}
Vector3 TextLabel::GetNaturalSize()
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
Vector3 naturalSize = mController->GetNaturalSize();
- naturalSize.width += ( padding.start + padding.end );
- naturalSize.height += ( padding.top + padding.bottom );
+ naturalSize.width += (padding.start + padding.end);
+ naturalSize.height += (padding.top + padding.bottom);
return naturalSize;
}
-float TextLabel::GetHeightForWidth( float width )
+float TextLabel::GetHeightForWidth(float width)
{
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
- return mController->GetHeightForWidth( width ) + padding.top + padding.bottom;
+ return mController->GetHeightForWidth(width) + padding.top + padding.bottom;
}
-void TextLabel::OnPropertySet( Property::Index index, const Property::Value& propertyValue )
+void TextLabel::OnPropertySet(Property::Index index, const Property::Value& propertyValue)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextLabel::OnPropertySet index[%d]\n", index );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextLabel::OnPropertySet index[%d]\n", index);
- switch ( index )
+ switch(index)
{
case Toolkit::TextLabel::Property::TEXT_COLOR:
{
- const Vector4& textColor = propertyValue.Get< Vector4 >();
- if( mController->GetDefaultColor() != textColor )
+ const Vector4& textColor = propertyValue.Get<Vector4>();
+ if(mController->GetDefaultColor() != textColor)
{
- mController->SetDefaultColor( textColor );
- mTextUpdateNeeded = true;
+ mController->SetDefaultColor(textColor);
+ mTextUpdateNeeded = true;
}
break;
}
default:
{
- Control::OnPropertySet( index, propertyValue ); // up call to control for non-handled properties
+ Control::OnPropertySet(index, propertyValue); // up call to control for non-handled properties
break;
}
}
}
-void TextLabel::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void TextLabel::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::OnRelayout\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::OnRelayout\n");
Extents padding;
- padding = Self().GetProperty<Extents>( Toolkit::Control::Property::PADDING );
+ padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
- Vector2 contentSize( size.x - ( padding.start + padding.end ), size.y - ( padding.top + padding.bottom ) );
+ Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom));
- if( mController->IsTextFitEnabled() )
+ if(mController->IsTextFitEnabled())
{
- mController->FitPointSizeforLayout( contentSize );
- mController->SetTextFitContentSize( contentSize );
+ mController->FitPointSizeforLayout(contentSize);
+ mController->SetTextFitContentSize(contentSize);
}
// Support Right-To-Left
Dali::LayoutDirection::Type layoutDirection;
- if( mController->IsMatchSystemLanguageDirection() )
+ if(mController->IsMatchSystemLanguageDirection())
{
- layoutDirection = static_cast<Dali::LayoutDirection::Type>( DevelWindow::Get( Self() ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ layoutDirection = static_cast<Dali::LayoutDirection::Type>(DevelWindow::Get(Self()).GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
}
else
{
- layoutDirection = static_cast<Dali::LayoutDirection::Type>( Self().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ layoutDirection = static_cast<Dali::LayoutDirection::Type>(Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
}
- const Text::Controller::UpdateTextType updateTextType = mController->Relayout( contentSize, layoutDirection );
+ const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection);
- if( ( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) )
- || mTextUpdateNeeded )
+ if((Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType)) || mTextUpdateNeeded)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::OnRelayout IsAutoScrollEnabled[%s] [%p]\n", ( mController->IsAutoScrollEnabled())?"true":"false", this );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::OnRelayout IsAutoScrollEnabled[%s] [%p]\n", (mController->IsAutoScrollEnabled()) ? "true" : "false", this);
// Update the visual
- TextVisual::EnableRendererUpdate( mVisual );
+ TextVisual::EnableRendererUpdate(mVisual);
// Support Right-To-Left of padding
- if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection )
+ if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection)
{
- std::swap( padding.start, padding.end );
+ std::swap(padding.start, padding.end);
}
// Calculate the size of the visual that can fit the text
Size layoutSize = mController->GetTextModel()->GetLayoutSize();
- layoutSize.x = contentSize.x;
+ layoutSize.x = contentSize.x;
const Vector2& shadowOffset = mController->GetTextModel()->GetShadowOffset();
- if ( shadowOffset.y > Math::MACHINE_EPSILON_1 )
+ if(shadowOffset.y > Math::MACHINE_EPSILON_1)
{
layoutSize.y += shadowOffset.y;
}
float outlineWidth = mController->GetTextModel()->GetOutlineWidth();
layoutSize.y += outlineWidth * 2.0f;
- layoutSize.y = std::min( layoutSize.y, contentSize.y );
+ layoutSize.y = std::min(layoutSize.y, contentSize.y);
// Calculate the offset for vertical alignment only, as the layout engine will do the horizontal alignment.
Vector2 alignmentOffset;
alignmentOffset.x = 0.0f;
- alignmentOffset.y = ( contentSize.y - layoutSize.y ) * VERTICAL_ALIGNMENT_TABLE[mController->GetVerticalAlignment()];
+ alignmentOffset.y = (contentSize.y - layoutSize.y) * VERTICAL_ALIGNMENT_TABLE[mController->GetVerticalAlignment()];
Property::Map visualTransform;
- visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, layoutSize )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::OFFSET, Vector2( padding.start, padding.top ) + alignmentOffset )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) )
- .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN )
- .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN );
- mVisual.SetTransformAndSize( visualTransform, size );
-
- if ( mController->IsAutoScrollEnabled() )
+ visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, layoutSize)
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::OFFSET, Vector2(padding.start, padding.top) + alignmentOffset)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE))
+ .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN)
+ .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN);
+ mVisual.SetTransformAndSize(visualTransform, size);
+
+ if(mController->IsAutoScrollEnabled())
{
SetUpAutoScrolling();
}
void TextLabel::SetUpAutoScrolling()
{
- const Size& controlSize = mController->GetView().GetControlSize();
- const Size textNaturalSize = GetNaturalSize().GetVectorXY(); // As relayout of text may not be done at this point natural size is used to get size. Single line scrolling only.
- const Text::CharacterDirection direction = mController->GetAutoScrollDirection();
+ const Size& controlSize = mController->GetView().GetControlSize();
+ const Size textNaturalSize = GetNaturalSize().GetVectorXY(); // As relayout of text may not be done at this point natural size is used to get size. Single line scrolling only.
+ const Text::CharacterDirection direction = mController->GetAutoScrollDirection();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::SetUpAutoScrolling textNaturalSize[%f,%f] controlSize[%f,%f]\n",
- textNaturalSize.x,textNaturalSize.y , controlSize.x,controlSize.y );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::SetUpAutoScrolling textNaturalSize[%f,%f] controlSize[%f,%f]\n", textNaturalSize.x, textNaturalSize.y, controlSize.x, controlSize.y);
- if ( !mTextScroller )
+ if(!mTextScroller)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::SetUpAutoScrolling Creating default TextScoller\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::SetUpAutoScrolling Creating default TextScoller\n");
// If speed, loopCount or gap not set via property system then will need to create a TextScroller with defaults
- mTextScroller = Text::TextScroller::New( *this );
+ mTextScroller = Text::TextScroller::New(*this);
}
// Calculate the actual gap before scrolling wraps.
- int textPadding = std::max( controlSize.x - textNaturalSize.x, 0.0f );
- float wrapGap = std::max( mTextScroller->GetGap(), textPadding );
+ int textPadding = std::max(controlSize.x - textNaturalSize.x, 0.0f);
+ float wrapGap = std::max(mTextScroller->GetGap(), textPadding);
Vector2 textureSize = textNaturalSize + Vector2(wrapGap, 0.0f); // Add the gap as a part of the texture
// Create a texture of the text for scrolling
- Size verifiedSize = textureSize;
+ Size verifiedSize = textureSize;
const int maxTextureSize = Dali::GetMaxTextureSize();
//if the texture size width exceed maxTextureSize, modify the visual model size and enabled the ellipsis
bool actualellipsis = mController->IsTextElideEnabled();
- if( verifiedSize.width > maxTextureSize )
+ if(verifiedSize.width > maxTextureSize)
{
verifiedSize.width = maxTextureSize;
- if( textNaturalSize.width > maxTextureSize )
+ if(textNaturalSize.width > maxTextureSize)
{
- mController->SetTextElideEnabled( true );
+ mController->SetTextElideEnabled(true);
}
- GetHeightForWidth( maxTextureSize );
- wrapGap = std::max( maxTextureSize - textNaturalSize.width, 0.0f );
+ GetHeightForWidth(maxTextureSize);
+ wrapGap = std::max(maxTextureSize - textNaturalSize.width, 0.0f);
}
- Text::TypesetterPtr typesetter = Text::Typesetter::New( mController->GetTextModel() );
+ Text::TypesetterPtr typesetter = Text::Typesetter::New(mController->GetTextModel());
- PixelData data = typesetter->Render( verifiedSize, mController->GetTextDirection(), Text::Typesetter::RENDER_TEXT_AND_STYLES, true, Pixel::RGBA8888 ); // ignore the horizontal alignment
- Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D,
- data.GetPixelFormat(),
- data.GetWidth(),
- data.GetHeight() );
- texture.Upload( data );
+ PixelData data = typesetter->Render(verifiedSize, mController->GetTextDirection(), Text::Typesetter::RENDER_TEXT_AND_STYLES, true, Pixel::RGBA8888); // ignore the horizontal alignment
+ Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D,
+ data.GetPixelFormat(),
+ data.GetWidth(),
+ data.GetHeight());
+ texture.Upload(data);
TextureSet textureSet = TextureSet::New();
- textureSet.SetTexture( 0u, texture );
+ textureSet.SetTexture(0u, texture);
// Filter mode needs to be set to linear to produce better quality while scaling.
Sampler sampler = Sampler::New();
- sampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
- sampler.SetWrapMode( Dali::WrapMode::DEFAULT, Dali::WrapMode::REPEAT, Dali::WrapMode::DEFAULT ); // Wrap the texture in the x direction
- textureSet.SetSampler( 0u, sampler );
+ sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR);
+ sampler.SetWrapMode(Dali::WrapMode::DEFAULT, Dali::WrapMode::REPEAT, Dali::WrapMode::DEFAULT); // Wrap the texture in the x direction
+ textureSet.SetSampler(0u, sampler);
// Set parameters for scrolling
- Renderer renderer = static_cast<Internal::Visual::Base&>( GetImplementation( mVisual ) ).GetRenderer();
- mTextScroller->SetParameters( Self(), renderer, textureSet, controlSize, verifiedSize, wrapGap, direction, mController->GetHorizontalAlignment(), mController->GetVerticalAlignment() );
- mController->SetTextElideEnabled( actualellipsis );
+ Renderer renderer = static_cast<Internal::Visual::Base&>(GetImplementation(mVisual)).GetRenderer();
+ mTextScroller->SetParameters(Self(), renderer, textureSet, controlSize, verifiedSize, wrapGap, direction, mController->GetHorizontalAlignment(), mController->GetVerticalAlignment());
+ mController->SetTextElideEnabled(actualellipsis);
}
void TextLabel::ScrollingFinished()
{
// Pure Virtual from TextScroller Interface
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::ScrollingFinished\n");
- mController->SetAutoScrollEnabled( false );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::ScrollingFinished\n");
+ mController->SetAutoScrollEnabled(false);
RequestTextRelayout();
}
TextLabel::TextLabel()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
- mRenderingBackend( DEFAULT_RENDERING_BACKEND ),
- mTextUpdateNeeded( false )
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
+ mRenderingBackend(DEFAULT_RENDERING_BACKEND),
+ mTextUpdateNeeded(false)
{
}
std::string TextLabel::AccessibleImpl::GetNameRaw()
{
- auto slf = Toolkit::TextLabel::DownCast( self );
- return slf.GetProperty( Toolkit::TextLabel::Property::TEXT ).Get< std::string >();
+ auto slf = Toolkit::TextLabel::DownCast(self);
+ return slf.GetProperty(Toolkit::TextLabel::Property::TEXT).Get<std::string>();
}
Property::Index TextLabel::AccessibleImpl::GetNamePropertyIndex()
return Toolkit::TextLabel::Property::TEXT;
}
-std::string TextLabel::AccessibleImpl::GetText( size_t startOffset,
- size_t endOffset )
+std::string TextLabel::AccessibleImpl::GetText(size_t startOffset,
+ size_t endOffset)
{
- if( endOffset <= startOffset )
+ if(endOffset <= startOffset)
return {};
- auto slf = Toolkit::TextLabel::DownCast( self );
+ auto slf = Toolkit::TextLabel::DownCast(self);
auto txt =
- slf.GetProperty( Toolkit::TextLabel::Property::TEXT ).Get< std::string >();
+ slf.GetProperty(Toolkit::TextLabel::Property::TEXT).Get<std::string>();
- if( startOffset > txt.size() || endOffset > txt.size() )
+ if(startOffset > txt.size() || endOffset > txt.size())
return {};
- return txt.substr( startOffset, endOffset - startOffset );
+ return txt.substr(startOffset, endOffset - startOffset);
}
size_t TextLabel::AccessibleImpl::GetCharacterCount()
{
- auto slf = Toolkit::TextLabel::DownCast( self );
+ auto slf = Toolkit::TextLabel::DownCast(self);
auto txt =
- slf.GetProperty( Toolkit::TextLabel::Property::TEXT ).Get< std::string >();
+ slf.GetProperty(Toolkit::TextLabel::Property::TEXT).Get<std::string>();
return txt.size();
}
size_t TextLabel::AccessibleImpl::GetCaretOffset()
{
- return {};
+ return {};
}
bool TextLabel::AccessibleImpl::SetCaretOffset(size_t offset)
{
- return {};
+ return {};
}
Dali::Accessibility::Range TextLabel::AccessibleImpl::GetTextAtOffset(
- size_t offset, Dali::Accessibility::TextBoundary boundary )
+ size_t offset, Dali::Accessibility::TextBoundary boundary)
{
- auto slf = Toolkit::TextLabel::DownCast( self );
- auto txt = slf.GetProperty( Toolkit::TextLabel::Property::TEXT ).Get< std::string >();
+ auto slf = Toolkit::TextLabel::DownCast(self);
+ auto txt = slf.GetProperty(Toolkit::TextLabel::Property::TEXT).Get<std::string>();
auto txt_size = txt.size();
auto range = Dali::Accessibility::Range{};
switch(boundary)
{
case Dali::Accessibility::TextBoundary::CHARACTER:
+ {
+ if(offset < txt_size)
{
- if (offset < txt_size)
- {
- range.content = txt[offset];
- range.startOffset = offset;
- range.endOffset = offset + 1;
- }
+ range.content = txt[offset];
+ range.startOffset = offset;
+ range.endOffset = offset + 1;
}
- break;
+ }
+ break;
case Dali::Accessibility::TextBoundary::WORD:
case Dali::Accessibility::TextBoundary::LINE:
- {
- auto txt_c_string = txt.c_str();
- auto breaks = std::vector< char >( txt_size, 0 );
- if(boundary == Dali::Accessibility::TextBoundary::WORD)
- Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data());
+ {
+ auto txt_c_string = txt.c_str();
+ auto breaks = std::vector<char>(txt_size, 0);
+ if(boundary == Dali::Accessibility::TextBoundary::WORD)
+ Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data());
+ else
+ Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data());
+ auto index = 0u;
+ auto counter = 0u;
+ while(index < txt_size && counter <= offset)
+ {
+ auto start = index;
+ if(breaks[index])
+ {
+ while(breaks[index])
+ index++;
+ counter++;
+ }
else
- Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data());
- auto index = 0u;
- auto counter = 0u;
- while( index < txt_size && counter <= offset )
{
- auto start = index;
- if(breaks[index])
- {
- while(breaks[index])
- index++;
+ if(boundary == Dali::Accessibility::TextBoundary::WORD)
+ index++;
+ if(boundary == Dali::Accessibility::TextBoundary::LINE)
counter++;
- }
- else
- {
- if (boundary == Dali::Accessibility::TextBoundary::WORD)
- index++;
- if (boundary == Dali::Accessibility::TextBoundary::LINE)
- counter++;
- }
- if ((counter > 0) && ((counter - 1) == offset))
- {
- range.content = txt.substr(start, index - start + 1);
- range.startOffset = start;
- range.endOffset = index + 1;
- }
- if (boundary == Dali::Accessibility::TextBoundary::LINE)
- index++;
}
+ if((counter > 0) && ((counter - 1) == offset))
+ {
+ range.content = txt.substr(start, index - start + 1);
+ range.startOffset = start;
+ range.endOffset = index + 1;
+ }
+ if(boundary == Dali::Accessibility::TextBoundary::LINE)
+ index++;
}
- break;
+ }
+ break;
case Dali::Accessibility::TextBoundary::SENTENCE:
- {
- /* not supported by efl */
- }
- break;
+ {
+ /* not supported by efl */
+ }
+ break;
case Dali::Accessibility::TextBoundary::PARAGRAPH:
- {
- /* Paragraph is not supported by libunibreak library */
- }
- break;
+ {
+ /* Paragraph is not supported by libunibreak library */
+ }
+ break;
default:
break;
}
}
Dali::Accessibility::Range
-TextLabel::AccessibleImpl::GetSelection( size_t selectionNum )
+TextLabel::AccessibleImpl::GetSelection(size_t selectionNum)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return {};
- auto slf = Toolkit::TextLabel::DownCast( self );
- auto ctrl = Dali::Toolkit::GetImpl( slf ).getController();
+ auto slf = Toolkit::TextLabel::DownCast(self);
+ auto ctrl = Dali::Toolkit::GetImpl(slf).getController();
std::string ret;
- ctrl->RetrieveSelection( ret );
+ ctrl->RetrieveSelection(ret);
auto r = ctrl->GetSelectionIndexes();
- return { static_cast<size_t>(r.first), static_cast<size_t>(r.second), ret };
+ return {static_cast<size_t>(r.first), static_cast<size_t>(r.second), ret};
}
-bool TextLabel::AccessibleImpl::RemoveSelection( size_t selectionNum )
+bool TextLabel::AccessibleImpl::RemoveSelection(size_t selectionNum)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return false;
- auto slf = Toolkit::TextLabel::DownCast( self );
- Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( 0, 0 );
+ auto slf = Toolkit::TextLabel::DownCast(self);
+ Dali::Toolkit::GetImpl(slf).getController()->SetSelection(0, 0);
return true;
}
-bool TextLabel::AccessibleImpl::SetSelection( size_t selectionNum,
- size_t startOffset,
- size_t endOffset )
+bool TextLabel::AccessibleImpl::SetSelection(size_t selectionNum,
+ size_t startOffset,
+ size_t endOffset)
{
// Since DALi supports only one selection indexes higher than 0 are ignored
- if( selectionNum > 0 )
+ if(selectionNum > 0)
return false;
- auto slf = Toolkit::TextLabel::DownCast( self );
- Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( startOffset,
- endOffset );
+ auto slf = Toolkit::TextLabel::DownCast(self);
+ Dali::Toolkit::GetImpl(slf).getController()->SetSelection(startOffset,
+ endOffset);
return true;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#if defined(__GLIBC__)
#include <libintl.h>
#endif
-#include <string.h>
-#include <cfloat>
+#include <dali/integration-api/debug.h>
#include <dali/public-api/animation/animation.h>
#include <dali/public-api/math/vector2.h>
#include <dali/public-api/math/vector4.h>
#include <dali/public-api/object/property-map.h>
#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/integration-api/debug.h>
+#include <string.h>
+#include <cfloat>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/text-controls/text-label.h>
+#include <dali-toolkit/devel-api/controls/buttons/button-devel.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
-#include <dali-toolkit/devel-api/controls/buttons/button-devel.h>
#include <dali-toolkit/devel-api/controls/text-controls/text-selection-popup-callback-interface.h>
+#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
+#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/helpers/color-conversion.h>
+#include <dali-toolkit/public-api/controls/text-controls/text-label.h>
#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/helpers/color-conversion.h>
-#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
-#include <dali-toolkit/internal/controls/control/control-data-impl.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
#if defined(__GLIBC__)
#define GET_LOCALE_TEXT(string) dgettext("dali-toolkit", string)
#endif
-const std::string TEXT_SELECTION_POPUP_BUTTON_STYLE_NAME( "TextSelectionPopupButton" );
-const Dali::Vector4 DEFAULT_OPTION_PRESSED_COLOR( Dali::Vector4( 0.24f, 0.72f, 0.8f, 1.0f ) );
+const std::string TEXT_SELECTION_POPUP_BUTTON_STYLE_NAME("TextSelectionPopupButton");
+const Dali::Vector4 DEFAULT_OPTION_PRESSED_COLOR(Dali::Vector4(0.24f, 0.72f, 0.8f, 1.0f));
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
#ifdef DGETTEXT_ENABLED
#else
-#define POPUP_CUT_STRING "Cut"
-#define POPUP_COPY_STRING "Copy"
-#define POPUP_PASTE_STRING "Paste"
-#define POPUP_SELECT_STRING "Select"
-#define POPUP_SELECT_ALL_STRING "Select All"
-#define POPUP_CLIPBOARD_STRING "Clipboard"
+#define POPUP_CUT_STRING "Cut"
+#define POPUP_COPY_STRING "Copy"
+#define POPUP_PASTE_STRING "Paste"
+#define POPUP_SELECT_STRING "Select"
+#define POPUP_SELECT_ALL_STRING "Select All"
+#define POPUP_CLIPBOARD_STRING "Clipboard"
#endif
-const char* const OPTION_SELECT_WORD = "option-select_word"; // "Select Word" popup option.
-const char* const OPTION_SELECT_ALL("option-select_all"); // "Select All" popup option.
-const char* const OPTION_CUT("optionCut"); // "Cut" popup option.
-const char* const OPTION_COPY("optionCopy"); // "Copy" popup option.
-const char* const OPTION_PASTE("optionPaste"); // "Paste" popup option.
-const char* const OPTION_CLIPBOARD("optionClipboard"); // "Clipboard" popup option.
+const char* const OPTION_SELECT_WORD = "option-select_word"; // "Select Word" popup option.
+const char* const OPTION_SELECT_ALL("option-select_all"); // "Select All" popup option.
+const char* const OPTION_CUT("optionCut"); // "Cut" popup option.
+const char* const OPTION_COPY("optionCopy"); // "Copy" popup option.
+const char* const OPTION_PASTE("optionPaste"); // "Paste" popup option.
+const char* const OPTION_CLIPBOARD("optionClipboard"); // "Clipboard" popup option.
-const std::string IDS_LTR( "IDS_LTR" );
-const std::string RTL_DIRECTION( "RTL" );
+const std::string IDS_LTR("IDS_LTR");
+const std::string RTL_DIRECTION("RTL");
BaseHandle Create()
{
- return Toolkit::TextSelectionPopup::New( NULL );
+ return Toolkit::TextSelectionPopup::New(NULL);
}
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextSelectionPopup, Toolkit::Control, Create );
-
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupMaxSize", VECTOR2, POPUP_MAX_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupMinSize", VECTOR2, POPUP_MIN_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "optionMaxSize", VECTOR2, OPTION_MAX_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "optionMinSize", VECTOR2, OPTION_MIN_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "optionDividerSize", VECTOR2, OPTION_DIVIDER_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupClipboardButtonImage", STRING, POPUP_CLIPBOARD_BUTTON_ICON_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupCutButtonImage", STRING, POPUP_CUT_BUTTON_ICON_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupCopyButtonImage", STRING, POPUP_COPY_BUTTON_ICON_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupPasteButtonImage", STRING, POPUP_PASTE_BUTTON_ICON_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupSelectButtonImage", STRING, POPUP_SELECT_BUTTON_ICON_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupSelectAllButtonImage", STRING, POPUP_SELECT_ALL_BUTTON_ICON_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupDividerColor", VECTOR4, POPUP_DIVIDER_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupIconColor", VECTOR4, POPUP_ICON_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupPressedColor", VECTOR4, POPUP_PRESSED_COLOR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupPressedImage", STRING, POPUP_PRESSED_IMAGE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupFadeInDuration", FLOAT, POPUP_FADE_IN_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupFadeOutDuration", FLOAT, POPUP_FADE_OUT_DURATION )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "backgroundBorder", MAP, BACKGROUND_BORDER )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextSelectionPopup, Toolkit::Control, Create);
+
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupMaxSize", VECTOR2, POPUP_MAX_SIZE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupMinSize", VECTOR2, POPUP_MIN_SIZE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "optionMaxSize", VECTOR2, OPTION_MAX_SIZE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "optionMinSize", VECTOR2, OPTION_MIN_SIZE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "optionDividerSize", VECTOR2, OPTION_DIVIDER_SIZE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupClipboardButtonImage", STRING, POPUP_CLIPBOARD_BUTTON_ICON_IMAGE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupCutButtonImage", STRING, POPUP_CUT_BUTTON_ICON_IMAGE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupCopyButtonImage", STRING, POPUP_COPY_BUTTON_ICON_IMAGE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupPasteButtonImage", STRING, POPUP_PASTE_BUTTON_ICON_IMAGE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupSelectButtonImage", STRING, POPUP_SELECT_BUTTON_ICON_IMAGE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupSelectAllButtonImage", STRING, POPUP_SELECT_ALL_BUTTON_ICON_IMAGE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupDividerColor", VECTOR4, POPUP_DIVIDER_COLOR)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupIconColor", VECTOR4, POPUP_ICON_COLOR)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupPressedColor", VECTOR4, POPUP_PRESSED_COLOR)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupPressedImage", STRING, POPUP_PRESSED_IMAGE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupFadeInDuration", FLOAT, POPUP_FADE_IN_DURATION)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupFadeOutDuration", FLOAT, POPUP_FADE_OUT_DURATION)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "backgroundBorder", MAP, BACKGROUND_BORDER)
DALI_TYPE_REGISTRATION_END()
} // namespace
-
-Dali::Toolkit::TextSelectionPopup TextSelectionPopup::New( TextSelectionPopupCallbackInterface* callbackInterface )
+Dali::Toolkit::TextSelectionPopup TextSelectionPopup::New(TextSelectionPopupCallbackInterface* callbackInterface)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextSelectionPopup::New\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextSelectionPopup::New\n");
- // Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< TextSelectionPopup > impl = new TextSelectionPopup( callbackInterface );
+ // Create the implementation, temporarily owned by this handle on stack
+ IntrusivePtr<TextSelectionPopup> impl = new TextSelectionPopup(callbackInterface);
// Pass ownership to CustomActor handle
- Dali::Toolkit::TextSelectionPopup handle( *impl );
+ Dali::Toolkit::TextSelectionPopup handle(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-void TextSelectionPopup::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void TextSelectionPopup::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::TextSelectionPopup selectionPopup = Toolkit::TextSelectionPopup::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextSelectionPopup selectionPopup = Toolkit::TextSelectionPopup::DownCast(Dali::BaseHandle(object));
- if( selectionPopup )
+ if(selectionPopup)
{
- TextSelectionPopup& impl( GetImpl( selectionPopup ) );
+ TextSelectionPopup& impl(GetImpl(selectionPopup));
- switch( index )
+ switch(index)
{
case Toolkit::TextSelectionPopup::Property::POPUP_MAX_SIZE:
{
- impl.SetDimensionToCustomise( POPUP_MAXIMUM_SIZE, value.Get< Vector2 >() );
- break;
+ impl.SetDimensionToCustomise(POPUP_MAXIMUM_SIZE, value.Get<Vector2>());
+ break;
}
case Toolkit::TextSelectionPopup::Property::OPTION_MAX_SIZE:
{
- impl.SetDimensionToCustomise( OPTION_MAXIMUM_SIZE, value.Get< Vector2 >() );
+ impl.SetDimensionToCustomise(OPTION_MAXIMUM_SIZE, value.Get<Vector2>());
break;
}
case Toolkit::TextSelectionPopup::Property::OPTION_MIN_SIZE:
{
- impl.SetDimensionToCustomise( OPTION_MINIMUM_SIZE, value.Get< Vector2>() );
+ impl.SetDimensionToCustomise(OPTION_MINIMUM_SIZE, value.Get<Vector2>());
break;
}
case Toolkit::TextSelectionPopup::Property::OPTION_DIVIDER_SIZE:
{
- impl.SetDimensionToCustomise( OPTION_DIVIDER_SIZE, value.Get< Vector2>() );
+ impl.SetDimensionToCustomise(OPTION_DIVIDER_SIZE, value.Get<Vector2>());
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_CLIPBOARD_BUTTON_ICON_IMAGE:
{
- impl.SetButtonImage( Toolkit::TextSelectionPopup::CLIPBOARD, value.Get< std::string >() );
+ impl.SetButtonImage(Toolkit::TextSelectionPopup::CLIPBOARD, value.Get<std::string>());
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_CUT_BUTTON_ICON_IMAGE:
{
- impl.SetButtonImage( Toolkit::TextSelectionPopup::CUT, value.Get< std::string >() );
+ impl.SetButtonImage(Toolkit::TextSelectionPopup::CUT, value.Get<std::string>());
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_COPY_BUTTON_ICON_IMAGE:
{
- impl.SetButtonImage( Toolkit::TextSelectionPopup::COPY, value.Get< std::string >() );
+ impl.SetButtonImage(Toolkit::TextSelectionPopup::COPY, value.Get<std::string>());
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_PASTE_BUTTON_ICON_IMAGE:
{
- impl.SetButtonImage( Toolkit::TextSelectionPopup::PASTE, value.Get< std::string >() );
+ impl.SetButtonImage(Toolkit::TextSelectionPopup::PASTE, value.Get<std::string>());
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_SELECT_BUTTON_ICON_IMAGE:
{
- impl.SetButtonImage( Toolkit::TextSelectionPopup::SELECT, value.Get< std::string >() );
+ impl.SetButtonImage(Toolkit::TextSelectionPopup::SELECT, value.Get<std::string>());
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_SELECT_ALL_BUTTON_ICON_IMAGE:
{
- impl.SetButtonImage( Toolkit::TextSelectionPopup::SELECT_ALL, value.Get< std::string >() );
+ impl.SetButtonImage(Toolkit::TextSelectionPopup::SELECT_ALL, value.Get<std::string>());
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_DIVIDER_COLOR:
{
- impl.mDividerColor = value.Get< Vector4 >();
+ impl.mDividerColor = value.Get<Vector4>();
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_ICON_COLOR:
{
- impl.mIconColor = value.Get< Vector4 >();
+ impl.mIconColor = value.Get<Vector4>();
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_PRESSED_COLOR:
{
- impl.mPressedColor = value.Get< Vector4 >();
+ impl.mPressedColor = value.Get<Vector4>();
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_PRESSED_IMAGE:
{
- impl.SetPressedImage( value.Get< std::string >() );
+ impl.SetPressedImage(value.Get<std::string>());
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_FADE_IN_DURATION:
{
- impl.mFadeInDuration = value.Get < float >();
+ impl.mFadeInDuration = value.Get<float>();
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_FADE_OUT_DURATION:
{
- impl.mFadeOutDuration = value.Get < float >();
+ impl.mFadeOutDuration = value.Get<float>();
break;
}
case Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER:
{
Property::Map map = value.Get<Property::Map>();
- impl.CreateBackgroundBorder( map );
+ impl.CreateBackgroundBorder(map);
break;
}
} // switch
- } // TextSelectionPopup
+ } // TextSelectionPopup
}
-Property::Value TextSelectionPopup::GetProperty( BaseObject* object, Property::Index index )
+Property::Value TextSelectionPopup::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::TextSelectionPopup selectionPopup = Toolkit::TextSelectionPopup::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextSelectionPopup selectionPopup = Toolkit::TextSelectionPopup::DownCast(Dali::BaseHandle(object));
- if( selectionPopup )
+ if(selectionPopup)
{
- TextSelectionPopup& impl( GetImpl( selectionPopup ) );
+ TextSelectionPopup& impl(GetImpl(selectionPopup));
- switch( index )
+ switch(index)
{
case Toolkit::TextSelectionPopup::Property::POPUP_MAX_SIZE:
{
- value = impl.GetDimensionToCustomise( POPUP_MAXIMUM_SIZE );
+ value = impl.GetDimensionToCustomise(POPUP_MAXIMUM_SIZE);
break;
}
case Toolkit::TextSelectionPopup::Property::OPTION_MAX_SIZE:
{
- value = impl.GetDimensionToCustomise( OPTION_MAXIMUM_SIZE );
+ value = impl.GetDimensionToCustomise(OPTION_MAXIMUM_SIZE);
break;
}
case Toolkit::TextSelectionPopup::Property::OPTION_MIN_SIZE:
{
- value = impl.GetDimensionToCustomise( OPTION_MINIMUM_SIZE );
+ value = impl.GetDimensionToCustomise(OPTION_MINIMUM_SIZE);
break;
}
case Toolkit::TextSelectionPopup::Property::OPTION_DIVIDER_SIZE:
{
- value = impl.GetDimensionToCustomise( OPTION_DIVIDER_SIZE );
+ value = impl.GetDimensionToCustomise(OPTION_DIVIDER_SIZE);
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_CLIPBOARD_BUTTON_ICON_IMAGE:
{
- value = impl.GetButtonImage( Toolkit::TextSelectionPopup::CLIPBOARD );
+ value = impl.GetButtonImage(Toolkit::TextSelectionPopup::CLIPBOARD);
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_CUT_BUTTON_ICON_IMAGE:
{
- value = impl.GetButtonImage( Toolkit::TextSelectionPopup::CUT );
+ value = impl.GetButtonImage(Toolkit::TextSelectionPopup::CUT);
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_COPY_BUTTON_ICON_IMAGE:
{
- value = impl.GetButtonImage( Toolkit::TextSelectionPopup::COPY );
+ value = impl.GetButtonImage(Toolkit::TextSelectionPopup::COPY);
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_PASTE_BUTTON_ICON_IMAGE:
{
- value = impl.GetButtonImage( Toolkit::TextSelectionPopup::PASTE );
+ value = impl.GetButtonImage(Toolkit::TextSelectionPopup::PASTE);
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_SELECT_BUTTON_ICON_IMAGE:
{
- value = impl.GetButtonImage( Toolkit::TextSelectionPopup::SELECT );
+ value = impl.GetButtonImage(Toolkit::TextSelectionPopup::SELECT);
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_SELECT_ALL_BUTTON_ICON_IMAGE:
{
- value = impl.GetButtonImage( Toolkit::TextSelectionPopup::SELECT_ALL );
+ value = impl.GetButtonImage(Toolkit::TextSelectionPopup::SELECT_ALL);
break;
}
case Toolkit::TextSelectionPopup::Property::POPUP_PRESSED_IMAGE:
}
case Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER:
{
- Property::Map map;
- Toolkit::Visual::Base visual = DevelControl::GetVisual( impl, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER );
- if( visual )
+ Property::Map map;
+ Toolkit::Visual::Base visual = DevelControl::GetVisual(impl, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER);
+ if(visual)
{
- visual.CreatePropertyMap( map );
+ visual.CreatePropertyMap(map);
}
value = map;
break;
return value;
}
-void TextSelectionPopup::EnableButtons( Toolkit::TextSelectionPopup::Buttons buttonsToEnable )
+void TextSelectionPopup::EnableButtons(Toolkit::TextSelectionPopup::Buttons buttonsToEnable)
{
mEnabledButtons = buttonsToEnable;
mButtonsChanged = true;
}
-void TextSelectionPopup::RaiseAbove( Actor target )
+void TextSelectionPopup::RaiseAbove(Actor target)
{
- if( mToolbar )
+ if(mToolbar)
{
- mToolbar.RaiseAbove( target );
+ mToolbar.RaiseAbove(target);
}
}
void TextSelectionPopup::ShowPopup()
{
- if( ( !mPopupShowing || mButtonsChanged ) &&
- ( Toolkit::TextSelectionPopup::NONE != mEnabledButtons ) )
+ if((!mPopupShowing || mButtonsChanged) &&
+ (Toolkit::TextSelectionPopup::NONE != mEnabledButtons))
{
Actor self = Self();
- AddPopupOptionsToToolbar( mShowIcons, mShowCaptions );
+ AddPopupOptionsToToolbar(mShowIcons, mShowCaptions);
- Animation animation = Animation::New( mFadeInDuration );
- animation.AnimateTo( Property(self, Actor::Property::COLOR_ALPHA), 1.0f );
+ Animation animation = Animation::New(mFadeInDuration);
+ animation.AnimateTo(Property(self, Actor::Property::COLOR_ALPHA), 1.0f);
animation.Play();
mPopupShowing = true;
}
void TextSelectionPopup::HidePopup()
{
- if ( mPopupShowing )
+ if(mPopupShowing)
{
- mPopupShowing = false;
- Actor self = Self();
- Animation animation = Animation::New( mFadeOutDuration );
- animation.AnimateTo( Property(self, Actor::Property::COLOR_ALPHA), 0.0f );
- animation.FinishedSignal().Connect( this, &TextSelectionPopup::HideAnimationFinished );
+ mPopupShowing = false;
+ Actor self = Self();
+ Animation animation = Animation::New(mFadeOutDuration);
+ animation.AnimateTo(Property(self, Actor::Property::COLOR_ALPHA), 0.0f);
+ animation.FinishedSignal().Connect(this, &TextSelectionPopup::HideAnimationFinished);
animation.Play();
}
}
void TextSelectionPopup::OnInitialize()
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextSelectionPopup::OnInitialize\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextSelectionPopup::OnInitialize\n");
Actor self = Self();
- self.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS );
- self.SetProperty( Actor::Property::COLOR_ALPHA, 0.0f );
-
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::DIALOG, true ) );
- } );
-
+ self.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS);
+ self.SetProperty(Actor::Property::COLOR_ALPHA, 0.0f);
+
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::DIALOG, true));
+ });
+
//Enable highightability
- self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true );
+ self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
}
-void TextSelectionPopup::HideAnimationFinished( Animation& animation )
+void TextSelectionPopup::HideAnimationFinished(Animation& animation)
{
Actor self = Self();
- if ( !mPopupShowing ) // During the Hide/Fade animation there could be a call to Show the Popup again, mPopupShowing will be true in this case.
+ if(!mPopupShowing) // During the Hide/Fade animation there could be a call to Show the Popup again, mPopupShowing will be true in this case.
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextSelectionPopup::HideAnimationFinished\n" );
- UnparentAndReset( mToolbar );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextSelectionPopup::HideAnimationFinished\n");
+ UnparentAndReset(mToolbar);
}
}
-bool TextSelectionPopup::OnCutButtonPressed( Toolkit::Button button )
+bool TextSelectionPopup::OnCutButtonPressed(Toolkit::Button button)
{
- if( mCallbackInterface )
+ if(mCallbackInterface)
{
- mCallbackInterface->TextPopupButtonTouched( Toolkit::TextSelectionPopup::CUT );
+ mCallbackInterface->TextPopupButtonTouched(Toolkit::TextSelectionPopup::CUT);
}
return true;
}
-bool TextSelectionPopup::OnCopyButtonPressed( Toolkit::Button button )
+bool TextSelectionPopup::OnCopyButtonPressed(Toolkit::Button button)
{
- if( mCallbackInterface )
+ if(mCallbackInterface)
{
- mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::COPY );
+ mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::COPY);
}
return true;
}
-bool TextSelectionPopup::OnPasteButtonPressed( Toolkit::Button button )
+bool TextSelectionPopup::OnPasteButtonPressed(Toolkit::Button button)
{
- if( mCallbackInterface )
+ if(mCallbackInterface)
{
- mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::PASTE );
+ mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::PASTE);
}
return true;
}
-bool TextSelectionPopup::OnSelectButtonPressed( Toolkit::Button button )
+bool TextSelectionPopup::OnSelectButtonPressed(Toolkit::Button button)
{
- if( mCallbackInterface )
+ if(mCallbackInterface)
{
- mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::SELECT );
+ mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::SELECT);
}
return true;
}
-bool TextSelectionPopup::OnSelectAllButtonPressed( Toolkit::Button button )
+bool TextSelectionPopup::OnSelectAllButtonPressed(Toolkit::Button button)
{
- if( mCallbackInterface )
+ if(mCallbackInterface)
{
- mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::SELECT_ALL );
+ mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::SELECT_ALL);
}
return true;
}
-bool TextSelectionPopup::OnClipboardButtonPressed( Toolkit::Button button )
+bool TextSelectionPopup::OnClipboardButtonPressed(Toolkit::Button button)
{
- if( mCallbackInterface )
+ if(mCallbackInterface)
{
- mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::CLIPBOARD );
+ mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::CLIPBOARD);
}
return true;
}
-void TextSelectionPopup::SetDimensionToCustomise( const PopupCustomisations& settingToCustomise, const Size& dimension )
+void TextSelectionPopup::SetDimensionToCustomise(const PopupCustomisations& settingToCustomise, const Size& dimension)
{
- switch( settingToCustomise )
+ switch(settingToCustomise)
{
- case POPUP_MAXIMUM_SIZE :
+ case POPUP_MAXIMUM_SIZE:
{
mPopupMaxSize = dimension;
- if ( mToolbar )
+ if(mToolbar)
{
- mToolbar.SetProperty( Toolkit::TextSelectionToolbar::Property::MAX_SIZE, dimension );
+ mToolbar.SetProperty(Toolkit::TextSelectionToolbar::Property::MAX_SIZE, dimension);
}
break;
}
- case OPTION_MAXIMUM_SIZE :
+ case OPTION_MAXIMUM_SIZE:
{
mOptionMaxSize = dimension;
// Option max size not currently currently supported
break;
}
- case OPTION_MINIMUM_SIZE :
+ case OPTION_MINIMUM_SIZE:
{
mOptionMinSize = dimension;
// Option min size not currently currently supported
break;
}
- case OPTION_DIVIDER_SIZE :
+ case OPTION_DIVIDER_SIZE:
{
mOptionDividerSize = dimension;
- if ( mToolbar )
+ if(mToolbar)
{
// Resize Dividers not currently supported
}
} // switch
}
-Size TextSelectionPopup::GetDimensionToCustomise( const PopupCustomisations& settingToCustomise ) const
+Size TextSelectionPopup::GetDimensionToCustomise(const PopupCustomisations& settingToCustomise) const
{
- switch( settingToCustomise )
+ switch(settingToCustomise)
{
- case POPUP_MAXIMUM_SIZE :
+ case POPUP_MAXIMUM_SIZE:
{
- if ( mToolbar )
+ if(mToolbar)
{
- return mToolbar.GetProperty( Toolkit::TextSelectionToolbar::Property::MAX_SIZE ).Get< Vector2 >();
+ return mToolbar.GetProperty(Toolkit::TextSelectionToolbar::Property::MAX_SIZE).Get<Vector2>();
}
else
{
return mPopupMaxSize;
}
}
- case OPTION_MAXIMUM_SIZE :
+ case OPTION_MAXIMUM_SIZE:
{
return mOptionMaxSize;
}
- case OPTION_MINIMUM_SIZE :
+ case OPTION_MINIMUM_SIZE:
{
return mOptionMinSize;
}
- case OPTION_DIVIDER_SIZE :
+ case OPTION_DIVIDER_SIZE:
{
return mOptionDividerSize;
}
return Size::ZERO;
}
-void TextSelectionPopup::SetButtonImage( Toolkit::TextSelectionPopup::Buttons button, const std::string& image )
-{
- switch ( button )
- {
- case Toolkit::TextSelectionPopup::CLIPBOARD:
- {
- mClipboardIconImage = image;
- break;
- }
- case Toolkit::TextSelectionPopup::CUT :
- {
- mCutIconImage = image;
- break;
- }
- case Toolkit::TextSelectionPopup::COPY :
- {
- mCopyIconImage = image;
- break;
- }
- case Toolkit::TextSelectionPopup::PASTE :
- {
- mPasteIconImage = image;
- break;
- }
- case Toolkit::TextSelectionPopup::SELECT :
- {
- mSelectIconImage = image;
- break;
- }
- case Toolkit::TextSelectionPopup::SELECT_ALL :
- {
- mSelectAllIconImage = image;
- break;
- }
- default :
- {
- DALI_ASSERT_DEBUG( "TextSelectionPopup SetPopupImage Unknown Button" );
- }
- } // switch
+void TextSelectionPopup::SetButtonImage(Toolkit::TextSelectionPopup::Buttons button, const std::string& image)
+{
+ switch(button)
+ {
+ case Toolkit::TextSelectionPopup::CLIPBOARD:
+ {
+ mClipboardIconImage = image;
+ break;
+ }
+ case Toolkit::TextSelectionPopup::CUT:
+ {
+ mCutIconImage = image;
+ break;
+ }
+ case Toolkit::TextSelectionPopup::COPY:
+ {
+ mCopyIconImage = image;
+ break;
+ }
+ case Toolkit::TextSelectionPopup::PASTE:
+ {
+ mPasteIconImage = image;
+ break;
+ }
+ case Toolkit::TextSelectionPopup::SELECT:
+ {
+ mSelectIconImage = image;
+ break;
+ }
+ case Toolkit::TextSelectionPopup::SELECT_ALL:
+ {
+ mSelectAllIconImage = image;
+ break;
+ }
+ default:
+ {
+ DALI_ASSERT_DEBUG("TextSelectionPopup SetPopupImage Unknown Button");
+ }
+ } // switch
}
-const std::string& TextSelectionPopup::GetButtonImage( Toolkit::TextSelectionPopup::Buttons button ) const
+const std::string& TextSelectionPopup::GetButtonImage(Toolkit::TextSelectionPopup::Buttons button) const
{
- switch ( button )
+ switch(button)
{
case Toolkit::TextSelectionPopup::CLIPBOARD:
{
}
} // switch
- DALI_ASSERT_DEBUG( "TextSelectionPopup GetPopupImage Unknown Button" );
+ DALI_ASSERT_DEBUG("TextSelectionPopup GetPopupImage Unknown Button");
static std::string empty;
return empty;
}
-void TextSelectionPopup::SetPressedImage( const std::string& filename )
+void TextSelectionPopup::SetPressedImage(const std::string& filename)
{
mPressedImage = filename;
}
return mPressedImage;
}
- void TextSelectionPopup::CreateOrderedListOfPopupOptions()
- {
- mOrderListOfButtons.clear();
- mOrderListOfButtons.reserve( 8u );
-
- // Create button for each possible option using Option priority
- mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::CUT, mCutOptionPriority, OPTION_CUT, POPUP_CUT_STRING , 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::CUT) ) );
- mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::COPY, mCopyOptionPriority, OPTION_COPY, POPUP_COPY_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::COPY) ) );
- mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::PASTE, mPasteOptionPriority, OPTION_PASTE, POPUP_PASTE_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::PASTE) ) );
- mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::SELECT, mSelectOptionPriority, OPTION_SELECT_WORD, POPUP_SELECT_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::SELECT) ) );
- mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::SELECT_ALL, mSelectAllOptionPriority, OPTION_SELECT_ALL, POPUP_SELECT_ALL_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::SELECT_ALL) ) );
- mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::CLIPBOARD, mClipboardOptionPriority, OPTION_CLIPBOARD, POPUP_CLIPBOARD_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::CLIPBOARD) ) );
-
- // Sort the buttons according their priorities.
- std::sort( mOrderListOfButtons.begin(), mOrderListOfButtons.end(), TextSelectionPopup::ButtonPriorityCompare() );
- }
-
- void TextSelectionPopup::AddOption( const ButtonRequirement& button, bool showDivider, bool showIcons, bool showCaption )
- {
- // 1. Create a option.
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextSelectionPopup::AddOption\n" );
-
- Toolkit::PushButton option = Toolkit::PushButton::New();
- option.SetProperty( Dali::Actor::Property::NAME, button.name );
- option.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
-
- switch( button.id )
- {
- case Toolkit::TextSelectionPopup::CUT:
- {
- option.ClickedSignal().Connect( this, &TextSelectionPopup::OnCutButtonPressed );
- break;
- }
- case Toolkit::TextSelectionPopup::COPY:
- {
- option.ClickedSignal().Connect( this, &TextSelectionPopup::OnCopyButtonPressed );
- break;
- }
- case Toolkit::TextSelectionPopup::PASTE:
- {
- option.ClickedSignal().Connect( this, &TextSelectionPopup::OnPasteButtonPressed );
- break;
- }
- case Toolkit::TextSelectionPopup::SELECT:
- {
- option.ClickedSignal().Connect( this, &TextSelectionPopup::OnSelectButtonPressed );
- break;
- }
- case Toolkit::TextSelectionPopup::SELECT_ALL:
- {
- option.ClickedSignal().Connect( this, &TextSelectionPopup::OnSelectAllButtonPressed );
- break;
- }
- case Toolkit::TextSelectionPopup::CLIPBOARD:
- {
- option.ClickedSignal().Connect( this, &TextSelectionPopup::OnClipboardButtonPressed );
- break;
- }
- case Toolkit::TextSelectionPopup::NONE:
- {
- // Nothing to do:
- break;
- }
- }
-
- // 2. Set the options contents.
- if( showCaption )
- {
- // PushButton layout properties.
- option.SetProperty( Toolkit::PushButton::Property::LABEL_PADDING, Vector4( 24.0f, 24.0f, 14.0f, 14.0f ) );
-
- // Label properties.
- Property::Map buttonLabelProperties;
- buttonLabelProperties.Insert( Toolkit::TextVisual::Property::TEXT, button.caption );
- option.SetProperty( Toolkit::Button::Property::LABEL, buttonLabelProperties );
- }
- if( showIcons )
- {
- option.SetProperty( Toolkit::PushButton::Property::ICON_PADDING, Vector4( 10.0f, 10.0f, 10.0f, 10.0f ) );
- option.SetProperty( Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT, "BOTTOM" );
-
- // TODO: This is temporarily disabled until the text-selection-popup image API is changed to strings.
- //option.SetProperty( Toolkit::Button::Property::SELECTED_VISUAL, button.icon );
- //option.SetProperty( Toolkit::Button::Property::UNSELECTED_VISUAL, button.icon );
- }
-
- // 3. Set the normal option image (blank / Transparent).
- option.SetProperty( Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, "" );
-
- // 4. Set the pressed option image.
- Property::Value selectedBackgroundValue( mPressedImage );
- if( mPressedImage.empty() )
- {
- // The image can be blank, the color can be used in that case.
- selectedBackgroundValue = Property::Value{ { Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR },
- { Toolkit::ColorVisual::Property::MIX_COLOR, mPressedColor } };
- }
- option.SetProperty( Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, selectedBackgroundValue );
- option.SetProperty( Toolkit::Control::Property::STYLE_NAME, TEXT_SELECTION_POPUP_BUTTON_STYLE_NAME );
-
- // 5 Add option to tool bar
- mToolbar.AddOption( option );
-
- // 6. Add the divider
- if( showDivider )
- {
- const Size size( mOptionDividerSize.width, 0.0f ); // Height FILL_TO_PARENT
-
- Toolkit::Control divider = Toolkit::Control::New();
+void TextSelectionPopup::CreateOrderedListOfPopupOptions()
+{
+ mOrderListOfButtons.clear();
+ mOrderListOfButtons.reserve(8u);
+
+ // Create button for each possible option using Option priority
+ mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::CUT, mCutOptionPriority, OPTION_CUT, POPUP_CUT_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::CUT)));
+ mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::COPY, mCopyOptionPriority, OPTION_COPY, POPUP_COPY_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::COPY)));
+ mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::PASTE, mPasteOptionPriority, OPTION_PASTE, POPUP_PASTE_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::PASTE)));
+ mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::SELECT, mSelectOptionPriority, OPTION_SELECT_WORD, POPUP_SELECT_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::SELECT)));
+ mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::SELECT_ALL, mSelectAllOptionPriority, OPTION_SELECT_ALL, POPUP_SELECT_ALL_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::SELECT_ALL)));
+ mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::CLIPBOARD, mClipboardOptionPriority, OPTION_CLIPBOARD, POPUP_CLIPBOARD_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::CLIPBOARD)));
+
+ // Sort the buttons according their priorities.
+ std::sort(mOrderListOfButtons.begin(), mOrderListOfButtons.end(), TextSelectionPopup::ButtonPriorityCompare());
+}
+
+void TextSelectionPopup::AddOption(const ButtonRequirement& button, bool showDivider, bool showIcons, bool showCaption)
+{
+ // 1. Create a option.
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextSelectionPopup::AddOption\n");
+
+ Toolkit::PushButton option = Toolkit::PushButton::New();
+ option.SetProperty(Dali::Actor::Property::NAME, button.name);
+ option.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS);
+
+ switch(button.id)
+ {
+ case Toolkit::TextSelectionPopup::CUT:
+ {
+ option.ClickedSignal().Connect(this, &TextSelectionPopup::OnCutButtonPressed);
+ break;
+ }
+ case Toolkit::TextSelectionPopup::COPY:
+ {
+ option.ClickedSignal().Connect(this, &TextSelectionPopup::OnCopyButtonPressed);
+ break;
+ }
+ case Toolkit::TextSelectionPopup::PASTE:
+ {
+ option.ClickedSignal().Connect(this, &TextSelectionPopup::OnPasteButtonPressed);
+ break;
+ }
+ case Toolkit::TextSelectionPopup::SELECT:
+ {
+ option.ClickedSignal().Connect(this, &TextSelectionPopup::OnSelectButtonPressed);
+ break;
+ }
+ case Toolkit::TextSelectionPopup::SELECT_ALL:
+ {
+ option.ClickedSignal().Connect(this, &TextSelectionPopup::OnSelectAllButtonPressed);
+ break;
+ }
+ case Toolkit::TextSelectionPopup::CLIPBOARD:
+ {
+ option.ClickedSignal().Connect(this, &TextSelectionPopup::OnClipboardButtonPressed);
+ break;
+ }
+ case Toolkit::TextSelectionPopup::NONE:
+ {
+ // Nothing to do:
+ break;
+ }
+ }
+
+ // 2. Set the options contents.
+ if(showCaption)
+ {
+ // PushButton layout properties.
+ option.SetProperty(Toolkit::PushButton::Property::LABEL_PADDING, Vector4(24.0f, 24.0f, 14.0f, 14.0f));
+
+ // Label properties.
+ Property::Map buttonLabelProperties;
+ buttonLabelProperties.Insert(Toolkit::TextVisual::Property::TEXT, button.caption);
+ option.SetProperty(Toolkit::Button::Property::LABEL, buttonLabelProperties);
+ }
+ if(showIcons)
+ {
+ option.SetProperty(Toolkit::PushButton::Property::ICON_PADDING, Vector4(10.0f, 10.0f, 10.0f, 10.0f));
+ option.SetProperty(Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT, "BOTTOM");
+
+ // TODO: This is temporarily disabled until the text-selection-popup image API is changed to strings.
+ //option.SetProperty( Toolkit::Button::Property::SELECTED_VISUAL, button.icon );
+ //option.SetProperty( Toolkit::Button::Property::UNSELECTED_VISUAL, button.icon );
+ }
+
+ // 3. Set the normal option image (blank / Transparent).
+ option.SetProperty(Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, "");
+
+ // 4. Set the pressed option image.
+ Property::Value selectedBackgroundValue(mPressedImage);
+ if(mPressedImage.empty())
+ {
+ // The image can be blank, the color can be used in that case.
+ selectedBackgroundValue = Property::Value{{Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR},
+ {Toolkit::ColorVisual::Property::MIX_COLOR, mPressedColor}};
+ }
+ option.SetProperty(Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, selectedBackgroundValue);
+ option.SetProperty(Toolkit::Control::Property::STYLE_NAME, TEXT_SELECTION_POPUP_BUTTON_STYLE_NAME);
+
+ // 5 Add option to tool bar
+ mToolbar.AddOption(option);
+
+ // 6. Add the divider
+ if(showDivider)
+ {
+ const Size size(mOptionDividerSize.width, 0.0f); // Height FILL_TO_PARENT
+
+ Toolkit::Control divider = Toolkit::Control::New();
#ifdef DECORATOR_DEBUG
- divider.SetProperty( Dali::Actor::Property::NAME,"Text's popup divider");
+ divider.SetProperty(Dali::Actor::Property::NAME, "Text's popup divider");
#endif
- divider.SetProperty( Actor::Property::SIZE, size );
- divider.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT );
- divider.SetBackgroundColor( mDividerColor );
- mToolbar.AddDivider( divider );
- }
- }
-
- std::size_t TextSelectionPopup::GetNumberOfEnabledOptions() const
- {
- std::size_t numberOfOptions = 0u;
- for( std::vector<ButtonRequirement>::const_iterator it = mOrderListOfButtons.begin(), endIt = mOrderListOfButtons.end(); ( it != endIt ); ++it )
- {
- const ButtonRequirement& button( *it );
- if( button.enabled )
- {
- ++numberOfOptions;
- }
- }
-
- return numberOfOptions;
- }
-
- void TextSelectionPopup::AddPopupOptionsToToolbar( bool showIcons, bool showCaptions )
- {
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextSelectionPopup::AddPopupOptionsToToolbar\n" );
-
- CreateOrderedListOfPopupOptions();
-
- mButtonsChanged = false;
- UnparentAndReset( mToolbar);
-
- if( !mToolbar )
- {
- Actor self = Self();
- mToolbar = Toolkit::TextSelectionToolbar::New();
- if ( mPopupMaxSize != Vector2::ZERO ) // If PopupMaxSize property set then apply to Toolbar. Toolbar currently is not retriving this from json
- {
- mToolbar.SetProperty( Toolkit::TextSelectionToolbar::Property::MAX_SIZE, mPopupMaxSize );
- }
- mToolbar.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ divider.SetProperty(Actor::Property::SIZE, size);
+ divider.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT);
+ divider.SetBackgroundColor(mDividerColor);
+ mToolbar.AddDivider(divider);
+ }
+}
+
+std::size_t TextSelectionPopup::GetNumberOfEnabledOptions() const
+{
+ std::size_t numberOfOptions = 0u;
+ for(std::vector<ButtonRequirement>::const_iterator it = mOrderListOfButtons.begin(), endIt = mOrderListOfButtons.end(); (it != endIt); ++it)
+ {
+ const ButtonRequirement& button(*it);
+ if(button.enabled)
+ {
+ ++numberOfOptions;
+ }
+ }
+
+ return numberOfOptions;
+}
+
+void TextSelectionPopup::AddPopupOptionsToToolbar(bool showIcons, bool showCaptions)
+{
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextSelectionPopup::AddPopupOptionsToToolbar\n");
+
+ CreateOrderedListOfPopupOptions();
+
+ mButtonsChanged = false;
+ UnparentAndReset(mToolbar);
+
+ if(!mToolbar)
+ {
+ Actor self = Self();
+ mToolbar = Toolkit::TextSelectionToolbar::New();
+ if(mPopupMaxSize != Vector2::ZERO) // If PopupMaxSize property set then apply to Toolbar. Toolbar currently is not retriving this from json
+ {
+ mToolbar.SetProperty(Toolkit::TextSelectionToolbar::Property::MAX_SIZE, mPopupMaxSize);
+ }
+ mToolbar.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
#ifdef DECORATOR_DEBUG
- mToolbar.SetProperty( Dali::Actor::Property::NAME,"TextSelectionToolbar");
+ mToolbar.SetProperty(Dali::Actor::Property::NAME, "TextSelectionToolbar");
#endif
- self.Add( mToolbar );
- }
+ self.Add(mToolbar);
+ }
- // Whether to mirror the list of buttons (for right to left languages)
- bool mirror = false;
+ // Whether to mirror the list of buttons (for right to left languages)
+ bool mirror = false;
#if defined(__GLIBC__)
- char* idsLtr = GET_LOCALE_TEXT( IDS_LTR.c_str() );
- if( NULL != idsLtr )
- {
- mirror = ( 0 == strcmp( idsLtr, RTL_DIRECTION.c_str() ) );
-
- if( mirror )
- {
- std::reverse( mOrderListOfButtons.begin(), mOrderListOfButtons.end() );
- }
- }
+ char* idsLtr = GET_LOCALE_TEXT(IDS_LTR.c_str());
+ if(NULL != idsLtr)
+ {
+ mirror = (0 == strcmp(idsLtr, RTL_DIRECTION.c_str()));
+
+ if(mirror)
+ {
+ std::reverse(mOrderListOfButtons.begin(), mOrderListOfButtons.end());
+ }
+ }
#endif
- // Iterate list of buttons and add active ones to Toolbar
- std::size_t numberOfOptionsRequired = GetNumberOfEnabledOptions();
- std::size_t numberOfOptionsAdded = 0u;
- for( std::vector<ButtonRequirement>::const_iterator it = mOrderListOfButtons.begin(), endIt = mOrderListOfButtons.end(); ( it != endIt ); ++it )
- {
- const ButtonRequirement& button( *it );
- if ( button.enabled )
- {
- numberOfOptionsAdded++;
- AddOption( button, ( numberOfOptionsAdded < numberOfOptionsRequired ) , showIcons, showCaptions );
- }
- }
-
- if( mirror )
- {
- mToolbar.ScrollTo( Vector2( mPopupMaxSize.x, 0.f ) );
- }
- }
-
-void TextSelectionPopup::CreateBackgroundBorder( Property::Map& propertyMap )
+ // Iterate list of buttons and add active ones to Toolbar
+ std::size_t numberOfOptionsRequired = GetNumberOfEnabledOptions();
+ std::size_t numberOfOptionsAdded = 0u;
+ for(std::vector<ButtonRequirement>::const_iterator it = mOrderListOfButtons.begin(), endIt = mOrderListOfButtons.end(); (it != endIt); ++it)
+ {
+ const ButtonRequirement& button(*it);
+ if(button.enabled)
+ {
+ numberOfOptionsAdded++;
+ AddOption(button, (numberOfOptionsAdded < numberOfOptionsRequired), showIcons, showCaptions);
+ }
+ }
+
+ if(mirror)
+ {
+ mToolbar.ScrollTo(Vector2(mPopupMaxSize.x, 0.f));
+ }
+}
+
+void TextSelectionPopup::CreateBackgroundBorder(Property::Map& propertyMap)
{
// Removes previous image if necessary
- DevelControl::UnregisterVisual( *this, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER );
+ DevelControl::UnregisterVisual(*this, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER);
- if( ! propertyMap.Empty() )
+ if(!propertyMap.Empty())
{
- Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( propertyMap );
+ Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(propertyMap);
- if( visual )
+ if(visual)
{
- DevelControl::RegisterVisual( *this, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER, visual, DepthIndex::CONTENT );
+ DevelControl::RegisterVisual(*this, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER, visual, DepthIndex::CONTENT);
}
}
}
-TextSelectionPopup::TextSelectionPopup( TextSelectionPopupCallbackInterface* callbackInterface )
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+TextSelectionPopup::TextSelectionPopup(TextSelectionPopupCallbackInterface* callbackInterface)
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mToolbar(),
mPopupMaxSize(),
mOptionMaxSize(),
mOptionMinSize(),
mOptionDividerSize(),
- mEnabledButtons( Toolkit::TextSelectionPopup::NONE ),
- mCallbackInterface( callbackInterface ),
- mPressedColor( DEFAULT_OPTION_PRESSED_COLOR ),
- mDividerColor( Color::WHITE ),
- mIconColor( Color::WHITE ),
- mSelectOptionPriority( 1 ),
- mSelectAllOptionPriority ( 2 ),
- mCutOptionPriority ( 4 ),
- mCopyOptionPriority ( 3 ),
- mPasteOptionPriority ( 5 ),
- mClipboardOptionPriority( 6 ),
+ mEnabledButtons(Toolkit::TextSelectionPopup::NONE),
+ mCallbackInterface(callbackInterface),
+ mPressedColor(DEFAULT_OPTION_PRESSED_COLOR),
+ mDividerColor(Color::WHITE),
+ mIconColor(Color::WHITE),
+ mSelectOptionPriority(1),
+ mSelectAllOptionPriority(2),
+ mCutOptionPriority(4),
+ mCopyOptionPriority(3),
+ mPasteOptionPriority(5),
+ mClipboardOptionPriority(6),
mFadeInDuration(0.0f),
mFadeOutDuration(0.0f),
- mShowIcons( false ),
- mShowCaptions( true ),
- mPopupShowing( false ),
- mButtonsChanged( false )
+ mShowIcons(false),
+ mShowCaptions(true),
+ mPopupShowing(false),
+ mButtonsChanged(false)
{
}
{
}
-
} // namespace Internal
} // namespace Toolkit
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/controls/text-controls/text-selection-toolbar-impl.h>
// EXTERNAL INCLUDES
-#include <cfloat>
#include <dali/public-api/math/vector2.h>
#include <dali/public-api/math/vector4.h>
#include <dali/public-api/object/property-map.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <cfloat>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
-#include <dali-toolkit/internal/helpers/color-conversion.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
+#include <dali-toolkit/internal/helpers/color-conversion.h>
+#include <dali-toolkit/public-api/controls/image-view/image-view.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-const Dali::Vector2 DEFAULT_SCROLL_BAR_PADDING( 8.0f, 6.0f );
+const Dali::Vector2 DEFAULT_SCROLL_BAR_PADDING(8.0f, 6.0f);
BaseHandle Create()
{
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextSelectionToolbar, Toolkit::Control, Create );
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextSelectionToolbar, Toolkit::Control, Create);
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "maxSize", VECTOR2, MAX_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "enableOvershoot", BOOLEAN, ENABLE_OVERSHOOT )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "enableScrollBar", BOOLEAN, ENABLE_SCROLL_BAR )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "scrollBarPadding", VECTOR2, SCROLL_BAR_PADDING )
-DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "scrollView", MAP, SCROLL_VIEW )
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "maxSize", VECTOR2, MAX_SIZE)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "enableOvershoot", BOOLEAN, ENABLE_OVERSHOOT)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "enableScrollBar", BOOLEAN, ENABLE_SCROLL_BAR)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "scrollBarPadding", VECTOR2, SCROLL_BAR_PADDING)
+DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "scrollView", MAP, SCROLL_VIEW)
DALI_TYPE_REGISTRATION_END()
Dali::Toolkit::TextSelectionToolbar TextSelectionToolbar::New()
{
// Create the implementation, temporarily owned by this handle on stack
- IntrusivePtr< TextSelectionToolbar > impl = new TextSelectionToolbar();
+ IntrusivePtr<TextSelectionToolbar> impl = new TextSelectionToolbar();
// Pass ownership to CustomActor handle
- Dali::Toolkit::TextSelectionToolbar handle( *impl );
+ Dali::Toolkit::TextSelectionToolbar handle(*impl);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return handle;
}
-void TextSelectionToolbar::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void TextSelectionToolbar::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::TextSelectionToolbar selectionPopup = Toolkit::TextSelectionToolbar::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextSelectionToolbar selectionPopup = Toolkit::TextSelectionToolbar::DownCast(Dali::BaseHandle(object));
- if( selectionPopup )
+ if(selectionPopup)
{
- TextSelectionToolbar& impl( GetImpl( selectionPopup ) );
+ TextSelectionToolbar& impl(GetImpl(selectionPopup));
- switch( index )
+ switch(index)
{
case Toolkit::TextSelectionToolbar::Property::MAX_SIZE:
{
- impl.SetPopupMaxSize( value.Get< Vector2 >() );
- break;
+ impl.SetPopupMaxSize(value.Get<Vector2>());
+ break;
}
case Toolkit::TextSelectionToolbar::Property::ENABLE_OVERSHOOT:
{
- if( !impl.mScrollView )
+ if(!impl.mScrollView)
{
- impl.mScrollView = Toolkit::ScrollView::New();
+ impl.mScrollView = Toolkit::ScrollView::New();
}
- impl.mScrollView.SetOvershootEnabled( value.Get< bool >() );
+ impl.mScrollView.SetOvershootEnabled(value.Get<bool>());
break;
}
case Toolkit::TextSelectionToolbar::Property::ENABLE_SCROLL_BAR:
{
- impl.SetUpScrollBar( value.Get< bool >() );
+ impl.SetUpScrollBar(value.Get<bool>());
break;
}
case Toolkit::TextSelectionToolbar::Property::SCROLL_BAR_PADDING:
{
- impl.SetScrollBarPadding( value.Get< Vector2 >() );
+ impl.SetScrollBarPadding(value.Get<Vector2>());
break;
}
case Toolkit::TextSelectionToolbar::Property::SCROLL_VIEW:
{
// Get a Property::Map from the property if possible.
Property::Map setPropertyMap;
- if( value.Get( setPropertyMap ) )
+ if(value.Get(setPropertyMap))
{
- impl.ConfigureScrollview( setPropertyMap );
+ impl.ConfigureScrollview(setPropertyMap);
}
break;
}
} // switch
- } // TextSelectionToolbar
+ } // TextSelectionToolbar
}
-Property::Value TextSelectionToolbar::GetProperty( BaseObject* object, Property::Index index )
+Property::Value TextSelectionToolbar::GetProperty(BaseObject* object, Property::Index index)
{
Property::Value value;
- Toolkit::TextSelectionToolbar selectionPopup = Toolkit::TextSelectionToolbar::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::TextSelectionToolbar selectionPopup = Toolkit::TextSelectionToolbar::DownCast(Dali::BaseHandle(object));
- if( selectionPopup )
+ if(selectionPopup)
{
- TextSelectionToolbar& impl( GetImpl( selectionPopup ) );
+ TextSelectionToolbar& impl(GetImpl(selectionPopup));
- switch( index )
+ switch(index)
{
case Toolkit::TextSelectionToolbar::Property::MAX_SIZE:
{
{
SetUp();
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::TOOL_BAR ));
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::TOOL_BAR));
+ });
}
-void TextSelectionToolbar::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void TextSelectionToolbar::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- float width = std::max ( mTableOfButtons.GetNaturalSize().width, size.width );
- mRulerX->SetDomain( RulerDomain( 0.0, width, true ) );
- mScrollView.SetRulerX( mRulerX );
+ float width = std::max(mTableOfButtons.GetNaturalSize().width, size.width);
+ mRulerX->SetDomain(RulerDomain(0.0, width, true));
+ mScrollView.SetRulerX(mRulerX);
- if( mScrollBar )
+ if(mScrollBar)
{
- float barWidth = std::min( mTableOfButtons.GetNaturalSize().width, size.width ) - 2.f * mScrollBarPadding.x;
- mScrollBar.SetProperty( Actor::Property::SIZE, Vector2( 0.0f, barWidth ) );
+ float barWidth = std::min(mTableOfButtons.GetNaturalSize().width, size.width) - 2.f * mScrollBarPadding.x;
+ mScrollBar.SetProperty(Actor::Property::SIZE, Vector2(0.0f, barWidth));
}
}
-void TextSelectionToolbar::SetPopupMaxSize( const Size& maxSize )
+void TextSelectionToolbar::SetPopupMaxSize(const Size& maxSize)
{
mMaxSize = maxSize;
- if( mScrollView && mToolbarActor )
+ if(mScrollView && mToolbarActor)
{
- mScrollView.SetProperty( Actor::Property::MAXIMUM_SIZE, mMaxSize );
- mToolbarActor.SetProperty( Actor::Property::MAXIMUM_SIZE, mMaxSize );
+ mScrollView.SetProperty(Actor::Property::MAXIMUM_SIZE, mMaxSize);
+ mToolbarActor.SetProperty(Actor::Property::MAXIMUM_SIZE, mMaxSize);
}
}
void TextSelectionToolbar::SetUpScrollView()
{
- mScrollView.SetProperty( Dali::Actor::Property::NAME,"TextSelectionScrollView");
- mScrollView.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS );
- mScrollView.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT );
- mScrollView.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT );
+ mScrollView.SetProperty(Dali::Actor::Property::NAME, "TextSelectionScrollView");
+ mScrollView.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS);
+ mScrollView.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT);
+ mScrollView.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT);
- mScrollView.SetScrollingDirection( PanGestureDetector::DIRECTION_HORIZONTAL, Degree( 40.0f ) );
- mScrollView.SetAxisAutoLock( true );
- mScrollView.ScrollStartedSignal().Connect( this, &TextSelectionToolbar::OnScrollStarted );
- mScrollView.ScrollCompletedSignal().Connect( this, &TextSelectionToolbar::OnScrollCompleted );
- mScrollView.SetProperty( Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX ); // In a new layer, so clip to scroll-view's bounding box
+ mScrollView.SetScrollingDirection(PanGestureDetector::DIRECTION_HORIZONTAL, Degree(40.0f));
+ mScrollView.SetAxisAutoLock(true);
+ mScrollView.ScrollStartedSignal().Connect(this, &TextSelectionToolbar::OnScrollStarted);
+ mScrollView.ScrollCompletedSignal().Connect(this, &TextSelectionToolbar::OnScrollCompleted);
+ mScrollView.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX); // In a new layer, so clip to scroll-view's bounding box
- mRulerX = new DefaultRuler(); // IntrusivePtr which is unreferenced when ScrollView is destroyed.
+ mRulerX = new DefaultRuler(); // IntrusivePtr which is unreferenced when ScrollView is destroyed.
- RulerPtr rulerY = new DefaultRuler(); // IntrusivePtr which is unreferenced when ScrollView is destroyed.
+ RulerPtr rulerY = new DefaultRuler(); // IntrusivePtr which is unreferenced when ScrollView is destroyed.
rulerY->Disable();
- mScrollView.SetRulerY( rulerY );
+ mScrollView.SetRulerY(rulerY);
- mScrollView.SetOvershootEnabled( true );
+ mScrollView.SetOvershootEnabled(true);
}
void TextSelectionToolbar::SetUp()
{
Actor self = Self();
- self.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS );
+ self.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS);
// Create Actor to house the toolbar.
mToolbarActor = Actor::New();
- mToolbarActor.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS );
- mToolbarActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- mToolbarActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mToolbarActor.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS);
+ mToolbarActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mToolbarActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
- if( !mScrollView )
+ if(!mScrollView)
{
mScrollView = Toolkit::ScrollView::New();
}
SetUpScrollView();
// Toolbar must start with at least one option, adding further options with increase it's size
- mTableOfButtons = Dali::Toolkit::TableView::New( 1, 1 );
- mTableOfButtons.SetFitHeight( 0 );
- mTableOfButtons.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT );
- mTableOfButtons.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT );
+ mTableOfButtons = Dali::Toolkit::TableView::New(1, 1);
+ mTableOfButtons.SetFitHeight(0);
+ mTableOfButtons.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT);
+ mTableOfButtons.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT);
- mScrollView.Add( mTableOfButtons );
- mToolbarActor.Add( mScrollView );
+ mScrollView.Add(mTableOfButtons);
+ mToolbarActor.Add(mScrollView);
- self.Add( mToolbarActor );
+ self.Add(mToolbarActor);
}
-void TextSelectionToolbar::SetUpScrollBar( bool enable )
+void TextSelectionToolbar::SetUpScrollBar(bool enable)
{
- if( enable )
+ if(enable)
{
- if( ! mScrollBar )
+ if(!mScrollBar)
{
Toolkit::ImageView indicator = Toolkit::ImageView::New();
- indicator.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- indicator.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- indicator.SetStyleName( "TextSelectionScrollIndicator" );
-
- mScrollBar = Toolkit::ScrollBar::New( Toolkit::ScrollBar::HORIZONTAL );
- mScrollBar.SetProperty( Dali::Actor::Property::NAME, "Text popup scroll bar" );
- mScrollBar.SetStyleName( "TextSelectionScrollBar" );
- mScrollBar.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_LEFT );
- mScrollBar.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- mScrollBar.SetProperty( Actor::Property::POSITION, Vector2( mScrollBarPadding.x, -mScrollBarPadding.y ));
- mScrollBar.SetResizePolicy( Dali::ResizePolicy::FIT_TO_CHILDREN, Dali::Dimension::WIDTH );
- mScrollBar.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( 1.5f * Math::PI ), Vector3::ZAXIS ) ) );
- mScrollBar.SetScrollIndicator( indicator );
+ indicator.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ indicator.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ indicator.SetStyleName("TextSelectionScrollIndicator");
+
+ mScrollBar = Toolkit::ScrollBar::New(Toolkit::ScrollBar::HORIZONTAL);
+ mScrollBar.SetProperty(Dali::Actor::Property::NAME, "Text popup scroll bar");
+ mScrollBar.SetStyleName("TextSelectionScrollBar");
+ mScrollBar.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_LEFT);
+ mScrollBar.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ mScrollBar.SetProperty(Actor::Property::POSITION, Vector2(mScrollBarPadding.x, -mScrollBarPadding.y));
+ mScrollBar.SetResizePolicy(Dali::ResizePolicy::FIT_TO_CHILDREN, Dali::Dimension::WIDTH);
+ mScrollBar.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(1.5f * Math::PI), Vector3::ZAXIS)));
+ mScrollBar.SetScrollIndicator(indicator);
mScrollBar.GetPanGestureDetector().DetachAll();
- mScrollView.Add( mScrollBar );
+ mScrollView.Add(mScrollBar);
}
}
else
{
- UnparentAndReset( mScrollBar );
+ UnparentAndReset(mScrollBar);
}
}
-void TextSelectionToolbar::OnScrollStarted( const Vector2& position )
+void TextSelectionToolbar::OnScrollStarted(const Vector2& position)
{
- if( mFirstScrollEnd )
+ if(mFirstScrollEnd)
{
- mScrollView.SetOvershootEnabled( true );
+ mScrollView.SetOvershootEnabled(true);
}
- mTableOfButtons.SetProperty( Actor::Property::SENSITIVE, false );
+ mTableOfButtons.SetProperty(Actor::Property::SENSITIVE, false);
}
-void TextSelectionToolbar::OnScrollCompleted( const Vector2& position )
+void TextSelectionToolbar::OnScrollCompleted(const Vector2& position)
{
mFirstScrollEnd = true;
- mTableOfButtons.SetProperty( Actor::Property::SENSITIVE, true );
+ mTableOfButtons.SetProperty(Actor::Property::SENSITIVE, true);
}
-void TextSelectionToolbar::AddOption( Actor& option )
+void TextSelectionToolbar::AddOption(Actor& option)
{
- mTableOfButtons.AddChild( option, Toolkit::TableView::CellPosition( 0, mIndexInTable ) );
- mTableOfButtons.SetFitWidth( mIndexInTable );
+ mTableOfButtons.AddChild(option, Toolkit::TableView::CellPosition(0, mIndexInTable));
+ mTableOfButtons.SetFitWidth(mIndexInTable);
mIndexInTable++;
}
-void TextSelectionToolbar::AddDivider( Actor& divider )
+void TextSelectionToolbar::AddDivider(Actor& divider)
{
- AddOption( divider );
- mDividerIndexes.PushBack( mIndexInTable - 1u );
+ AddOption(divider);
+ mDividerIndexes.PushBack(mIndexInTable - 1u);
}
-void TextSelectionToolbar::ResizeDividers( Size& size )
+void TextSelectionToolbar::ResizeDividers(Size& size)
{
- for( unsigned int i = 0; i < mDividerIndexes.Count(); ++i )
+ for(unsigned int i = 0; i < mDividerIndexes.Count(); ++i)
{
- Actor divider = mTableOfButtons.GetChildAt( Toolkit::TableView::CellPosition( 0, mDividerIndexes[ i ] ) );
- divider.SetProperty( Actor::Property::SIZE, size );
+ Actor divider = mTableOfButtons.GetChildAt(Toolkit::TableView::CellPosition(0, mDividerIndexes[i]));
+ divider.SetProperty(Actor::Property::SIZE, size);
}
RelayoutRequest();
}
-void TextSelectionToolbar::RaiseAbove( Actor target )
+void TextSelectionToolbar::RaiseAbove(Actor target)
{
- mToolbarActor.RaiseAbove( target );
+ mToolbarActor.RaiseAbove(target);
}
-void TextSelectionToolbar::SetScrollBarPadding( const Vector2& padding )
+void TextSelectionToolbar::SetScrollBarPadding(const Vector2& padding)
{
mScrollBarPadding = padding;
- if( mScrollBar )
+ if(mScrollBar)
{
- mScrollBar.SetProperty( Actor::Property::POSITION, Vector2( mScrollBarPadding.x, -mScrollBarPadding.y ));
+ mScrollBar.SetProperty(Actor::Property::POSITION, Vector2(mScrollBarPadding.x, -mScrollBarPadding.y));
}
RelayoutRequest();
}
-void TextSelectionToolbar::ScrollTo( const Vector2& position )
+void TextSelectionToolbar::ScrollTo(const Vector2& position)
{
mFirstScrollEnd = false;
- mScrollView.SetOvershootEnabled( false );
- mScrollView.ScrollTo( position, 0.f );
+ mScrollView.SetOvershootEnabled(false);
+ mScrollView.ScrollTo(position, 0.f);
}
-void TextSelectionToolbar::ConfigureScrollview( const Property::Map& properties )
+void TextSelectionToolbar::ConfigureScrollview(const Property::Map& properties)
{
// Set any properties specified for the label by iterating through all property key-value pairs.
- for( unsigned int i = 0, mapCount = properties.Count(); i < mapCount; ++i )
+ for(unsigned int i = 0, mapCount = properties.Count(); i < mapCount; ++i)
{
- const StringValuePair& propertyPair( properties.GetPair( i ) );
+ const StringValuePair& propertyPair(properties.GetPair(i));
// Convert the property string to a property index.
- Property::Index setPropertyIndex = mScrollView.GetPropertyIndex( propertyPair.first );
- if( setPropertyIndex != Property::INVALID_INDEX )
+ Property::Index setPropertyIndex = mScrollView.GetPropertyIndex(propertyPair.first);
+ if(setPropertyIndex != Property::INVALID_INDEX)
{
// Convert the string representation of a color into a Vector4
- if( setPropertyIndex == Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR )
+ if(setPropertyIndex == Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR)
{
Vector4 color;
- if( ConvertPropertyToColor( propertyPair.second, color ) )
+ if(ConvertPropertyToColor(propertyPair.second, color))
{
- mScrollView.SetOvershootEffectColor( color );
+ mScrollView.SetOvershootEffectColor(color);
}
}
else
{
// If the conversion worked, we have a valid property index,
// Set the property to the new value.
- mScrollView.SetProperty( setPropertyIndex, propertyPair.second );
+ mScrollView.SetProperty(setPropertyIndex, propertyPair.second);
}
}
}
}
TextSelectionToolbar::TextSelectionToolbar()
-: Control( ControlBehaviour( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ) ),
- mMaxSize (),
- mScrollBarPadding( DEFAULT_SCROLL_BAR_PADDING ),
- mIndexInTable( 0 ),
+: Control(ControlBehaviour(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT))),
+ mMaxSize(),
+ mScrollBarPadding(DEFAULT_SCROLL_BAR_PADDING),
+ mIndexInTable(0),
mDividerIndexes(),
- mFirstScrollEnd( false )
+ mFirstScrollEnd(false)
{
}
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
#include <dali/public-api/animation/constraints.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/alignment/alignment.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
return Toolkit::ToolBar::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ToolBar, Toolkit::Control, Create )
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ToolBar, Toolkit::Control, Create)
DALI_TYPE_REGISTRATION_END()
-const float DEFAULT_RELATIVE_SIZE( 0.1f );
-const Toolkit::Alignment::Type DEFAULT_ALIGNMENT( Toolkit::Alignment::HORIZONTAL_LEFT );
+const float DEFAULT_RELATIVE_SIZE(0.1f);
+const Toolkit::Alignment::Type DEFAULT_ALIGNMENT(Toolkit::Alignment::HORIZONTAL_LEFT);
} // namespace
Toolkit::ToolBar ToolBar::New()
{
// Create the implementation, temporarily owned on stack
- IntrusivePtr< ToolBar > internalToolBar = new ToolBar();
+ IntrusivePtr<ToolBar> internalToolBar = new ToolBar();
// Pass ownership to Toolkit::Toolbar
- Toolkit::ToolBar toolBar( *internalToolBar );
+ Toolkit::ToolBar toolBar(*internalToolBar);
// Second-phase init of the implementation
// This can only be done after the CustomActor connection has been made...
return toolBar;
}
-void ToolBar::AddControl( Actor control, float relativeSize, Toolkit::Alignment::Type alignment, const Toolkit::Alignment::Padding& padding )
+void ToolBar::AddControl(Actor control, float relativeSize, Toolkit::Alignment::Type alignment, const Toolkit::Alignment::Padding& padding)
{
// Work out index and update bases and offsets for further insertions.
unsigned int index = 0;
- switch( alignment )
+ switch(alignment)
{
case Toolkit::Alignment::HORIZONTAL_LEFT:
{
}
default:
{
- DALI_ASSERT_ALWAYS( false );
+ DALI_ASSERT_ALWAYS(false);
}
}
// Create a new column for the new control.
- mLayout.InsertColumn( index );
+ mLayout.InsertColumn(index);
// Create an alignment container where to place the control.
- Toolkit::Alignment alignmentContainer = Toolkit::Alignment::New( alignment );
- alignmentContainer.SetProperty( Actor::Property::SIZE_SCALE_POLICY, SizeScalePolicy::FIT_WITH_ASPECT_RATIO );
- alignmentContainer.SetPadding( padding );
- alignmentContainer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
- alignmentContainer.Add( control );
+ Toolkit::Alignment alignmentContainer = Toolkit::Alignment::New(alignment);
+ alignmentContainer.SetProperty(Actor::Property::SIZE_SCALE_POLICY, SizeScalePolicy::FIT_WITH_ASPECT_RATIO);
+ alignmentContainer.SetPadding(padding);
+ alignmentContainer.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
+ alignmentContainer.Add(control);
// Insert the control in the table view.
- mLayout.AddChild( alignmentContainer, Toolkit::TableView::CellPosition( 0, index ) );
- mLayout.SetRelativeWidth( index, relativeSize );
+ mLayout.AddChild(alignmentContainer, Toolkit::TableView::CellPosition(0, index));
+ mLayout.SetRelativeWidth(index, relativeSize);
// Relate control and alignmentContainer in order to allow removing controls.
mControls[control] = alignmentContainer;
mAccumulatedRelativeSpace += relativeSize;
// Update spaces between left, center and right groups of controls.
- switch( alignment )
+ switch(alignment)
{
case Toolkit::Alignment::HORIZONTAL_LEFT:
{
mLeftRelativeSpace -= relativeSize;
- if ( mLeftRelativeSpace < 0.f )
+ if(mLeftRelativeSpace < 0.f)
{
mLeftRelativeSpace = 0.f;
}
case Toolkit::Alignment::HORIZONTAL_CENTER:
{
mLeftRelativeSpace -= 0.5f * relativeSize;
- if ( mLeftRelativeSpace < 0.f )
+ if(mLeftRelativeSpace < 0.f)
{
mLeftRelativeSpace = 0.f;
}
mRightRelativeSpace -= 0.5f * relativeSize;
- if ( mRightRelativeSpace < 0.f )
+ if(mRightRelativeSpace < 0.f)
{
mRightRelativeSpace = 0.f;
}
case Toolkit::Alignment::HORIZONTAL_RIGHT:
{
mRightRelativeSpace -= relativeSize;
- if ( mRightRelativeSpace < 0.f )
+ if(mRightRelativeSpace < 0.f)
{
mRightRelativeSpace = 0.f;
}
}
default:
{
- DALI_ASSERT_ALWAYS( false );
+ DALI_ASSERT_ALWAYS(false);
}
}
- mLayout.SetRelativeWidth( mLeftOffset, mLeftRelativeSpace );
- mLayout.SetRelativeWidth( mCenterBase + mCenterOffset, mRightRelativeSpace );
+ mLayout.SetRelativeWidth(mLeftOffset, mLeftRelativeSpace);
+ mLayout.SetRelativeWidth(mCenterBase + mCenterOffset, mRightRelativeSpace);
}
-void ToolBar::RemoveControl( Actor control )
+void ToolBar::RemoveControl(Actor control)
{
Toolkit::TableView::CellPosition position;
// Find the alignment where the control is placed.
- std::map<Actor,Toolkit::Alignment>::iterator it = mControls.find( control );
+ std::map<Actor, Toolkit::Alignment>::iterator it = mControls.find(control);
- if( ( it != mControls.end() ) && ( mLayout.FindChildPosition( it->second, position ) ) )
+ if((it != mControls.end()) && (mLayout.FindChildPosition(it->second, position)))
{
// Update accumulated relative space.
- mAccumulatedRelativeSpace -= mLayout.GetRelativeWidth( position.columnIndex );
+ mAccumulatedRelativeSpace -= mLayout.GetRelativeWidth(position.columnIndex);
// Update spaces between left, center and right groups of controls.
- if( 1.0 > mAccumulatedRelativeSpace )
+ if(1.0 > mAccumulatedRelativeSpace)
{
Toolkit::Alignment::Type alignment = Toolkit::Alignment::HORIZONTAL_LEFT;
- if( position.columnIndex < mLeftOffset )
+ if(position.columnIndex < mLeftOffset)
{
alignment = Toolkit::Alignment::HORIZONTAL_LEFT;
}
- else if( ( position.columnIndex > mLeftOffset ) && ( position.columnIndex < mCenterBase + mCenterOffset ) )
+ else if((position.columnIndex > mLeftOffset) && (position.columnIndex < mCenterBase + mCenterOffset))
{
alignment = Toolkit::Alignment::HORIZONTAL_CENTER;
}
- else if( position.columnIndex > mCenterBase + mCenterOffset )
+ else if(position.columnIndex > mCenterBase + mCenterOffset)
{
alignment = Toolkit::Alignment::HORIZONTAL_RIGHT;
}
else
{
- DALI_ASSERT_ALWAYS( false );
+ DALI_ASSERT_ALWAYS(false);
}
- float relativeSize = mLayout.GetRelativeWidth( position.columnIndex );
+ float relativeSize = mLayout.GetRelativeWidth(position.columnIndex);
- switch( alignment )
+ switch(alignment)
{
case Toolkit::Alignment::HORIZONTAL_LEFT:
{
mLeftRelativeSpace += relativeSize;
- if ( mLeftRelativeSpace < 0.f )
+ if(mLeftRelativeSpace < 0.f)
{
mLeftRelativeSpace = 0.f;
}
case Toolkit::Alignment::HORIZONTAL_CENTER:
{
mLeftRelativeSpace += 0.5f * relativeSize;
- if ( mLeftRelativeSpace < 0.f )
+ if(mLeftRelativeSpace < 0.f)
{
mLeftRelativeSpace = 0.f;
}
mRightRelativeSpace += 0.5f * relativeSize;
- if ( mRightRelativeSpace < 0.f )
+ if(mRightRelativeSpace < 0.f)
{
mRightRelativeSpace = 0.f;
}
case Toolkit::Alignment::HORIZONTAL_RIGHT:
{
mRightRelativeSpace += relativeSize;
- if ( mRightRelativeSpace < 0.f )
+ if(mRightRelativeSpace < 0.f)
{
mRightRelativeSpace = 0.f;
}
}
default:
{
- DALI_ASSERT_ALWAYS( false );
+ DALI_ASSERT_ALWAYS(false);
}
}
- mLayout.SetRelativeWidth( mLeftOffset, mLeftRelativeSpace );
- mLayout.SetRelativeWidth( mCenterBase + mCenterOffset, mRightRelativeSpace );
+ mLayout.SetRelativeWidth(mLeftOffset, mLeftRelativeSpace);
+ mLayout.SetRelativeWidth(mCenterBase + mCenterOffset, mRightRelativeSpace);
}
// Remove alignment as parent of control.
- it->second.Remove( control );
+ it->second.Remove(control);
// Remove the relationship between control and alignment.
- mControls.erase( it );
+ mControls.erase(it);
// Remove column from tableview.
- mLayout.DeleteColumn( position.columnIndex );
+ mLayout.DeleteColumn(position.columnIndex);
// Update bases and offsets.
- if( position.columnIndex < mCenterBase )
+ if(position.columnIndex < mCenterBase)
{
// Control is on the left side. Decrease left offset and center and right bases.
--mLeftOffset;
--mCenterBase;
--mRightBase;
}
- else if( position.columnIndex < mCenterBase + mCenterOffset )
+ else if(position.columnIndex < mCenterBase + mCenterOffset)
{
// Control is on the center side. Decrease center offset and right base.
--mCenterOffset;
}
ToolBar::ToolBar()
-: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
+: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)),
mLayout(),
- mLeftOffset( 0 ),
- mCenterBase( 1 ),
- mCenterOffset( 0 ),
- mRightBase( 2 ),
- mRightOffset( 0 ),
- mLeftRelativeSpace( 0.5f ),
- mRightRelativeSpace( 0.5f ),
- mAccumulatedRelativeSpace( 0.f ),
- mInitializing( false ),
+ mLeftOffset(0),
+ mCenterBase(1),
+ mCenterOffset(0),
+ mRightBase(2),
+ mRightOffset(0),
+ mLeftRelativeSpace(0.5f),
+ mRightRelativeSpace(0.5f),
+ mAccumulatedRelativeSpace(0.f),
+ mInitializing(false),
mControls()
{
}
void ToolBar::OnInitialize()
{
- Lock lock( mInitializing );
+ Lock lock(mInitializing);
// Layout
- mLayout = Toolkit::TableView::New( 1, 1 );
- mLayout.SetProperty( Dali::Actor::Property::NAME, "TOOLBAR_LAYOUT" );
- mLayout.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
- mLayout.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mLayout = Toolkit::TableView::New(1, 1);
+ mLayout.SetProperty(Dali::Actor::Property::NAME, "TOOLBAR_LAYOUT");
+ mLayout.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
+ mLayout.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
- Self().Add( mLayout );
+ Self().Add(mLayout);
// Add two default actors to create spaces between controls grouped on the left, center and right.
- Actor leftSpace = Actor::New();
+ Actor leftSpace = Actor::New();
Actor rightSpace = Actor::New();
- mLayout.AddChild( leftSpace, Toolkit::TableView::CellPosition( 0, 0 ) );
- mLayout.AddChild( rightSpace, Toolkit::TableView::CellPosition( 0, 1 ) );
- mLayout.SetRelativeWidth( 0, mLeftRelativeSpace );
- mLayout.SetRelativeWidth( 1, mRightRelativeSpace );
-
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::TOOL_BAR ));
- } );
+ mLayout.AddChild(leftSpace, Toolkit::TableView::CellPosition(0, 0));
+ mLayout.AddChild(rightSpace, Toolkit::TableView::CellPosition(0, 1));
+ mLayout.SetRelativeWidth(0, mLeftRelativeSpace);
+ mLayout.SetRelativeWidth(1, mRightRelativeSpace);
+
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::TOOL_BAR));
+ });
}
void ToolBar::OnChildAdd(Actor& child)
{
- if( !mInitializing )
+ if(!mInitializing)
{
// An actor is being added through the Actor's API.
// Remove child from tool bar actor and insert it in table view with some 'default' values
- if ( child && child.GetParent() )
+ if(child && child.GetParent())
{
- child.GetParent().Remove( child );
+ child.GetParent().Remove(child);
}
- AddControl( child, DEFAULT_RELATIVE_SIZE, DEFAULT_ALIGNMENT, Toolkit::ToolBar::DEFAULT_PADDING );
+ AddControl(child, DEFAULT_RELATIVE_SIZE, DEFAULT_ALIGNMENT, Toolkit::ToolBar::DEFAULT_PADDING);
}
// No OnChildRemove method required because Actors are added to the mLayout table view, so if an
// actor is removed using the Actor::RemoveChild method it will not remove anything because the
// actor is in mLayout not in Self().
- Control::OnChildAdd( child );
+ Control::OnChildAdd(child);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
#include <cmath>
-#include <dali/public-api/events/hover-event.h>
-#include <dali/public-api/adaptor-framework/timer.h>
#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/scripting/enum-helper.h>
+#include <dali/public-api/adaptor-framework/timer.h>
+#include <dali/public-api/events/hover-event.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/table-view/table-view.h>
-#include <dali-toolkit/public-api/controls/text-controls/text-label.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/controls/tooltip/tooltip-properties.h>
-#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/controls/popup/popup-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
+#include <dali-toolkit/public-api/controls/text-controls/text-label.h>
+#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( TOOLTIP_POSITION )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Tooltip::Position, ABOVE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Tooltip::Position, BELOW )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Tooltip::Position, HOVER_POINT )
-DALI_ENUM_TO_STRING_TABLE_END( TOOLTIP_POSITION )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(TOOLTIP_POSITION)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Tooltip::Position, ABOVE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Tooltip::Position, BELOW)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Tooltip::Position, HOVER_POINT)
+DALI_ENUM_TO_STRING_TABLE_END(TOOLTIP_POSITION)
const float MILLISECONDS_PER_SECOND = 1000.0f;
-const char * const PROPERTY_CONTENT_NAME = "content";
-const char * const PROPERTY_LAYOUT_NAME = "layout";
-const char * const PROPERTY_WAIT_TIME_NAME = "waitTime";
-const char * const PROPERTY_BACKGROUND_NAME = "background";
-const char * const PROPERTY_TAIL_NAME = "tail";
-const char * const PROPERTY_POSITION_NAME = "position";
-const char * const PROPERTY_HOVER_POINT_OFFSET_NAME = "hoverPointOffset";
-const char * const PROPERTY_MOVEMENT_THRESHOLD = "movementThreshold";
-const char * const PROPERTY_DISAPPEAR_ON_MOVEMENT = "disappearOnMovement";
+const char* const PROPERTY_CONTENT_NAME = "content";
+const char* const PROPERTY_LAYOUT_NAME = "layout";
+const char* const PROPERTY_WAIT_TIME_NAME = "waitTime";
+const char* const PROPERTY_BACKGROUND_NAME = "background";
+const char* const PROPERTY_TAIL_NAME = "tail";
+const char* const PROPERTY_POSITION_NAME = "position";
+const char* const PROPERTY_HOVER_POINT_OFFSET_NAME = "hoverPointOffset";
+const char* const PROPERTY_MOVEMENT_THRESHOLD = "movementThreshold";
+const char* const PROPERTY_DISAPPEAR_ON_MOVEMENT = "disappearOnMovement";
-const char * const PROPERTY_BACKGROUND_VISUAL = "visual";
-const char * const PROPERTY_BACKGROUND_BORDER = "border";
+const char* const PROPERTY_BACKGROUND_VISUAL = "visual";
+const char* const PROPERTY_BACKGROUND_BORDER = "border";
-const char * const PROPERTY_TAIL_VISIBILITY = "visibility";
-const char * const PROPERTY_TAIL_ABOVE_VISUAL = "aboveVisual";
-const char * const PROPERTY_TAIL_BELOW_VISUAL = "belowVisual";
+const char* const PROPERTY_TAIL_VISIBILITY = "visibility";
+const char* const PROPERTY_TAIL_ABOVE_VISUAL = "aboveVisual";
+const char* const PROPERTY_TAIL_BELOW_VISUAL = "belowVisual";
} // unnamed namespace
-TooltipPtr Tooltip::New( Toolkit::Control control )
+TooltipPtr Tooltip::New(Toolkit::Control control)
{
- return new Tooltip( control );
+ return new Tooltip(control);
}
-void Tooltip::SetProperties( const Property::Value& value )
+void Tooltip::SetProperties(const Property::Value& value)
{
Toolkit::Control control = mControl.GetHandle();
- if( control )
+ if(control)
{
const Property::Map* properties = value.GetMap();
- if( properties )
+ if(properties)
{
const Property::Map::SizeType count = properties->Count();
- for( Property::Map::SizeType position = 0; position < count; ++position )
+ for(Property::Map::SizeType position = 0; position < count; ++position)
{
- KeyValuePair keyValue = properties->GetKeyValue( position );
- Property::Key& key = keyValue.first;
- Property::Value& value = keyValue.second;
+ KeyValuePair keyValue = properties->GetKeyValue(position);
+ Property::Key& key = keyValue.first;
+ Property::Value& value = keyValue.second;
- if( key == Toolkit::Tooltip::Property::CONTENT || key == PROPERTY_CONTENT_NAME )
+ if(key == Toolkit::Tooltip::Property::CONTENT || key == PROPERTY_CONTENT_NAME)
{
- SetContent( control, value );
+ SetContent(control, value);
}
- else if( key == Toolkit::Tooltip::Property::LAYOUT || key == PROPERTY_LAYOUT_NAME )
+ else if(key == Toolkit::Tooltip::Property::LAYOUT || key == PROPERTY_LAYOUT_NAME)
{
- value.Get( mLayout );
+ value.Get(mLayout);
}
- else if( key == Toolkit::Tooltip::Property::WAIT_TIME || key == PROPERTY_WAIT_TIME_NAME )
+ else if(key == Toolkit::Tooltip::Property::WAIT_TIME || key == PROPERTY_WAIT_TIME_NAME)
{
float waitTime = 0.0f;
- if( value.Get( waitTime ) )
+ if(value.Get(waitTime))
{
mWaitTime = waitTime * MILLISECONDS_PER_SECOND;
}
}
- else if( key == Toolkit::Tooltip::Property::BACKGROUND || key == PROPERTY_BACKGROUND_NAME )
+ else if(key == Toolkit::Tooltip::Property::BACKGROUND || key == PROPERTY_BACKGROUND_NAME)
{
- SetBackground( value );
+ SetBackground(value);
}
- else if( key == Toolkit::Tooltip::Property::TAIL || key == PROPERTY_TAIL_NAME )
+ else if(key == Toolkit::Tooltip::Property::TAIL || key == PROPERTY_TAIL_NAME)
{
- SetTail( value );
+ SetTail(value);
}
- else if( key == Toolkit::Tooltip::Property::POSITION || key == PROPERTY_POSITION_NAME )
+ else if(key == Toolkit::Tooltip::Property::POSITION || key == PROPERTY_POSITION_NAME)
{
- Scripting::GetEnumerationProperty< Toolkit::Tooltip::Position::Type >( value, TOOLTIP_POSITION_TABLE, TOOLTIP_POSITION_TABLE_COUNT, mPositionType );
+ Scripting::GetEnumerationProperty<Toolkit::Tooltip::Position::Type>(value, TOOLTIP_POSITION_TABLE, TOOLTIP_POSITION_TABLE_COUNT, mPositionType);
}
- else if( key == Toolkit::Tooltip::Property::HOVER_POINT_OFFSET || key == PROPERTY_HOVER_POINT_OFFSET_NAME )
+ else if(key == Toolkit::Tooltip::Property::HOVER_POINT_OFFSET || key == PROPERTY_HOVER_POINT_OFFSET_NAME)
{
- value.Get( mHoverPointOffset );
+ value.Get(mHoverPointOffset);
}
- else if( key == Toolkit::Tooltip::Property::MOVEMENT_THRESHOLD || key == PROPERTY_MOVEMENT_THRESHOLD )
+ else if(key == Toolkit::Tooltip::Property::MOVEMENT_THRESHOLD || key == PROPERTY_MOVEMENT_THRESHOLD)
{
- value.Get( mMovementThreshold );
+ value.Get(mMovementThreshold);
}
- else if( key == Toolkit::Tooltip::Property::DISAPPEAR_ON_MOVEMENT || key == PROPERTY_DISAPPEAR_ON_MOVEMENT )
+ else if(key == Toolkit::Tooltip::Property::DISAPPEAR_ON_MOVEMENT || key == PROPERTY_DISAPPEAR_ON_MOVEMENT)
{
- value.Get( mDisappearOnMovement );
+ value.Get(mDisappearOnMovement);
}
}
}
else
{
Property::Type type = value.GetType();
- if( ( value.GetType() == Property::STRING ) || ( type == Property::ARRAY ) )
+ if((value.GetType() == Property::STRING) || (type == Property::ARRAY))
{
- SetContent( control, value );
+ SetContent(control, value);
}
}
}
}
-void Tooltip::CreatePropertyMap( Property::Map& map ) const
+void Tooltip::CreatePropertyMap(Property::Map& map) const
{
- if( ! mContentTextVisual.Empty() )
+ if(!mContentTextVisual.Empty())
{
Property::Map content = mContentTextVisual; // Need this copy as there's no Value constructor which takes in a 'const Property::Map&'.
- map.Insert( Toolkit::Tooltip::Property::CONTENT, content );
+ map.Insert(Toolkit::Tooltip::Property::CONTENT, content);
}
- else if( ! mContentArray.Empty() )
+ else if(!mContentArray.Empty())
{
Property::Array content = mContentArray; // Need this copy as there's no Value constructor which takes in a 'const Property::Array&'.
- map.Insert( Toolkit::Tooltip::Property::CONTENT, content );
+ map.Insert(Toolkit::Tooltip::Property::CONTENT, content);
}
- map.Insert( Toolkit::Tooltip::Property::LAYOUT, mLayout );
- map.Insert( Toolkit::Tooltip::Property::WAIT_TIME, static_cast<float>( mWaitTime ) / MILLISECONDS_PER_SECOND );
- map.Insert( Toolkit::Tooltip::Property::BACKGROUND,
- Property::Map().Add( Toolkit::Tooltip::Background::Property::VISUAL, mBackgroundImage )
- .Add( Toolkit::Tooltip::Background::Property::BORDER, mBackgroundBorder ) );
- map.Insert( Toolkit::Tooltip::Property::TAIL,
- Property::Map().Add( Toolkit::Tooltip::Tail::Property::VISIBILITY, mTailVisibility )
- .Add( Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL, mTailImages[ Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL ])
- .Add( Toolkit::Tooltip::Tail::Property::BELOW_VISUAL, mTailImages[ Toolkit::Tooltip::Tail::Property::BELOW_VISUAL ]) );
- map.Insert( Toolkit::Tooltip::Property::POSITION, mPositionType );
- map.Insert( Toolkit::Tooltip::Property::HOVER_POINT_OFFSET, mHoverPointOffset );
- map.Insert( Toolkit::Tooltip::Property::MOVEMENT_THRESHOLD, mMovementThreshold );
- map.Insert( Toolkit::Tooltip::Property::DISAPPEAR_ON_MOVEMENT, mDisappearOnMovement );
+ map.Insert(Toolkit::Tooltip::Property::LAYOUT, mLayout);
+ map.Insert(Toolkit::Tooltip::Property::WAIT_TIME, static_cast<float>(mWaitTime) / MILLISECONDS_PER_SECOND);
+ map.Insert(Toolkit::Tooltip::Property::BACKGROUND,
+ Property::Map().Add(Toolkit::Tooltip::Background::Property::VISUAL, mBackgroundImage).Add(Toolkit::Tooltip::Background::Property::BORDER, mBackgroundBorder));
+ map.Insert(Toolkit::Tooltip::Property::TAIL,
+ Property::Map().Add(Toolkit::Tooltip::Tail::Property::VISIBILITY, mTailVisibility).Add(Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL, mTailImages[Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL]).Add(Toolkit::Tooltip::Tail::Property::BELOW_VISUAL, mTailImages[Toolkit::Tooltip::Tail::Property::BELOW_VISUAL]));
+ map.Insert(Toolkit::Tooltip::Property::POSITION, mPositionType);
+ map.Insert(Toolkit::Tooltip::Property::HOVER_POINT_OFFSET, mHoverPointOffset);
+ map.Insert(Toolkit::Tooltip::Property::MOVEMENT_THRESHOLD, mMovementThreshold);
+ map.Insert(Toolkit::Tooltip::Property::DISAPPEAR_ON_MOVEMENT, mDisappearOnMovement);
}
-Tooltip::Tooltip( Toolkit::Control control )
+Tooltip::Tooltip(Toolkit::Control control)
: mPopup(),
mTooltipTimer(),
- mControl( control ),
+ mControl(control),
mContentTextVisual(),
mTailImages(),
mContentArray(),
- mBackgroundBorder( 0, 0, 0, 0 ),
- mLayout( 1, 1 ),
+ mBackgroundBorder(0, 0, 0, 0),
+ mLayout(1, 1),
mHoverPoint(),
- mHoverPointOffset( 10.0f, 10.0f ),
+ mHoverPointOffset(10.0f, 10.0f),
mBackgroundImage(),
- mMovementThreshold( 5.0f ),
- mWaitTime( 500 ),
- mPositionType( Toolkit::Tooltip::Position::ABOVE ),
- mTailVisibility( false ),
- mDisappearOnMovement( false ),
- mSignalsConnected( false )
+ mMovementThreshold(5.0f),
+ mWaitTime(500),
+ mPositionType(Toolkit::Tooltip::Position::ABOVE),
+ mTailVisibility(false),
+ mDisappearOnMovement(false),
+ mSignalsConnected(false)
{
- mTailImages[ Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL ] = "";
- mTailImages[ Toolkit::Tooltip::Tail::Property::BELOW_VISUAL ] = "";
+ mTailImages[Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL] = "";
+ mTailImages[Toolkit::Tooltip::Tail::Property::BELOW_VISUAL] = "";
}
Tooltip::~Tooltip()
{
- if( mPopup )
+ if(mPopup)
{
mPopup.Unparent();
mPopup.Reset();
}
}
-void Tooltip::SetContent( Toolkit::Control& control, const Property::Value& value )
+void Tooltip::SetContent(Toolkit::Control& control, const Property::Value& value)
{
// Delete popup & timer
- if( mTooltipTimer )
+ if(mTooltipTimer)
{
mTooltipTimer.Stop();
mTooltipTimer.Reset();
}
- if( mPopup )
+ if(mPopup)
{
mPopup.Unparent();
mPopup.Reset();
bool connectSignals = false;
Property::Type type = value.GetType();
- if( type == Property::MAP )
+ if(type == Property::MAP)
{
const Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
- mContentTextVisual.Merge( *map );
+ mContentTextVisual.Merge(*map);
- Property::Value* typeValue = map->Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE );
- if( typeValue )
+ Property::Value* typeValue = map->Find(Toolkit::Visual::Property::TYPE, VISUAL_TYPE);
+ if(typeValue)
{
// Set to an invalid value so it definitely changes if set in Scripting::GetEnumerationProperty
- Toolkit::Visual::Type visualType = static_cast< Toolkit::Visual::Type >( -1 );
+ Toolkit::Visual::Type visualType = static_cast<Toolkit::Visual::Type>(-1);
- if( Scripting::GetEnumerationProperty( *typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, visualType ) )
+ if(Scripting::GetEnumerationProperty(*typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, visualType))
{
- if( visualType == Toolkit::Visual::TEXT )
+ if(visualType == Toolkit::Visual::TEXT)
{
// Visual Type is text, ensure we have a the TEXT property set before we connect to the signals.
- if( map->Find( Toolkit::TextVisual::Property::TEXT, TEXT_PROPERTY ) )
+ if(map->Find(Toolkit::TextVisual::Property::TEXT, TEXT_PROPERTY))
{
mContentArray.Clear();
connectSignals = true;
}
}
}
- else if( type == Property::ARRAY )
+ else if(type == Property::ARRAY)
{
- if( value.Get( mContentArray ) )
+ if(value.Get(mContentArray))
{
mContentTextVisual.Clear();
connectSignals = true;
}
}
- else if( type == Property::STRING )
+ else if(type == Property::STRING)
{
std::string text;
- if( value.Get( text ) )
+ if(value.Get(text))
{
- mContentTextVisual[ Toolkit::TextVisual::Property::TEXT ] = text;
- mContentTextVisual[ Toolkit::Visual::Property::TYPE ] = Toolkit::Visual::TEXT;
+ mContentTextVisual[Toolkit::TextVisual::Property::TEXT] = text;
+ mContentTextVisual[Toolkit::Visual::Property::TYPE] = Toolkit::Visual::TEXT;
mContentArray.Clear();
connectSignals = true;
}
}
- if( connectSignals && ! mSignalsConnected )
+ if(connectSignals && !mSignalsConnected)
{
- control.HoveredSignal().Connect( this, &Tooltip::OnHovered );
- control.SetProperty( Actor::Property::LEAVE_REQUIRED, true );
+ control.HoveredSignal().Connect(this, &Tooltip::OnHovered);
+ control.SetProperty(Actor::Property::LEAVE_REQUIRED, true);
mSignalsConnected = true;
}
}
-void Tooltip::SetBackground( const Property::Value& value )
+void Tooltip::SetBackground(const Property::Value& value)
{
Property::Type type = value.GetType();
- if( type == Property::STRING )
+ if(type == Property::STRING)
{
- value.Get( mBackgroundImage );
- mBackgroundBorder.Set( 0, 0, 0, 0 );
+ value.Get(mBackgroundImage);
+ mBackgroundBorder.Set(0, 0, 0, 0);
}
- else if( type == Property::MAP )
+ else if(type == Property::MAP)
{
const Property::Map* map = value.GetMap();
- if( map )
+ if(map)
{
const Property::Map::SizeType count = map->Count();
- for( Property::Map::SizeType position = 0; position < count; ++position )
+ for(Property::Map::SizeType position = 0; position < count; ++position)
{
- KeyValuePair keyValue = map->GetKeyValue( position );
- Property::Key& key = keyValue.first;
- Property::Value& value = keyValue.second;
+ KeyValuePair keyValue = map->GetKeyValue(position);
+ Property::Key& key = keyValue.first;
+ Property::Value& value = keyValue.second;
- if( key == Toolkit::Tooltip::Background::Property::VISUAL || key == PROPERTY_BACKGROUND_VISUAL )
+ if(key == Toolkit::Tooltip::Background::Property::VISUAL || key == PROPERTY_BACKGROUND_VISUAL)
{
- value.Get( mBackgroundImage );
+ value.Get(mBackgroundImage);
}
- else if( key == Toolkit::Tooltip::Background::Property::BORDER || key == PROPERTY_BACKGROUND_BORDER )
+ else if(key == Toolkit::Tooltip::Background::Property::BORDER || key == PROPERTY_BACKGROUND_BORDER)
{
- if( ! value.Get( mBackgroundBorder ) )
+ if(!value.Get(mBackgroundBorder))
{
// If not a Property::RECTANGLE, then check if it's a Vector4 and set it accordingly
Vector4 valueVector4;
- if( value.Get( valueVector4 ) )
+ if(value.Get(valueVector4))
{
mBackgroundBorder.left = valueVector4.x;
mBackgroundBorder.right = valueVector4.y;
}
}
-void Tooltip::SetTail( const Property::Value& value )
+void Tooltip::SetTail(const Property::Value& value)
{
Property::Type type = value.GetType();
- if( type == Property::BOOLEAN )
+ if(type == Property::BOOLEAN)
{
- value.Get( mTailVisibility );
+ value.Get(mTailVisibility);
}
- else if( type == Property::MAP )
+ else if(type == Property::MAP)
{
Property::Map map;
- if( value.Get( map ) )
+ if(value.Get(map))
{
const Property::Map::SizeType count = map.Count();
- for( Property::Map::SizeType position = 0; position < count; ++position )
+ for(Property::Map::SizeType position = 0; position < count; ++position)
{
- KeyValuePair keyValue = map.GetKeyValue( position );
- Property::Key& key = keyValue.first;
- Property::Value& value = keyValue.second;
+ KeyValuePair keyValue = map.GetKeyValue(position);
+ Property::Key& key = keyValue.first;
+ Property::Value& value = keyValue.second;
// Set the values manually rather than merging so that we only have to deal with Property indices when creating the actual tooltip.
- if( key == Toolkit::Tooltip::Tail::Property::VISIBILITY || key == PROPERTY_TAIL_VISIBILITY )
+ if(key == Toolkit::Tooltip::Tail::Property::VISIBILITY || key == PROPERTY_TAIL_VISIBILITY)
{
- value.Get( mTailVisibility );
+ value.Get(mTailVisibility);
}
- else if( key == Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL || key == PROPERTY_TAIL_ABOVE_VISUAL )
+ else if(key == Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL || key == PROPERTY_TAIL_ABOVE_VISUAL)
{
std::string path;
- if( value.Get( path ) )
+ if(value.Get(path))
{
- mTailImages[ Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL ] = path;
+ mTailImages[Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL] = path;
}
}
- else if( key == Toolkit::Tooltip::Tail::Property::BELOW_VISUAL || key == PROPERTY_TAIL_BELOW_VISUAL )
+ else if(key == Toolkit::Tooltip::Tail::Property::BELOW_VISUAL || key == PROPERTY_TAIL_BELOW_VISUAL)
{
std::string path;
- if( value.Get( path ) )
+ if(value.Get(path))
{
- mTailImages[ Toolkit::Tooltip::Tail::Property::BELOW_VISUAL ] = path;
+ mTailImages[Toolkit::Tooltip::Tail::Property::BELOW_VISUAL] = path;
}
}
}
}
}
-bool Tooltip::OnHovered( Actor /* actor */, const HoverEvent& hover )
+bool Tooltip::OnHovered(Actor /* actor */, const HoverEvent& hover)
{
- const PointState::Type state = hover.GetState( 0 );
- switch( state )
+ const PointState::Type state = hover.GetState(0);
+ switch(state)
{
case PointState::STARTED:
case PointState::MOTION:
{
- if( ! mPopup )
+ if(!mPopup)
{
- if( ! mTooltipTimer )
+ if(!mTooltipTimer)
{
- mHoverPoint = hover.GetScreenPosition( 0 );
- mTooltipTimer = Timer::New( mWaitTime );
- mTooltipTimer.TickSignal().Connect( this, &Tooltip::OnTimeout );
+ mHoverPoint = hover.GetScreenPosition(0);
+ mTooltipTimer = Timer::New(mWaitTime);
+ mTooltipTimer.TickSignal().Connect(this, &Tooltip::OnTimeout);
mTooltipTimer.Start();
}
else
{
- Vector2 movement = mHoverPoint - hover.GetScreenPosition( 0 );
- if( std::abs( movement.Length() ) > mMovementThreshold )
+ Vector2 movement = mHoverPoint - hover.GetScreenPosition(0);
+ if(std::abs(movement.Length()) > mMovementThreshold)
{
mTooltipTimer.Stop();
mTooltipTimer.Reset();
- mHoverPoint = hover.GetScreenPosition( 0 );
- mTooltipTimer = Timer::New( mWaitTime );
- mTooltipTimer.TickSignal().Connect( this, &Tooltip::OnTimeout );
+ mHoverPoint = hover.GetScreenPosition(0);
+ mTooltipTimer = Timer::New(mWaitTime);
+ mTooltipTimer.TickSignal().Connect(this, &Tooltip::OnTimeout);
mTooltipTimer.Start();
}
}
}
- else if( mDisappearOnMovement )
+ else if(mDisappearOnMovement)
{
// Popup is showing, and we're set to disappear on excessive movement so make sure we're still within the threshold.
- Vector2 movement = mHoverPoint - hover.GetScreenPosition( 0 );
- if( std::abs( movement.Length() ) > mMovementThreshold )
+ Vector2 movement = mHoverPoint - hover.GetScreenPosition(0);
+ if(std::abs(movement.Length()) > mMovementThreshold)
{
// Exceeding the threshold, hide the popup.
- if( mTooltipTimer )
+ if(mTooltipTimer)
{
mTooltipTimer.Stop();
mTooltipTimer.Reset();
}
- if( mPopup )
+ if(mPopup)
{
mPopup.Unparent();
mPopup.Reset();
case PointState::LEAVE:
case PointState::INTERRUPTED:
{
- if( mTooltipTimer )
+ if(mTooltipTimer)
{
mTooltipTimer.Stop();
mTooltipTimer.Reset();
}
- if( mPopup )
+ if(mPopup)
{
mPopup.Unparent();
mPopup.Reset();
bool Tooltip::OnTimeout()
{
Toolkit::Control control = mControl.GetHandle();
- if( ! mPopup && control )
+ if(!mPopup && control)
{
mPopup = Toolkit::Popup::New();
// General set up of popup
- mPopup.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS );
- mPopup.SetProperty( Toolkit::Popup::Property::CONTEXTUAL_MODE, "NON_CONTEXTUAL" );
- mPopup.SetProperty( Toolkit::Popup::Property::ANIMATION_MODE, "NONE" );
- mPopup.SetProperty( Toolkit::Popup::Property::BACKING_ENABLED, false ); // Disable the dimmed backing.
- mPopup.SetProperty( Toolkit::Popup::Property::TOUCH_TRANSPARENT, true ); // Let events pass through the popup
- mPopup.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- mPopup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
+ mPopup.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS);
+ mPopup.SetProperty(Toolkit::Popup::Property::CONTEXTUAL_MODE, "NON_CONTEXTUAL");
+ mPopup.SetProperty(Toolkit::Popup::Property::ANIMATION_MODE, "NONE");
+ mPopup.SetProperty(Toolkit::Popup::Property::BACKING_ENABLED, false); // Disable the dimmed backing.
+ mPopup.SetProperty(Toolkit::Popup::Property::TOUCH_TRANSPARENT, true); // Let events pass through the popup
+ mPopup.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ mPopup.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
// Background
- mPopup.SetProperty( Toolkit::Popup::Property::POPUP_BACKGROUND_IMAGE, mBackgroundImage );
- mPopup.SetProperty( Toolkit::Popup::Property::POPUP_BACKGROUND_BORDER, mBackgroundBorder );
+ mPopup.SetProperty(Toolkit::Popup::Property::POPUP_BACKGROUND_IMAGE, mBackgroundImage);
+ mPopup.SetProperty(Toolkit::Popup::Property::POPUP_BACKGROUND_BORDER, mBackgroundBorder);
// Tail
- mPopup.SetProperty( Toolkit::Popup::Property::TAIL_VISIBILITY, mTailVisibility );
- mPopup.SetProperty( Toolkit::Popup::Property::TAIL_UP_IMAGE, mTailImages[ Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL ] );
- mPopup.SetProperty( Toolkit::Popup::Property::TAIL_DOWN_IMAGE, mTailImages[ Toolkit::Tooltip::Tail::Property::BELOW_VISUAL ] );
+ mPopup.SetProperty(Toolkit::Popup::Property::TAIL_VISIBILITY, mTailVisibility);
+ mPopup.SetProperty(Toolkit::Popup::Property::TAIL_UP_IMAGE, mTailImages[Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL]);
+ mPopup.SetProperty(Toolkit::Popup::Property::TAIL_DOWN_IMAGE, mTailImages[Toolkit::Tooltip::Tail::Property::BELOW_VISUAL]);
Vector3 tailPosition;
- switch( mPositionType )
+ switch(mPositionType)
{
case Toolkit::Tooltip::Position::HOVER_POINT:
case Toolkit::Tooltip::Position::BELOW:
{
- tailPosition = Vector3( 0.5f, 0.0f, 0.0 );
+ tailPosition = Vector3(0.5f, 0.0f, 0.0);
break;
}
case Toolkit::Tooltip::Position::ABOVE:
{
- tailPosition = Vector3( 0.5f, 1.0f, 0.0 );
+ tailPosition = Vector3(0.5f, 1.0f, 0.0);
break;
}
}
- mPopup.SetProperty( Toolkit::Popup::Property::TAIL_POSITION, tailPosition );
+ mPopup.SetProperty(Toolkit::Popup::Property::TAIL_POSITION, tailPosition);
// Content
Actor content;
- if( ! mContentTextVisual.Empty() )
+ if(!mContentTextVisual.Empty())
{
content = Toolkit::Control::New();
- content.SetProperty( Toolkit::Control::Property::BACKGROUND, mContentTextVisual );
+ content.SetProperty(Toolkit::Control::Property::BACKGROUND, mContentTextVisual);
}
- else if( ! mContentArray.Empty() )
+ else if(!mContentArray.Empty())
{
const unsigned int visuals = mContentArray.Size();
- unsigned int rows = mLayout.x;
- unsigned int columns = mLayout.y;
- if( Equals( mLayout.x, 1.0f, Math::MACHINE_EPSILON_1 ) &&
- Equals( mLayout.y, 1.0f, Math::MACHINE_EPSILON_1 ) &&
- visuals > 1 )
+ unsigned int rows = mLayout.x;
+ unsigned int columns = mLayout.y;
+ if(Equals(mLayout.x, 1.0f, Math::MACHINE_EPSILON_1) &&
+ Equals(mLayout.y, 1.0f, Math::MACHINE_EPSILON_1) &&
+ visuals > 1)
{
- rows = mLayout.x;
+ rows = mLayout.x;
columns = visuals;
}
- Toolkit::TableView tableView = Toolkit::TableView::New( rows, columns );
- tableView.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
+ Toolkit::TableView tableView = Toolkit::TableView::New(rows, columns);
+ tableView.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS);
- for( unsigned int currentContent = 0, currentRow = 0; currentRow < rows && currentContent < visuals; ++currentRow )
+ for(unsigned int currentContent = 0, currentRow = 0; currentRow < rows && currentContent < visuals; ++currentRow)
{
- tableView.SetFitHeight( currentRow );
- for( unsigned int currentColumn = 0; currentColumn < columns && currentContent < visuals; ++currentColumn )
+ tableView.SetFitHeight(currentRow);
+ for(unsigned int currentColumn = 0; currentColumn < columns && currentContent < visuals; ++currentColumn)
{
Actor child = Toolkit::Control::New();
- child.SetProperty( Toolkit::Control::Property::BACKGROUND, mContentArray[ currentContent ] );
+ child.SetProperty(Toolkit::Control::Property::BACKGROUND, mContentArray[currentContent]);
- Toolkit::TableView::CellPosition cellPosition( currentRow, currentColumn );
- tableView.AddChild( child, cellPosition );
- tableView.SetCellAlignment( cellPosition, HorizontalAlignment::CENTER, VerticalAlignment::CENTER );
- tableView.SetFitWidth( currentColumn );
+ Toolkit::TableView::CellPosition cellPosition(currentRow, currentColumn);
+ tableView.AddChild(child, cellPosition);
+ tableView.SetCellAlignment(cellPosition, HorizontalAlignment::CENTER, VerticalAlignment::CENTER);
+ tableView.SetFitWidth(currentColumn);
++currentContent;
}
}
content = tableView;
}
- mPopup.SetContent( content );
+ mPopup.SetContent(content);
// Connect to the relayout signal of the background of the popup as at that point we have the full size
- Actor popupBackground = GetImpl( mPopup ).GetPopupBackgroundImage();
- if( popupBackground )
+ Actor popupBackground = GetImpl(mPopup).GetPopupBackgroundImage();
+ if(popupBackground)
{
- popupBackground.OnRelayoutSignal().Connect( this, &Tooltip::OnRelayout );
+ popupBackground.OnRelayoutSignal().Connect(this, &Tooltip::OnRelayout);
}
- mPopup.SetDisplayState( Toolkit::Popup::SHOWN );
+ mPopup.SetDisplayState(Toolkit::Popup::SHOWN);
- Stage::GetCurrent().Add( mPopup );
+ Stage::GetCurrent().Add(mPopup);
}
return false;
}
-void Tooltip::OnRelayout( Actor actor )
+void Tooltip::OnRelayout(Actor actor)
{
- if( mPopup && actor )
+ if(mPopup && actor)
{
- float popupWidth = actor.GetRelayoutSize( Dimension::WIDTH );
- float popupHeight = actor.GetRelayoutSize( Dimension::HEIGHT );
- float tailHeight = 0.0f;
+ float popupWidth = actor.GetRelayoutSize(Dimension::WIDTH);
+ float popupHeight = actor.GetRelayoutSize(Dimension::HEIGHT);
+ float tailHeight = 0.0f;
Actor tail;
- if( mTailVisibility )
+ if(mTailVisibility)
{
// Popup's background has the tail, we want to know the tail size as well.
- if( actor.GetChildCount() )
+ if(actor.GetChildCount())
{
- tail = actor.GetChildAt( 0 );
- if( tail )
+ tail = actor.GetChildAt(0);
+ if(tail)
{
- tailHeight = tail.GetRelayoutSize( Dimension::HEIGHT );
+ tailHeight = tail.GetRelayoutSize(Dimension::HEIGHT);
}
}
}
Vector2 stageSize = Stage::GetCurrent().GetSize();
Vector3 position;
- switch( mPositionType )
+ switch(mPositionType)
{
case Toolkit::Tooltip::Position::HOVER_POINT:
{
case Toolkit::Tooltip::Position::ABOVE:
{
Toolkit::Control control = mControl.GetHandle();
- if( control )
+ if(control)
{
- Vector3 worldPos = control.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION );
- float height = control.GetRelayoutSize( Dimension::HEIGHT );
+ Vector3 worldPos = control.GetCurrentProperty<Vector3>(Actor::Property::WORLD_POSITION);
+ float height = control.GetRelayoutSize(Dimension::HEIGHT);
position.x = stageSize.width * 0.5f + worldPos.x - popupWidth * 0.5f;
position.y = stageSize.height * 0.5f + worldPos.y - height * 0.5f - popupHeight * 1.0f - tailHeight;
case Toolkit::Tooltip::Position::BELOW:
{
Toolkit::Control control = mControl.GetHandle();
- if( control )
+ if(control)
{
- Vector3 worldPos = control.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION );
- float height = control.GetRelayoutSize( Dimension::HEIGHT );
+ Vector3 worldPos = control.GetCurrentProperty<Vector3>(Actor::Property::WORLD_POSITION);
+ float height = control.GetRelayoutSize(Dimension::HEIGHT);
position.x = stageSize.width * 0.5f + worldPos.x - popupWidth * 0.5f;
position.y = stageSize.height * 0.5f + worldPos.y + height * 0.5f + tailHeight;
// Ensure the Popup is still on the screen
- if( position.x < 0.0f )
+ if(position.x < 0.0f)
{
position.x = 0.0f;
}
- else if( ( position.x + popupWidth ) > stageSize.width )
+ else if((position.x + popupWidth) > stageSize.width)
{
position.x -= position.x + popupWidth - stageSize.width;
}
bool yPosChanged = false;
- if( position.y < 0.0f )
+ if(position.y < 0.0f)
{
yPosChanged = true;
- position.y = 0.0f;
+ position.y = 0.0f;
}
- else if( ( position.y + popupHeight ) > stageSize.height )
+ else if((position.y + popupHeight) > stageSize.height)
{
yPosChanged = true;
position.y -= position.y + popupHeight - stageSize.height;
}
- if( yPosChanged && tail )
+ if(yPosChanged && tail)
{
// If we change the y position, then the tail may be shown pointing to the wrong control so just hide it.
- tail.SetProperty( Actor::Property::VISIBLE, false );
+ tail.SetProperty(Actor::Property::VISIBLE, false);
}
- mPopup.SetProperty( Actor::Property::POSITION, position );
+ mPopup.SetProperty(Actor::Property::POSITION, position);
}
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "video-view-impl.h"
// EXTERNAL INCLUDES
-#include <cstring>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/devel-api/scripting/scripting.h>
+#include <dali/devel-api/actors/actor-devel.h>
#include <dali/devel-api/adaptor-framework/window-devel.h>
-#include <dali/public-api/adaptor-framework/native-image-source.h>
+#include <dali/devel-api/scripting/scripting.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/adaptor-framework/native-image-source.h>
#include <dali/public-api/animation/constraint.h>
-#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/video-view/video-view.h>
-#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
-#include <dali/integration-api/adaptor-framework/adaptor.h>
#include <dali-toolkit/internal/controls/control/control-data-impl.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/public-api/controls/video-view/video-view.h>
+#include <dali/integration-api/adaptor-framework/adaptor.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
return Toolkit::VideoView::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::VideoView, Toolkit::Control, Create );
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::VideoView, Toolkit::Control, Create);
-DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "video", MAP, VIDEO )
-DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "looping", BOOLEAN, LOOPING )
-DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "muted", BOOLEAN, MUTED )
-DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "volume", MAP, VOLUME )
-DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "underlay", BOOLEAN, UNDERLAY )
-DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "playPosition", INTEGER, PLAY_POSITION )
-DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "displayMode", INTEGER, DISPLAY_MODE )
+DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "video", MAP, VIDEO)
+DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "looping", BOOLEAN, LOOPING)
+DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "muted", BOOLEAN, MUTED)
+DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "volume", MAP, VOLUME)
+DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "underlay", BOOLEAN, UNDERLAY)
+DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "playPosition", INTEGER, PLAY_POSITION)
+DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "displayMode", INTEGER, DISPLAY_MODE)
-DALI_SIGNAL_REGISTRATION( Toolkit, VideoView, "finished", FINISHED_SIGNAL )
+DALI_SIGNAL_REGISTRATION(Toolkit, VideoView, "finished", FINISHED_SIGNAL)
-DALI_ACTION_REGISTRATION( Toolkit, VideoView, "play", ACTION_VIDEOVIEW_PLAY )
-DALI_ACTION_REGISTRATION( Toolkit, VideoView, "pause", ACTION_VIDEOVIEW_PAUSE )
-DALI_ACTION_REGISTRATION( Toolkit, VideoView, "stop", ACTION_VIDEOVIEW_STOP )
-DALI_ACTION_REGISTRATION( Toolkit, VideoView, "forward", ACTION_VIDEOVIEW_FORWARD )
-DALI_ACTION_REGISTRATION( Toolkit, VideoView, "backward", ACTION_VIDEOVIEW_BACKWARD )
+DALI_ACTION_REGISTRATION(Toolkit, VideoView, "play", ACTION_VIDEOVIEW_PLAY)
+DALI_ACTION_REGISTRATION(Toolkit, VideoView, "pause", ACTION_VIDEOVIEW_PAUSE)
+DALI_ACTION_REGISTRATION(Toolkit, VideoView, "stop", ACTION_VIDEOVIEW_STOP)
+DALI_ACTION_REGISTRATION(Toolkit, VideoView, "forward", ACTION_VIDEOVIEW_FORWARD)
+DALI_ACTION_REGISTRATION(Toolkit, VideoView, "backward", ACTION_VIDEOVIEW_BACKWARD)
DALI_TYPE_REGISTRATION_END()
-const char* const VOLUME_LEFT( "volumeLeft" );
-const char* const VOLUME_RIGHT( "volumeRight" );
+const char* const VOLUME_LEFT("volumeLeft");
+const char* const VOLUME_RIGHT("volumeRight");
// 3.0 TC uses RENDERING_TARGET. It should be removed in next release
-const char* const RENDERING_TARGET( "renderingTarget" );
-const char* const WINDOW_SURFACE_TARGET( "windowSurfaceTarget" );
-const char* const NATIVE_IMAGE_TARGET( "nativeImageTarget" );
+const char* const RENDERING_TARGET("renderingTarget");
+const char* const WINDOW_SURFACE_TARGET("windowSurfaceTarget");
+const char* const NATIVE_IMAGE_TARGET("nativeImageTarget");
-const char* const CUSTOM_SHADER( "shader" );
-const char* const CUSTOM_VERTEX_SHADER( "vertexShader" );
-const char* const CUSTOM_FRAGMENT_SHADER( "fragmentShader" );
-const char* const DEFAULT_SAMPLER_TYPE_NAME( "sampler2D" );
-const char* const CUSTOM_SAMPLER_TYPE_NAME( "samplerExternalOES" );
+const char* const CUSTOM_SHADER("shader");
+const char* const CUSTOM_VERTEX_SHADER("vertexShader");
+const char* const CUSTOM_FRAGMENT_SHADER("fragmentShader");
+const char* const DEFAULT_SAMPLER_TYPE_NAME("sampler2D");
+const char* const CUSTOM_SAMPLER_TYPE_NAME("samplerExternalOES");
-} // anonymous namepsace
+} // namespace
-VideoView::VideoView( Dali::VideoSyncMode syncMode )
-: Control( ControlBehaviour( ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS ) ),
- mCurrentVideoPlayPosition( 0 ),
- mFrameID( 0 ),
- mIsPlay( false ),
- mIsUnderlay( true ),
- mSyncMode( syncMode )
+VideoView::VideoView(Dali::VideoSyncMode syncMode)
+: Control(ControlBehaviour(ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS)),
+ mCurrentVideoPlayPosition(0),
+ mFrameID(0),
+ mIsPlay(false),
+ mIsUnderlay(true),
+ mSyncMode(syncMode)
{
}
{
}
-Toolkit::VideoView VideoView::New( VideoSyncMode syncMode )
+Toolkit::VideoView VideoView::New(VideoSyncMode syncMode)
{
- VideoView* impl = new VideoView( syncMode );
- Toolkit::VideoView handle = Toolkit::VideoView( *impl );
+ VideoView* impl = new VideoView(syncMode);
+ Toolkit::VideoView handle = Toolkit::VideoView(*impl);
- impl->mVideoPlayer = Dali::VideoPlayer::New( impl->Self(), syncMode );
+ impl->mVideoPlayer = Dali::VideoPlayer::New(impl->Self(), syncMode);
impl->Initialize();
return handle;
}
void VideoView::OnInitialize()
{
- mVideoPlayer.FinishedSignal().Connect( this, &VideoView::EmitSignalFinish );
+ mVideoPlayer.FinishedSignal().Connect(this, &VideoView::EmitSignalFinish);
- DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) {
- return std::unique_ptr< Dali::Accessibility::Accessible >(
- new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::VIDEO ));
- } );
+ DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
+ return std::unique_ptr<Dali::Accessibility::Accessible>(
+ new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::VIDEO));
+ });
}
-void VideoView::SetUrl( const std::string& url )
+void VideoView::SetUrl(const std::string& url)
{
- mUrl = url;
- mPropertyMap.Clear();
+ mUrl = url;
+ mPropertyMap.Clear();
- mVideoPlayer.SetUrl( mUrl );
+ mVideoPlayer.SetUrl(mUrl);
}
-void VideoView::SetPropertyMap( Property::Map map )
+void VideoView::SetPropertyMap(Property::Map map)
{
mPropertyMap = map;
- Property::Value* target = map.Find( RENDERING_TARGET );
- std::string targetType;
+ Property::Value* target = map.Find(RENDERING_TARGET);
+ std::string targetType;
- if( target && target->Get( targetType ) && targetType == WINDOW_SURFACE_TARGET )
+ if(target && target->Get(targetType) && targetType == WINDOW_SURFACE_TARGET)
{
mIsUnderlay = true;
SetWindowSurfaceTarget();
}
- else if( target && target->Get( targetType ) && targetType == NATIVE_IMAGE_TARGET )
+ else if(target && target->Get(targetType) && targetType == NATIVE_IMAGE_TARGET)
{
mIsUnderlay = false;
SetNativeImageTarget();
// Custom shader
Property::Value* shaderValue;
- if( !map.Empty() )
+ if(!map.Empty())
{
- shaderValue = map.Find( CUSTOM_SHADER );
+ shaderValue = map.Find(CUSTOM_SHADER);
- if( shaderValue )
+ if(shaderValue)
{
Property::Map* shaderMap = shaderValue->GetMap();
- if( shaderMap )
+ if(shaderMap)
{
mEffectPropertyMap = *shaderMap;
}
}
}
- if( mTextureRenderer && !mEffectPropertyMap.Empty() )
+ if(mTextureRenderer && !mEffectPropertyMap.Empty())
{
Dali::Shader shader = CreateShader();
- mTextureRenderer.SetShader( shader );
+ mTextureRenderer.SetShader(shader);
}
RelayoutRequest();
return mUrl;
}
-void VideoView::SetLooping( bool looping )
+void VideoView::SetLooping(bool looping)
{
- mVideoPlayer.SetLooping( looping );
+ mVideoPlayer.SetLooping(looping);
}
bool VideoView::IsLooping()
mIsPlay = false;
}
-void VideoView::Forward( int millisecond )
+void VideoView::Forward(int millisecond)
{
int curPos = mVideoPlayer.GetPlayPosition();
int nextPos = curPos + millisecond;
- mVideoPlayer.SetPlayPosition( nextPos );
+ mVideoPlayer.SetPlayPosition(nextPos);
}
-void VideoView::Backward( int millisecond )
+void VideoView::Backward(int millisecond)
{
int curPos = mVideoPlayer.GetPlayPosition();
int nextPos = curPos - millisecond;
- nextPos = ( nextPos < 0 )? 0: nextPos;
+ nextPos = (nextPos < 0) ? 0 : nextPos;
- mVideoPlayer.SetPlayPosition( nextPos );
+ mVideoPlayer.SetPlayPosition(nextPos);
}
-void VideoView::SetMute( bool mute )
+void VideoView::SetMute(bool mute)
{
- mVideoPlayer.SetMute( mute );
+ mVideoPlayer.SetMute(mute);
}
bool VideoView::IsMuted()
return mVideoPlayer.IsMuted();
}
-void VideoView::SetVolume( float left, float right )
+void VideoView::SetVolume(float left, float right)
{
- mVideoPlayer.SetVolume( left, right );
+ mVideoPlayer.SetVolume(left, right);
}
-void VideoView::GetVolume( float& left, float& right )
+void VideoView::GetVolume(float& left, float& right)
{
- mVideoPlayer.GetVolume( left, right );
+ mVideoPlayer.GetVolume(left, right);
}
Dali::Toolkit::VideoView::VideoViewSignalType& VideoView::FinishedSignal()
void VideoView::EmitSignalFinish()
{
- if ( !mFinishedSignal.Empty() )
+ if(!mFinishedSignal.Empty())
{
- Dali::Toolkit::VideoView handle( GetOwner() );
- mFinishedSignal.Emit( handle );
+ Dali::Toolkit::VideoView handle(GetOwner());
+ mFinishedSignal.Emit(handle);
}
}
-bool VideoView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
+bool VideoView::DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes)
{
bool ret = false;
- Dali::BaseHandle handle( object );
- Toolkit::VideoView videoView = Toolkit::VideoView::DownCast( handle );
+ Dali::BaseHandle handle(object);
+ Toolkit::VideoView videoView = Toolkit::VideoView::DownCast(handle);
- if( !videoView )
+ if(!videoView)
{
return ret;
}
- VideoView& impl = GetImpl( videoView );
+ VideoView& impl = GetImpl(videoView);
- if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_PLAY ) == 0 )
+ if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_PLAY) == 0)
{
impl.Play();
ret = true;
}
- else if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_PAUSE ) == 0 )
+ else if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_PAUSE) == 0)
{
impl.Pause();
ret = true;
}
- else if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_STOP ) == 0 )
+ else if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_STOP) == 0)
{
impl.Stop();
ret = true;
}
- else if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_FORWARD ) == 0 )
+ else if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_FORWARD) == 0)
{
int millisecond = 0;
- if( attributes["videoForward"].Get( millisecond ) )
+ if(attributes["videoForward"].Get(millisecond))
{
- impl.Forward( millisecond );
+ impl.Forward(millisecond);
ret = true;
}
}
- else if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_BACKWARD ) == 0 )
+ else if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_BACKWARD) == 0)
{
int millisecond = 0;
- if( attributes["videoBackward"].Get( millisecond ) )
+ if(attributes["videoBackward"].Get(millisecond))
{
- impl.Backward( millisecond );
+ impl.Backward(millisecond);
ret = true;
}
}
return ret;
}
-bool VideoView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool VideoView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::VideoView videoView = Toolkit::VideoView::DownCast( handle );
+ bool connected(true);
+ Toolkit::VideoView videoView = Toolkit::VideoView::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), FINISHED_SIGNAL ) )
+ if(0 == strcmp(signalName.c_str(), FINISHED_SIGNAL))
{
- videoView.FinishedSignal().Connect( tracker, functor );
+ videoView.FinishedSignal().Connect(tracker, functor);
}
else
{
return connected;
}
-void VideoView::SetPropertyInternal( Property::Index index, const Property::Value& value )
+void VideoView::SetPropertyInternal(Property::Index index, const Property::Value& value)
{
- switch( index )
+ switch(index)
{
case Toolkit::VideoView::Property::VIDEO:
{
- std::string videoUrl;
+ std::string videoUrl;
Property::Map map;
- if( value.Get( videoUrl ) )
+ if(value.Get(videoUrl))
{
- SetUrl( videoUrl );
+ SetUrl(videoUrl);
}
- else if( value.Get( map ) )
+ else if(value.Get(map))
{
- SetPropertyMap( map );
+ SetPropertyMap(map);
}
break;
}
case Toolkit::VideoView::Property::LOOPING:
{
bool looping;
- if( value.Get( looping ) )
+ if(value.Get(looping))
{
- SetLooping( looping );
+ SetLooping(looping);
}
break;
}
case Toolkit::VideoView::Property::MUTED:
{
bool mute;
- if( value.Get( mute ) )
+ if(value.Get(mute))
{
- SetMute( mute );
+ SetMute(mute);
}
break;
}
case Toolkit::VideoView::Property::VOLUME:
{
Property::Map map;
- float left, right;
- if( value.Get( map ) )
+ float left, right;
+ if(value.Get(map))
{
- Property::Value* volumeLeft = map.Find( VOLUME_LEFT );
- Property::Value* volumeRight = map.Find( VOLUME_RIGHT );
- if( volumeLeft && volumeLeft->Get( left ) && volumeRight && volumeRight->Get( right ) )
+ Property::Value* volumeLeft = map.Find(VOLUME_LEFT);
+ Property::Value* volumeRight = map.Find(VOLUME_RIGHT);
+ if(volumeLeft && volumeLeft->Get(left) && volumeRight && volumeRight->Get(right))
{
- SetVolume( left, right );
+ SetVolume(left, right);
}
}
break;
case Toolkit::VideoView::Property::UNDERLAY:
{
bool underlay;
- if( value.Get( underlay ) )
+ if(value.Get(underlay))
{
- SetUnderlay( underlay );
+ SetUnderlay(underlay);
}
break;
}
case Toolkit::VideoView::Property::PLAY_POSITION:
{
int pos;
- if( value.Get( pos ) )
+ if(value.Get(pos))
{
- SetPlayPosition( pos );
+ SetPlayPosition(pos);
}
break;
}
case Toolkit::VideoView::Property::DISPLAY_MODE:
{
int mode;
- if( value.Get( mode ) )
+ if(value.Get(mode))
{
- SetDisplayMode( mode );
+ SetDisplayMode(mode);
}
break;
}
}
}
-void VideoView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void VideoView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::VideoView videoView = Toolkit::VideoView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::VideoView videoView = Toolkit::VideoView::DownCast(Dali::BaseHandle(object));
- if( videoView )
+ if(videoView)
{
- VideoView& impl = GetImpl( videoView );
+ VideoView& impl = GetImpl(videoView);
- impl.SetPropertyInternal( index, value );
+ impl.SetPropertyInternal(index, value);
- if( index != Toolkit::VideoView::Property::UNDERLAY )
+ if(index != Toolkit::VideoView::Property::UNDERLAY)
{
// Backup values.
// These values will be used when underlay mode is changed.
}
}
-Property::Value VideoView::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value VideoView::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
- Property::Value value;
- Toolkit::VideoView videoView = Toolkit::VideoView::DownCast( Dali::BaseHandle( object ) );
+ Property::Value value;
+ Toolkit::VideoView videoView = Toolkit::VideoView::DownCast(Dali::BaseHandle(object));
- if( videoView )
+ if(videoView)
{
- VideoView& impl = GetImpl( videoView );
+ VideoView& impl = GetImpl(videoView);
- switch( propertyIndex )
+ switch(propertyIndex)
{
case Toolkit::VideoView::Property::VIDEO:
{
- if( !impl.mUrl.empty() )
+ if(!impl.mUrl.empty())
{
value = impl.mUrl;
}
- else if( !impl.mPropertyMap.Empty() )
+ else if(!impl.mPropertyMap.Empty())
{
value = impl.mPropertyMap;
}
case Toolkit::VideoView::Property::VOLUME:
{
Property::Map map;
- float left, right;
+ float left, right;
- impl.GetVolume( left, right );
- map.Insert( VOLUME_LEFT, left );
- map.Insert( VOLUME_RIGHT, right );
+ impl.GetVolume(left, right);
+ map.Insert(VOLUME_LEFT, left);
+ map.Insert(VOLUME_RIGHT, right);
value = map;
break;
}
return value;
}
-void VideoView::SetDepthIndex( int depthIndex )
+void VideoView::SetDepthIndex(int depthIndex)
{
- if( mTextureRenderer )
+ if(mTextureRenderer)
{
- mTextureRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, depthIndex );
+ mTextureRenderer.SetProperty(Renderer::Property::DEPTH_INDEX, depthIndex);
}
}
-void VideoView::OnSceneConnection( int depth )
+void VideoView::OnSceneConnection(int depth)
{
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
- if( mIsUnderlay )
+ if(mIsUnderlay)
{
SetWindowSurfaceTarget();
}
Control::OnSceneDisconnection();
}
-void VideoView::OnSizeSet( const Vector3& targetSize )
+void VideoView::OnSizeSet(const Vector3& targetSize)
{
- if( mIsUnderlay && mSyncMode == Dali::VideoSyncMode::ENABLED )
+ if(mIsUnderlay && mSyncMode == Dali::VideoSyncMode::ENABLED)
{
SetFrameRenderCallback();
mVideoPlayer.StartSynchronization();
}
- Control::OnSizeSet( targetSize );
+ Control::OnSizeSet(targetSize);
}
Vector3 VideoView::GetNaturalSize()
size.x = mVideoSize.GetWidth();
size.y = mVideoSize.GetHeight();
- if( size.x > 0 && size.y > 0 )
+ if(size.x > 0 && size.y > 0)
{
- size.z = std::min( size.x, size.y );
+ size.z = std::min(size.x, size.y);
return size;
}
else
}
}
-float VideoView::GetHeightForWidth( float width )
+float VideoView::GetHeightForWidth(float width)
{
- if( mVideoSize.GetWidth() > 0 && mVideoSize.GetHeight() > 0 )
+ if(mVideoSize.GetWidth() > 0 && mVideoSize.GetHeight() > 0)
{
- return GetHeightForWidthBase( width );
+ return GetHeightForWidthBase(width);
}
else
{
- return Control::GetHeightForWidthBase( width );
+ return Control::GetHeightForWidthBase(width);
}
}
-float VideoView::GetWidthForHeight( float height )
+float VideoView::GetWidthForHeight(float height)
{
- if( mVideoSize.GetWidth() > 0 && mVideoSize.GetHeight() > 0 )
+ if(mVideoSize.GetWidth() > 0 && mVideoSize.GetHeight() > 0)
{
- return GetWidthForHeightBase( height );
+ return GetWidthForHeightBase(height);
}
else
{
- return Control::GetWidthForHeightBase( height );
+ return Control::GetWidthForHeightBase(height);
}
}
{
Actor self = Self();
- if( !self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if(!self.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
// When the control is off the stage, it does not have Window.
return;
int curPos = mVideoPlayer.GetPlayPosition();
- if( mIsPlay )
+ if(mIsPlay)
{
mVideoPlayer.Pause();
}
- mPositionUpdateNotification = self.AddPropertyNotification( Actor::Property::WORLD_POSITION, StepCondition( 1.0f, 1.0f ) );
- mSizeUpdateNotification = self.AddPropertyNotification( Actor::Property::SIZE, StepCondition( 1.0f, 1.0f ) );
- mScaleUpdateNotification = self.AddPropertyNotification( Actor::Property::WORLD_SCALE, StepCondition( 0.1f, 1.0f ) );
- mPositionUpdateNotification.NotifySignal().Connect( this, &VideoView::UpdateDisplayArea );
- mSizeUpdateNotification.NotifySignal().Connect( this, &VideoView::UpdateDisplayArea );
- mScaleUpdateNotification.NotifySignal().Connect( this, &VideoView::UpdateDisplayArea );
+ mPositionUpdateNotification = self.AddPropertyNotification(Actor::Property::WORLD_POSITION, StepCondition(1.0f, 1.0f));
+ mSizeUpdateNotification = self.AddPropertyNotification(Actor::Property::SIZE, StepCondition(1.0f, 1.0f));
+ mScaleUpdateNotification = self.AddPropertyNotification(Actor::Property::WORLD_SCALE, StepCondition(0.1f, 1.0f));
+ mPositionUpdateNotification.NotifySignal().Connect(this, &VideoView::UpdateDisplayArea);
+ mSizeUpdateNotification.NotifySignal().Connect(this, &VideoView::UpdateDisplayArea);
+ mScaleUpdateNotification.NotifySignal().Connect(this, &VideoView::UpdateDisplayArea);
- if( mTextureRenderer )
+ if(mTextureRenderer)
{
- self.RemoveRenderer( mTextureRenderer );
+ self.RemoveRenderer(mTextureRenderer);
}
// Note VideoPlayer::SetRenderingTarget resets all the options. (e.g. url, mute, looping)
- mVideoPlayer.SetRenderingTarget( Dali::Adaptor::Get().GetNativeWindowHandle( self ) );
+ mVideoPlayer.SetRenderingTarget(Dali::Adaptor::Get().GetNativeWindowHandle(self));
ApplyBackupProperties();
- if( !mOverlayRenderer )
+ if(!mOverlayRenderer)
{
// For underlay rendering mode, video display area have to be transparent.
Geometry geometry = VisualFactoryCache::CreateQuadGeometry();
- Shader shader = Shader::New( SHADER_VIDEO_VIEW_VERT, SHADER_VIDEO_VIEW_FRAG );
- mOverlayRenderer = Renderer::New( geometry, shader );
- mOverlayRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::OFF );
+ Shader shader = Shader::New(SHADER_VIDEO_VIEW_VERT, SHADER_VIDEO_VIEW_FRAG);
+ mOverlayRenderer = Renderer::New(geometry, shader);
+ mOverlayRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::OFF);
}
- Self().AddRenderer( mOverlayRenderer );
+ Self().AddRenderer(mOverlayRenderer);
- if( mIsPlay )
+ if(mIsPlay)
{
Play();
}
- if( curPos > 0 )
+ if(curPos > 0)
{
- mVideoPlayer.SetPlayPosition( curPos );
+ mVideoPlayer.SetPlayPosition(curPos);
}
}
void VideoView::SetNativeImageTarget()
{
- if( mVideoPlayer.IsVideoTextureSupported() == false )
+ if(mVideoPlayer.IsVideoTextureSupported() == false)
{
- DALI_LOG_ERROR( "Platform doesn't support decoded video frame images\n" );
+ DALI_LOG_ERROR("Platform doesn't support decoded video frame images\n");
mIsUnderlay = true;
return;
}
- if( mIsPlay )
+ if(mIsPlay)
{
mVideoPlayer.Pause();
}
- Actor self( Self() );
+ Actor self(Self());
- if( mOverlayRenderer )
+ if(mOverlayRenderer)
{
- self.RemoveRenderer( mOverlayRenderer );
+ self.RemoveRenderer(mOverlayRenderer);
mOverlayRenderer.Reset();
}
- self.RemovePropertyNotification( mPositionUpdateNotification );
- self.RemovePropertyNotification( mSizeUpdateNotification );
- self.RemovePropertyNotification( mScaleUpdateNotification );
+ self.RemovePropertyNotification(mPositionUpdateNotification);
+ self.RemovePropertyNotification(mSizeUpdateNotification);
+ self.RemovePropertyNotification(mScaleUpdateNotification);
int curPos = mVideoPlayer.GetPlayPosition();
- Any source;
- Dali::NativeImageSourcePtr nativeImageSourcePtr = Dali::NativeImageSource::New( source );
- mNativeTexture = Dali::Texture::New( *nativeImageSourcePtr );
+ Any source;
+ Dali::NativeImageSourcePtr nativeImageSourcePtr = Dali::NativeImageSource::New(source);
+ mNativeTexture = Dali::Texture::New(*nativeImageSourcePtr);
- if( !mTextureRenderer )
+ if(!mTextureRenderer)
{
- Dali::Geometry geometry = VisualFactoryCache::CreateQuadGeometry();
- Dali::Shader shader = CreateShader();
+ Dali::Geometry geometry = VisualFactoryCache::CreateQuadGeometry();
+ Dali::Shader shader = CreateShader();
Dali::TextureSet textureSet = Dali::TextureSet::New();
- textureSet.SetTexture( 0u, mNativeTexture );
+ textureSet.SetTexture(0u, mNativeTexture);
- mTextureRenderer = Renderer::New( geometry, shader );
- mTextureRenderer.SetTextures( textureSet );
+ mTextureRenderer = Renderer::New(geometry, shader);
+ mTextureRenderer.SetTextures(textureSet);
}
else
{
Dali::TextureSet textureSet = mTextureRenderer.GetTextures();
- textureSet.SetTexture( 0u, mNativeTexture );
+ textureSet.SetTexture(0u, mNativeTexture);
}
- Self().AddRenderer( mTextureRenderer );
+ Self().AddRenderer(mTextureRenderer);
// Note VideoPlayer::SetRenderingTarget resets all the options. (e.g. url, mute, looping)
- mVideoPlayer.SetRenderingTarget( nativeImageSourcePtr );
+ mVideoPlayer.SetRenderingTarget(nativeImageSourcePtr);
ApplyBackupProperties();
- if( mIsPlay )
+ if(mIsPlay)
{
Play();
}
- if( curPos > 0 )
+ if(curPos > 0)
{
- mVideoPlayer.SetPlayPosition( curPos );
+ mVideoPlayer.SetPlayPosition(curPos);
}
}
-void VideoView::UpdateDisplayArea( Dali::PropertyNotification& source )
+void VideoView::UpdateDisplayArea(Dali::PropertyNotification& source)
{
// If mSyncMode is enabled, Video player's size and poistion is updated in Video player's constraint.
// Because video view and player should be work syncronization.
- if( !mIsUnderlay || mSyncMode == Dali::VideoSyncMode::ENABLED )
+ if(!mIsUnderlay || mSyncMode == Dali::VideoSyncMode::ENABLED)
{
return;
}
- Actor self( Self() );
+ Actor self(Self());
- bool positionUsesAnchorPoint = self.GetProperty( Actor::Property::POSITION_USES_ANCHOR_POINT ).Get< bool >();
- Vector3 actorSize = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * self.GetCurrentProperty< Vector3 >( Actor::Property::SCALE );
- Vector3 anchorPointOffSet = actorSize * ( positionUsesAnchorPoint ? self.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) : AnchorPoint::TOP_LEFT );
+ bool positionUsesAnchorPoint = self.GetProperty(Actor::Property::POSITION_USES_ANCHOR_POINT).Get<bool>();
+ Vector3 actorSize = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE) * self.GetCurrentProperty<Vector3>(Actor::Property::SCALE);
+ Vector3 anchorPointOffSet = actorSize * (positionUsesAnchorPoint ? self.GetCurrentProperty<Vector3>(Actor::Property::ANCHOR_POINT) : AnchorPoint::TOP_LEFT);
- Vector2 screenPosition = self.GetProperty( Actor::Property::SCREEN_POSITION ).Get< Vector2 >();
+ Vector2 screenPosition = self.GetProperty(Actor::Property::SCREEN_POSITION).Get<Vector2>();
- mDisplayArea.x = screenPosition.x - anchorPointOffSet.x;
- mDisplayArea.y = screenPosition.y - anchorPointOffSet.y;
- mDisplayArea.width = actorSize.x;
+ mDisplayArea.x = screenPosition.x - anchorPointOffSet.x;
+ mDisplayArea.y = screenPosition.y - anchorPointOffSet.y;
+ mDisplayArea.width = actorSize.x;
mDisplayArea.height = actorSize.y;
- mVideoPlayer.SetDisplayArea( mDisplayArea );
+ mVideoPlayer.SetDisplayArea(mDisplayArea);
}
-void VideoView::SetUnderlay( bool set )
+void VideoView::SetUnderlay(bool set)
{
- if( set != mIsUnderlay )
+ if(set != mIsUnderlay)
{
mIsUnderlay = set;
- if( mIsUnderlay )
+ if(mIsUnderlay)
{
SetWindowSurfaceTarget();
}
return mIsUnderlay;
}
-void VideoView::SetSWCodec( bool on )
+void VideoView::SetSWCodec(bool on)
{
// If setting SW or HW type is failed , video-view shows video by default codec type.
// The default codec type is selected by platform.
- if( on )
+ if(on)
{
- mVideoPlayer.SetCodecType( Dali::VideoPlayerPlugin::CodecType::SW );
+ mVideoPlayer.SetCodecType(Dali::VideoPlayerPlugin::CodecType::SW);
}
else
{
- mVideoPlayer.SetCodecType( Dali::VideoPlayerPlugin::CodecType::HW );
+ mVideoPlayer.SetCodecType(Dali::VideoPlayerPlugin::CodecType::HW);
}
}
return mVideoPlayer.GetPlayPosition();
}
-void VideoView::SetPlayPosition( int pos )
+void VideoView::SetPlayPosition(int pos)
{
- mVideoPlayer.SetPlayPosition( pos );
+ mVideoPlayer.SetPlayPosition(pos);
}
-void VideoView::SetDisplayMode( int mode )
+void VideoView::SetDisplayMode(int mode)
{
- mVideoPlayer.SetDisplayMode( static_cast< Dali::VideoPlayerPlugin::DisplayMode::Type >( mode ) );
+ mVideoPlayer.SetDisplayMode(static_cast<Dali::VideoPlayerPlugin::DisplayMode::Type>(mode));
}
int VideoView::GetDisplayMode() const
{
- return static_cast< int >( mVideoPlayer.GetDisplayMode() );
+ return static_cast<int>(mVideoPlayer.GetDisplayMode());
}
Any VideoView::GetMediaPlayer()
return mVideoPlayer.GetMediaPlayer();
}
-void VideoView::OnAnimationFinished( Animation& animation )
+void VideoView::OnAnimationFinished(Animation& animation)
{
// send desync
SetFrameRenderCallback();
}
-void VideoView::PlayAnimation( Dali::Animation animation )
+void VideoView::PlayAnimation(Dali::Animation animation)
{
- if( mIsUnderlay && mSyncMode == Dali::VideoSyncMode::ENABLED )
+ if(mIsUnderlay && mSyncMode == Dali::VideoSyncMode::ENABLED)
{
mVideoPlayer.StartSynchronization();
- animation.FinishedSignal().Connect( this, &VideoView::OnAnimationFinished );
+ animation.FinishedSignal().Connect(this, &VideoView::OnAnimationFinished);
}
animation.Play();
}
std::string fragmentShader = "#extension GL_OES_EGL_image_external:require\n";
std::string vertexShader;
std::string customFragmentShader;
- bool checkShader = false;
+ bool checkShader = false;
- if( !mEffectPropertyMap.Empty() )
+ if(!mEffectPropertyMap.Empty())
{
- Property::Value* vertexShaderValue = mEffectPropertyMap.Find( CUSTOM_VERTEX_SHADER );
- if( vertexShaderValue )
+ Property::Value* vertexShaderValue = mEffectPropertyMap.Find(CUSTOM_VERTEX_SHADER);
+ if(vertexShaderValue)
{
- checkShader = GetStringFromProperty( *vertexShaderValue, vertexShader );
+ checkShader = GetStringFromProperty(*vertexShaderValue, vertexShader);
}
- if( !vertexShaderValue || !checkShader )
+ if(!vertexShaderValue || !checkShader)
{
vertexShader = SHADER_VIDEO_VIEW_TEXTURE_VERT.data();
}
- Property::Value* fragmentShaderValue = mEffectPropertyMap.Find( CUSTOM_FRAGMENT_SHADER );
- if( fragmentShaderValue )
+ Property::Value* fragmentShaderValue = mEffectPropertyMap.Find(CUSTOM_FRAGMENT_SHADER);
+ if(fragmentShaderValue)
{
- checkShader = GetStringFromProperty( *fragmentShaderValue, customFragmentShader );
+ checkShader = GetStringFromProperty(*fragmentShaderValue, customFragmentShader);
- if( checkShader )
+ if(checkShader)
{
fragmentShader = customFragmentShader;
}
}
- if( !fragmentShaderValue || !checkShader )
+ if(!fragmentShaderValue || !checkShader)
{
fragmentShader += SHADER_VIDEO_VIEW_TEXTURE_FRAG.data();
}
fragmentShader += SHADER_VIDEO_VIEW_TEXTURE_FRAG.data();
}
- return Dali::Shader::New( vertexShader, fragmentShader );
+ return Dali::Shader::New(vertexShader, fragmentShader);
}
-bool VideoView::GetStringFromProperty( const Dali::Property::Value& value, std::string& output )
+bool VideoView::GetStringFromProperty(const Dali::Property::Value& value, std::string& output)
{
bool extracted = false;
- if( value.Get( output ) )
+ if(value.Get(output))
{
extracted = true;
}
void VideoView::ApplyBackupProperties()
{
- Property::Map::SizeType pos = 0;
+ Property::Map::SizeType pos = 0;
Property::Map::SizeType count = mPropertyBackup.Count();
- for( ; pos < count; pos++ )
+ for(; pos < count; pos++)
{
- KeyValuePair property = mPropertyBackup.GetKeyValue( pos );
+ KeyValuePair property = mPropertyBackup.GetKeyValue(pos);
- SetPropertyInternal( property.first.indexKey, property.second );
+ SetPropertyInternal(property.first.indexKey, property.second);
}
}
-void VideoView::FrameRenderCallback( int frameID )
+void VideoView::FrameRenderCallback(int frameID)
{
// send desync
- if( frameID == mFrameID )
+ if(frameID == mFrameID)
{
mVideoPlayer.FinishSynchronization();
mFrameID = 0;
void VideoView::SetFrameRenderCallback()
{
mFrameID++;
- DevelWindow::AddFrameRenderedCallback( DevelWindow::Get( Self() ),
- std::unique_ptr< CallbackBase >( MakeCallback( this, &VideoView::FrameRenderCallback ) ), mFrameID );
+ DevelWindow::AddFrameRenderedCallback(DevelWindow::Get(Self()),
+ std::unique_ptr<CallbackBase>(MakeCallback(this, &VideoView::FrameRenderCallback)),
+ mFrameID);
}
} // namespace Internal
-} // namespace toolkit
+} // namespace Toolkit
} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "web-view-impl.h"
// EXTERNAL INCLUDES
-#include <cstring>
#include <dali/devel-api/adaptor-framework/web-engine-back-forward-list.h>
#include <dali/devel-api/adaptor-framework/web-engine-context.h>
#include <dali/devel-api/adaptor-framework/web-engine-cookie-manager.h>
#include <dali/devel-api/adaptor-framework/web-engine-settings.h>
+#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/devel-api/scripting/scripting.h>
-#include <dali/devel-api/common/stage.h>
#include <dali/public-api/adaptor-framework/native-image-source.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/control-devel.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
return Toolkit::WebView::New();
}
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::WebView, Toolkit::Control, Create )
+// clang-format off
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::WebView, Toolkit::Control, Create)
-DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "url", STRING, URL )
-DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "userAgent", STRING, USER_AGENT )
-DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "scrollPosition", VECTOR2, SCROLL_POSITION )
-DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "scrollSize", VECTOR2, SCROLL_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "contentSize", VECTOR2, CONTENT_SIZE )
-DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "title", STRING, TITLE )
-DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "videoHoleEnabled", BOOLEAN, VIDEO_HOLE_ENABLED )
+DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "url", STRING, URL )
+DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "userAgent", STRING, USER_AGENT )
+DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "scrollPosition", VECTOR2, SCROLL_POSITION )
+DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "scrollSize", VECTOR2, SCROLL_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "contentSize", VECTOR2, CONTENT_SIZE )
+DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "title", STRING, TITLE )
+DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "videoHoleEnabled", BOOLEAN, VIDEO_HOLE_ENABLED)
-DALI_SIGNAL_REGISTRATION( Toolkit, WebView, "pageLoadStarted", PAGE_LOAD_STARTED_SIGNAL )
-DALI_SIGNAL_REGISTRATION( Toolkit, WebView, "pageLoadFinished", PAGE_LOAD_FINISHED_SIGNAL )
-DALI_SIGNAL_REGISTRATION( Toolkit, WebView, "pageLoadError", PAGE_LOAD_ERROR_SIGNAL )
-DALI_SIGNAL_REGISTRATION( Toolkit, WebView, "scrollEdgeReached", SCROLL_EDGE_REACHED_SIGNAL )
+DALI_SIGNAL_REGISTRATION(Toolkit, WebView, "pageLoadStarted", PAGE_LOAD_STARTED_SIGNAL )
+DALI_SIGNAL_REGISTRATION(Toolkit, WebView, "pageLoadFinished", PAGE_LOAD_FINISHED_SIGNAL )
+DALI_SIGNAL_REGISTRATION(Toolkit, WebView, "pageLoadError", PAGE_LOAD_ERROR_SIGNAL )
+DALI_SIGNAL_REGISTRATION(Toolkit, WebView, "scrollEdgeReached", SCROLL_EDGE_REACHED_SIGNAL)
DALI_TYPE_REGISTRATION_END()
+// clang-format on
const std::string kEmptyString;
-} // anonymous namepsace
+} // namespace
-#define GET_ENUM_STRING( structName, inputExp ) \
- Scripting::GetLinearEnumerationName< Toolkit::WebView::structName::Type >( static_cast< Toolkit::WebView::structName::Type >( inputExp ), structName##_TABLE, structName##_TABLE_COUNT )
+#define GET_ENUM_STRING(structName, inputExp) \
+ Scripting::GetLinearEnumerationName<Toolkit::WebView::structName::Type>(static_cast<Toolkit::WebView::structName::Type>(inputExp), structName##_TABLE, structName##_TABLE_COUNT)
-#define GET_ENUM_VALUE( structName, inputExp, outputExp ) \
- Scripting::GetEnumerationProperty< Toolkit::WebView::structName::Type >( inputExp, structName##_TABLE, structName##_TABLE_COUNT, outputExp )
+#define GET_ENUM_VALUE(structName, inputExp, outputExp) \
+ Scripting::GetEnumerationProperty<Toolkit::WebView::structName::Type>(inputExp, structName##_TABLE, structName##_TABLE_COUNT, outputExp)
-WebView::WebView( const std::string& locale, const std::string& timezoneId )
-: Control( ControlBehaviour( ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS ) ),
+WebView::WebView(const std::string& locale, const std::string& timezoneId)
+: Control(ControlBehaviour(ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS)),
mUrl(),
mVisual(),
- mWebViewSize( Stage::GetCurrent().GetSize() ),
+ mWebViewSize(Stage::GetCurrent().GetSize()),
mWebEngine(),
mPageLoadStartedSignal(),
mPageLoadFinishedSignal(),
mPageLoadErrorSignal(),
- mVideoHoleEnabled( true ),
- mWebViewArea ( 0, 0, mWebViewSize.width, mWebViewSize.height )
+ mVideoHoleEnabled(true),
+ mWebViewArea(0, 0, mWebViewSize.width, mWebViewSize.height)
{
mWebEngine = Dali::WebEngine::New();
// WebEngine is empty when it is not properly initialized.
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.Create( mWebViewSize.width, mWebViewSize.height, locale, timezoneId );
+ mWebEngine.Create(mWebViewSize.width, mWebViewSize.height, locale, timezoneId);
}
}
-WebView::WebView( int argc, char** argv )
-: Control( ControlBehaviour( ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS ) ),
+WebView::WebView(int argc, char** argv)
+: Control(ControlBehaviour(ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS)),
mUrl(),
mVisual(),
- mWebViewSize( Stage::GetCurrent().GetSize() ),
+ mWebViewSize(Stage::GetCurrent().GetSize()),
mWebEngine(),
mPageLoadStartedSignal(),
mPageLoadFinishedSignal(),
mPageLoadErrorSignal(),
- mVideoHoleEnabled( true ),
- mWebViewArea ( 0, 0, mWebViewSize.width, mWebViewSize.height )
+ mVideoHoleEnabled(true),
+ mWebViewArea(0, 0, mWebViewSize.width, mWebViewSize.height)
{
mWebEngine = Dali::WebEngine::New();
// WebEngine is empty when it is not properly initialized.
- if ( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.Create( mWebViewSize.width, mWebViewSize.height, argc, argv );
+ mWebEngine.Create(mWebViewSize.width, mWebViewSize.height, argc, argv);
}
}
WebView::WebView()
-: WebView( "", "" )
+: WebView("", "")
{
}
WebView::~WebView()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.Destroy();
}
Toolkit::WebView WebView::New()
{
- WebView* impl = new WebView();
- Toolkit::WebView handle = Toolkit::WebView( *impl );
+ WebView* impl = new WebView();
+ Toolkit::WebView handle = Toolkit::WebView(*impl);
impl->Initialize();
return handle;
}
-Toolkit::WebView WebView::New( const std::string& locale, const std::string& timezoneId )
+Toolkit::WebView WebView::New(const std::string& locale, const std::string& timezoneId)
{
- WebView* impl = new WebView( locale, timezoneId );
- Toolkit::WebView handle = Toolkit::WebView( *impl );
+ WebView* impl = new WebView(locale, timezoneId);
+ Toolkit::WebView handle = Toolkit::WebView(*impl);
impl->Initialize();
return handle;
}
-Toolkit::WebView WebView::New( int argc, char** argv )
+Toolkit::WebView WebView::New(int argc, char** argv)
{
- WebView* impl = new WebView( argc, argv );
- Toolkit::WebView handle = Toolkit::WebView( *impl );
+ WebView* impl = new WebView(argc, argv);
+ Toolkit::WebView handle = Toolkit::WebView(*impl);
impl->Initialize();
return handle;
{
Actor self = Self();
- self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true );
- self.TouchedSignal().Connect( this, &WebView::OnTouchEvent );
+ self.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true);
+ self.TouchedSignal().Connect(this, &WebView::OnTouchEvent);
- mPositionUpdateNotification = self.AddPropertyNotification( Actor::Property::WORLD_POSITION, StepCondition( 1.0f, 1.0f ) );
- mSizeUpdateNotification = self.AddPropertyNotification( Actor::Property::SIZE, StepCondition( 1.0f, 1.0f ) );
- mScaleUpdateNotification = self.AddPropertyNotification( Actor::Property::WORLD_SCALE, StepCondition( 0.1f, 1.0f ) );
- mPositionUpdateNotification.NotifySignal().Connect( this, &WebView::UpdateDisplayArea );
- mSizeUpdateNotification.NotifySignal().Connect( this, &WebView::UpdateDisplayArea );
- mScaleUpdateNotification.NotifySignal().Connect( this, &WebView::UpdateDisplayArea );
+ mPositionUpdateNotification = self.AddPropertyNotification(Actor::Property::WORLD_POSITION, StepCondition(1.0f, 1.0f));
+ mSizeUpdateNotification = self.AddPropertyNotification(Actor::Property::SIZE, StepCondition(1.0f, 1.0f));
+ mScaleUpdateNotification = self.AddPropertyNotification(Actor::Property::WORLD_SCALE, StepCondition(0.1f, 1.0f));
+ mPositionUpdateNotification.NotifySignal().Connect(this, &WebView::UpdateDisplayArea);
+ mSizeUpdateNotification.NotifySignal().Connect(this, &WebView::UpdateDisplayArea);
+ mScaleUpdateNotification.NotifySignal().Connect(this, &WebView::UpdateDisplayArea);
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.PageLoadStartedSignal().Connect( this, &WebView::OnPageLoadStarted );
- mWebEngine.PageLoadFinishedSignal().Connect( this, &WebView::OnPageLoadFinished );
- mWebEngine.PageLoadErrorSignal().Connect( this, &WebView::OnPageLoadError );
- mWebEngine.ScrollEdgeReachedSignal().Connect( this, &WebView::OnScrollEdgeReached );
+ mWebEngine.PageLoadStartedSignal().Connect(this, &WebView::OnPageLoadStarted);
+ mWebEngine.PageLoadFinishedSignal().Connect(this, &WebView::OnPageLoadFinished);
+ mWebEngine.PageLoadErrorSignal().Connect(this, &WebView::OnPageLoadError);
+ mWebEngine.ScrollEdgeReachedSignal().Connect(this, &WebView::OnScrollEdgeReached);
- mWebContext = std::unique_ptr<Dali::Toolkit::WebContext>( new WebContext( mWebEngine.GetContext() ) );
- mWebCookieManager = std::unique_ptr<Dali::Toolkit::WebCookieManager>( new WebCookieManager( mWebEngine.GetCookieManager() ) );
- mWebSettings = std::unique_ptr<Dali::Toolkit::WebSettings>( new WebSettings( mWebEngine.GetSettings() ) );
- mWebBackForwardList = std::unique_ptr<Dali::Toolkit::WebBackForwardList>( new WebBackForwardList( mWebEngine.GetBackForwardList() ) );
+ mWebContext = std::unique_ptr<Dali::Toolkit::WebContext>(new WebContext(mWebEngine.GetContext()));
+ mWebCookieManager = std::unique_ptr<Dali::Toolkit::WebCookieManager>(new WebCookieManager(mWebEngine.GetCookieManager()));
+ mWebSettings = std::unique_ptr<Dali::Toolkit::WebSettings>(new WebSettings(mWebEngine.GetSettings()));
+ mWebBackForwardList = std::unique_ptr<Dali::Toolkit::WebBackForwardList>(new WebBackForwardList(mWebEngine.GetBackForwardList()));
}
}
Dali::Toolkit::ImageView& WebView::GetFavicon()
{
- if ( mWebEngine )
+ if(mWebEngine)
{
Dali::PixelData pixelData = mWebEngine.GetFavicon();
- std::string url = Dali::Toolkit::Image::GenerateUrl( pixelData );
- mFaviconView = Dali::Toolkit::ImageView::New( url );
- mFaviconView.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );
- mFaviconView.SetProperty( Dali::Actor::Property::SIZE, Vector2( pixelData.GetWidth(), pixelData.GetHeight() ) );
+ std::string url = Dali::Toolkit::Image::GenerateUrl(pixelData);
+ mFaviconView = Dali::Toolkit::ImageView::New(url);
+ mFaviconView.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS);
+ mFaviconView.SetProperty(Dali::Actor::Property::SIZE, Vector2(pixelData.GetWidth(), pixelData.GetHeight()));
}
return mFaviconView;
}
-void WebView::LoadUrl( const std::string& url )
+void WebView::LoadUrl(const std::string& url)
{
mUrl = url;
- if( mWebEngine )
+ if(mWebEngine)
{
- Texture texture = Dali::Texture::New( *mWebEngine.GetNativeImageSource() );
- const std::string nativeImageUrl = Dali::Toolkit::TextureManager::AddTexture( texture );
- mVisual = Toolkit::VisualFactory::Get().CreateVisual(
- { { Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE } ,
- { Toolkit::ImageVisual::Property::URL, nativeImageUrl } } );
+ Texture texture = Dali::Texture::New(*mWebEngine.GetNativeImageSource());
+ const std::string nativeImageUrl = Dali::Toolkit::TextureManager::AddTexture(texture);
+ mVisual = Toolkit::VisualFactory::Get().CreateVisual(
+ {{Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE},
+ {Toolkit::ImageVisual::Property::URL, nativeImageUrl}});
- if( mVisual )
+ if(mVisual)
{
// Clean up previously registered visual and add new one.
- DevelControl::RegisterVisual( *this, Toolkit::WebView::Property::URL, mVisual );
- mWebEngine.LoadUrl( url );
+ DevelControl::RegisterVisual(*this, Toolkit::WebView::Property::URL, mVisual);
+ mWebEngine.LoadUrl(url);
}
- if ( mVideoHoleEnabled )
+ if(mVideoHoleEnabled)
{
- EnableBlendMode( false );
+ EnableBlendMode(false);
}
}
}
-void WebView::LoadHtmlString( const std::string& htmlString )
+void WebView::LoadHtmlString(const std::string& htmlString)
{
- if( mWebEngine )
+ if(mWebEngine)
{
- Texture texture = Dali::Texture::New( *mWebEngine.GetNativeImageSource() );
- const std::string nativeImageUrl = Dali::Toolkit::TextureManager::AddTexture( texture );
- mVisual = Toolkit::VisualFactory::Get().CreateVisual(
- { { Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE } ,
- { Toolkit::ImageVisual::Property::URL, nativeImageUrl } } );
+ Texture texture = Dali::Texture::New(*mWebEngine.GetNativeImageSource());
+ const std::string nativeImageUrl = Dali::Toolkit::TextureManager::AddTexture(texture);
+ mVisual = Toolkit::VisualFactory::Get().CreateVisual(
+ {{Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE},
+ {Toolkit::ImageVisual::Property::URL, nativeImageUrl}});
- if( mVisual )
+ if(mVisual)
{
- DevelControl::RegisterVisual( *this, Toolkit::WebView::Property::URL, mVisual );
- mWebEngine.LoadHtmlString( htmlString );
+ DevelControl::RegisterVisual(*this, Toolkit::WebView::Property::URL, mVisual);
+ mWebEngine.LoadHtmlString(htmlString);
}
- if ( mVideoHoleEnabled )
+ if(mVideoHoleEnabled)
{
- EnableBlendMode( false );
+ EnableBlendMode(false);
}
}
}
void WebView::Reload()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.Reload();
}
void WebView::StopLoading()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.StopLoading();
}
void WebView::Suspend()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.Suspend();
}
void WebView::Resume()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.Resume();
}
}
-void WebView::ScrollBy( int deltaX, int deltaY )
+void WebView::ScrollBy(int deltaX, int deltaY)
{
- if ( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.ScrollBy( deltaX, deltaY );
+ mWebEngine.ScrollBy(deltaX, deltaY);
}
}
void WebView::GoForward()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.GoForward();
}
void WebView::GoBack()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.GoBack();
}
}
-void WebView::EvaluateJavaScript( const std::string& script, std::function< void( const std::string& ) > resultHandler )
+void WebView::EvaluateJavaScript(const std::string& script, std::function<void(const std::string&)> resultHandler)
{
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.EvaluateJavaScript( script, resultHandler );
+ mWebEngine.EvaluateJavaScript(script, resultHandler);
}
}
-void WebView::AddJavaScriptMessageHandler( const std::string& exposedObjectName, std::function< void( const std::string& ) > handler )
+void WebView::AddJavaScriptMessageHandler(const std::string& exposedObjectName, std::function<void(const std::string&)> handler)
{
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.AddJavaScriptMessageHandler( exposedObjectName, handler );
+ mWebEngine.AddJavaScriptMessageHandler(exposedObjectName, handler);
}
}
void WebView::ClearAllTilesResources()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.ClearAllTilesResources();
}
void WebView::ClearHistory()
{
- if( mWebEngine )
+ if(mWebEngine)
{
mWebEngine.ClearHistory();
}
}
-void WebView::UpdateDisplayArea( Dali::PropertyNotification& /*source*/ )
+void WebView::UpdateDisplayArea(Dali::PropertyNotification& /*source*/)
{
- if( !mWebEngine )
+ if(!mWebEngine)
return;
- Actor self( Self() );
+ Actor self(Self());
- bool positionUsesAnchorPoint = self.GetProperty< bool >( Actor::Property::POSITION_USES_ANCHOR_POINT );
- Vector3 actorSize = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * self.GetCurrentProperty< Vector3 >( Actor::Property::SCALE );
- Vector3 anchorPointOffSet = actorSize * ( positionUsesAnchorPoint ? self.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) : AnchorPoint::TOP_LEFT );
- Vector2 screenPosition = self.GetProperty< Vector2 >( Actor::Property::SCREEN_POSITION );
+ bool positionUsesAnchorPoint = self.GetProperty<bool>(Actor::Property::POSITION_USES_ANCHOR_POINT);
+ Vector3 actorSize = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE) * self.GetCurrentProperty<Vector3>(Actor::Property::SCALE);
+ Vector3 anchorPointOffSet = actorSize * (positionUsesAnchorPoint ? self.GetCurrentProperty<Vector3>(Actor::Property::ANCHOR_POINT) : AnchorPoint::TOP_LEFT);
+ Vector2 screenPosition = self.GetProperty<Vector2>(Actor::Property::SCREEN_POSITION);
- Dali::Rect< int > displayArea;
- displayArea.x = screenPosition.x - anchorPointOffSet.x;
- displayArea.y = screenPosition.y - anchorPointOffSet.y;
- displayArea.width = actorSize.x;
+ Dali::Rect<int> displayArea;
+ displayArea.x = screenPosition.x - anchorPointOffSet.x;
+ displayArea.y = screenPosition.y - anchorPointOffSet.y;
+ displayArea.width = actorSize.x;
displayArea.height = actorSize.y;
- Size displaySize = Size( displayArea.width, displayArea.height );
- if ( mWebViewSize != displaySize )
+ Size displaySize = Size(displayArea.width, displayArea.height);
+ if(mWebViewSize != displaySize)
{
mWebViewSize = displaySize;
}
- if (mWebViewArea != displayArea )
+ if(mWebViewArea != displayArea)
{
mWebViewArea = displayArea;
- mWebEngine.UpdateDisplayArea( mWebViewArea );
+ mWebEngine.UpdateDisplayArea(mWebViewArea);
}
}
-void WebView::EnableVideoHole( bool enabled )
+void WebView::EnableVideoHole(bool enabled)
{
mVideoHoleEnabled = enabled;
- EnableBlendMode( !mVideoHoleEnabled );
+ EnableBlendMode(!mVideoHoleEnabled);
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.EnableVideoHole( mVideoHoleEnabled );
+ mWebEngine.EnableVideoHole(mVideoHoleEnabled);
}
}
-void WebView::EnableBlendMode( bool blendEnabled )
+void WebView::EnableBlendMode(bool blendEnabled)
{
Actor self = Self();
- for (uint32_t i = 0; i < self.GetRendererCount(); i++)
+ for(uint32_t i = 0; i < self.GetRendererCount(); i++)
{
- Dali::Renderer render = self.GetRendererAt( i );
- render.SetProperty( Renderer::Property::BLEND_MODE, blendEnabled ? BlendMode::ON : BlendMode::OFF );
+ Dali::Renderer render = self.GetRendererAt(i);
+ render.SetProperty(Renderer::Property::BLEND_MODE, blendEnabled ? BlendMode::ON : BlendMode::OFF);
}
}
return mScrollEdgeReachedSignal;
}
-void WebView::OnPageLoadStarted( const std::string& url )
+void WebView::OnPageLoadStarted(const std::string& url)
{
- if( !mPageLoadStartedSignal.Empty() )
+ if(!mPageLoadStartedSignal.Empty())
{
- Dali::Toolkit::WebView handle( GetOwner() );
- mPageLoadStartedSignal.Emit( handle, url );
+ Dali::Toolkit::WebView handle(GetOwner());
+ mPageLoadStartedSignal.Emit(handle, url);
}
}
-void WebView::OnPageLoadFinished( const std::string& url )
+void WebView::OnPageLoadFinished(const std::string& url)
{
- if( !mPageLoadFinishedSignal.Empty() )
+ if(!mPageLoadFinishedSignal.Empty())
{
- Dali::Toolkit::WebView handle( GetOwner() );
- mPageLoadFinishedSignal.Emit( handle, url );
+ Dali::Toolkit::WebView handle(GetOwner());
+ mPageLoadFinishedSignal.Emit(handle, url);
}
}
-void WebView::OnPageLoadError( const std::string& url, int errorCode )
+void WebView::OnPageLoadError(const std::string& url, int errorCode)
{
- if( !mPageLoadErrorSignal.Empty() )
+ if(!mPageLoadErrorSignal.Empty())
{
- Dali::Toolkit::WebView handle( GetOwner() );
- mPageLoadErrorSignal.Emit( handle, url, static_cast< Toolkit::WebView::LoadErrorCode >( errorCode ) );
+ Dali::Toolkit::WebView handle(GetOwner());
+ mPageLoadErrorSignal.Emit(handle, url, static_cast<Toolkit::WebView::LoadErrorCode>(errorCode));
}
}
-void WebView::OnScrollEdgeReached( Dali::WebEnginePlugin::ScrollEdge edge )
+void WebView::OnScrollEdgeReached(Dali::WebEnginePlugin::ScrollEdge edge)
{
- if( !mScrollEdgeReachedSignal.Empty() )
+ if(!mScrollEdgeReachedSignal.Empty())
{
- Dali::Toolkit::WebView handle( GetOwner() );
- mScrollEdgeReachedSignal.Emit( handle, edge );
+ Dali::Toolkit::WebView handle(GetOwner());
+ mScrollEdgeReachedSignal.Emit(handle, edge);
}
}
-bool WebView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool WebView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected = false;
- Toolkit::WebView webView = Toolkit::WebView::DownCast( handle );
+ bool connected = false;
+ Toolkit::WebView webView = Toolkit::WebView::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), PAGE_LOAD_STARTED_SIGNAL ) )
+ if(0 == strcmp(signalName.c_str(), PAGE_LOAD_STARTED_SIGNAL))
{
- webView.PageLoadStartedSignal().Connect( tracker, functor );
+ webView.PageLoadStartedSignal().Connect(tracker, functor);
connected = true;
}
- else if( 0 == strcmp( signalName.c_str(), PAGE_LOAD_FINISHED_SIGNAL ) )
+ else if(0 == strcmp(signalName.c_str(), PAGE_LOAD_FINISHED_SIGNAL))
{
- webView.PageLoadFinishedSignal().Connect( tracker, functor );
+ webView.PageLoadFinishedSignal().Connect(tracker, functor);
connected = true;
}
- else if( 0 == strcmp( signalName.c_str(), PAGE_LOAD_ERROR_SIGNAL ) )
+ else if(0 == strcmp(signalName.c_str(), PAGE_LOAD_ERROR_SIGNAL))
{
- webView.PageLoadErrorSignal().Connect( tracker, functor );
+ webView.PageLoadErrorSignal().Connect(tracker, functor);
connected = true;
}
- else if( 0 == strcmp( signalName.c_str(), SCROLL_EDGE_REACHED_SIGNAL ) )
+ else if(0 == strcmp(signalName.c_str(), SCROLL_EDGE_REACHED_SIGNAL))
{
- webView.ScrollEdgeReachedSignal().Connect( tracker, functor );
+ webView.ScrollEdgeReachedSignal().Connect(tracker, functor);
connected = true;
}
Vector3 WebView::GetNaturalSize()
{
- if( mVisual )
+ if(mVisual)
{
Vector2 rendererNaturalSize;
- mVisual.GetNaturalSize( rendererNaturalSize );
- return Vector3( rendererNaturalSize );
+ mVisual.GetNaturalSize(rendererNaturalSize);
+ return Vector3(rendererNaturalSize);
}
- return Vector3( mWebViewSize );
+ return Vector3(mWebViewSize);
}
-void WebView::OnSceneConnection( int depth )
+void WebView::OnSceneConnection(int depth)
{
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
- EnableBlendMode( !mVideoHoleEnabled );
+ EnableBlendMode(!mVideoHoleEnabled);
}
-void WebView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
+void WebView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
{
- Toolkit::WebView webView = Toolkit::WebView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::WebView webView = Toolkit::WebView::DownCast(Dali::BaseHandle(object));
- if( webView )
+ if(webView)
{
- WebView& impl = GetImpl( webView );
- switch( index )
+ WebView& impl = GetImpl(webView);
+ switch(index)
{
case Toolkit::WebView::Property::URL:
{
std::string url;
- if( value.Get( url ) )
+ if(value.Get(url))
{
- impl.LoadUrl( url );
+ impl.LoadUrl(url);
}
break;
}
case Toolkit::WebView::Property::USER_AGENT:
{
std::string input;
- if( value.Get( input ) )
+ if(value.Get(input))
{
- impl.SetUserAgent( input );
+ impl.SetUserAgent(input);
}
break;
}
case Toolkit::WebView::Property::SCROLL_POSITION:
{
Vector2 input;
- if ( value.Get( input ) )
+ if(value.Get(input))
{
- impl.SetScrollPosition( input.x, input.y );
+ impl.SetScrollPosition(input.x, input.y);
}
break;
}
case Toolkit::WebView::Property::VIDEO_HOLE_ENABLED:
{
bool input;
- if( value.Get( input ) )
+ if(value.Get(input))
{
- impl.EnableVideoHole( input );
+ impl.EnableVideoHole(input);
}
break;
}
}
}
-Property::Value WebView::GetProperty( BaseObject* object, Property::Index propertyIndex )
+Property::Value WebView::GetProperty(BaseObject* object, Property::Index propertyIndex)
{
Property::Value value;
- Toolkit::WebView webView = Toolkit::WebView::DownCast( Dali::BaseHandle( object ) );
+ Toolkit::WebView webView = Toolkit::WebView::DownCast(Dali::BaseHandle(object));
- if( webView )
+ if(webView)
{
- WebView& impl = GetImpl( webView );
- switch( propertyIndex )
+ WebView& impl = GetImpl(webView);
+ switch(propertyIndex)
{
case Toolkit::WebView::Property::URL:
{
break;
}
default:
- break;
+ break;
}
}
return value;
}
-bool WebView::OnTouchEvent( Actor actor, const Dali::TouchEvent& touch )
+bool WebView::OnTouchEvent(Actor actor, const Dali::TouchEvent& touch)
{
bool result = false;
- if( mWebEngine )
+ if(mWebEngine)
{
- result = mWebEngine.SendTouchEvent( touch );
+ result = mWebEngine.SendTouchEvent(touch);
}
return result;
}
-bool WebView::OnKeyEvent( const Dali::KeyEvent& event )
+bool WebView::OnKeyEvent(const Dali::KeyEvent& event)
{
bool result = false;
- if( mWebEngine )
+ if(mWebEngine)
{
- result = mWebEngine.SendKeyEvent( event );
+ result = mWebEngine.SendKeyEvent(event);
}
return result;
}
void WebView::OnKeyInputFocusGained()
{
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.SetFocus( true );
+ mWebEngine.SetFocus(true);
}
- EmitKeyInputFocusSignal( true ); // Calls back into the Control hence done last.
+ EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last.
}
void WebView::OnKeyInputFocusLost()
{
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.SetFocus( false );
+ mWebEngine.SetFocus(false);
}
- EmitKeyInputFocusSignal( false ); // Calls back into the Control hence done last.
+ EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last.
}
-void WebView::SetScrollPosition( int x, int y )
+void WebView::SetScrollPosition(int x, int y)
{
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.SetScrollPosition( x, y );
+ mWebEngine.SetScrollPosition(x, y);
}
}
std::string WebView::GetTitle() const
{
- return mWebEngine ? mWebEngine.GetTitle() : kEmptyString;
+ return mWebEngine ? mWebEngine.GetTitle() : kEmptyString;
}
const std::string& WebView::GetUserAgent() const
return mWebEngine ? mWebEngine.GetUserAgent() : kEmptyString;
}
-void WebView::SetUserAgent( const std::string& userAgent )
+void WebView::SetUserAgent(const std::string& userAgent)
{
- if( mWebEngine )
+ if(mWebEngine)
{
- mWebEngine.SetUserAgent( userAgent );
+ mWebEngine.SetUserAgent(userAgent);
}
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
Dali::Toolkit::DragAndDropDetector DragAndDropDetector::New()
{
Dali::Toolkit::DragAndDropDetector detector = Dali::Toolkit::DragAndDropDetector(new DragAndDropDetector());
}
mControls.push_back(control);
control.TouchedSignal().Connect(this, &DragAndDropDetector::OnDrag);
- mFirstEnter.push_back(control.GetProperty< int >( Actor::Property::ID ));
+ mFirstEnter.push_back(control.GetProperty<int>(Actor::Property::ID));
mPanGestureDetector.Attach(control);
mPanGestureDetector.DetectedSignal().Connect(this, &DragAndDropDetector::OnPan);
}
-
}
void DragAndDropDetector::Detach(Dali::Toolkit::Control& control)
{
match->TouchedSignal().Disconnect(this, &DragAndDropDetector::OnDrag);
mPanGestureDetector.Detach(*match);
- mFirstEnter.erase(std::find(mFirstEnter.begin(), mFirstEnter.end(), control.GetProperty< int >( Actor::Property::ID )));
+ mFirstEnter.erase(std::find(mFirstEnter.begin(), mFirstEnter.end(), control.GetProperty<int>(Actor::Property::ID)));
mControls.erase(match);
}
}
if(!mControls.empty())
{
auto iter = mControls.begin();
- for(;iter != mControls.end();)
+ for(; iter != mControls.end();)
{
iter->TouchedSignal().Disconnect(this, &DragAndDropDetector::OnDrag);
mPanGestureDetector.Detach(*iter);
if(!mFirstEnter.empty())
{
auto iter = mFirstEnter.begin();
- for(;iter != mFirstEnter.end();)
+ for(; iter != mFirstEnter.end();)
{
iter = mFirstEnter.erase(iter);
}
if(state == GestureState::STARTED)
{
mDragLocalPosition = gesture.GetPosition();
- mPointDown = true;
- mDragControl = control;
+ mPointDown = true;
+ mDragControl = control;
mFirstEnter.clear();
- for( auto&& control : mControls)
+ for(auto&& control : mControls)
{
- mFirstEnter.push_back(control.GetProperty< int >( Actor::Property::ID ));
+ mFirstEnter.push_back(control.GetProperty<int>(Actor::Property::ID));
}
- float width = control.GetProperty<float>(Dali::Actor::Property::SIZE_WIDTH);
- float height = control.GetProperty<float>(Dali::Actor::Property::SIZE_HEIGHT);
+ float width = control.GetProperty<float>(Dali::Actor::Property::SIZE_WIDTH);
+ float height = control.GetProperty<float>(Dali::Actor::Property::SIZE_HEIGHT);
Vector3 actorPos = control.GetProperty<Vector3>(Dali::Actor::Property::POSITION);
mShadowControl = Dali::Toolkit::Control::New();
- mShadowControl.SetProperty( Actor::Property::POSITION, actorPos );
- mShadowControl.SetProperty( Actor::Property::SIZE, Vector2( width, height ) );
+ mShadowControl.SetProperty(Actor::Property::POSITION, actorPos);
+ mShadowControl.SetProperty(Actor::Property::SIZE, Vector2(width, height));
mShadowControl.SetBackgroundColor(Vector4(0.3f, 0.3f, 0.3f, 0.7f));
- mShadowControl.SetProperty( Actor::Property::PARENT_ORIGIN, control.GetCurrentProperty< Vector3 >( Actor::Property::PARENT_ORIGIN ) );
- mShadowControl.SetProperty( Actor::Property::ANCHOR_POINT,control.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ));
+ mShadowControl.SetProperty(Actor::Property::PARENT_ORIGIN, control.GetCurrentProperty<Vector3>(Actor::Property::PARENT_ORIGIN));
+ mShadowControl.SetProperty(Actor::Property::ANCHOR_POINT, control.GetCurrentProperty<Vector3>(Actor::Property::ANCHOR_POINT));
control.GetParent().Add(mShadowControl);
SetPosition(gesture.GetScreenPosition());
EmitStartedSignal(control);
}
if(state == GestureState::CONTINUING)
{
- Vector2 screenPosition = gesture.GetScreenPosition();
- control.GetParent().ScreenToLocal(mLocalPosition.x, mLocalPosition.y, screenPosition.x, screenPosition.y);
- mShadowControl.SetProperty( Actor::Property::POSITION, Vector2(mLocalPosition.x - mDragLocalPosition.x, mLocalPosition.y - mDragLocalPosition.y));
+ Vector2 screenPosition = gesture.GetScreenPosition();
+ control.GetParent().ScreenToLocal(mLocalPosition.x, mLocalPosition.y, screenPosition.x, screenPosition.y);
+ mShadowControl.SetProperty(Actor::Property::POSITION, Vector2(mLocalPosition.x - mDragLocalPosition.x, mLocalPosition.y - mDragLocalPosition.y));
}
if(state == GestureState::FINISHED)
{
bool DragAndDropDetector::OnDrag(Dali::Actor actor, const Dali::TouchEvent& data)
{
Dali::Toolkit::Control control = Dali::Toolkit::Control::DownCast(actor);
- PointState::Type type = data.GetState(0);
+ PointState::Type type = data.GetState(0);
if(type == PointState::MOTION)
{
if(mDragControl != control && mPointDown)
{
- auto found = std::find(mFirstEnter.begin(), mFirstEnter.end(), control.GetProperty< int >( Actor::Property::ID ));
+ auto found = std::find(mFirstEnter.begin(), mFirstEnter.end(), control.GetProperty<int>(Actor::Property::ID));
if(mFirstEnter.end() != found)
{
SetPosition(data.GetScreenPosition(0));
{
if(mDragControl != control && mPointDown)
{
- mFirstEnter.push_back(control.GetProperty< int >( Actor::Property::ID ));
+ mFirstEnter.push_back(control.GetProperty<int>(Actor::Property::ID));
EmitExitedSignal(control);
}
}
{
SetPosition(data.GetScreenPosition(0));
ClearContent();
- SetContent(mDragControl.GetProperty< std::string >( Dali::Actor::Property::NAME ));
+ SetContent(mDragControl.GetProperty<std::string>(Dali::Actor::Property::NAME));
EmitDroppedSignal(control);
}
if(mShadowControl)
{
- control.GetParent().Remove(mShadowControl);
+ control.GetParent().Remove(mShadowControl);
}
mPointDown = false;
}
return mScreenPosition;
}
-void DragAndDropDetector::SetContent( const std::string& content )
+void DragAndDropDetector::SetContent(const std::string& content)
{
mContent = content;
}
mContent.clear();
}
-void DragAndDropDetector::SetPosition( const Vector2& screenPosition )
+void DragAndDropDetector::SetPosition(const Vector2& screenPosition)
{
mScreenPosition = screenPosition;
}
void DragAndDropDetector::EmitStartedSignal(Dali::Toolkit::Control& control)
{
- if( !mStartedSignal.Empty() )
+ if(!mStartedSignal.Empty())
{
- Dali::Toolkit::DragAndDropDetector handle( this );
- mStartedSignal.Emit( control, handle );
+ Dali::Toolkit::DragAndDropDetector handle(this);
+ mStartedSignal.Emit(control, handle);
}
}
void DragAndDropDetector::EmitEnteredSignal(Dali::Toolkit::Control& control)
{
- if ( !mEnteredSignal.Empty() )
+ if(!mEnteredSignal.Empty())
{
- Dali::Toolkit::DragAndDropDetector handle( this );
- mEnteredSignal.Emit( control, handle );
+ Dali::Toolkit::DragAndDropDetector handle(this);
+ mEnteredSignal.Emit(control, handle);
}
}
void DragAndDropDetector::EmitExitedSignal(Dali::Toolkit::Control& control)
{
- if ( !mExitedSignal.Empty() )
+ if(!mExitedSignal.Empty())
{
- Dali::Toolkit::DragAndDropDetector handle( this );
- mExitedSignal.Emit( control, handle );
+ Dali::Toolkit::DragAndDropDetector handle(this);
+ mExitedSignal.Emit(control, handle);
}
}
void DragAndDropDetector::EmitMovedSignal(Dali::Toolkit::Control& control)
{
- if ( !mMovedSignal.Empty() )
+ if(!mMovedSignal.Empty())
{
- Dali::Toolkit::DragAndDropDetector handle( this );
- mMovedSignal.Emit( control, handle );
+ Dali::Toolkit::DragAndDropDetector handle(this);
+ mMovedSignal.Emit(control, handle);
}
}
void DragAndDropDetector::EmitDroppedSignal(Dali::Toolkit::Control& control)
{
- if ( !mDroppedSignal.Empty() )
+ if(!mDroppedSignal.Empty())
{
- Dali::Toolkit::DragAndDropDetector handle( this );
- mDroppedSignal.Emit( control, handle );
+ Dali::Toolkit::DragAndDropDetector handle(this);
+ mDroppedSignal.Emit(control, handle);
}
}
void DragAndDropDetector::EmitEndedSignal(Dali::Toolkit::Control& control)
{
- if( !mEndedSignal.Empty() )
+ if(!mEndedSignal.Empty())
{
- Dali::Toolkit::DragAndDropDetector handle( this );
- mEndedSignal.Emit( control, handle );
+ Dali::Toolkit::DragAndDropDetector handle(this);
+ mEndedSignal.Emit(control, handle);
}
}
mScreenPosition()
{
mPanGestureDetector = Dali::PanGestureDetector::New();
- mPointDown = false;
+ mPointDown = false;
}
DragAndDropDetector::~DragAndDropDetector()
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/feedback/feedback-style.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
+#include <dali/devel-api/adaptor-framework/style-monitor.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/common/vector-wrapper.h>
#include <dali/public-api/object/object-registry.h>
-#include <dali/devel-api/adaptor-framework/style-monitor.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
namespace // unnamed namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::General, false, "LOG_FEEDBACK");
#endif
void GetIfString(const Dali::Toolkit::TreeNode& node, const std::string& name, bool& exists, std::string& str)
{
const Dali::Toolkit::TreeNode* child = node.GetChild(name);
- if( child &&
- Dali::Toolkit::TreeNode::STRING == child->GetType() )
+ if(child &&
+ Dali::Toolkit::TreeNode::STRING == child->GetType())
{
exists = true;
- str = child->GetString();
+ str = child->GetString();
}
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
struct SignalFeedbackInfo
{
/**
* Default constructor.
*/
SignalFeedbackInfo()
- :mHasHapticFeedbackInfo(false),
- mHasSoundFeedbackInfo(false)
+ : mHasHapticFeedbackInfo(false),
+ mHasSoundFeedbackInfo(false)
{
}
- bool mHasHapticFeedbackInfo;
- bool mHasSoundFeedbackInfo;
+ bool mHasHapticFeedbackInfo;
+ bool mHasSoundFeedbackInfo;
std::string mSignalName;
std::string mHapticFeedbackPattern;
std::string mSoundFeedbackPattern;
std::string mSoundFeedbackFile;
};
-typedef std::vector<SignalFeedbackInfo> SignalFeedbackInfoContainer;
+typedef std::vector<SignalFeedbackInfo> SignalFeedbackInfoContainer;
typedef SignalFeedbackInfoContainer::const_iterator SignalFeedbackInfoConstIter;
struct FeedbackStyleInfo
{
mFeedback = Dali::FeedbackPlayer::Get();
- const std::string styleDirPath = AssetManager::GetDaliStylePath();
+ const std::string styleDirPath = AssetManager::GetDaliStylePath();
const std::string defaultThemeFilePath = styleDirPath + DEFAULT_FEEDBACK_THEME_FILE_NAME;
std::string defaultTheme;
- if( mFeedback && mFeedback.LoadFile( defaultThemeFilePath, defaultTheme ) )
+ if(mFeedback && mFeedback.LoadFile(defaultThemeFilePath, defaultTheme))
{
- LoadTheme( defaultTheme );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "ResourceLoader::LoadTheme(%s) - loaded %d bytes\n",
- defaultThemeFilePath.c_str(), defaultTheme.size() );
+ LoadTheme(defaultTheme);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "ResourceLoader::LoadTheme(%s) - loaded %d bytes\n", defaultThemeFilePath.c_str(), defaultTheme.size());
}
else
{
DALI_LOG_ERROR("ResourceLoader::LoadTheme(%s) - failed to load\n", defaultThemeFilePath.c_str());
}
-
}
FeedbackStyle::~FeedbackStyle()
struct PlayFeedbackFromSignal
{
- PlayFeedbackFromSignal( FeedbackStyle& controller, const std::string& typeName, const std::string& signalName )
- : mController( controller ),
- mTypeName( typeName ),
- mSignalName( signalName )
+ PlayFeedbackFromSignal(FeedbackStyle& controller, const std::string& typeName, const std::string& signalName)
+ : mController(controller),
+ mTypeName(typeName),
+ mSignalName(signalName)
{
}
void operator()()
{
- mController.PlayFeedback( mTypeName, mSignalName );
+ mController.PlayFeedback(mTypeName, mSignalName);
}
FeedbackStyle& mController;
- std::string mTypeName;
- std::string mSignalName;
+ std::string mTypeName;
+ std::string mSignalName;
};
-
-void FeedbackStyle::ObjectCreated( BaseHandle handle )
+void FeedbackStyle::ObjectCreated(BaseHandle handle)
{
- if( handle )
+ if(handle)
{
const std::string& type = handle.GetTypeName();
- const FeedbackStyleInfo styleInfo = GetStyleInfo( type );
+ const FeedbackStyleInfo styleInfo = GetStyleInfo(type);
- for( SignalFeedbackInfoConstIter iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter )
+ for(SignalFeedbackInfoConstIter iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter)
{
const SignalFeedbackInfo& info = *iter;
- if( info.mHasHapticFeedbackInfo || info.mHasSoundFeedbackInfo )
+ if(info.mHasHapticFeedbackInfo || info.mHasSoundFeedbackInfo)
{
- if( !info.mHapticFeedbackPattern.empty() || !info.mHapticFeedbackFile.empty() ||
- !info.mSoundFeedbackPattern.empty() || !info.mSoundFeedbackFile.empty() )
+ if(!info.mHapticFeedbackPattern.empty() || !info.mHapticFeedbackFile.empty() ||
+ !info.mSoundFeedbackPattern.empty() || !info.mSoundFeedbackFile.empty())
{
- handle.ConnectSignal( this,
- info.mSignalName,
- PlayFeedbackFromSignal( *this, type, info.mSignalName ) );
+ handle.ConnectSignal(this,
+ info.mSignalName,
+ PlayFeedbackFromSignal(*this, type, info.mSignalName));
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FeedbackStyle::Set found Haptic pattern %s for Object type: %s, Signal Type: %s\n",
- info.mHapticFeedbackPattern.c_str(), type.c_str(), info.mSignalName.c_str() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FeedbackStyle::Set found Haptic pattern %s for Object type: %s, Signal Type: %s\n", info.mHapticFeedbackPattern.c_str(), type.c_str(), info.mSignalName.c_str());
}
else
{
}
}
-const FeedbackStyleInfo& FeedbackStyle::GetStyleInfo( const std::string& type ) const
+const FeedbackStyleInfo& FeedbackStyle::GetStyleInfo(const std::string& type) const
{
- std::map<const std::string, FeedbackStyleInfo>::const_iterator iter( mStyleInfoLut.find( type ) );
- if( iter != mStyleInfoLut.end() )
+ std::map<const std::string, FeedbackStyleInfo>::const_iterator iter(mStyleInfoLut.find(type));
+ if(iter != mStyleInfoLut.end())
{
return iter->second;
}
}
}
-void FeedbackStyle::StyleChanged( const std::string& userDefinedThemePath, Dali::StyleChange::Type styleChange )
+void FeedbackStyle::StyleChanged(const std::string& userDefinedThemePath, Dali::StyleChange::Type styleChange)
{
- if( styleChange == StyleChange::THEME_CHANGE )
+ if(styleChange == StyleChange::THEME_CHANGE)
{
std::string userDefinedTheme;
- if( mFeedback && mFeedback.LoadFile( userDefinedThemePath, userDefinedTheme ) )
+ if(mFeedback && mFeedback.LoadFile(userDefinedThemePath, userDefinedTheme))
{
- if( !LoadTheme( userDefinedTheme ) )
+ if(!LoadTheme(userDefinedTheme))
{
DALI_LOG_ERROR("FeedbackStyle::StyleChanged() User defined theme failed to load! \n");
- const std::string styleDirPath = AssetManager::GetDaliStylePath();
+ const std::string styleDirPath = AssetManager::GetDaliStylePath();
const std::string defaultThemeFilePath = styleDirPath + DEFAULT_FEEDBACK_THEME_FILE_NAME;
//If there is any problem is using the user defined theme, then fall back to default theme
- if( !LoadTheme( defaultThemeFilePath ) )
+ if(!LoadTheme(defaultThemeFilePath))
{
//If the default theme fails, Then No luck!
DALI_LOG_ERROR("FeedbackStyle::StyleChanged() Default theme failed to load! \n");
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "ResourceLoader::LoadTheme(%s) - loaded %d bytes\n",
- userDefinedThemePath.c_str(), userDefinedTheme.size() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "ResourceLoader::LoadTheme(%s) - loaded %d bytes\n", userDefinedThemePath.c_str(), userDefinedTheme.size());
}
}
else
}
}
-bool FeedbackStyle::LoadTheme( const std::string& data )
+bool FeedbackStyle::LoadTheme(const std::string& data)
{
bool result = false;
try
{
- LoadFromString( data );
+ LoadFromString(data);
result = true;
}
catch(...)
{
//Problem in user set theme, So fallback to use default theme.
- DALI_LOG_ERROR( "FeedbackStyle::LoadTheme() Failed to load theme\n" );
+ DALI_LOG_ERROR("FeedbackStyle::LoadTheme() Failed to load theme\n");
}
return result;
}
-void FeedbackStyle::LoadFromString( const std::string& data )
+void FeedbackStyle::LoadFromString(const std::string& data)
{
- Toolkit::JsonParser parser = Toolkit::JsonParser::New();
- const Toolkit::TreeNode* root = NULL;
+ Toolkit::JsonParser parser = Toolkit::JsonParser::New();
+ const Toolkit::TreeNode* root = NULL;
- if( !parser.Parse( data ) )
+ if(!parser.Parse(data))
{
- DALI_LOG_WARNING( "JSON Parse Error:'%s'\n", parser.GetErrorDescription().c_str() );
- DALI_LOG_WARNING( "JSON Parse Line :'%d (%d)'\n",
- parser.GetErrorLineNumber(),
- parser.GetErrorColumn() );
+ DALI_LOG_WARNING("JSON Parse Error:'%s'\n", parser.GetErrorDescription().c_str());
+ DALI_LOG_WARNING("JSON Parse Line :'%d (%d)'\n",
+ parser.GetErrorLineNumber(),
+ parser.GetErrorColumn());
}
else
{
mStyleInfoLut.clear();
// Parse style
- if( const TreeNode* node = root->GetChild("style") )
+ if(const TreeNode* node = root->GetChild("style"))
{
Toolkit::TreeNode::ConstIterator iter = node->CBegin();
- Toolkit::TreeNode::ConstIterator end = node->CEnd();
- for( ; iter != end; ++iter )
+ Toolkit::TreeNode::ConstIterator end = node->CEnd();
+ for(; iter != end; ++iter)
{
- const char* key = (*iter).first;
+ const char* key = (*iter).first;
FeedbackStyleInfo themeInfo;
themeInfo.mTypeName = key;
- if( const TreeNode* signals = (*iter).second.GetChild("signals") )
+ if(const TreeNode* signals = (*iter).second.GetChild("signals"))
{
TreeNode::ConstIterator signalIter = signals->CBegin();
- TreeNode::ConstIterator signalEnd = signals->CEnd();
- for( ; signalIter != signalEnd; ++signalIter )
+ TreeNode::ConstIterator signalEnd = signals->CEnd();
+ for(; signalIter != signalEnd; ++signalIter)
{
SignalFeedbackInfo signalFeedbackInfo;
DALI_ASSERT_ALWAYS(type && TreeNode::STRING == type->GetType() && "Signal must have a type");
signalFeedbackInfo.mSignalName = type->GetString();
- GetIfString( (*signalIter).second, "hapticFeedbackPattern",
- signalFeedbackInfo.mHasHapticFeedbackInfo,
- signalFeedbackInfo.mHapticFeedbackPattern );
+ GetIfString((*signalIter).second, "hapticFeedbackPattern", signalFeedbackInfo.mHasHapticFeedbackInfo, signalFeedbackInfo.mHapticFeedbackPattern);
- GetIfString( (*signalIter).second, "hapticFeedbackFile",
- signalFeedbackInfo.mHasHapticFeedbackInfo,
- signalFeedbackInfo.mHapticFeedbackFile );
+ GetIfString((*signalIter).second, "hapticFeedbackFile", signalFeedbackInfo.mHasHapticFeedbackInfo, signalFeedbackInfo.mHapticFeedbackFile);
- GetIfString( (*signalIter).second, "soundFeedbackPattern",
- signalFeedbackInfo.mHasSoundFeedbackInfo,
- signalFeedbackInfo.mSoundFeedbackPattern );
+ GetIfString((*signalIter).second, "soundFeedbackPattern", signalFeedbackInfo.mHasSoundFeedbackInfo, signalFeedbackInfo.mSoundFeedbackPattern);
- GetIfString( (*signalIter).second, "hapticFeedbackFile",
- signalFeedbackInfo.mHasSoundFeedbackInfo,
- signalFeedbackInfo.mSoundFeedbackFile );
+ GetIfString((*signalIter).second, "hapticFeedbackFile", signalFeedbackInfo.mHasSoundFeedbackInfo, signalFeedbackInfo.mSoundFeedbackFile);
- if( signalFeedbackInfo.mHasHapticFeedbackInfo || signalFeedbackInfo.mHasSoundFeedbackInfo )
+ if(signalFeedbackInfo.mHasHapticFeedbackInfo || signalFeedbackInfo.mHasSoundFeedbackInfo)
{
- AddSignalInfo( themeInfo, std::move( signalFeedbackInfo ) );
+ AddSignalInfo(themeInfo, std::move(signalFeedbackInfo));
}
}
}
mStyleInfoLut[key] = themeInfo;
} // for styles
- } // if(style)
- } // if(root)
+ } // if(style)
+ } // if(root)
} // LoadFromString()
-void FeedbackStyle::AddSignalInfo( FeedbackStyleInfo& styleInfo, SignalFeedbackInfo&& signalInfo )
+void FeedbackStyle::AddSignalInfo(FeedbackStyleInfo& styleInfo, SignalFeedbackInfo&& signalInfo)
{
- bool updated = false;
+ bool updated = false;
SignalFeedbackInfoContainer::iterator iter;
// If info exists for the signal then update it, else add new
- for( iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter )
+ for(iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter)
{
- if( (*iter).mSignalName == signalInfo.mSignalName )
+ if((*iter).mSignalName == signalInfo.mSignalName)
{
(*iter).mHasHapticFeedbackInfo = signalInfo.mHasHapticFeedbackInfo;
(*iter).mHapticFeedbackPattern = signalInfo.mHapticFeedbackPattern;
}
}
- if( !updated )
+ if(!updated)
{
- styleInfo.mSignalFeedbackInfoList.emplace_back( std::move( signalInfo ) );
+ styleInfo.mSignalFeedbackInfoList.emplace_back(std::move(signalInfo));
}
}
void FeedbackStyle::PlayFeedback(const std::string& type, const std::string& signalName)
{
- const FeedbackStyleInfo styleInfo = GetStyleInfo(type);
+ const FeedbackStyleInfo styleInfo = GetStyleInfo(type);
SignalFeedbackInfoConstIter iter;
for(iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter)
{
if(!info.mHapticFeedbackPattern.empty())
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FeedbackStyle::PlayFeedback Playing Haptic effect: Object type: %s, Signal type: %s, pattern type: %s\n",
- type.c_str(), signalName.c_str(), info.mHapticFeedbackPattern.c_str());
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FeedbackStyle::PlayFeedback Playing Haptic effect: Object type: %s, Signal type: %s, pattern type: %s\n", type.c_str(), signalName.c_str(), info.mHapticFeedbackPattern.c_str());
- mFeedback.PlayFeedbackPattern( FEEDBACK_TYPE_VIBRATION, GetFeedbackPattern(info.mHapticFeedbackPattern) );
+ mFeedback.PlayFeedbackPattern(FEEDBACK_TYPE_VIBRATION, GetFeedbackPattern(info.mHapticFeedbackPattern));
}
else if(!info.mHapticFeedbackFile.empty())
{
- mFeedback.PlayFile( info.mHapticFeedbackFile );
+ mFeedback.PlayFile(info.mHapticFeedbackFile);
}
}
{
if(!info.mSoundFeedbackPattern.empty())
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FeedbackStyle::PlayFeedback Playing Sound effect: Object type: %s, Signal type: %s, pattern type: %s\n",
- type.c_str(), signalName.c_str(), info.mHapticFeedbackPattern.c_str());
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FeedbackStyle::PlayFeedback Playing Sound effect: Object type: %s, Signal type: %s, pattern type: %s\n", type.c_str(), signalName.c_str(), info.mHapticFeedbackPattern.c_str());
- mFeedback.PlayFeedbackPattern( FEEDBACK_TYPE_SOUND, GetFeedbackPattern(info.mSoundFeedbackPattern) );
+ mFeedback.PlayFeedbackPattern(FEEDBACK_TYPE_SOUND, GetFeedbackPattern(info.mSoundFeedbackPattern));
}
else if(!info.mSoundFeedbackFile.empty())
{
- mFeedback.PlaySound( info.mSoundFeedbackFile );
+ mFeedback.PlaySound(info.mSoundFeedbackFile);
}
}
}
}
-FeedbackPattern FeedbackStyle::GetFeedbackPattern( const std::string &pattern )
+FeedbackPattern FeedbackStyle::GetFeedbackPattern(const std::string& pattern)
{
- if( 0 == mFeedbackPatternLut.size() )
+ if(0 == mFeedbackPatternLut.size())
{
mFeedbackPatternLut["FEEDBACK_PATTERN_NONE"] = Dali::FEEDBACK_PATTERN_NONE;
mFeedbackPatternLut["FEEDBACK_PATTERN_TAP"] = Dali::FEEDBACK_PATTERN_TAP;
mFeedbackPatternLut["FEEDBACK_PATTERN_SLIDER_SWEEP"] = Dali::FEEDBACK_PATTERN_SLIDER_SWEEP;
}
- std::map<const std::string, FeedbackPattern>::const_iterator iter( mFeedbackPatternLut.find( pattern ) );
+ std::map<const std::string, FeedbackPattern>::const_iterator iter(mFeedbackPatternLut.find(pattern));
- if( iter != mFeedbackPatternLut.end() )
+ if(iter != mFeedbackPatternLut.end())
{
return iter->second;
}
else
{
- DALI_LOG_ERROR( "Unknown feedback pattern type: %s, So Defaulting to FEEDBACK_PATTERN_NONE!\n" );
+ DALI_LOG_ERROR("Unknown feedback pattern type: %s, So Defaulting to FEEDBACK_PATTERN_NONE!\n");
return Dali::FEEDBACK_PATTERN_NONE;
}
}
-} // namespace Toolkit
-
} // namespace Internal
+} // namespace Toolkit
+
} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "blur-two-pass-filter.h"
// EXTERNAL INCLUDES
-#include <sstream>
-#include <dali/public-api/animation/constraints.h>
#include <dali/devel-api/common/stage.h>
+#include <dali/public-api/animation/constraints.h>
#include <dali/public-api/object/property-map.h>
#include <dali/public-api/render-tasks/render-task-list.h>
#include <dali/public-api/rendering/renderer.h>
+#include <sstream>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/controls/control/control-renderers.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
+const float DEFAULT_KERNEL0[] = {12.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f};
-const float DEFAULT_KERNEL0[] = { 12.0f/16.0f, 2.0f/16.0f, 2.0f/16.0f };
+const float DEFAULT_KERNEL1[] = {8.0f / 16.0f, 2.75f / 16.0f, 2.75f / 16.0f, 1.25f / 16.0f, 1.25f / 16.0f};
-const float DEFAULT_KERNEL1[] = { 8.0f/16.0f, 2.75f/16.0f, 2.75f/16.0f, 1.25f/16.0f,
- 1.25f/16.0f };
+const float DEFAULT_KERNEL2[] = {5.0f / 16.0f, 2.75f / 16.0f, 2.75f / 16.0f, 1.75f / 16.0f, 1.75f / 16.0f, 1.5f / 16.0f, 1.5f / 16.0f};
-const float DEFAULT_KERNEL2[] = { 5.0f/16.0f, 2.75f/16.0f, 2.75f/16.0f, 1.75f/16.0f,
- 1.75f/16.0f, 1.5f/16.0f, 1.5f/16.0f };
+const float DEFAULT_KERNEL3[] = {3.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 0.5f / 16.0f, 0.5f / 16.0f};
-const float DEFAULT_KERNEL3[] = { 3.0f/16.0f, 2.0f/16.0f, 2.0f/16.0f, 2.0f/16.0f,
- 2.0f/16.0f, 2.0f/16.0f, 2.0f/16.0f, 0.5f/16.0f,
- 0.5f/16.0f };
+const float DEFAULT_KERNEL4[] = {2.0f / 16.0f, 1.5f / 16.0f, 1.5f / 16.0f, 1.5f / 16.0f, 1.5f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 0.5f / 16.0f, 0.5f / 16.0f, 0.5f / 16.0f, 0.5f / 16.0f};
-const float DEFAULT_KERNEL4[] = { 2.0f/16.0f, 1.5f/16.0f, 1.5f/16.0f, 1.5f/16.0f,
- 1.5f/16.0f, 1.0f/16.0f, 1.0f/16.0f, 1.0f/16.0f,
- 1.0f/16.0f, 1.0f/16.0f, 1.0f/16.0f, 0.5f/16.0f,
- 0.5f/16.0f, 0.5f/16.0f, 0.5f/16.0f };
-
-std::string GetOffsetUniformName( int index )
+std::string GetOffsetUniformName(int index)
{
std::ostringstream oss;
oss << "uSampleOffsets[" << index << "]";
return oss.str();
}
-std::string GetWeightUniformName( int index )
+std::string GetWeightUniformName(int index)
{
std::ostringstream oss;
oss << "uSampleWeights[" << index << "]";
return oss.str();
}
-const char* const BLUR_STRENGTH_UNIFORM_NAME( "uBlurStrength" );
-const char* const EFFECT_IMAGE_NAME( "sEffect" );
+const char* const BLUR_STRENGTH_UNIFORM_NAME("uBlurStrength");
+const char* const EFFECT_IMAGE_NAME("sEffect");
} // namespace
-
BlurTwoPassFilter::BlurTwoPassFilter()
: ImageFilter()
{
// create blending actor and register the property in constructor
// to make sure that GetBlurStrengthPropertyIndex() always returns a valid index
- mActorForBlending = Actor::New();
- mBlurStrengthPropertyIndex = mActorForBlending.RegisterProperty( BLUR_STRENGTH_UNIFORM_NAME, 1.f );
+ mActorForBlending = Actor::New();
+ mBlurStrengthPropertyIndex = mActorForBlending.RegisterProperty(BLUR_STRENGTH_UNIFORM_NAME, 1.f);
}
BlurTwoPassFilter::~BlurTwoPassFilter()
void BlurTwoPassFilter::Enable()
{
// create custom shader effect
- if( !GetKernelSize() )
+ if(!GetKernelSize())
{
- CreateKernel( DEFAULT_KERNEL4, sizeof(DEFAULT_KERNEL4)/sizeof(DEFAULT_KERNEL4[0]) );
+ CreateKernel(DEFAULT_KERNEL4, sizeof(DEFAULT_KERNEL4) / sizeof(DEFAULT_KERNEL4[0]));
}
- int kernelSize( static_cast< int >(GetKernelSize()) );
+ int kernelSize(static_cast<int>(GetKernelSize()));
// Set up blur-two-pass custom shader
std::ostringstream sstream;
sstream << "#define NUM_SAMPLES " << kernelSize << "\n";
sstream << SHADER_BLUR_TWO_PASS_SHADER_FRAG;
- std::string fragmentSource( sstream.str() );
+ std::string fragmentSource(sstream.str());
// create actor to render input with applied emboss effect
mActorForInput = Actor::New();
- mActorForInput.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActorForInput.SetProperty( Actor::Property::SIZE, mTargetSize );
- Renderer rendererForInput = CreateRenderer( BASIC_VERTEX_SOURCE, fragmentSource.c_str() );
- SetRendererTexture( rendererForInput, mInputTexture );
- mActorForInput.AddRenderer( rendererForInput );
+ mActorForInput.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActorForInput.SetProperty(Actor::Property::SIZE, mTargetSize);
+ Renderer rendererForInput = CreateRenderer(BASIC_VERTEX_SOURCE, fragmentSource.c_str());
+ SetRendererTexture(rendererForInput, mInputTexture);
+ mActorForInput.AddRenderer(rendererForInput);
// create internal offscreen for result of horizontal pass
- mFrameBufferForHorz = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture textureForHorz = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mFrameBufferForHorz.AttachColorTexture( textureForHorz );
+ mFrameBufferForHorz = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture textureForHorz = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mFrameBufferForHorz.AttachColorTexture(textureForHorz);
// create an actor to render mImageForHorz for vertical blur pass
mActorForHorz = Actor::New();
- mActorForHorz.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActorForHorz.SetProperty( Actor::Property::SIZE, mTargetSize );
- Renderer rendererForHorz = CreateRenderer( BASIC_VERTEX_SOURCE, fragmentSource.c_str() );
- SetRendererTexture( rendererForHorz, textureForHorz );
- mActorForHorz.AddRenderer( rendererForHorz );
+ mActorForHorz.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActorForHorz.SetProperty(Actor::Property::SIZE, mTargetSize);
+ Renderer rendererForHorz = CreateRenderer(BASIC_VERTEX_SOURCE, fragmentSource.c_str());
+ SetRendererTexture(rendererForHorz, textureForHorz);
+ mActorForHorz.AddRenderer(rendererForHorz);
// create internal offscreen for result of the two pass blurred image
- mBlurredFrameBuffer = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture blurredTexture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mBlurredFrameBuffer.AttachColorTexture( blurredTexture );
+ mBlurredFrameBuffer = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture blurredTexture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mBlurredFrameBuffer.AttachColorTexture(blurredTexture);
// create an actor to blend the blurred image and the input image with the given blur strength
- Renderer rendererForBlending = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_BLUR_TWO_IMAGES_SHADER_FRAG );
+ Renderer rendererForBlending = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_BLUR_TWO_IMAGES_SHADER_FRAG);
TextureSet textureSetForBlending = rendererForBlending.GetTextures();
- textureSetForBlending.SetTexture( 0u, blurredTexture );
- textureSetForBlending.SetTexture( 1u, mInputTexture );
- mActorForBlending.AddRenderer( rendererForBlending );
- mActorForBlending.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActorForBlending.SetProperty( Actor::Property::SIZE, mTargetSize );
+ textureSetForBlending.SetTexture(0u, blurredTexture);
+ textureSetForBlending.SetTexture(1u, mInputTexture);
+ mActorForBlending.AddRenderer(rendererForBlending);
+ mActorForBlending.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActorForBlending.SetProperty(Actor::Property::SIZE, mTargetSize);
- for( int i = 0; i < kernelSize; ++i )
+ for(int i = 0; i < kernelSize; ++i)
{
- const std::string offsetUniform( GetOffsetUniformName( i ) );
- const std::string weightUniform( GetWeightUniformName( i ) );
+ const std::string offsetUniform(GetOffsetUniformName(i));
+ const std::string weightUniform(GetWeightUniformName(i));
- mActorForInput.RegisterProperty( offsetUniform, Vector2(mKernel[i]) * Vector2::XAXIS );
- mActorForInput.RegisterProperty( weightUniform, mKernel[i].z );
+ mActorForInput.RegisterProperty(offsetUniform, Vector2(mKernel[i]) * Vector2::XAXIS);
+ mActorForInput.RegisterProperty(weightUniform, mKernel[i].z);
- mActorForHorz.RegisterProperty( offsetUniform, Vector2(mKernel[i]) * Vector2::YAXIS );
- mActorForHorz.RegisterProperty( weightUniform, mKernel[i].z );
+ mActorForHorz.RegisterProperty(offsetUniform, Vector2(mKernel[i]) * Vector2::YAXIS);
+ mActorForHorz.RegisterProperty(weightUniform, mKernel[i].z);
}
- mRootActor.Add( mActorForInput );
- mRootActor.Add( mActorForHorz );
- mRootActor.Add( mActorForBlending );
+ mRootActor.Add(mActorForInput);
+ mRootActor.Add(mActorForHorz);
+ mRootActor.Add(mActorForBlending);
SetupCamera();
CreateRenderTasks();
void BlurTwoPassFilter::Disable()
{
- if( mRootActor )
+ if(mRootActor)
{
- if( mCameraActor )
+ if(mCameraActor)
{
- mRootActor.Remove( mCameraActor );
+ mRootActor.Remove(mCameraActor);
mCameraActor.Reset();
}
- if( mActorForInput )
+ if(mActorForInput)
{
- mRootActor.Remove( mActorForInput );
+ mRootActor.Remove(mActorForInput);
mActorForInput.Reset();
}
- if( mActorForHorz )
+ if(mActorForHorz)
{
- mRootActor.Remove( mActorForHorz );
+ mRootActor.Remove(mActorForHorz);
mActorForHorz.Reset();
}
RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
- if( mRenderTaskForHorz )
+ if(mRenderTaskForHorz)
{
taskList.RemoveTask(mRenderTaskForHorz);
}
- if( mRenderTaskForVert )
+ if(mRenderTaskForVert)
{
taskList.RemoveTask(mRenderTaskForVert);
}
- if( mRenderTaskForBlending )
+ if(mRenderTaskForBlending)
{
taskList.RemoveTask(mRenderTaskForBlending);
}
void BlurTwoPassFilter::Refresh()
{
- if( mRenderTaskForHorz )
+ if(mRenderTaskForHorz)
{
- mRenderTaskForHorz.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
+ mRenderTaskForHorz.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
}
- if( mRenderTaskForVert )
+ if(mRenderTaskForVert)
{
- mRenderTaskForVert.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
+ mRenderTaskForVert.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
}
- if( mRenderTaskForBlending )
+ if(mRenderTaskForBlending)
{
- mRenderTaskForBlending.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
+ mRenderTaskForBlending.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
}
}
-void BlurTwoPassFilter::SetSize( const Vector2& size )
+void BlurTwoPassFilter::SetSize(const Vector2& size)
{
mTargetSize = size;
- if( mActorForInput )
+ if(mActorForInput)
{
- mActorForInput.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForInput.SetProperty(Actor::Property::SIZE, mTargetSize);
}
- if( mActorForHorz )
+ if(mActorForHorz)
{
- mActorForHorz.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForHorz.SetProperty(Actor::Property::SIZE, mTargetSize);
}
- if( mActorForBlending )
+ if(mActorForBlending)
{
- mActorForBlending.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForBlending.SetProperty(Actor::Property::SIZE, mTargetSize);
}
}
// perform a horizontal blur targeting the internal buffer
mRenderTaskForHorz = taskList.CreateTask();
- mRenderTaskForHorz.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForHorz.SetSourceActor( mActorForInput );
+ mRenderTaskForHorz.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForHorz.SetSourceActor(mActorForInput);
mRenderTaskForHorz.SetExclusive(true);
- mRenderTaskForHorz.SetInputEnabled( false );
- mRenderTaskForHorz.SetClearEnabled( true );
- mRenderTaskForHorz.SetClearColor( mBackgroundColor );
- mRenderTaskForHorz.SetFrameBuffer( mFrameBufferForHorz );
- mRenderTaskForHorz.SetCameraActor( mCameraActor );
+ mRenderTaskForHorz.SetInputEnabled(false);
+ mRenderTaskForHorz.SetClearEnabled(true);
+ mRenderTaskForHorz.SetClearColor(mBackgroundColor);
+ mRenderTaskForHorz.SetFrameBuffer(mFrameBufferForHorz);
+ mRenderTaskForHorz.SetCameraActor(mCameraActor);
// use the internal buffer and perform a horizontal blur targeting the output buffer
mRenderTaskForVert = taskList.CreateTask();
- mRenderTaskForVert.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForVert.SetSourceActor( mActorForHorz );
+ mRenderTaskForVert.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForVert.SetSourceActor(mActorForHorz);
mRenderTaskForVert.SetExclusive(true);
- mRenderTaskForVert.SetInputEnabled( false );
- mRenderTaskForVert.SetClearEnabled( true );
- mRenderTaskForVert.SetClearColor( mBackgroundColor );
- mRenderTaskForVert.SetFrameBuffer( mBlurredFrameBuffer );
- mRenderTaskForVert.SetCameraActor( mCameraActor );
+ mRenderTaskForVert.SetInputEnabled(false);
+ mRenderTaskForVert.SetClearEnabled(true);
+ mRenderTaskForVert.SetClearColor(mBackgroundColor);
+ mRenderTaskForVert.SetFrameBuffer(mBlurredFrameBuffer);
+ mRenderTaskForVert.SetCameraActor(mCameraActor);
//Perform a blending between the blurred image and the input image
mRenderTaskForBlending = taskList.CreateTask();
- mRenderTaskForBlending.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForBlending.SetSourceActor( mActorForBlending );
+ mRenderTaskForBlending.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForBlending.SetSourceActor(mActorForBlending);
mRenderTaskForBlending.SetExclusive(true);
- mRenderTaskForBlending.SetInputEnabled( false );
- mRenderTaskForBlending.SetClearEnabled( true );
- mRenderTaskForBlending.SetClearColor( mBackgroundColor );
- mRenderTaskForBlending.SetFrameBuffer( mOutputFrameBuffer );
- mRenderTaskForBlending.SetCameraActor( mCameraActor );
+ mRenderTaskForBlending.SetInputEnabled(false);
+ mRenderTaskForBlending.SetClearEnabled(true);
+ mRenderTaskForBlending.SetClearColor(mBackgroundColor);
+ mRenderTaskForBlending.SetFrameBuffer(mOutputFrameBuffer);
+ mRenderTaskForBlending.SetCameraActor(mCameraActor);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "emboss-filter.h"
// EXTERNAL INCLUDES
-#include <sstream>
-#include <dali/public-api/animation/constraints.h>
#include <dali/devel-api/common/stage.h>
+#include <dali/public-api/animation/constraints.h>
#include <dali/public-api/object/property-map.h>
#include <dali/public-api/render-tasks/render-task-list.h>
#include <dali/public-api/rendering/renderer.h>
+#include <sstream>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/controls/control/control-renderers.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-const char* const TEX_SCALE_UNIFORM_NAME( "uTexScale" );
-const char* const COEFFICIENT_UNIFORM_NAME( "uCoefficient" );
-const char* const COLOR_UNIFORM_NAME( "uEffectColor" );
+const char* const TEX_SCALE_UNIFORM_NAME("uTexScale");
+const char* const COEFFICIENT_UNIFORM_NAME("uCoefficient");
+const char* const COLOR_UNIFORM_NAME("uEffectColor");
} // namespace
void EmbossFilter::Enable()
{
- mFrameBufferForEmboss1 = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture texture1 = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mFrameBufferForEmboss1.AttachColorTexture( texture1 );
+ mFrameBufferForEmboss1 = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture texture1 = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mFrameBufferForEmboss1.AttachColorTexture(texture1);
- mFrameBufferForEmboss2 = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture texture2 = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mFrameBufferForEmboss2.AttachColorTexture( texture2 );
+ mFrameBufferForEmboss2 = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture texture2 = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mFrameBufferForEmboss2.AttachColorTexture(texture2);
// create actor to render input with applied emboss effect
mActorForInput1 = Actor::New();
- mActorForInput1.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActorForInput1.SetProperty( Actor::Property::SIZE, mTargetSize);
- Vector2 textureScale( 1.5f/mTargetSize.width, 1.5f/mTargetSize.height);
- mActorForInput1.RegisterProperty( TEX_SCALE_UNIFORM_NAME, textureScale );
- mActorForInput1.RegisterProperty( COEFFICIENT_UNIFORM_NAME, Vector3( 2.f, -1.f, -1.f ) );
+ mActorForInput1.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActorForInput1.SetProperty(Actor::Property::SIZE, mTargetSize);
+ Vector2 textureScale(1.5f / mTargetSize.width, 1.5f / mTargetSize.height);
+ mActorForInput1.RegisterProperty(TEX_SCALE_UNIFORM_NAME, textureScale);
+ mActorForInput1.RegisterProperty(COEFFICIENT_UNIFORM_NAME, Vector3(2.f, -1.f, -1.f));
// set EMBOSS custom shader
- Renderer renderer1 = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_SHADER_FRAG );
- SetRendererTexture( renderer1, mInputTexture );
- mActorForInput1.AddRenderer( renderer1 );
- mRootActor.Add( mActorForInput1 );
+ Renderer renderer1 = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_SHADER_FRAG);
+ SetRendererTexture(renderer1, mInputTexture);
+ mActorForInput1.AddRenderer(renderer1);
+ mRootActor.Add(mActorForInput1);
mActorForInput2 = Actor::New();
- mActorForInput2.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActorForInput2.SetProperty( Actor::Property::SIZE, mTargetSize);
- mActorForInput2.RegisterProperty( TEX_SCALE_UNIFORM_NAME, textureScale );
- mActorForInput2.RegisterProperty( COEFFICIENT_UNIFORM_NAME, Vector3( -1.f, -1.f, 2.f ) );
+ mActorForInput2.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActorForInput2.SetProperty(Actor::Property::SIZE, mTargetSize);
+ mActorForInput2.RegisterProperty(TEX_SCALE_UNIFORM_NAME, textureScale);
+ mActorForInput2.RegisterProperty(COEFFICIENT_UNIFORM_NAME, Vector3(-1.f, -1.f, 2.f));
// set EMBOSS custom shader
- Renderer renderer2 = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_SHADER_FRAG );
- SetRendererTexture( renderer2, mInputTexture );
- mActorForInput2.AddRenderer( renderer2 );
- mRootActor.Add( mActorForInput2 );
+ Renderer renderer2 = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_SHADER_FRAG);
+ SetRendererTexture(renderer2, mInputTexture);
+ mActorForInput2.AddRenderer(renderer2);
+ mRootActor.Add(mActorForInput2);
mActorForComposite = Actor::New();
- mActorForComposite.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActorForComposite.SetProperty( Actor::Property::SIZE, mTargetSize);
- mActorForComposite.SetProperty( Actor::Property::COLOR, Color::BLACK );
+ mActorForComposite.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActorForComposite.SetProperty(Actor::Property::SIZE, mTargetSize);
+ mActorForComposite.SetProperty(Actor::Property::COLOR, Color::BLACK);
- mRootActor.Add( mActorForComposite );
+ mRootActor.Add(mActorForComposite);
- mRendererForEmboss1 = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_COMPOSITE_SHADER_FRAG );
- SetRendererTexture( mRendererForEmboss1, mFrameBufferForEmboss1 );
- mRendererForEmboss1.RegisterProperty( COLOR_UNIFORM_NAME, Color::BLACK );
- mActorForComposite.AddRenderer( mRendererForEmboss1 );
+ mRendererForEmboss1 = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_COMPOSITE_SHADER_FRAG);
+ SetRendererTexture(mRendererForEmboss1, mFrameBufferForEmboss1);
+ mRendererForEmboss1.RegisterProperty(COLOR_UNIFORM_NAME, Color::BLACK);
+ mActorForComposite.AddRenderer(mRendererForEmboss1);
- mRendererForEmboss2 = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_COMPOSITE_SHADER_FRAG );
- SetRendererTexture( mRendererForEmboss2, mFrameBufferForEmboss2 );
- mRendererForEmboss2.RegisterProperty( COLOR_UNIFORM_NAME, Color::WHITE );
- mActorForComposite.AddRenderer( mRendererForEmboss2 );
+ mRendererForEmboss2 = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_COMPOSITE_SHADER_FRAG);
+ SetRendererTexture(mRendererForEmboss2, mFrameBufferForEmboss2);
+ mRendererForEmboss2.RegisterProperty(COLOR_UNIFORM_NAME, Color::WHITE);
+ mActorForComposite.AddRenderer(mRendererForEmboss2);
SetupCamera();
CreateRenderTasks();
void EmbossFilter::Disable()
{
- if( mRootActor )
+ if(mRootActor)
{
- if( mCameraActor )
+ if(mCameraActor)
{
- mRootActor.Remove( mCameraActor );
+ mRootActor.Remove(mCameraActor);
mCameraActor.Reset();
}
- if( mActorForInput1 )
+ if(mActorForInput1)
{
- mRootActor.Remove( mActorForInput1 );
+ mRootActor.Remove(mActorForInput1);
mActorForInput1.Reset();
}
- if( mActorForInput2 )
+ if(mActorForInput2)
{
- mRootActor.Remove( mActorForInput2 );
+ mRootActor.Remove(mActorForInput2);
mActorForInput2.Reset();
}
- if( mActorForComposite )
+ if(mActorForComposite)
{
- mActorForComposite.RemoveRenderer( mRendererForEmboss1 );
+ mActorForComposite.RemoveRenderer(mRendererForEmboss1);
mRendererForEmboss1.Reset();
- mActorForComposite.RemoveRenderer( mRendererForEmboss2 );
+ mActorForComposite.RemoveRenderer(mRendererForEmboss2);
mRendererForEmboss2.Reset();
- mRootActor.Remove( mActorForComposite );
+ mRootActor.Remove(mActorForComposite);
mActorForComposite.Reset();
}
RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
- if( mRenderTaskForEmboss1 )
+ if(mRenderTaskForEmboss1)
{
taskList.RemoveTask(mRenderTaskForEmboss1);
}
- if( mRenderTaskForEmboss2 )
+ if(mRenderTaskForEmboss2)
{
taskList.RemoveTask(mRenderTaskForEmboss2);
}
- if( mRenderTaskForOutput )
+ if(mRenderTaskForOutput)
{
- taskList.RemoveTask( mRenderTaskForOutput );
+ taskList.RemoveTask(mRenderTaskForOutput);
}
mRootActor.Reset();
void EmbossFilter::Refresh()
{
- if( mRenderTaskForEmboss1 )
+ if(mRenderTaskForEmboss1)
{
- mRenderTaskForEmboss1.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
+ mRenderTaskForEmboss1.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
}
- if( mRenderTaskForEmboss2 )
+ if(mRenderTaskForEmboss2)
{
- mRenderTaskForEmboss2.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
+ mRenderTaskForEmboss2.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
}
}
-void EmbossFilter::SetSize( const Vector2& size )
+void EmbossFilter::SetSize(const Vector2& size)
{
mTargetSize = size;
- if( mActorForInput1 )
+ if(mActorForInput1)
{
- mActorForInput1.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForInput1.SetProperty(Actor::Property::SIZE, mTargetSize);
}
- if( mActorForInput2 )
+ if(mActorForInput2)
{
- mActorForInput2.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForInput2.SetProperty(Actor::Property::SIZE, mTargetSize);
}
- if( mActorForComposite )
+ if(mActorForComposite)
{
- mActorForComposite.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForComposite.SetProperty(Actor::Property::SIZE, mTargetSize);
}
}
RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
mRenderTaskForEmboss1 = taskList.CreateTask();
- mRenderTaskForEmboss1.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForEmboss1.SetSourceActor( mActorForInput1 );
+ mRenderTaskForEmboss1.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForEmboss1.SetSourceActor(mActorForInput1);
mRenderTaskForEmboss1.SetExclusive(true);
- mRenderTaskForEmboss1.SetInputEnabled( false );
- mRenderTaskForEmboss1.SetClearColor( Vector4( 0.0f, 0.0f, 0.0f, 0.0f ) );
- mRenderTaskForEmboss1.SetClearEnabled( true );
- mRenderTaskForEmboss1.SetFrameBuffer( mFrameBufferForEmboss1 );
- mRenderTaskForEmboss1.SetCameraActor( mCameraActor );
+ mRenderTaskForEmboss1.SetInputEnabled(false);
+ mRenderTaskForEmboss1.SetClearColor(Vector4(0.0f, 0.0f, 0.0f, 0.0f));
+ mRenderTaskForEmboss1.SetClearEnabled(true);
+ mRenderTaskForEmboss1.SetFrameBuffer(mFrameBufferForEmboss1);
+ mRenderTaskForEmboss1.SetCameraActor(mCameraActor);
mRenderTaskForEmboss2 = taskList.CreateTask();
- mRenderTaskForEmboss2.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForEmboss2.SetSourceActor( mActorForInput2 );
+ mRenderTaskForEmboss2.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForEmboss2.SetSourceActor(mActorForInput2);
mRenderTaskForEmboss2.SetExclusive(true);
- mRenderTaskForEmboss2.SetInputEnabled( false );
- mRenderTaskForEmboss2.SetClearColor( Vector4( 1.0f, 1.0f, 1.0f, 0.0f ) );
- mRenderTaskForEmboss2.SetClearEnabled( true );
- mRenderTaskForEmboss2.SetFrameBuffer( mFrameBufferForEmboss2 );
- mRenderTaskForEmboss2.SetCameraActor( mCameraActor );
+ mRenderTaskForEmboss2.SetInputEnabled(false);
+ mRenderTaskForEmboss2.SetClearColor(Vector4(1.0f, 1.0f, 1.0f, 0.0f));
+ mRenderTaskForEmboss2.SetClearEnabled(true);
+ mRenderTaskForEmboss2.SetFrameBuffer(mFrameBufferForEmboss2);
+ mRenderTaskForEmboss2.SetCameraActor(mCameraActor);
mRenderTaskForOutput = taskList.CreateTask();
- mRenderTaskForOutput.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForOutput.SetSourceActor( mActorForComposite );
+ mRenderTaskForOutput.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForOutput.SetSourceActor(mActorForComposite);
mRenderTaskForOutput.SetExclusive(true);
- mRenderTaskForOutput.SetInputEnabled( false );
- mRenderTaskForOutput.SetClearColor( Vector4( 0.5f, 0.5f, 0.5f, 0.0f ) );
- mRenderTaskForOutput.SetClearEnabled( true );
- mRenderTaskForOutput.SetFrameBuffer( mOutputFrameBuffer );
- mRenderTaskForOutput.SetCameraActor( mCameraActor );
+ mRenderTaskForOutput.SetInputEnabled(false);
+ mRenderTaskForOutput.SetClearColor(Vector4(0.5f, 0.5f, 0.5f, 0.0f));
+ mRenderTaskForOutput.SetClearEnabled(true);
+ mRenderTaskForOutput.SetFrameBuffer(mOutputFrameBuffer);
+ mRenderTaskForOutput.SetCameraActor(mCameraActor);
}
} // namespace Internal
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f;
} // namespace
ImageFilter::ImageFilter()
-: mBackgroundColor( Vector4( 1.0f, 1.0f, 1.0f, 0.0f ) ),
- mTargetSize( Vector2::ZERO ),
- mPixelFormat( Pixel::RGBA8888 ),
- mRefreshOnDemand( false )
+: mBackgroundColor(Vector4(1.0f, 1.0f, 1.0f, 0.0f)),
+ mTargetSize(Vector2::ZERO),
+ mPixelFormat(Pixel::RGBA8888),
+ mRefreshOnDemand(false)
{
}
{
}
-void ImageFilter::SetRefreshOnDemand( bool onDemand )
+void ImageFilter::SetRefreshOnDemand(bool onDemand)
{
mRefreshOnDemand = onDemand;
}
-void ImageFilter::SetInputTexture( Texture texture )
+void ImageFilter::SetInputTexture(Texture texture)
{
mInputTexture = texture;
}
-void ImageFilter::SetOutputFrameBuffer( FrameBuffer frameBuffer )
+void ImageFilter::SetOutputFrameBuffer(FrameBuffer frameBuffer)
{
mOutputFrameBuffer = frameBuffer;
}
-void ImageFilter::SetSize( const Vector2& size )
+void ImageFilter::SetSize(const Vector2& size)
{
mTargetSize = size;
}
-void ImageFilter::SetPixelFormat( Pixel::Format pixelFormat )
+void ImageFilter::SetPixelFormat(Pixel::Format pixelFormat)
{
mPixelFormat = pixelFormat;
}
-void ImageFilter::SetKernel( const FilterKernel& kernel )
+void ImageFilter::SetKernel(const FilterKernel& kernel)
{
mKernel = kernel;
}
return mKernel.size();
}
-void ImageFilter::CreateKernel( const float* weights, size_t count )
+void ImageFilter::CreateKernel(const float* weights, size_t count)
{
- if( (mTargetSize.width * mTargetSize.height ) > 0.0f )
+ if((mTargetSize.width * mTargetSize.height) > 0.0f)
{
- Vector2 pixelsToUV( 1.0f / mTargetSize.width, 1.0f / mTargetSize.height );
+ Vector2 pixelsToUV(1.0f / mTargetSize.width, 1.0f / mTargetSize.height);
mKernel.clear();
- mKernel.push_back( Vector3( 0.0f, 0.0f, weights[0] ) );
- for( size_t i = 0; i < count >> 1; ++i )
+ mKernel.push_back(Vector3(0.0f, 0.0f, weights[0]));
+ for(size_t i = 0; i < count >> 1; ++i)
{
float offset = 1.5f + (i << 1);
- mKernel.push_back( Vector3( pixelsToUV.x * offset, pixelsToUV.y * offset, weights[(i << 1) + 1] ) );
- mKernel.push_back( Vector3( -pixelsToUV.x * offset, -pixelsToUV.y * offset, weights[(i << 1) + 2] ) );
+ mKernel.push_back(Vector3(pixelsToUV.x * offset, pixelsToUV.y * offset, weights[(i << 1) + 1]));
+ mKernel.push_back(Vector3(-pixelsToUV.x * offset, -pixelsToUV.y * offset, weights[(i << 1) + 2]));
}
}
}
-void ImageFilter::SetRootActor( Actor rootActor )
+void ImageFilter::SetRootActor(Actor rootActor)
{
mRootActor = rootActor;
}
-void ImageFilter::SetBackgroundColor( const Vector4& color )
+void ImageFilter::SetBackgroundColor(const Vector4& color)
{
mBackgroundColor = color;
}
void ImageFilter::SetupCamera()
{
- if( !mCameraActor )
+ if(!mCameraActor)
{
// create a camera for the render task, corresponding to its render target size
mCameraActor = CameraActor::New(mTargetSize);
- mCameraActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mCameraActor.SetInvertYAxis( true );
- mRootActor.Add( mCameraActor );
+ mCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mCameraActor.SetInvertYAxis(true);
+ mRootActor.Add(mCameraActor);
}
else
{
mCameraActor.SetNearClippingPlane(1.0f);
mCameraActor.SetAspectRatio(mTargetSize.width / mTargetSize.height);
mCameraActor.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
- mCameraActor.SetProperty( Actor::Property::POSITION, Vector3( 0.0f, 0.0f, ( (mTargetSize.height * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f) ) ) );
+ mCameraActor.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, ((mTargetSize.height * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f))));
}
}
-
} // namespace Internal
} // namespace Toolkit
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "spread-filter.h"
// EXTERNAL INCLUDES
-#include <dali/public-api/animation/constraints.h>
#include <dali/devel-api/common/stage.h>
+#include <dali/public-api/animation/constraints.h>
#include <dali/public-api/object/property-map.h>
#include <dali/public-api/render-tasks/render-task-list.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-const char* const SPREAD_UNIFORM_NAME( "uSpread" );
-const char* const TEX_SCALE_UNIFORM_NAME( "uTexScale" );
+const char* const SPREAD_UNIFORM_NAME("uSpread");
+const char* const TEX_SCALE_UNIFORM_NAME("uTexScale");
} // namespace
-
SpreadFilter::SpreadFilter()
: ImageFilter(),
mSpread(2)
{
}
-void SpreadFilter::SetSpread( float spread )
+void SpreadFilter::SetSpread(float spread)
{
mSpread = spread;
}
{
// create actor to render input with applied emboss effect
mActorForInput = Actor::New();
- mActorForInput.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActorForInput.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForInput.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActorForInput.SetProperty(Actor::Property::SIZE, mTargetSize);
// register properties as shader uniforms
- mActorForInput.RegisterProperty( SPREAD_UNIFORM_NAME, mSpread );
- mActorForInput.RegisterProperty( TEX_SCALE_UNIFORM_NAME, Vector2( 1.0f / mTargetSize.width, 0.0f ) );
+ mActorForInput.RegisterProperty(SPREAD_UNIFORM_NAME, mSpread);
+ mActorForInput.RegisterProperty(TEX_SCALE_UNIFORM_NAME, Vector2(1.0f / mTargetSize.width, 0.0f));
- Renderer rendererForInput = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_SPREAD_FILTER_SHADER_FRAG );
- SetRendererTexture( rendererForInput, mInputTexture );
- mActorForInput.AddRenderer( rendererForInput );
+ Renderer rendererForInput = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_SPREAD_FILTER_SHADER_FRAG);
+ SetRendererTexture(rendererForInput, mInputTexture);
+ mActorForInput.AddRenderer(rendererForInput);
// create internal offscreen for result of horizontal pass
- mFrameBufferForHorz = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE );
- Texture textureForHorz = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) );
- mFrameBufferForHorz.AttachColorTexture( textureForHorz );
+ mFrameBufferForHorz = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE);
+ Texture textureForHorz = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height));
+ mFrameBufferForHorz.AttachColorTexture(textureForHorz);
// create an actor to render mImageForHorz for vertical blur pass
mActorForHorz = Actor::New();
- mActorForHorz.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActorForHorz.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForHorz.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActorForHorz.SetProperty(Actor::Property::SIZE, mTargetSize);
// register properties as shader uniforms
- mActorForHorz.RegisterProperty( SPREAD_UNIFORM_NAME, mSpread );
- mActorForHorz.RegisterProperty( TEX_SCALE_UNIFORM_NAME, Vector2( 0.0f, 1.0f / mTargetSize.height ) );
- Renderer rendererForHorz = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_SPREAD_FILTER_SHADER_FRAG );
- SetRendererTexture( rendererForHorz, textureForHorz );
- mActorForHorz.AddRenderer( rendererForHorz );
+ mActorForHorz.RegisterProperty(SPREAD_UNIFORM_NAME, mSpread);
+ mActorForHorz.RegisterProperty(TEX_SCALE_UNIFORM_NAME, Vector2(0.0f, 1.0f / mTargetSize.height));
+ Renderer rendererForHorz = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_SPREAD_FILTER_SHADER_FRAG);
+ SetRendererTexture(rendererForHorz, textureForHorz);
+ mActorForHorz.AddRenderer(rendererForHorz);
- mRootActor.Add( mActorForInput );
- mRootActor.Add( mActorForHorz );
+ mRootActor.Add(mActorForInput);
+ mRootActor.Add(mActorForHorz);
SetupCamera();
CreateRenderTasks();
void SpreadFilter::Disable()
{
- if( mRootActor )
+ if(mRootActor)
{
- if( mCameraActor )
+ if(mCameraActor)
{
- mRootActor.Remove( mCameraActor );
+ mRootActor.Remove(mCameraActor);
mCameraActor.Reset();
}
- if( mActorForInput )
+ if(mActorForInput)
{
- mRootActor.Remove( mActorForInput );
+ mRootActor.Remove(mActorForInput);
mActorForInput.Reset();
}
- if( mActorForHorz )
+ if(mActorForHorz)
{
- mRootActor.Remove( mActorForHorz );
+ mRootActor.Remove(mActorForHorz);
mActorForHorz.Reset();
}
RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
- if( mRenderTaskForHorz )
+ if(mRenderTaskForHorz)
{
taskList.RemoveTask(mRenderTaskForHorz);
}
- if( mRenderTaskForVert )
+ if(mRenderTaskForVert)
{
taskList.RemoveTask(mRenderTaskForVert);
}
void SpreadFilter::Refresh()
{
- if( mRenderTaskForHorz )
+ if(mRenderTaskForHorz)
{
- mRenderTaskForHorz.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
+ mRenderTaskForHorz.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
}
- if( mRenderTaskForVert )
+ if(mRenderTaskForVert)
{
- mRenderTaskForVert.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
+ mRenderTaskForVert.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
}
}
-void SpreadFilter::SetSize( const Vector2& size )
+void SpreadFilter::SetSize(const Vector2& size)
{
mTargetSize = size;
- if( mActorForInput )
+ if(mActorForInput)
{
- mActorForInput.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForInput.SetProperty(Actor::Property::SIZE, mTargetSize);
}
- if( mActorForHorz )
+ if(mActorForHorz)
{
- mActorForHorz.SetProperty( Actor::Property::SIZE, mTargetSize);
+ mActorForHorz.SetProperty(Actor::Property::SIZE, mTargetSize);
}
}
// perform a horizontal blur targeting the internal buffer
mRenderTaskForHorz = taskList.CreateTask();
- mRenderTaskForHorz.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForHorz.SetSourceActor( mActorForInput );
+ mRenderTaskForHorz.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForHorz.SetSourceActor(mActorForInput);
mRenderTaskForHorz.SetExclusive(true);
- mRenderTaskForHorz.SetInputEnabled( false );
- mRenderTaskForHorz.SetClearEnabled( true );
- mRenderTaskForHorz.SetClearColor( mBackgroundColor );
- mRenderTaskForHorz.SetFrameBuffer( mFrameBufferForHorz );
- mRenderTaskForHorz.SetCameraActor( mCameraActor );
+ mRenderTaskForHorz.SetInputEnabled(false);
+ mRenderTaskForHorz.SetClearEnabled(true);
+ mRenderTaskForHorz.SetClearColor(mBackgroundColor);
+ mRenderTaskForHorz.SetFrameBuffer(mFrameBufferForHorz);
+ mRenderTaskForHorz.SetCameraActor(mCameraActor);
// use the internal buffer and perform a horizontal blur targeting the output buffer
mRenderTaskForVert = taskList.CreateTask();
- mRenderTaskForVert.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS );
- mRenderTaskForVert.SetSourceActor( mActorForHorz );
+ mRenderTaskForVert.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS);
+ mRenderTaskForVert.SetSourceActor(mActorForHorz);
mRenderTaskForVert.SetExclusive(true);
- mRenderTaskForVert.SetInputEnabled( false );
- mRenderTaskForVert.SetClearEnabled( true );
- mRenderTaskForVert.SetClearColor( mBackgroundColor );
- mRenderTaskForVert.SetFrameBuffer( mOutputFrameBuffer );
- mRenderTaskForVert.SetCameraActor( mCameraActor );
+ mRenderTaskForVert.SetInputEnabled(false);
+ mRenderTaskForVert.SetClearEnabled(true);
+ mRenderTaskForVert.SetClearColor(mBackgroundColor);
+ mRenderTaskForVert.SetFrameBuffer(mOutputFrameBuffer);
+ mRenderTaskForVert.SetCameraActor(mCameraActor);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "keyboard-focus-manager-impl.h"
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
-#include <dali/public-api/actors/layer.h>
-#include <dali/devel-api/common/singleton-service.h>
#include <dali/devel-api/adaptor-framework/lifecycle-controller.h>
+#include <dali/devel-api/common/singleton-service.h>
+#include <dali/integration-api/adaptor-framework/adaptor.h>
+#include <dali/integration-api/adaptor-framework/scene-holder.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/actors/layer.h>
#include <dali/public-api/animation/constraints.h>
#include <dali/public-api/events/key-event.h>
#include <dali/public-api/events/touch-event.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/public-api/object/property-map.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/adaptor-framework/adaptor.h>
-#include <dali/integration-api/adaptor-framework/scene-holder.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
-#include <dali-toolkit/public-api/controls/control.h>
+#include <dali-toolkit/devel-api/controls/control-devel.h>
+#include <dali-toolkit/devel-api/styling/style-manager-devel.h>
#include <dali-toolkit/public-api/controls/control-impl.h>
+#include <dali-toolkit/public-api/controls/control.h>
#include <dali-toolkit/public-api/controls/image-view/image-view.h>
-#include <dali-toolkit/devel-api/controls/control-devel.h>
#include <dali-toolkit/public-api/styling/style-manager.h>
-#include <dali-toolkit/devel-api/styling/style-manager-devel.h>
#include <dali/devel-api/adaptor-framework/accessibility.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace // Unnamed namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_KEYBOARD_FOCUS_MANAGER");
#endif
{
BaseHandle handle = KeyboardFocusManager::Get();
- if ( !handle )
+ if(!handle)
{
- SingletonService singletonService( SingletonService::Get() );
- if ( singletonService )
+ SingletonService singletonService(SingletonService::Get());
+ if(singletonService)
{
- Toolkit::KeyboardFocusManager manager = Toolkit::KeyboardFocusManager( new Internal::KeyboardFocusManager() );
- singletonService.Register( typeid( manager ), manager );
+ Toolkit::KeyboardFocusManager manager = Toolkit::KeyboardFocusManager(new Internal::KeyboardFocusManager());
+ singletonService.Register(typeid(manager), manager);
handle = manager;
}
}
return handle;
}
-DALI_TYPE_REGISTRATION_BEGIN_CREATE( Toolkit::KeyboardFocusManager, Dali::BaseHandle, Create, true )
+DALI_TYPE_REGISTRATION_BEGIN_CREATE(Toolkit::KeyboardFocusManager, Dali::BaseHandle, Create, true)
-DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardPreFocusChange", SIGNAL_PRE_FOCUS_CHANGE )
-DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusChanged", SIGNAL_FOCUS_CHANGED )
-DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusGroupChanged", SIGNAL_FOCUS_GROUP_CHANGED )
-DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusedActorEnterKey", SIGNAL_FOCUSED_ACTOR_ENTER_KEY )
+DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardPreFocusChange", SIGNAL_PRE_FOCUS_CHANGE)
+DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusChanged", SIGNAL_FOCUS_CHANGED)
+DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusGroupChanged", SIGNAL_FOCUS_GROUP_CHANGED)
+DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusedActorEnterKey", SIGNAL_FOCUSED_ACTOR_ENTER_KEY)
DALI_TYPE_REGISTRATION_END()
{
Toolkit::KeyboardFocusManager manager;
- SingletonService singletonService( SingletonService::Get() );
- if ( singletonService )
+ SingletonService singletonService(SingletonService::Get());
+ if(singletonService)
{
// Check whether the keyboard focus manager is already created
- Dali::BaseHandle handle = singletonService.GetSingleton( typeid( Toolkit::KeyboardFocusManager ) );
+ Dali::BaseHandle handle = singletonService.GetSingleton(typeid(Toolkit::KeyboardFocusManager));
if(handle)
{
// If so, downcast the handle of singleton to keyboard focus manager
- manager = Toolkit::KeyboardFocusManager( dynamic_cast< KeyboardFocusManager* >( handle.GetObjectPtr() ) );
+ manager = Toolkit::KeyboardFocusManager(dynamic_cast<KeyboardFocusManager*>(handle.GetObjectPtr()));
}
}
mCurrentFocusActor(),
mFocusIndicatorActor(),
mFocusHistory(),
- mSlotDelegate( this ),
+ mSlotDelegate(this),
mCustomAlgorithmInterface(NULL),
mCurrentFocusedWindow(),
- mIsFocusIndicatorShown( UNKNOWN ),
- mEnableFocusIndicator( ENABLE ),
- mAlwaysShowIndicator( ALWAYS_SHOW ),
- mFocusGroupLoopEnabled( false ),
- mIsWaitingKeyboardFocusChangeCommit( false ),
- mClearFocusOnTouch( true )
+ mIsFocusIndicatorShown(UNKNOWN),
+ mEnableFocusIndicator(ENABLE),
+ mAlwaysShowIndicator(ALWAYS_SHOW),
+ mFocusGroupLoopEnabled(false),
+ mIsWaitingKeyboardFocusChangeCommit(false),
+ mClearFocusOnTouch(true)
{
// TODO: Get FocusIndicatorEnable constant from stylesheet to set mIsFocusIndicatorShown.
- LifecycleController::Get().InitSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnAdaptorInit );
+ LifecycleController::Get().InitSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnAdaptorInit);
}
void KeyboardFocusManager::OnAdaptorInit()
{
- if( Adaptor::IsAvailable() )
+ if(Adaptor::IsAvailable())
{
// Retrieve all the existing scene holders
Dali::SceneHolderList sceneHolders = Adaptor::Get().GetSceneHolders();
- for( auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter )
+ for(auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter)
{
- ( *iter ).KeyEventSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnKeyEvent );
- ( *iter ).TouchedSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnTouch );
- Dali::Window window = DevelWindow::DownCast( *iter );
- if( window )
+ (*iter).KeyEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnKeyEvent);
+ (*iter).TouchedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnTouch);
+ Dali::Window window = DevelWindow::DownCast(*iter);
+ if(window)
{
- window.FocusChangeSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged);
+ window.FocusChangeSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged);
}
}
// Get notified when any new scene holder is created afterwards
- Adaptor::Get().WindowCreatedSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnSceneHolderCreated );
+ Adaptor::Get().WindowCreatedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnSceneHolderCreated);
}
}
-void KeyboardFocusManager::OnSceneHolderCreated( Dali::Integration::SceneHolder& sceneHolder )
+void KeyboardFocusManager::OnSceneHolderCreated(Dali::Integration::SceneHolder& sceneHolder)
{
- sceneHolder.KeyEventSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnKeyEvent );
- sceneHolder.TouchedSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnTouch );
- Dali::Window window = DevelWindow::DownCast( sceneHolder );
- if( window )
+ sceneHolder.KeyEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnKeyEvent);
+ sceneHolder.TouchedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnTouch);
+ Dali::Window window = DevelWindow::DownCast(sceneHolder);
+ if(window)
{
- window.FocusChangeSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged);
+ window.FocusChangeSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged);
}
}
void KeyboardFocusManager::GetConfigurationFromStyleManger()
{
- Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
- if( styleManager )
- {
- Property::Map config = Toolkit::DevelStyleManager::GetConfigurations( styleManager );
- mAlwaysShowIndicator = config["alwaysShowFocus"].Get<bool>() ? ALWAYS_SHOW : NONE;
- mIsFocusIndicatorShown = ( mAlwaysShowIndicator == ALWAYS_SHOW )? SHOW : HIDE;
- mClearFocusOnTouch = ( mIsFocusIndicatorShown == SHOW ) ? false : true;
- }
+ Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
+ if(styleManager)
+ {
+ Property::Map config = Toolkit::DevelStyleManager::GetConfigurations(styleManager);
+ mAlwaysShowIndicator = config["alwaysShowFocus"].Get<bool>() ? ALWAYS_SHOW : NONE;
+ mIsFocusIndicatorShown = (mAlwaysShowIndicator == ALWAYS_SHOW) ? SHOW : HIDE;
+ mClearFocusOnTouch = (mIsFocusIndicatorShown == SHOW) ? false : true;
+ }
}
-bool KeyboardFocusManager::SetCurrentFocusActor( Actor actor )
+bool KeyboardFocusManager::SetCurrentFocusActor(Actor actor)
{
- DALI_ASSERT_DEBUG( !mIsWaitingKeyboardFocusChangeCommit && "Calling this function in the PreFocusChangeSignal callback?" );
+ DALI_ASSERT_DEBUG(!mIsWaitingKeyboardFocusChangeCommit && "Calling this function in the PreFocusChangeSignal callback?");
- if( mIsFocusIndicatorShown == UNKNOWN )
+ if(mIsFocusIndicatorShown == UNKNOWN)
{
GetConfigurationFromStyleManger();
}
- return DoSetCurrentFocusActor( actor );
+ return DoSetCurrentFocusActor(actor);
}
-bool KeyboardFocusManager::DoSetCurrentFocusActor( Actor actor )
+bool KeyboardFocusManager::DoSetCurrentFocusActor(Actor actor)
{
bool success = false;
- if( actor && actor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) && actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if(actor && actor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && actor.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
- Integration::SceneHolder currentWindow = Integration::SceneHolder::Get( actor );
+ Integration::SceneHolder currentWindow = Integration::SceneHolder::Get(actor);
- if( currentWindow.GetRootLayer() != mCurrentFocusedWindow.GetHandle())
+ if(currentWindow.GetRootLayer() != mCurrentFocusedWindow.GetHandle())
{
- Layer rootLayer = currentWindow.GetRootLayer();
+ Layer rootLayer = currentWindow.GetRootLayer();
mCurrentFocusedWindow = rootLayer;
}
}
Actor currentFocusedActor = GetCurrentFocusActor();
// If developer set focus on same actor, doing nothing
- if( actor == currentFocusedActor )
+ if(actor == currentFocusedActor)
{
- if( !actor )
+ if(!actor)
{
return false;
}
}
// Check whether the actor is in the stage and is keyboard focusable.
- if( actor && actor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) && actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if(actor && actor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && actor.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
- if( ( mIsFocusIndicatorShown == SHOW ) && ( mEnableFocusIndicator == ENABLE ) )
+ if((mIsFocusIndicatorShown == SHOW) && (mEnableFocusIndicator == ENABLE))
{
- actor.Add( GetFocusIndicatorActor() );
+ actor.Add(GetFocusIndicatorActor());
}
// Send notification for the change of focus actor
- if( !mFocusChangedSignal.Empty() )
+ if(!mFocusChangedSignal.Empty())
{
mFocusChangedSignal.Emit(currentFocusedActor, actor);
}
Toolkit::Control currentlyFocusedControl = Toolkit::Control::DownCast(currentFocusedActor);
- if( currentlyFocusedControl )
+ if(currentlyFocusedControl)
{
// Do we need it to remember if it was previously DISABLED?
- currentlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::NORMAL );
+ currentlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::NORMAL);
currentlyFocusedControl.ClearKeyInputFocus();
}
- DALI_LOG_INFO( gLogFilter, Debug::General, "[%s:%d] Focus Changed\n", __FUNCTION__, __LINE__);
+ DALI_LOG_INFO(gLogFilter, Debug::General, "[%s:%d] Focus Changed\n", __FUNCTION__, __LINE__);
// Save the current focused actor
mCurrentFocusActor = actor;
bool focusedWindowFound = false;
- for( unsigned int i = 0; i < mCurrentFocusActors.size(); i++ )
+ for(unsigned int i = 0; i < mCurrentFocusActors.size(); i++)
{
- if( mCurrentFocusActors[i].first == mCurrentFocusedWindow )
+ if(mCurrentFocusActors[i].first == mCurrentFocusedWindow)
{
mCurrentFocusActors[i].second = actor;
- focusedWindowFound = true;
+ focusedWindowFound = true;
break;
}
}
- if( !focusedWindowFound)
+ if(!focusedWindowFound)
{
// A new window gains the focus, so store the focused actor in that window.
- mCurrentFocusActors.push_back( std::pair< WeakHandle< Layer>, WeakHandle< Actor > >( mCurrentFocusedWindow , actor ));
+ mCurrentFocusActors.push_back(std::pair<WeakHandle<Layer>, WeakHandle<Actor> >(mCurrentFocusedWindow, actor));
}
Toolkit::Control newlyFocusedControl = Toolkit::Control::DownCast(actor);
- if( newlyFocusedControl )
+ if(newlyFocusedControl)
{
- newlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::FOCUSED );
+ newlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::FOCUSED);
newlyFocusedControl.SetKeyInputFocus();
}
// Push Current Focused Actor to FocusHistory
- mFocusHistory.push_back( actor );
+ mFocusHistory.push_back(actor);
// Delete first element before add new element when Stack is full.
- if( mFocusHistory.size() > MAX_HISTORY_AMOUNT )
+ if(mFocusHistory.size() > MAX_HISTORY_AMOUNT)
{
- FocusStackIterator beginPos = mFocusHistory.begin();
- mFocusHistory.erase( beginPos );
+ FocusStackIterator beginPos = mFocusHistory.begin();
+ mFocusHistory.erase(beginPos);
}
- DALI_LOG_INFO( gLogFilter, Debug::General, "[%s:%d] SUCCEED\n", __FUNCTION__, __LINE__);
+ DALI_LOG_INFO(gLogFilter, Debug::General, "[%s:%d] SUCCEED\n", __FUNCTION__, __LINE__);
success = true;
}
else
{
Actor actor = mCurrentFocusActor.GetHandle();
- if( actor && ! actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if(actor && !actor.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
// If the actor has been removed from the stage, then it should not be focused
actor.Reset();
Actor KeyboardFocusManager::GetFocusActorFromCurrentWindow()
{
- Actor actor;
+ Actor actor;
unsigned int index;
- for( index = 0; index < mCurrentFocusActors.size(); index++ )
+ for(index = 0; index < mCurrentFocusActors.size(); index++)
{
- if( mCurrentFocusActors[index].first == mCurrentFocusedWindow )
+ if(mCurrentFocusActors[index].first == mCurrentFocusedWindow)
{
actor = mCurrentFocusActors[index].second.GetHandle();
break;
}
}
- if( actor && ! actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if(actor && !actor.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
// If the actor has been removed from the window, then the window doesn't have any focused actor
actor.Reset();
- mCurrentFocusActors.erase( mCurrentFocusActors.begin() + index );
+ mCurrentFocusActors.erase(mCurrentFocusActors.begin() + index);
}
return actor;
void KeyboardFocusManager::MoveFocusBackward()
{
// Find Pre Focused Actor when the list size is more than 1
- if( mFocusHistory.size() > 1 )
+ if(mFocusHistory.size() > 1)
{
// Delete current focused actor in history
mFocusHistory.pop_back();
// If pre-focused actors are not on stage or deleted, remove them in stack
- while( mFocusHistory.size() > 0 )
+ while(mFocusHistory.size() > 0)
{
// Get pre focused actor
- Actor target = mFocusHistory[ mFocusHistory.size() -1 ].GetHandle();
+ Actor target = mFocusHistory[mFocusHistory.size() - 1].GetHandle();
// Impl of Actor is not null
- if( target && target.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
+ if(target && target.GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
// Delete pre focused actor in history because it will pushed again by SetCurrentFocusActor()
mFocusHistory.pop_back();
- SetCurrentFocusActor( target );
+ SetCurrentFocusActor(target);
break;
}
else
}
// if there is no actor which can get focus, then push current focus actor in stack again
- if( mFocusHistory.size() == 0 )
+ if(mFocusHistory.size() == 0)
{
Actor currentFocusedActor = GetCurrentFocusActor();
- mFocusHistory.push_back( currentFocusedActor );
+ mFocusHistory.push_back(currentFocusedActor);
}
}
}
bool KeyboardFocusManager::IsLayoutControl(Actor actor) const
{
Toolkit::Control control = Toolkit::Control::DownCast(actor);
- return control && GetImplementation( control ).IsKeyboardNavigationSupported();
+ return control && GetImplementation(control).IsKeyboardNavigationSupported();
}
Toolkit::Control KeyboardFocusManager::GetParentLayoutControl(Actor actor) const
Actor parent;
if(actor)
{
- Integration::SceneHolder window = Integration::SceneHolder::Get( actor );
- if ( window )
+ Integration::SceneHolder window = Integration::SceneHolder::Get(actor);
+ if(window)
{
rootActor = window.GetRootLayer();
}
parent = actor.GetParent();
}
- while( parent && !IsLayoutControl(parent) && parent != rootActor )
+ while(parent && !IsLayoutControl(parent) && parent != rootActor)
{
parent = parent.GetParent();
}
bool succeed = false;
// Go through the actor's hierarchy until we find a layout control that knows how to move the focus
- Toolkit::Control parentLayoutControl = GetParentLayoutControl( currentFocusActor );
- while( parentLayoutControl && !succeed )
+ Toolkit::Control parentLayoutControl = GetParentLayoutControl(currentFocusActor);
+ while(parentLayoutControl && !succeed)
{
- succeed = DoMoveFocusWithinLayoutControl( parentLayoutControl, currentFocusActor, direction );
- parentLayoutControl = GetParentLayoutControl( parentLayoutControl );
+ succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, currentFocusActor, direction);
+ parentLayoutControl = GetParentLayoutControl(parentLayoutControl);
}
- if( !succeed )
+ if(!succeed)
{
Actor nextFocusableActor;
Toolkit::Control currentFocusControl = Toolkit::Control::DownCast(currentFocusActor);
// If the current focused actor is a control, then find the next focusable actor via the focusable properties.
- if( currentFocusControl )
+ if(currentFocusControl)
{
- int actorId = -1;
- Property::Index index = Property::INVALID_INDEX;
+ int actorId = -1;
+ Property::Index index = Property::INVALID_INDEX;
Property::Value value;
// Find property index based upon focus direction
- switch ( direction )
+ switch(direction)
{
case Toolkit::Control::KeyboardFocus::LEFT:
{
}
// If the focusable property is set then determine next focusable actor
- if( index != Property::INVALID_INDEX)
+ if(index != Property::INVALID_INDEX)
{
- value = currentFocusActor.GetProperty( index );
+ value = currentFocusActor.GetProperty(index);
actorId = value.Get<int>();
// If actor's id is valid then find actor form actor's id. The actor should be on the stage.
- if( actorId != -1 )
+ if(actorId != -1)
{
- if( currentFocusActor.GetParent() )
+ if(currentFocusActor.GetParent())
{
- nextFocusableActor = currentFocusActor.GetParent().FindChildById( actorId );
+ nextFocusableActor = currentFocusActor.GetParent().FindChildById(actorId);
}
- if( !nextFocusableActor )
+ if(!nextFocusableActor)
{
- Integration::SceneHolder window = Integration::SceneHolder::Get( currentFocusActor );
- if ( window )
+ Integration::SceneHolder window = Integration::SceneHolder::Get(currentFocusActor);
+ if(window)
{
- nextFocusableActor = window.GetRootLayer().FindChildById( actorId );
+ nextFocusableActor = window.GetRootLayer().FindChildById(actorId);
}
}
}
}
}
- if( !nextFocusableActor )
+ if(!nextFocusableActor)
{
// If the implementation of CustomAlgorithmInterface is provided then the PreFocusChangeSignal is no longer emitted.
- if( mCustomAlgorithmInterface )
+ if(mCustomAlgorithmInterface)
{
mIsWaitingKeyboardFocusChangeCommit = true;
- nextFocusableActor = mCustomAlgorithmInterface->GetNextFocusableActor( currentFocusActor, Actor(), direction );
+ nextFocusableActor = mCustomAlgorithmInterface->GetNextFocusableActor(currentFocusActor, Actor(), direction);
mIsWaitingKeyboardFocusChangeCommit = false;
}
- else if( !mPreFocusChangeSignal.Empty() )
+ else if(!mPreFocusChangeSignal.Empty())
{
// Don't know how to move the focus further. The application needs to tell us which actor to move the focus to
mIsWaitingKeyboardFocusChangeCommit = true;
- nextFocusableActor = mPreFocusChangeSignal.Emit( currentFocusActor, Actor(), direction );
+ nextFocusableActor = mPreFocusChangeSignal.Emit(currentFocusActor, Actor(), direction);
mIsWaitingKeyboardFocusChangeCommit = false;
}
}
- if( nextFocusableActor && nextFocusableActor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) )
+ if(nextFocusableActor && nextFocusableActor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
// Whether the next focusable actor is a layout control
- if( IsLayoutControl( nextFocusableActor ) )
+ if(IsLayoutControl(nextFocusableActor))
{
// If so, move the focus inside it.
- Toolkit::Control layoutControl = Toolkit::Control::DownCast( nextFocusableActor) ;
- succeed = DoMoveFocusWithinLayoutControl( layoutControl, currentFocusActor, direction );
+ Toolkit::Control layoutControl = Toolkit::Control::DownCast(nextFocusableActor);
+ succeed = DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction);
}
else
{
// Otherwise, just set focus to the next focusable actor
- succeed = SetCurrentFocusActor( nextFocusableActor );
+ succeed = SetCurrentFocusActor(nextFocusableActor);
}
}
}
bool KeyboardFocusManager::DoMoveFocusWithinLayoutControl(Toolkit::Control control, Actor actor, Toolkit::Control::KeyboardFocus::Direction direction)
{
// Ask the control for the next actor to focus
- Actor nextFocusableActor = GetImplementation( control ).GetNextKeyboardFocusableActor(actor, direction, mFocusGroupLoopEnabled);
+ Actor nextFocusableActor = GetImplementation(control).GetNextKeyboardFocusableActor(actor, direction, mFocusGroupLoopEnabled);
if(nextFocusableActor)
{
- if(!nextFocusableActor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ))
+ if(!nextFocusableActor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
// If the actor is not focusable, ask the same layout control for the next actor to focus
return DoMoveFocusWithinLayoutControl(control, nextFocusableActor, direction);
}
else
{
- Actor currentFocusActor = GetCurrentFocusActor();
+ Actor currentFocusActor = GetCurrentFocusActor();
Actor committedFocusActor = nextFocusableActor;
// We will try to move the focus to the actor. Emit a signal to notify the proposed actor to focus
// Signal handler can check the proposed actor and return a different actor if it wishes.
- if( !mPreFocusChangeSignal.Empty() )
+ if(!mPreFocusChangeSignal.Empty())
{
mIsWaitingKeyboardFocusChangeCommit = true;
- committedFocusActor = mPreFocusChangeSignal.Emit(currentFocusActor, nextFocusableActor, direction);
+ committedFocusActor = mPreFocusChangeSignal.Emit(currentFocusActor, nextFocusableActor, direction);
mIsWaitingKeyboardFocusChangeCommit = false;
}
- if (committedFocusActor && committedFocusActor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ))
+ if(committedFocusActor && committedFocusActor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE))
{
// Whether the commited focusable actor is a layout control
if(IsLayoutControl(committedFocusActor))
// If the application hasn't changed our proposed actor, we informs the layout control we will
// move the focus to what the control returns. The control might wish to perform some actions
// before the focus is actually moved.
- GetImplementation( control ).OnKeyboardFocusChangeCommitted( committedFocusActor );
+ GetImplementation(control).OnKeyboardFocusChangeCommitted(committedFocusActor);
}
return SetCurrentFocusActor(committedFocusActor);
// If the current focus group has a parent layout control, we can probably automatically
// move the focus to the next focus group in the forward or backward direction.
Toolkit::Control::KeyboardFocus::Direction direction = forward ? Toolkit::Control::KeyboardFocus::RIGHT : Toolkit::Control::KeyboardFocus::LEFT;
- succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, GetCurrentFocusActor(), direction);
- parentLayoutControl = GetParentLayoutControl(parentLayoutControl);
+ succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, GetCurrentFocusActor(), direction);
+ parentLayoutControl = GetParentLayoutControl(parentLayoutControl);
}
if(!mFocusGroupChangedSignal.Empty())
void KeyboardFocusManager::DoKeyboardEnter(Actor actor)
{
- if( actor )
+ if(actor)
{
- Toolkit::Control control = Toolkit::Control::DownCast( actor );
- if( control )
+ Toolkit::Control control = Toolkit::Control::DownCast(actor);
+ if(control)
{
// Notify the control that enter has been pressed on it.
- GetImplementation( control ).KeyboardEnter();
+ GetImplementation(control).KeyboardEnter();
}
// Send a notification for the actor.
- if( !mFocusedActorEnterKeySignal.Empty() )
+ if(!mFocusedActorEnterKeySignal.Empty())
{
- mFocusedActorEnterKeySignal.Emit( actor );
+ mFocusedActorEnterKeySignal.Emit(actor);
}
}
}
void KeyboardFocusManager::ClearFocus()
{
Actor actor = GetCurrentFocusActor();
- if( actor )
+ if(actor)
{
- if( mFocusIndicatorActor )
+ if(mFocusIndicatorActor)
{
- actor.Remove( mFocusIndicatorActor );
+ actor.Remove(mFocusIndicatorActor);
}
// Send notification for the change of focus actor
- if( !mFocusChangedSignal.Empty() )
+ if(!mFocusChangedSignal.Empty())
{
- mFocusChangedSignal.Emit( actor, Actor() );
+ mFocusChangedSignal.Emit(actor, Actor());
}
- Toolkit::Control currentlyFocusedControl = Toolkit::Control::DownCast( actor );
- if( currentlyFocusedControl )
+ Toolkit::Control currentlyFocusedControl = Toolkit::Control::DownCast(actor);
+ if(currentlyFocusedControl)
{
- currentlyFocusedControl.SetProperty( DevelControl::Property::STATE, DevelControl::NORMAL );
+ currentlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::NORMAL);
currentlyFocusedControl.ClearKeyInputFocus();
}
}
mCurrentFocusActor.Reset();
- mIsFocusIndicatorShown = ( mAlwaysShowIndicator == ALWAYS_SHOW ) ? SHOW : HIDE;
+ mIsFocusIndicatorShown = (mAlwaysShowIndicator == ALWAYS_SHOW) ? SHOW : HIDE;
}
void KeyboardFocusManager::SetFocusGroupLoop(bool enabled)
if(actor)
{
// Create/Set focus group property.
- actor.RegisterProperty( IS_FOCUS_GROUP_PROPERTY_NAME, isFocusGroup, Property::READ_WRITE );
+ actor.RegisterProperty(IS_FOCUS_GROUP_PROPERTY_NAME, isFocusGroup, Property::READ_WRITE);
}
}
Actor KeyboardFocusManager::GetFocusGroup(Actor actor)
{
// Go through the actor's hierarchy to check which focus group the actor belongs to
- while (actor && !IsFocusGroup(actor))
+ while(actor && !IsFocusGroup(actor))
{
actor = actor.GetParent();
}
Actor KeyboardFocusManager::GetFocusIndicatorActor()
{
- if( ! mFocusIndicatorActor )
+ if(!mFocusIndicatorActor)
{
// Create the default if it hasn't been set and one that's shared by all the keyboard focusable actors
const std::string imageDirPath = AssetManager::GetDaliImagePath();
- mFocusIndicatorActor = Toolkit::ImageView::New( imageDirPath + FOCUS_BORDER_IMAGE_FILE_NAME );
+ mFocusIndicatorActor = Toolkit::ImageView::New(imageDirPath + FOCUS_BORDER_IMAGE_FILE_NAME);
// Apply size constraint to the focus indicator
- mFocusIndicatorActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mFocusIndicatorActor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
}
- mFocusIndicatorActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mFocusIndicatorActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- mFocusIndicatorActor.SetProperty( Actor::Property::POSITION, Vector2(0.0f, 0.0f));
+ mFocusIndicatorActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mFocusIndicatorActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mFocusIndicatorActor.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f));
return mFocusIndicatorActor;
}
{
std::string keyName = event.GetKeyName();
- if( mIsFocusIndicatorShown == UNKNOWN )
+ if(mIsFocusIndicatorShown == UNKNOWN)
{
GetConfigurationFromStyleManger();
}
if(event.GetState() == KeyEvent::DOWN)
{
- if (keyName == "Left")
+ if(keyName == "Left")
{
if(!mIsFocusIndicatorShown)
{
isFocusStartableKey = true;
}
- else if (keyName == "Right")
+ else if(keyName == "Right")
{
if(!mIsFocusIndicatorShown)
{
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
isFocusStartableKey = true;
}
- else if (keyName == "Up")
+ else if(keyName == "Up")
{
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
isFocusStartableKey = true;
}
- else if (keyName == "Down")
+ else if(keyName == "Down")
{
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
isFocusStartableKey = true;
}
- else if (keyName == "Prior")
+ else if(keyName == "Prior")
{
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
isFocusStartableKey = true;
}
- else if (keyName == "Next")
+ else if(keyName == "Next")
{
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
isFocusStartableKey = true;
}
- else if (keyName == "Tab")
+ else if(keyName == "Tab")
{
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
isFocusStartableKey = true;
}
- else if (keyName == "space")
+ else if(keyName == "space")
{
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
isFocusStartableKey = true;
}
- else if (keyName == "")
+ else if(keyName == "")
{
// Check the fake key event for evas-plugin case
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
isFocusStartableKey = true;
}
- else if (keyName == "Backspace")
+ else if(keyName == "Backspace")
{
// Emit signal to go back to the previous view???
}
- else if (keyName == "Escape")
+ else if(keyName == "Escape")
{
}
}
else if(event.GetState() == KeyEvent::UP)
{
- if (keyName == "Return")
+ if(keyName == "Return")
{
- if( mIsFocusIndicatorShown == HIDE )
+ if(mIsFocusIndicatorShown == HIDE)
{
// Show focus indicator
mIsFocusIndicatorShown = SHOW;
{
// The focused actor has enter pressed on it
Actor actor = GetCurrentFocusActor();
- if( actor )
+ if(actor)
{
- DoKeyboardEnter( actor );
+ DoKeyboardEnter(actor);
}
}
}
}
- if( isFocusStartableKey && mIsFocusIndicatorShown == SHOW )
+ if(isFocusStartableKey && mIsFocusIndicatorShown == SHOW)
{
Actor actor = GetCurrentFocusActor();
- if( actor )
+ if(actor)
{
- if( mEnableFocusIndicator == ENABLE )
+ if(mEnableFocusIndicator == ENABLE)
{
// Make sure the focused actor is highlighted
- actor.Add( GetFocusIndicatorActor() );
+ actor.Add(GetFocusIndicatorActor());
}
}
else
// Let's try to move the initial focus
MoveFocus(Toolkit::Control::KeyboardFocus::RIGHT);
}
-
}
}
{
// if mIsFocusIndicatorShown is UNKNOWN, it means Configuration is not loaded.
// Try to load configuration.
- if( mIsFocusIndicatorShown == UNKNOWN )
+ if(mIsFocusIndicatorShown == UNKNOWN)
{
GetConfigurationFromStyleManger();
}
// Clear the focus when user touch the screen.
// We only do this on a Down event, otherwise the clear action may override a manually focused actor.
// If mClearFocusOnTouch is false, do not clear the focus even if user touch the screen.
- if( (( touch.GetPointCount() < 1 ) || ( touch.GetState( 0 ) == PointState::DOWN )) && mClearFocusOnTouch )
+ if(((touch.GetPointCount() < 1) || (touch.GetState(0) == PointState::DOWN)) && mClearFocusOnTouch)
{
ClearFocus();
}
}
-void KeyboardFocusManager::OnWindowFocusChanged(Window window, bool focusIn )
+void KeyboardFocusManager::OnWindowFocusChanged(Window window, bool focusIn)
{
- if( focusIn && mCurrentFocusedWindow.GetHandle() != window.GetRootLayer() )
+ if(focusIn && mCurrentFocusedWindow.GetHandle() != window.GetRootLayer())
{
// Change Current Focused Window
- Layer rootLayer = window.GetRootLayer();
+ Layer rootLayer = window.GetRootLayer();
mCurrentFocusedWindow = rootLayer;
// Get Current Focused Actor from window
Actor currentFocusedActor = GetFocusActorFromCurrentWindow();
- SetCurrentFocusActor( currentFocusedActor );
+ SetCurrentFocusActor(currentFocusedActor);
- if( currentFocusedActor && ( mEnableFocusIndicator == ENABLE ) )
+ if(currentFocusedActor && (mEnableFocusIndicator == ENABLE))
{
// Make sure the focused actor is highlighted
- currentFocusedActor.Add( GetFocusIndicatorActor() );
+ currentFocusedActor.Add(GetFocusIndicatorActor());
mIsFocusIndicatorShown = SHOW;
}
}
return mFocusedActorEnterKeySignal;
}
-bool KeyboardFocusManager::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool KeyboardFocusManager::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- KeyboardFocusManager* manager = static_cast< KeyboardFocusManager* >( object ); // TypeRegistry guarantees that this is the correct type.
+ bool connected(true);
+ KeyboardFocusManager* manager = static_cast<KeyboardFocusManager*>(object); // TypeRegistry guarantees that this is the correct type.
- if( 0 == strcmp( signalName.c_str(), SIGNAL_PRE_FOCUS_CHANGE ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_PRE_FOCUS_CHANGE))
{
- manager->PreFocusChangeSignal().Connect( tracker, functor );
+ manager->PreFocusChangeSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUS_CHANGED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUS_CHANGED))
{
- manager->FocusChangedSignal().Connect( tracker, functor );
+ manager->FocusChangedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUS_GROUP_CHANGED ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUS_GROUP_CHANGED))
{
- manager->FocusGroupChangedSignal().Connect( tracker, functor );
+ manager->FocusGroupChangedSignal().Connect(tracker, functor);
}
- else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUSED_ACTOR_ENTER_KEY ) )
+ else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUSED_ACTOR_ENTER_KEY))
{
- manager->FocusedActorEnterKeySignal().Connect( tracker, functor );
+ manager->FocusedActorEnterKeySignal().Connect(tracker, functor);
}
else
{
void KeyboardFocusManager::EnableFocusIndicator(bool enable)
{
- if( !enable && mFocusIndicatorActor )
+ if(!enable && mFocusIndicatorActor)
{
mFocusIndicatorActor.Unparent();
}
- mEnableFocusIndicator = enable? ENABLE : DISABLE;
-
+ mEnableFocusIndicator = enable ? ENABLE : DISABLE;
}
bool KeyboardFocusManager::IsFocusIndicatorEnabled() const
{
- return ( mEnableFocusIndicator == ENABLE );
+ return (mEnableFocusIndicator == ENABLE);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "keyinput-focus-manager-impl.h"
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
-#include <dali/public-api/actors/layer.h>
#include <dali-toolkit/public-api/controls/control-impl.h>
-#include <dali/integration-api/debug.h>
#include <dali/integration-api/adaptor-framework/adaptor.h>
#include <dali/integration-api/adaptor-framework/scene-holder.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/actors/layer.h>
+#include <cstring> // for strcmp
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// Signals
const char* const SIGNAL_KEY_INPUT_FOCUS_CHANGED = "keyInputFocusChanged";
-}
+} // namespace
KeyInputFocusManager::KeyInputFocusManager()
-: mSlotDelegate( this ),
+: mSlotDelegate(this),
mCurrentFocusControl()
{
// Retrieve all the existing widnows
Dali::SceneHolderList sceneHolders = Adaptor::Get().GetSceneHolders();
- for( auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter )
+ for(auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter)
{
- ( *iter ).KeyEventGeneratedSignal().Connect( mSlotDelegate, &KeyInputFocusManager::OnKeyEvent );
+ (*iter).KeyEventGeneratedSignal().Connect(mSlotDelegate, &KeyInputFocusManager::OnKeyEvent);
}
// Get notified when any new scene holder is created afterwards
- Adaptor::Get().WindowCreatedSignal().Connect( mSlotDelegate, &KeyInputFocusManager::OnSceneHolderCreated );
+ Adaptor::Get().WindowCreatedSignal().Connect(mSlotDelegate, &KeyInputFocusManager::OnSceneHolderCreated);
}
KeyInputFocusManager::~KeyInputFocusManager()
{
}
-void KeyInputFocusManager::OnSceneHolderCreated( Dali::Integration::SceneHolder& sceneHolder )
+void KeyInputFocusManager::OnSceneHolderCreated(Dali::Integration::SceneHolder& sceneHolder)
{
- sceneHolder.KeyEventGeneratedSignal().Connect( mSlotDelegate, &KeyInputFocusManager::OnKeyEvent );
+ sceneHolder.KeyEventGeneratedSignal().Connect(mSlotDelegate, &KeyInputFocusManager::OnKeyEvent);
}
-void KeyInputFocusManager::SetFocus( Toolkit::Control control )
+void KeyInputFocusManager::SetFocus(Toolkit::Control control)
{
- if( !control )
+ if(!control)
{
// No-op
return;
}
- if( control == mCurrentFocusControl )
+ if(control == mCurrentFocusControl)
{
// Control already has focus
return;
}
- control.OffSceneSignal().Connect( mSlotDelegate, &KeyInputFocusManager::OnFocusControlSceneDisconnection );
+ control.OffSceneSignal().Connect(mSlotDelegate, &KeyInputFocusManager::OnFocusControlSceneDisconnection);
Dali::Toolkit::Control previousFocusControl = GetCurrentFocusControl();
- if( previousFocusControl )
+ if(previousFocusControl)
{
// Notify the control that it has lost key input focus
- GetImplementation( previousFocusControl ).OnKeyInputFocusLost();
+ GetImplementation(previousFocusControl).OnKeyInputFocusLost();
}
// Set control to currentFocusControl
mCurrentFocusControl = control;
// Tell the new actor that it has gained focus.
- GetImplementation( control ).OnKeyInputFocusGained();
+ GetImplementation(control).OnKeyInputFocusGained();
// Emit the signal to inform focus change to the application.
- if ( !mKeyInputFocusChangedSignal.Empty() )
+ if(!mKeyInputFocusChangedSignal.Empty())
{
- mKeyInputFocusChangedSignal.Emit( control, previousFocusControl );
+ mKeyInputFocusChangedSignal.Emit(control, previousFocusControl);
}
}
-void KeyInputFocusManager::RemoveFocus( Toolkit::Control control )
+void KeyInputFocusManager::RemoveFocus(Toolkit::Control control)
{
- if( control == mCurrentFocusControl )
+ if(control == mCurrentFocusControl)
{
- control.OffSceneSignal().Disconnect( mSlotDelegate, &KeyInputFocusManager::OnFocusControlSceneDisconnection );
+ control.OffSceneSignal().Disconnect(mSlotDelegate, &KeyInputFocusManager::OnFocusControlSceneDisconnection);
// Notify the control that it has lost key input focus
- GetImplementation( control ).OnKeyInputFocusLost();
+ GetImplementation(control).OnKeyInputFocusLost();
mCurrentFocusControl.Reset();
}
return mKeyInputFocusChangedSignal;
}
-bool KeyInputFocusManager::OnKeyEvent( const KeyEvent& event )
+bool KeyInputFocusManager::OnKeyEvent(const KeyEvent& event)
{
bool consumed = false;
Toolkit::Control control = GetCurrentFocusControl();
- if( control )
+ if(control)
{
// Notify the control about the key event
- consumed = EmitKeyEventSignal( control, event );
+ consumed = EmitKeyEventSignal(control, event);
}
return consumed;
}
-bool KeyInputFocusManager::EmitKeyEventSignal( Toolkit::Control control, const KeyEvent& event )
+bool KeyInputFocusManager::EmitKeyEventSignal(Toolkit::Control control, const KeyEvent& event)
{
bool consumed = false;
- if( control )
+ if(control)
{
- consumed = GetImplementation( control ).EmitKeyEventSignal( event );
+ consumed = GetImplementation(control).EmitKeyEventSignal(event);
// if control doesn't consume KeyEvent, give KeyEvent to its parent.
- if( !consumed )
+ if(!consumed)
{
- Toolkit::Control parent = Toolkit::Control::DownCast( control.GetParent() );
+ Toolkit::Control parent = Toolkit::Control::DownCast(control.GetParent());
- if( parent )
+ if(parent)
{
- consumed = EmitKeyEventSignal( parent, event );
+ consumed = EmitKeyEventSignal(parent, event);
}
}
}
return consumed;
}
-void KeyInputFocusManager::OnFocusControlSceneDisconnection( Dali::Actor actor )
+void KeyInputFocusManager::OnFocusControlSceneDisconnection(Dali::Actor actor)
{
- RemoveFocus( Dali::Toolkit::Control::DownCast( actor ) );
+ RemoveFocus(Dali::Toolkit::Control::DownCast(actor));
}
-
-bool KeyInputFocusManager::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool KeyInputFocusManager::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- bool connected( true );
- KeyInputFocusManager* manager = dynamic_cast<KeyInputFocusManager*>( object );
+ bool connected(true);
+ KeyInputFocusManager* manager = dynamic_cast<KeyInputFocusManager*>(object);
- if( manager )
+ if(manager)
{
- if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_CHANGED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_CHANGED))
{
- manager->KeyInputFocusChangedSignal().Connect( tracker, functor );
+ manager->KeyInputFocusChangedSignal().Connect(tracker, functor);
}
else
{
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/helpers/color-conversion.h>
// EXTERNAL INCLUDES
-#include <sstream>
-#include <dali/public-api/math/vector4.h>
#include <dali/devel-api/adaptor-framework/color-controller.h>
+#include <dali/public-api/math/vector4.h>
+#include <sstream>
using Dali::Vector4;
namespace
{
-
/**
* Converts a HTML style 'color' hex string ("#FF0000" for bright red) to a Vector4.
* The Vector4 alpha component will be set to 1.0f
* @param hexString The HTML style hex string
* @return a Vector4 containing the new color value
*/
-Vector4 HexStringToVector4( const char* s )
+Vector4 HexStringToVector4(const char* s)
{
unsigned int value(0u);
- std::istringstream( s ) >> std::hex >> value;
- return Vector4( ((value >> 16 ) & 0xff ) / 255.0f,
- ((value >> 8 ) & 0xff ) / 255.0f,
- (value & 0xff ) / 255.0f,
- 1.0f );
+ std::istringstream(s) >> std::hex >> value;
+ return Vector4(((value >> 16) & 0xff) / 255.0f,
+ ((value >> 8) & 0xff) / 255.0f,
+ (value & 0xff) / 255.0f,
+ 1.0f);
}
} // unnamed namespace
{
namespace Internal
{
-
-bool ConvertStringToColor( const std::string& colorString, Vector4& outColor )
+bool ConvertStringToColor(const std::string& colorString, Vector4& outColor)
{
- bool success( false );
+ bool success(false);
- if( ( '#' == colorString[0] ) &&
- ( 7 == colorString.size() ) )
+ if(('#' == colorString[0]) &&
+ (7 == colorString.size()))
{
const char* cString = colorString.c_str();
- outColor = HexStringToVector4( &cString[1] );
- success = true;
+ outColor = HexStringToVector4(&cString[1]);
+ success = true;
}
else
{
Dali::ColorController controller = Dali::ColorController::Get();
- if( controller )
+ if(controller)
{
- success = controller.RetrieveColor( colorString, outColor );
+ success = controller.RetrieveColor(colorString, outColor);
}
}
return success;
}
-bool ConvertPropertyToColor( const Property::Value& colorValue, Vector4& outColor )
+bool ConvertPropertyToColor(const Property::Value& colorValue, Vector4& outColor)
{
- bool success( false );
+ bool success(false);
- if( Property::VECTOR4 == colorValue.GetType() )
+ if(Property::VECTOR4 == colorValue.GetType())
{
- success = colorValue.Get( outColor );
+ success = colorValue.Get(outColor);
}
- else if( Property::STRING == colorValue.GetType() )
+ else if(Property::STRING == colorValue.GetType())
{
std::string colorString;
- if( colorValue.Get( colorString ) )
+ if(colorValue.Get(colorString))
{
- success = ConvertStringToColor( colorString, outColor );
+ success = ConvertStringToColor(colorString, outColor);
}
}
return success;
}
-} // Internal
-} // Toolkit
-} // Dali
+} // namespace Internal
+} // namespace Toolkit
+} // namespace Dali
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-bool GetStringFromProperty( const Property::Value& value, std::string& output )
+bool GetStringFromProperty(const Property::Value& value, std::string& output)
{
bool extracted = false;
- if( value.Get( output ) )
+ if(value.Get(output))
{
extracted = true;
}
else
{
const Property::Array* array = value.GetArray();
- if( array )
+ if(array)
{
const unsigned int arraySize = array->Size();
- for( unsigned int i = 0; i < arraySize; ++i )
+ for(unsigned int i = 0; i < arraySize; ++i)
{
std::string element;
- if( array->GetElementAt( i ).Get( element ) )
+ if(array->GetElementAt(i).Get(element))
{
extracted = true;
output += element + '\n';
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
AsyncImageLoader::AsyncImageLoader()
: mLoadedSignal(),
- mLoadThread( new EventThreadCallback( MakeCallback( this, &AsyncImageLoader::ProcessLoadedImage ) ) ),
- mLoadTaskId( 0u ),
- mIsLoadThreadStarted( false )
+ mLoadThread(new EventThreadCallback(MakeCallback(this, &AsyncImageLoader::ProcessLoadedImage))),
+ mLoadTaskId(0u),
+ mIsLoadThreadStarted(false)
{
}
return internal;
}
-uint32_t AsyncImageLoader::LoadAnimatedImage( Dali::AnimatedImageLoading animatedImageLoading,
- uint32_t frameIndex )
+uint32_t AsyncImageLoader::LoadAnimatedImage(Dali::AnimatedImageLoading animatedImageLoading,
+ uint32_t frameIndex)
{
- if( !mIsLoadThreadStarted )
+ if(!mIsLoadThreadStarted)
{
mLoadThread.Start();
mIsLoadThreadStarted = true;
}
- mLoadThread.AddTask( new LoadingTask( ++mLoadTaskId, animatedImageLoading, frameIndex ) );
+ mLoadThread.AddTask(new LoadingTask(++mLoadTaskId, animatedImageLoading, frameIndex));
return mLoadTaskId;
}
-uint32_t AsyncImageLoader::Load( const VisualUrl& url,
- ImageDimensions dimensions,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection,
- DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
+uint32_t AsyncImageLoader::Load(const VisualUrl& url,
+ ImageDimensions dimensions,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection,
+ DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
{
- if( !mIsLoadThreadStarted )
+ if(!mIsLoadThreadStarted)
{
mLoadThread.Start();
mIsLoadThreadStarted = true;
}
- mLoadThread.AddTask( new LoadingTask( ++mLoadTaskId, url, dimensions, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad ) );
+ mLoadThread.AddTask(new LoadingTask(++mLoadTaskId, url, dimensions, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad));
return mLoadTaskId;
}
-uint32_t AsyncImageLoader::ApplyMask( Devel::PixelBuffer pixelBuffer,
- Devel::PixelBuffer maskPixelBuffer,
- float contentScale,
- bool cropToMask,
- DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
+uint32_t AsyncImageLoader::ApplyMask(Devel::PixelBuffer pixelBuffer,
+ Devel::PixelBuffer maskPixelBuffer,
+ float contentScale,
+ bool cropToMask,
+ DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
{
- if( !mIsLoadThreadStarted )
+ if(!mIsLoadThreadStarted)
{
mLoadThread.Start();
mIsLoadThreadStarted = true;
}
- mLoadThread.AddTask( new LoadingTask( ++mLoadTaskId, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad ) );
+ mLoadThread.AddTask(new LoadingTask(++mLoadTaskId, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad));
return mLoadTaskId;
}
return mPixelBufferLoadedSignal;
}
-bool AsyncImageLoader::Cancel( uint32_t loadingTaskId )
+bool AsyncImageLoader::Cancel(uint32_t loadingTaskId)
{
- return mLoadThread.CancelTask( loadingTaskId );
+ return mLoadThread.CancelTask(loadingTaskId);
}
void AsyncImageLoader::CancelAll()
void AsyncImageLoader::ProcessLoadedImage()
{
- while( LoadingTask *next = mLoadThread.NextCompletedTask() )
+ while(LoadingTask* next = mLoadThread.NextCompletedTask())
{
- if( mPixelBufferLoadedSignal.GetConnectionCount() > 0 )
+ if(mPixelBufferLoadedSignal.GetConnectionCount() > 0)
{
- mPixelBufferLoadedSignal.Emit( next->id, next->pixelBuffer );
+ mPixelBufferLoadedSignal.Emit(next->id, next->pixelBuffer);
}
- else if( mLoadedSignal.GetConnectionCount() > 0 )
+ else if(mLoadedSignal.GetConnectionCount() > 0)
{
PixelData pixelData;
- if( next->pixelBuffer )
+ if(next->pixelBuffer)
{
- pixelData = Devel::PixelBuffer::Convert( next->pixelBuffer );
+ pixelData = Devel::PixelBuffer::Convert(next->pixelBuffer);
}
- mLoadedSignal.Emit( next->id, pixelData );
+ mLoadedSignal.Emit(next->id, pixelData);
}
delete next;
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "atlas-packer.h"
// EXTERNAL HEADER
-#include <cstdlib> // For abs()
#include <dali/integration-api/debug.h>
+#include <cstdlib> // For abs()
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-bool ApproximatelyEqual( uint32_t a, uint32_t b )
+bool ApproximatelyEqual(uint32_t a, uint32_t b)
{
- return std::abs( static_cast<int32_t>( a - b ) ) <= 1;
+ return std::abs(static_cast<int32_t>(a - b)) <= 1;
}
-uint16_t MaxDimension( const Uint16Pair& dimensions )
+uint16_t MaxDimension(const Uint16Pair& dimensions)
{
return dimensions.GetWidth() >= dimensions.GetHeight() ? dimensions.GetWidth() : dimensions.GetHeight();
}
-void Swap( Uint16Pair& first, Uint16Pair& second )
+void Swap(Uint16Pair& first, Uint16Pair& second)
{
Uint16Pair temp = first;
- first = second;
- second = temp;
+ first = second;
+ second = temp;
}
-}
+} // namespace
-AtlasPacker::Node::Node( Node* parent, SizeType x, SizeType y, SizeType width, SizeType height )
-: rectArea( x, y, width, height ),
+AtlasPacker::Node::Node(Node* parent, SizeType x, SizeType y, SizeType width, SizeType height)
+: rectArea(x, y, width, height),
parent(parent),
- occupied( false )
+ occupied(false)
{
child[0] = NULL;
child[1] = NULL;
}
-AtlasPacker:: AtlasPacker( SizeType atlasWidth, SizeType atlasHeight )
-: mAvailableArea( atlasWidth * atlasHeight )
+AtlasPacker::AtlasPacker(SizeType atlasWidth, SizeType atlasHeight)
+: mAvailableArea(atlasWidth * atlasHeight)
{
- mRoot = new Node( NULL, 0u, 0u, atlasWidth, atlasHeight );
+ mRoot = new Node(NULL, 0u, 0u, atlasWidth, atlasHeight);
}
AtlasPacker::~AtlasPacker()
{
- DeleteNode( mRoot );
+ DeleteNode(mRoot);
}
-bool AtlasPacker::Pack( SizeType blockWidth, SizeType blockHeight,
- SizeType& packPositionX, SizeType& packPositionY)
+bool AtlasPacker::Pack(SizeType blockWidth, SizeType blockHeight, SizeType& packPositionX, SizeType& packPositionY)
{
- Node* firstFit = InsertNode( mRoot, blockWidth, blockHeight );
- if( firstFit != NULL )
+ Node* firstFit = InsertNode(mRoot, blockWidth, blockHeight);
+ if(firstFit != NULL)
{
firstFit->occupied = true;
- packPositionX = firstFit->rectArea.x;
- packPositionY = firstFit->rectArea.y;
- mAvailableArea -= blockWidth*blockHeight;
+ packPositionX = firstFit->rectArea.x;
+ packPositionY = firstFit->rectArea.y;
+ mAvailableArea -= blockWidth * blockHeight;
return true;
}
return false;
}
-void AtlasPacker::DeleteBlock( SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight )
+void AtlasPacker::DeleteBlock(SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight)
{
- Node* node = SearchNode( mRoot, packPositionX, packPositionY, blockWidth, blockHeight );
- if( node != NULL )
+ Node* node = SearchNode(mRoot, packPositionX, packPositionY, blockWidth, blockHeight);
+ if(node != NULL)
{
- mAvailableArea += blockWidth*blockHeight;
- MergeToNonOccupied( node );
+ mAvailableArea += blockWidth * blockHeight;
+ MergeToNonOccupied(node);
}
}
return mAvailableArea;
}
-AtlasPacker::Node* AtlasPacker::InsertNode( Node* root, SizeType blockWidth, SizeType blockHeight )
+AtlasPacker::Node* AtlasPacker::InsertNode(Node* root, SizeType blockWidth, SizeType blockHeight)
{
- if( root == NULL )
+ if(root == NULL)
{
return NULL;
}
- if( root->occupied )
+ if(root->occupied)
{
// if not the leaf, then try insert into the first child.
Node* newNode = InsertNode(root->child[0], blockWidth, blockHeight);
- if( newNode == NULL )// no room, try insert into the second child.
+ if(newNode == NULL) // no room, try insert into the second child.
{
newNode = InsertNode(root->child[1], blockWidth, blockHeight);
}
}
// too small, return
- if( root->rectArea.width < blockWidth || root->rectArea.height < blockHeight )
+ if(root->rectArea.width < blockWidth || root->rectArea.height < blockHeight)
{
return NULL;
}
// right size, accept
- if( root->rectArea.width == blockWidth && root->rectArea.height == blockHeight )
+ if(root->rectArea.width == blockWidth && root->rectArea.height == blockHeight)
{
return root;
}
//too much room, need to split
- SplitNode( root, blockWidth, blockHeight );
+ SplitNode(root, blockWidth, blockHeight);
// insert into the first child created.
- return InsertNode( root->child[0], blockWidth, blockHeight);
+ return InsertNode(root->child[0], blockWidth, blockHeight);
}
-void AtlasPacker::SplitNode( Node* node, SizeType blockWidth, SizeType blockHeight )
+void AtlasPacker::SplitNode(Node* node, SizeType blockWidth, SizeType blockHeight)
{
node->occupied = true;
// decide which way to split
- SizeType remainingWidth = node->rectArea.width - blockWidth;
+ SizeType remainingWidth = node->rectArea.width - blockWidth;
SizeType remainingHeight = node->rectArea.height - blockHeight;
- if( remainingWidth > remainingHeight ) // split vertically
+ if(remainingWidth > remainingHeight) // split vertically
{
- node->child[0] = new Node( node, node->rectArea.x, node->rectArea.y, blockWidth, node->rectArea.height );
- node->child[1] = new Node( node, node->rectArea.x+blockWidth, node->rectArea.y, node->rectArea.width-blockWidth, node->rectArea.height );
+ node->child[0] = new Node(node, node->rectArea.x, node->rectArea.y, blockWidth, node->rectArea.height);
+ node->child[1] = new Node(node, node->rectArea.x + blockWidth, node->rectArea.y, node->rectArea.width - blockWidth, node->rectArea.height);
}
else // split horizontally
{
- node->child[0] = new Node( node, node->rectArea.x, node->rectArea.y, node->rectArea.width, blockHeight );
- node->child[1] = new Node( node, node->rectArea.x, node->rectArea.y+blockHeight, node->rectArea.width, node->rectArea.height-blockHeight );
+ node->child[0] = new Node(node, node->rectArea.x, node->rectArea.y, node->rectArea.width, blockHeight);
+ node->child[1] = new Node(node, node->rectArea.x, node->rectArea.y + blockHeight, node->rectArea.width, node->rectArea.height - blockHeight);
}
}
-AtlasPacker::Node* AtlasPacker::SearchNode( Node* node, SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight )
+AtlasPacker::Node* AtlasPacker::SearchNode(Node* node, SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight)
{
- if( node != NULL )
+ if(node != NULL)
{
- if( node->child[0] != NULL) //not a leaf
+ if(node->child[0] != NULL) //not a leaf
{
Node* newNode = SearchNode(node->child[0], packPositionX, packPositionY, blockWidth, blockHeight);
- if( newNode == NULL )// try search from the second child.
+ if(newNode == NULL) // try search from the second child.
{
newNode = SearchNode(node->child[1], packPositionX, packPositionY, blockWidth, blockHeight);
}
return newNode;
}
- else if( ApproximatelyEqual(node->rectArea.x, packPositionX) && ApproximatelyEqual(node->rectArea.y, packPositionY )
- && ApproximatelyEqual(node->rectArea.width, blockWidth) && ApproximatelyEqual( node->rectArea.height, blockHeight) )
+ else if(ApproximatelyEqual(node->rectArea.x, packPositionX) && ApproximatelyEqual(node->rectArea.y, packPositionY) && ApproximatelyEqual(node->rectArea.width, blockWidth) && ApproximatelyEqual(node->rectArea.height, blockHeight))
{
return node;
}
return NULL;
}
-void AtlasPacker::MergeToNonOccupied( Node* node )
+void AtlasPacker::MergeToNonOccupied(Node* node)
{
node->occupied = false;
- Node* parent = node->parent;
+ Node* parent = node->parent;
// both child are not occupied, merge the space to parent
- if( parent != NULL && parent->child[0]->occupied == false && parent->child[1]->occupied == false)
+ if(parent != NULL && parent->child[0]->occupied == false && parent->child[1]->occupied == false)
{
delete parent->child[0];
parent->child[0] = NULL;
delete parent->child[1];
parent->child[1] = NULL;
- MergeToNonOccupied( parent );
+ MergeToNonOccupied(parent);
}
}
-void AtlasPacker::DeleteNode( Node *node )
+void AtlasPacker::DeleteNode(Node* node)
{
- if( node != NULL )
+ if(node != NULL)
{
- DeleteNode( node->child[0] );
- DeleteNode( node->child[1] );
+ DeleteNode(node->child[0]);
+ DeleteNode(node->child[1]);
delete node;
}
}
-Uint16Pair AtlasPacker::GroupPack( const Dali::Vector<Uint16Pair>& blockSizes, Dali::Vector<Uint16Pair>& packPositions )
+Uint16Pair AtlasPacker::GroupPack(const Dali::Vector<Uint16Pair>& blockSizes, Dali::Vector<Uint16Pair>& packPositions)
{
uint16_t count = blockSizes.Count();
- packPositions.Resize( count );
+ packPositions.Resize(count);
// Sort the blocks according to its maximum dimension. The bigger blocks are packed first.
Dali::Vector<Uint16Pair> packOrder;
- packOrder.Resize( count );
- for( uint16_t i = 0; i < count; i++ )
+ packOrder.Resize(count);
+ for(uint16_t i = 0; i < count; i++)
{
- packOrder[i].SetX( MaxDimension( blockSizes[i] ) );
- packOrder[i].SetY( i );
+ packOrder[i].SetX(MaxDimension(blockSizes[i]));
+ packOrder[i].SetY(i);
}
- for( uint16_t i = 0; i < count-1; i++ )
- for( uint16_t j = 0; j < count-i-1; j++ )
+ for(uint16_t i = 0; i < count - 1; i++)
+ for(uint16_t j = 0; j < count - i - 1; j++)
{
- if( packOrder[j].GetX() < packOrder[j+1].GetX() )
+ if(packOrder[j].GetX() < packOrder[j + 1].GetX())
{
- Swap( packOrder[j], packOrder[j+1] );
+ Swap(packOrder[j], packOrder[j + 1]);
}
}
- int index = packOrder[0].GetY();
- AtlasPacker packer( blockSizes[index].GetWidth(), blockSizes[index].GetHeight() );
+ int index = packOrder[0].GetY();
+ AtlasPacker packer(blockSizes[index].GetWidth(), blockSizes[index].GetHeight());
SizeType packPositionX, packPositionY;
// pack the blocks one by one with descending size, grows as necessary to accommodate each subsequent block.
- for( uint16_t i = 0; i < count; i++ )
+ for(uint16_t i = 0; i < count; i++)
{
index = packOrder[i].GetY();
- packer.GrowPack( blockSizes[index].GetWidth(), blockSizes[index].GetHeight(),
- packPositionX, packPositionY );
- packPositions[index].SetX( packPositionX );
- packPositions[index].SetY( packPositionY );
+ packer.GrowPack(blockSizes[index].GetWidth(), blockSizes[index].GetHeight(), packPositionX, packPositionY);
+ packPositions[index].SetX(packPositionX);
+ packPositions[index].SetY(packPositionY);
}
- return Uint16Pair( packer.mRoot->rectArea.width, packer.mRoot->rectArea.height );
+ return Uint16Pair(packer.mRoot->rectArea.width, packer.mRoot->rectArea.height);
}
-void AtlasPacker::GrowPack( SizeType blockWidth, SizeType blockHeight,
- SizeType& packPositionX, SizeType& packPositionY )
+void AtlasPacker::GrowPack(SizeType blockWidth, SizeType blockHeight, SizeType& packPositionX, SizeType& packPositionY)
{
- Node* firstFit = InsertNode( mRoot, blockWidth, blockHeight );
- if( firstFit == NULL )
+ Node* firstFit = InsertNode(mRoot, blockWidth, blockHeight);
+ if(firstFit == NULL)
{
// Could fit in the current left space, grow the partition tree to get more space.
- GrowNode( blockWidth, blockHeight );
- firstFit = InsertNode( mRoot->child[1], blockWidth, blockHeight );
+ GrowNode(blockWidth, blockHeight);
+ firstFit = InsertNode(mRoot->child[1], blockWidth, blockHeight);
}
- DALI_ASSERT_ALWAYS( firstFit != NULL && "It should never happen!")
+ DALI_ASSERT_ALWAYS(firstFit != NULL && "It should never happen!")
firstFit->occupied = true;
- packPositionX = firstFit->rectArea.x;
- packPositionY = firstFit->rectArea.y;
+ packPositionX = firstFit->rectArea.x;
+ packPositionY = firstFit->rectArea.y;
}
-void AtlasPacker::GrowNode( SizeType blockWidth, SizeType blockHeight )
+void AtlasPacker::GrowNode(SizeType blockWidth, SizeType blockHeight)
{
// Attempts to maintain a roughly square ratio when choosing the growing direction: right or down
bool canGrowRight = blockWidth <= mRoot->rectArea.width;
- bool canGrowDown = blockHeight <= mRoot->rectArea.height;
+ bool canGrowDown = blockHeight <= mRoot->rectArea.height;
- bool shouldGrowRight = canGrowRight && mRoot->rectArea.height >= mRoot->rectArea.width+blockWidth;
- bool shouldGrowDown = canGrowDown && mRoot->rectArea.width >= mRoot->rectArea.height+blockHeight;
+ bool shouldGrowRight = canGrowRight && mRoot->rectArea.height >= mRoot->rectArea.width + blockWidth;
+ bool shouldGrowDown = canGrowDown && mRoot->rectArea.width >= mRoot->rectArea.height + blockHeight;
- if( canGrowRight && canGrowDown )
+ if(canGrowRight && canGrowDown)
{
- shouldGrowRight = mRoot->rectArea.width+blockWidth <= mRoot->rectArea.height+blockHeight;
- shouldGrowDown = !shouldGrowRight;
+ shouldGrowRight = mRoot->rectArea.width + blockWidth <= mRoot->rectArea.height + blockHeight;
+ shouldGrowDown = !shouldGrowRight;
}
- if( shouldGrowRight || ( canGrowRight && !shouldGrowDown ) )
+ if(shouldGrowRight || (canGrowRight && !shouldGrowDown))
{
- Node* newRoot = new Node( NULL, 0u, 0u, mRoot->rectArea.width+blockWidth, mRoot->rectArea.height );
+ Node* newRoot = new Node(NULL, 0u, 0u, mRoot->rectArea.width + blockWidth, mRoot->rectArea.height);
newRoot->occupied = true;
newRoot->child[0] = mRoot;
- newRoot->child[1] = new Node( newRoot, mRoot->rectArea.width, 0u, blockWidth, mRoot->rectArea.height );
+ newRoot->child[1] = new Node(newRoot, mRoot->rectArea.width, 0u, blockWidth, mRoot->rectArea.height);
mRoot = newRoot;
}
- else if( shouldGrowDown || ( canGrowDown && !shouldGrowRight ) )
+ else if(shouldGrowDown || (canGrowDown && !shouldGrowRight))
{
- Node* newRoot = new Node( NULL, 0u, 0u, mRoot->rectArea.width, mRoot->rectArea.height+blockHeight );
+ Node* newRoot = new Node(NULL, 0u, 0u, mRoot->rectArea.width, mRoot->rectArea.height + blockHeight);
newRoot->occupied = true;
newRoot->child[0] = mRoot;
- newRoot->child[1] = new Node( newRoot, 0u, mRoot->rectArea.height, mRoot->rectArea.width, blockHeight );
+ newRoot->child[1] = new Node(newRoot, 0u, mRoot->rectArea.height, mRoot->rectArea.width, blockHeight);
mRoot = newRoot;
}
else
{
- DALI_LOG_ERROR( " Atlas Packer failed to grow: make sure the packing order is sorted with the block size to avoid this happening");
+ DALI_LOG_ERROR(" Atlas Packer failed to grow: make sure the packing order is sorted with the block size to avoid this happening");
}
}
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "image-atlas-impl.h"
// EXTERNAL INCLUDES
-#include <string.h>
-#include <dali/public-api/signals/callback.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/signals/callback.h>
+#include <string.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
typedef unsigned char PixelBuffer;
-Texture ImageAtlas::PackToAtlas( const std::vector<PixelData>& pixelData, Dali::Vector<Vector4>& textureRects )
+Texture ImageAtlas::PackToAtlas(const std::vector<PixelData>& pixelData, Dali::Vector<Vector4>& textureRects)
{
// Record each block size
Dali::Vector<Uint16Pair> blockSizes;
- SizeType count = pixelData.size();
- for( SizeType index = 0; index < count; index++ )
+ SizeType count = pixelData.size();
+ for(SizeType index = 0; index < count; index++)
{
- blockSizes.PushBack( ImageDimensions( pixelData[index].GetWidth(), pixelData[index].GetHeight() ) );
+ blockSizes.PushBack(ImageDimensions(pixelData[index].GetWidth(), pixelData[index].GetHeight()));
}
// Ask atlasPacker for packing position of each block
Dali::Vector<Uint16Pair> packPositions;
- ImageDimensions atlasSize = AtlasPacker::GroupPack( blockSizes, packPositions );
+ ImageDimensions atlasSize = AtlasPacker::GroupPack(blockSizes, packPositions);
// Prepare for outout texture rect array
textureRects.Clear();
- textureRects.Resize( count );
+ textureRects.Resize(count);
// create the texture for uploading the multiple pixel data
- Texture atlasTexture = Texture::New( Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, atlasSize.GetWidth(), atlasSize.GetHeight() );
+ Texture atlasTexture = Texture::New(Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, atlasSize.GetWidth(), atlasSize.GetHeight());
- float atlasWidth = static_cast<float>( atlasTexture.GetWidth() );
- float atlasHeight = static_cast<float>( atlasTexture.GetHeight() );
- int packPositionX, packPositionY;
+ float atlasWidth = static_cast<float>(atlasTexture.GetWidth());
+ float atlasHeight = static_cast<float>(atlasTexture.GetHeight());
+ int packPositionX, packPositionY;
// Upload the pixel data one by one to its packing position, and record the texture rects
- for( SizeType index = 0; index < count; index++ )
+ for(SizeType index = 0; index < count; index++)
{
packPositionX = packPositions[index].GetX();
packPositionY = packPositions[index].GetY();
- atlasTexture.Upload( pixelData[index], 0u, 0u,
- packPositionX, packPositionY,
- pixelData[index].GetWidth(), pixelData[index].GetHeight() );
+ atlasTexture.Upload(pixelData[index], 0u, 0u, packPositionX, packPositionY, pixelData[index].GetWidth(), pixelData[index].GetHeight());
// Apply the half pixel correction to avoid the color bleeding between neighbour blocks
- textureRects[index].x = ( static_cast<float>( packPositionX ) +0.5f ) / atlasWidth; // left
- textureRects[index].y = ( static_cast<float>( packPositionY ) +0.5f ) / atlasHeight; // right
- textureRects[index].z = ( static_cast<float>( packPositionX + pixelData[index].GetWidth() )-0.5f ) / atlasWidth; // right
- textureRects[index].w = ( static_cast<float>( packPositionY + pixelData[index].GetHeight() )-0.5f ) / atlasHeight;// bottom
+ textureRects[index].x = (static_cast<float>(packPositionX) + 0.5f) / atlasWidth; // left
+ textureRects[index].y = (static_cast<float>(packPositionY) + 0.5f) / atlasHeight; // right
+ textureRects[index].z = (static_cast<float>(packPositionX + pixelData[index].GetWidth()) - 0.5f) / atlasWidth; // right
+ textureRects[index].w = (static_cast<float>(packPositionY + pixelData[index].GetHeight()) - 0.5f) / atlasHeight; // bottom
}
return atlasTexture;
}
-ImageAtlas::ImageAtlas( SizeType width, SizeType height, Pixel::Format pixelFormat )
-: mAtlas( Texture::New( Dali::TextureType::TEXTURE_2D, pixelFormat, width, height ) ),
- mPacker( width, height ),
- mAsyncLoader( Toolkit::AsyncImageLoader::New() ),
+ImageAtlas::ImageAtlas(SizeType width, SizeType height, Pixel::Format pixelFormat)
+: mAtlas(Texture::New(Dali::TextureType::TEXTURE_2D, pixelFormat, width, height)),
+ mPacker(width, height),
+ mAsyncLoader(Toolkit::AsyncImageLoader::New()),
mBrokenImageUrl(""),
mBrokenImageSize(),
- mWidth( static_cast<float>(width) ),
- mHeight( static_cast<float>( height ) ),
- mPixelFormat( pixelFormat )
+ mWidth(static_cast<float>(width)),
+ mHeight(static_cast<float>(height)),
+ mPixelFormat(pixelFormat)
{
- mAsyncLoader.ImageLoadedSignal().Connect( this, &ImageAtlas::UploadToAtlas );
+ mAsyncLoader.ImageLoadedSignal().Connect(this, &ImageAtlas::UploadToAtlas);
}
ImageAtlas::~ImageAtlas()
{
const std::size_t count = mLoadingTaskInfoContainer.Count();
- for( std::size_t i=0; i < count; ++i )
+ for(std::size_t i = 0; i < count; ++i)
{
// Call unregister to every observer in the list.
// Note that, the Atlas can be registered to same observer multiple times, and the Unregister method only remove one item each time.
// In this way, the atlas is actually detached from a observer either every upload call invoked by this observer is completed or atlas is destroyed.
- if( mLoadingTaskInfoContainer[i]->observer )
+ if(mLoadingTaskInfoContainer[i]->observer)
{
- mLoadingTaskInfoContainer[i]->observer->Unregister( *this );
+ mLoadingTaskInfoContainer[i]->observer->Unregister(*this);
}
}
mLoadingTaskInfoContainer.Clear();
}
-IntrusivePtr<ImageAtlas> ImageAtlas::New( SizeType width, SizeType height, Pixel::Format pixelFormat )
+IntrusivePtr<ImageAtlas> ImageAtlas::New(SizeType width, SizeType height, Pixel::Format pixelFormat)
{
- IntrusivePtr<ImageAtlas> internal = new ImageAtlas( width, height, pixelFormat );
+ IntrusivePtr<ImageAtlas> internal = new ImageAtlas(width, height, pixelFormat);
return internal;
}
float ImageAtlas::GetOccupancyRate() const
{
- return 1.f - static_cast<float>( mPacker.GetAvailableArea() ) / ( mWidth*mHeight );
+ return 1.f - static_cast<float>(mPacker.GetAvailableArea()) / (mWidth * mHeight);
}
-void ImageAtlas::SetBrokenImage( const std::string& brokenImageUrl )
+void ImageAtlas::SetBrokenImage(const std::string& brokenImageUrl)
{
- mBrokenImageSize = Dali::GetClosestImageSize( brokenImageUrl );
- if(mBrokenImageSize.GetWidth() > 0 && mBrokenImageSize.GetHeight() > 0 ) // check the url is valid
+ mBrokenImageSize = Dali::GetClosestImageSize(brokenImageUrl);
+ if(mBrokenImageSize.GetWidth() > 0 && mBrokenImageSize.GetHeight() > 0) // check the url is valid
{
mBrokenImageUrl = brokenImageUrl;
}
}
-bool ImageAtlas::Upload( Vector4& textureRect,
- const std::string& url,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- bool orientationCorrection,
- AtlasUploadObserver* atlasUploadObserver )
+bool ImageAtlas::Upload(Vector4& textureRect,
+ const std::string& url,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ bool orientationCorrection,
+ AtlasUploadObserver* atlasUploadObserver)
{
ImageDimensions dimensions = size;
ImageDimensions zero;
- if( size == zero ) // image size not provided
+ if(size == zero) // image size not provided
{
- dimensions = Dali::GetClosestImageSize( url );
- if( dimensions == zero ) // Fail to read the image & broken image file exists
+ dimensions = Dali::GetClosestImageSize(url);
+ if(dimensions == zero) // Fail to read the image & broken image file exists
{
- if( !mBrokenImageUrl.empty() )
+ if(!mBrokenImageUrl.empty())
{
- return Upload( textureRect, mBrokenImageUrl, mBrokenImageSize, FittingMode::DEFAULT, true, atlasUploadObserver );
+ return Upload(textureRect, mBrokenImageUrl, mBrokenImageSize, FittingMode::DEFAULT, true, atlasUploadObserver);
}
else
{
unsigned int packPositionX = 0;
unsigned int packPositionY = 0;
- if( mPacker.Pack( dimensions.GetWidth(), dimensions.GetHeight(), packPositionX, packPositionY ) )
+ if(mPacker.Pack(dimensions.GetWidth(), dimensions.GetHeight(), packPositionX, packPositionY))
{
- unsigned short loadId = mAsyncLoader.Load( url, size, fittingMode, SamplingMode::BOX_THEN_LINEAR, orientationCorrection);
- mLoadingTaskInfoContainer.PushBack( new LoadingTaskInfo( loadId, packPositionX, packPositionY, dimensions.GetWidth(), dimensions.GetHeight(), atlasUploadObserver ) );
+ unsigned short loadId = mAsyncLoader.Load(url, size, fittingMode, SamplingMode::BOX_THEN_LINEAR, orientationCorrection);
+ mLoadingTaskInfoContainer.PushBack(new LoadingTaskInfo(loadId, packPositionX, packPositionY, dimensions.GetWidth(), dimensions.GetHeight(), atlasUploadObserver));
// apply the half pixel correction
- textureRect.x = ( static_cast<float>( packPositionX ) +0.5f ) / mWidth; // left
- textureRect.y = ( static_cast<float>( packPositionY ) +0.5f ) / mHeight; // right
- textureRect.z = ( static_cast<float>( packPositionX + dimensions.GetX() )-0.5f ) / mWidth; // right
- textureRect.w = ( static_cast<float>( packPositionY + dimensions.GetY() )-0.5f ) / mHeight;// bottom
+ textureRect.x = (static_cast<float>(packPositionX) + 0.5f) / mWidth; // left
+ textureRect.y = (static_cast<float>(packPositionY) + 0.5f) / mHeight; // right
+ textureRect.z = (static_cast<float>(packPositionX + dimensions.GetX()) - 0.5f) / mWidth; // right
+ textureRect.w = (static_cast<float>(packPositionY + dimensions.GetY()) - 0.5f) / mHeight; // bottom
- if( atlasUploadObserver )
+ if(atlasUploadObserver)
{
// register to the observer,
// Not that a matching unregister call should be invoked in UploadToAtlas if the observer is still alive by then.
- atlasUploadObserver->Register( *this );
+ atlasUploadObserver->Register(*this);
}
return true;
return false;
}
-bool ImageAtlas::Upload( Vector4& textureRect, PixelData pixelData )
+bool ImageAtlas::Upload(Vector4& textureRect, PixelData pixelData)
{
unsigned int packPositionX = 0;
unsigned int packPositionY = 0;
- if( mPacker.Pack( pixelData.GetWidth(), pixelData.GetHeight(), packPositionX, packPositionY ) )
+ if(mPacker.Pack(pixelData.GetWidth(), pixelData.GetHeight(), packPositionX, packPositionY))
{
- mAtlas.Upload( pixelData, 0u, 0u, packPositionX, packPositionY, pixelData.GetWidth(), pixelData.GetHeight() );
+ mAtlas.Upload(pixelData, 0u, 0u, packPositionX, packPositionY, pixelData.GetWidth(), pixelData.GetHeight());
// apply the half pixel correction
- textureRect.x = ( static_cast<float>( packPositionX ) +0.5f ) / mWidth; // left
- textureRect.y = ( static_cast<float>( packPositionY ) +0.5f ) / mHeight; // right
- textureRect.z = ( static_cast<float>( packPositionX + pixelData.GetWidth() )-0.5f ) / mWidth; // right
- textureRect.w = ( static_cast<float>( packPositionY + pixelData.GetHeight() )-0.5f ) / mHeight;// bottom
+ textureRect.x = (static_cast<float>(packPositionX) + 0.5f) / mWidth; // left
+ textureRect.y = (static_cast<float>(packPositionY) + 0.5f) / mHeight; // right
+ textureRect.z = (static_cast<float>(packPositionX + pixelData.GetWidth()) - 0.5f) / mWidth; // right
+ textureRect.w = (static_cast<float>(packPositionY + pixelData.GetHeight()) - 0.5f) / mHeight; // bottom
return true;
}
return false;
}
-void ImageAtlas::Remove( const Vector4& textureRect )
+void ImageAtlas::Remove(const Vector4& textureRect)
{
- mPacker.DeleteBlock( static_cast<SizeType>(textureRect.x*mWidth),
- static_cast<SizeType>(textureRect.y*mHeight),
- static_cast<SizeType>((textureRect.z-textureRect.x)*mWidth+1.f),
- static_cast<SizeType>((textureRect.w-textureRect.y)*mHeight+1.f) );
+ mPacker.DeleteBlock(static_cast<SizeType>(textureRect.x * mWidth),
+ static_cast<SizeType>(textureRect.y * mHeight),
+ static_cast<SizeType>((textureRect.z - textureRect.x) * mWidth + 1.f),
+ static_cast<SizeType>((textureRect.w - textureRect.y) * mHeight + 1.f));
}
-void ImageAtlas::ObserverDestroyed( AtlasUploadObserver* observer )
+void ImageAtlas::ObserverDestroyed(AtlasUploadObserver* observer)
{
const std::size_t count = mLoadingTaskInfoContainer.Count();
- for( std::size_t i=0; i < count; ++i )
+ for(std::size_t i = 0; i < count; ++i)
{
- if( mLoadingTaskInfoContainer[i]->observer == observer )
+ if(mLoadingTaskInfoContainer[i]->observer == observer)
{
// the observer is destructing, so its member function should not be called anymore
mLoadingTaskInfoContainer[i]->observer = NULL;
}
}
-void ImageAtlas::UploadToAtlas( uint32_t id, PixelData pixelData )
+void ImageAtlas::UploadToAtlas(uint32_t id, PixelData pixelData)
{
- if( mLoadingTaskInfoContainer[0]->loadTaskId == id)
+ if(mLoadingTaskInfoContainer[0]->loadTaskId == id)
{
- Rect<unsigned int> packRect( mLoadingTaskInfoContainer[0]->packRect );
- if( !pixelData || ( pixelData.GetWidth() ==0 && pixelData.GetHeight() == 0 ))
+ Rect<unsigned int> packRect(mLoadingTaskInfoContainer[0]->packRect);
+ if(!pixelData || (pixelData.GetWidth() == 0 && pixelData.GetHeight() == 0))
{
if(!mBrokenImageUrl.empty()) // replace with the broken image
{
- UploadBrokenImage( packRect );
+ UploadBrokenImage(packRect);
}
}
else
{
- if( pixelData.GetWidth() < packRect.width || pixelData.GetHeight() < packRect.height )
+ if(pixelData.GetWidth() < packRect.width || pixelData.GetHeight() < packRect.height)
{
- DALI_LOG_ERROR( "Can not upscale the image from actual loaded size [ %d, %d ] to specified size [ %d, %d ]\n",
- pixelData.GetWidth(), pixelData.GetHeight(),
- packRect.width, packRect.height );
+ DALI_LOG_ERROR("Can not upscale the image from actual loaded size [ %d, %d ] to specified size [ %d, %d ]\n",
+ pixelData.GetWidth(),
+ pixelData.GetHeight(),
+ packRect.width,
+ packRect.height);
}
- mAtlas.Upload( pixelData, 0u, 0u, packRect.x, packRect.y, packRect.width, packRect.height );
+ mAtlas.Upload(pixelData, 0u, 0u, packRect.x, packRect.y, packRect.width, packRect.height);
}
- if( mLoadingTaskInfoContainer[0]->observer )
+ if(mLoadingTaskInfoContainer[0]->observer)
{
mLoadingTaskInfoContainer[0]->observer->UploadCompleted();
- mLoadingTaskInfoContainer[0]->observer->Unregister( *this );
+ mLoadingTaskInfoContainer[0]->observer->Unregister(*this);
}
- mLoadingTaskInfoContainer.Erase( mLoadingTaskInfoContainer.Begin() );
+ mLoadingTaskInfoContainer.Erase(mLoadingTaskInfoContainer.Begin());
}
}
-void ImageAtlas::UploadBrokenImage( const Rect<unsigned int>& area )
+void ImageAtlas::UploadBrokenImage(const Rect<unsigned int>& area)
{
- Devel::PixelBuffer brokenBuffer = LoadImageFromFile( mBrokenImageUrl, ImageDimensions( area.width, area.height ) );
- SizeType loadedWidth = brokenBuffer.GetWidth();
- SizeType loadedHeight = brokenBuffer.GetHeight();
+ Devel::PixelBuffer brokenBuffer = LoadImageFromFile(mBrokenImageUrl, ImageDimensions(area.width, area.height));
+ SizeType loadedWidth = brokenBuffer.GetWidth();
+ SizeType loadedHeight = brokenBuffer.GetHeight();
- bool needBackgroundClear = false;
- SizeType packX = area.x;
- SizeType packY = area.y;
+ bool needBackgroundClear = false;
+ SizeType packX = area.x;
+ SizeType packY = area.y;
// locate the broken image in the middle.
- if( area.width > loadedWidth)
+ if(area.width > loadedWidth)
{
- packX += (area.width - loadedWidth)/2;
+ packX += (area.width - loadedWidth) / 2;
needBackgroundClear = true;
}
- if( area.height > loadedHeight)
+ if(area.height > loadedHeight)
{
- packY += (area.height - loadedHeight)/2;
+ packY += (area.height - loadedHeight) / 2;
needBackgroundClear = true;
}
- if( needBackgroundClear )
+ if(needBackgroundClear)
{
- SizeType size = area.width * area.height * Pixel::GetBytesPerPixel( mPixelFormat );
- Devel::PixelBuffer background = Devel::PixelBuffer::New( area.width, area.height, mPixelFormat );
- unsigned char* buffer = background.GetBuffer();
- for( SizeType idx = 0; idx < size; idx++ )
+ SizeType size = area.width * area.height * Pixel::GetBytesPerPixel(mPixelFormat);
+ Devel::PixelBuffer background = Devel::PixelBuffer::New(area.width, area.height, mPixelFormat);
+ unsigned char* buffer = background.GetBuffer();
+ for(SizeType idx = 0; idx < size; idx++)
{
buffer[idx] = 0x00;
}
- PixelData pixelData = Devel::PixelBuffer::Convert( background );
- mAtlas.Upload( pixelData, 0u, 0u, area.x, area.y, area.width, area.height );
+ PixelData pixelData = Devel::PixelBuffer::Convert(background);
+ mAtlas.Upload(pixelData, 0u, 0u, area.x, area.y, area.width, area.height);
}
- PixelData brokenPixelData = Devel::PixelBuffer::Convert( brokenBuffer );
- mAtlas.Upload( brokenPixelData, 0u, 0u, packX, packY, loadedWidth, loadedHeight );
+ PixelData brokenPixelData = Devel::PixelBuffer::Convert(brokenBuffer);
+ mAtlas.Upload(brokenPixelData, 0u, 0u, packX, packY, loadedWidth, loadedHeight);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-LoadingTask::LoadingTask( uint32_t id, Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex )
+LoadingTask::LoadingTask(uint32_t id, Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex)
: pixelBuffer(),
url(),
- id( id ),
+ id(id),
dimensions(),
fittingMode(),
samplingMode(),
orientationCorrection(),
- preMultiplyOnLoad( DevelAsyncImageLoader::PreMultiplyOnLoad::OFF ),
- isMaskTask( false ),
+ preMultiplyOnLoad(DevelAsyncImageLoader::PreMultiplyOnLoad::OFF),
+ isMaskTask(false),
maskPixelBuffer(),
- contentScale( 1.0f ),
- cropToMask( false ),
- animatedImageLoading( animatedImageLoading ),
- frameIndex( frameIndex )
+ contentScale(1.0f),
+ cropToMask(false),
+ animatedImageLoading(animatedImageLoading),
+ frameIndex(frameIndex)
{
}
-LoadingTask::LoadingTask( uint32_t id, const VisualUrl& url, ImageDimensions dimensions,
- FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection, DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
+LoadingTask::LoadingTask(uint32_t id, const VisualUrl& url, ImageDimensions dimensions, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection, DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
: pixelBuffer(),
- url( url ),
- id( id ),
- dimensions( dimensions ),
- fittingMode( fittingMode ),
- samplingMode( samplingMode ),
- orientationCorrection( orientationCorrection ),
- preMultiplyOnLoad( preMultiplyOnLoad ),
- isMaskTask( false ),
+ url(url),
+ id(id),
+ dimensions(dimensions),
+ fittingMode(fittingMode),
+ samplingMode(samplingMode),
+ orientationCorrection(orientationCorrection),
+ preMultiplyOnLoad(preMultiplyOnLoad),
+ isMaskTask(false),
maskPixelBuffer(),
- contentScale( 1.0f ),
- cropToMask( false ),
+ contentScale(1.0f),
+ cropToMask(false),
animatedImageLoading(),
- frameIndex( 0u )
+ frameIndex(0u)
{
}
-LoadingTask::LoadingTask( uint32_t id, Devel::PixelBuffer pixelBuffer, Devel::PixelBuffer maskPixelBuffer, float contentScale, bool cropToMask,
- DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
-: pixelBuffer( pixelBuffer ),
- url( "" ),
- id( id ),
+LoadingTask::LoadingTask(uint32_t id, Devel::PixelBuffer pixelBuffer, Devel::PixelBuffer maskPixelBuffer, float contentScale, bool cropToMask, DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
+: pixelBuffer(pixelBuffer),
+ url(""),
+ id(id),
dimensions(),
fittingMode(),
samplingMode(),
orientationCorrection(),
- preMultiplyOnLoad( preMultiplyOnLoad ),
- isMaskTask( true ),
- maskPixelBuffer( maskPixelBuffer ),
- contentScale( contentScale ),
- cropToMask( cropToMask ),
+ preMultiplyOnLoad(preMultiplyOnLoad),
+ isMaskTask(true),
+ maskPixelBuffer(maskPixelBuffer),
+ contentScale(contentScale),
+ cropToMask(cropToMask),
animatedImageLoading(),
- frameIndex( 0u )
+ frameIndex(0u)
{
}
void LoadingTask::Load()
{
- if( animatedImageLoading )
+ if(animatedImageLoading)
{
- pixelBuffer = animatedImageLoading.LoadFrame( frameIndex );
+ pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
}
- else if( url.IsLocalResource() )
+ else if(url.IsLocalResource())
{
- pixelBuffer = Dali::LoadImageFromFile( url.GetUrl(), dimensions, fittingMode, samplingMode, orientationCorrection );
+ pixelBuffer = Dali::LoadImageFromFile(url.GetUrl(), dimensions, fittingMode, samplingMode, orientationCorrection);
}
else
{
- pixelBuffer = Dali::DownloadImageSynchronously ( url.GetUrl(), dimensions, fittingMode, samplingMode, orientationCorrection );
+ pixelBuffer = Dali::DownloadImageSynchronously(url.GetUrl(), dimensions, fittingMode, samplingMode, orientationCorrection);
}
- if( !pixelBuffer )
+ if(!pixelBuffer)
{
- DALI_LOG_ERROR( "LoadingTask::Load: Loading is failed: %s\n", url.GetUrl().c_str() );
+ DALI_LOG_ERROR("LoadingTask::Load: Loading is failed: %s\n", url.GetUrl().c_str());
}
}
void LoadingTask::ApplyMask()
{
- pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
+ pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask);
}
void LoadingTask::MultiplyAlpha()
{
- if( pixelBuffer && Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
+ if(pixelBuffer && Pixel::HasAlpha(pixelBuffer.GetPixelFormat()))
{
- if( preMultiplyOnLoad == DevelAsyncImageLoader::PreMultiplyOnLoad::ON )
+ if(preMultiplyOnLoad == DevelAsyncImageLoader::PreMultiplyOnLoad::ON)
{
pixelBuffer.MultiplyColorByAlpha();
}
}
}
-ImageLoadThread::ImageLoadThread( EventThreadCallback* trigger )
-: mTrigger( trigger ),
- mLogFactory( Dali::Adaptor::Get().GetLogFactory() )
+ImageLoadThread::ImageLoadThread(EventThreadCallback* trigger)
+: mTrigger(trigger),
+ mLogFactory(Dali::Adaptor::Get().GetLogFactory())
{
}
ImageLoadThread::~ImageLoadThread()
{
// add an empty task would stop the thread from conditional wait.
- AddTask( NULL );
+ AddTask(NULL);
// stop the thread
Join();
delete mTrigger;
- for( auto&& iter : mLoadQueue )
+ for(auto&& iter : mLoadQueue)
{
delete iter;
}
mLoadQueue.Clear();
- for( auto&& iter : mCompleteQueue )
+ for(auto&& iter : mCompleteQueue)
{
delete iter;
}
void ImageLoadThread::Run()
{
- SetThreadName( "ImageLoadThread" );
+ SetThreadName("ImageLoadThread");
mLogFactory.InstallLogFunction();
- while( LoadingTask* task = NextTaskToProcess() )
+ while(LoadingTask* task = NextTaskToProcess())
{
- if( !task->isMaskTask )
+ if(!task->isMaskTask)
{
task->Load();
}
}
task->MultiplyAlpha();
- AddCompletedTask( task );
+ AddCompletedTask(task);
}
}
-void ImageLoadThread::AddTask( LoadingTask* task )
+void ImageLoadThread::AddTask(LoadingTask* task)
{
bool wasEmpty = false;
{
// Lock while adding task to the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
wasEmpty = mLoadQueue.Empty();
- mLoadQueue.PushBack( task );
+ mLoadQueue.PushBack(task);
}
- if( wasEmpty )
+ if(wasEmpty)
{
// wake up the image loading thread
mConditionalWait.Notify();
LoadingTask* ImageLoadThread::NextCompletedTask()
{
// Lock while popping task out from the queue
- Mutex::ScopedLock lock( mMutex );
+ Mutex::ScopedLock lock(mMutex);
- if( mCompleteQueue.Empty() )
+ if(mCompleteQueue.Empty())
{
return NULL;
}
- Vector< LoadingTask* >::Iterator next = mCompleteQueue.Begin();
- LoadingTask* nextTask = *next;
- mCompleteQueue.Erase( next );
+ Vector<LoadingTask*>::Iterator next = mCompleteQueue.Begin();
+ LoadingTask* nextTask = *next;
+ mCompleteQueue.Erase(next);
return nextTask;
}
-bool ImageLoadThread::CancelTask( uint32_t loadingTaskId )
+bool ImageLoadThread::CancelTask(uint32_t loadingTaskId)
{
// Lock while remove task from the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- for( Vector< LoadingTask* >::Iterator iter = mLoadQueue.Begin(); iter != mLoadQueue.End(); ++iter )
+ for(Vector<LoadingTask*>::Iterator iter = mLoadQueue.Begin(); iter != mLoadQueue.End(); ++iter)
{
- if( (*iter)->id == loadingTaskId )
+ if((*iter)->id == loadingTaskId)
{
- delete (*iter);
- mLoadQueue.Erase( iter );
+ delete(*iter);
+ mLoadQueue.Erase(iter);
return true;
}
}
return false;
}
-
void ImageLoadThread::CancelAll()
{
// Lock while remove task from the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- for( Vector< LoadingTask* >::Iterator iter = mLoadQueue.Begin(); iter != mLoadQueue.End(); ++iter )
+ for(Vector<LoadingTask*>::Iterator iter = mLoadQueue.Begin(); iter != mLoadQueue.End(); ++iter)
{
- delete ( *iter );
+ delete(*iter);
}
mLoadQueue.Clear();
}
LoadingTask* ImageLoadThread::NextTaskToProcess()
{
// Lock while popping task out from the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- while( mLoadQueue.Empty() )
+ while(mLoadQueue.Empty())
{
- mConditionalWait.Wait( lock );
+ mConditionalWait.Wait(lock);
}
- Vector< LoadingTask* >::Iterator next = mLoadQueue.Begin();
- LoadingTask* nextTask = *next;
- mLoadQueue.Erase( next );
+ Vector<LoadingTask*>::Iterator next = mLoadQueue.Begin();
+ LoadingTask* nextTask = *next;
+ mLoadQueue.Erase(next);
return nextTask;
}
-void ImageLoadThread::AddCompletedTask( LoadingTask* task )
+void ImageLoadThread::AddCompletedTask(LoadingTask* task)
{
// Lock while adding task to the queue
- Mutex::ScopedLock lock( mMutex );
- mCompleteQueue.PushBack( task );
+ Mutex::ScopedLock lock(mMutex);
+ mCompleteQueue.PushBack(task);
// wake up the main thread
mTrigger->Trigger();
/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
#include <dali/devel-api/common/singleton-service.h>
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/adaptor-framework/application.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
#include <dali-toolkit/internal/builder/builder-impl.h>
-#include <dali-toolkit/public-api/controls/control.h>
+#include <dali-toolkit/internal/feedback/feedback-style.h>
#include <dali-toolkit/public-api/controls/control-impl.h>
+#include <dali-toolkit/public-api/controls/control.h>
#include <dali-toolkit/public-api/styling/style-manager.h>
-#include <dali-toolkit/internal/feedback/feedback-style.h>
namespace
{
-
//const char* LANDSCAPE_QUALIFIER = "landscape";
const char* PORTRAIT_QUALIFIER = "portrait";
const char* FONT_SIZE_QUALIFIER = "fontsize";
const char* DEFAULT_THEME_FILE_NAME = "dali-toolkit-default-theme.json";
-const char* PACKAGE_PATH_KEY = "PACKAGE_PATH";
+const char* PACKAGE_PATH_KEY = "PACKAGE_PATH";
const char* APPLICATION_RESOURCE_PATH_KEY = "APPLICATION_RESOURCE_PATH";
const char* DEFAULT_TOOLKIT_PACKAGE_PATH = "/toolkit/";
#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_STYLE");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_STYLE");
#endif
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
BaseHandle Create()
{
BaseHandle handle = StyleManager::Get();
- if ( !handle )
+ if(!handle)
{
- SingletonService singletonService( SingletonService::Get() );
- if ( singletonService )
+ SingletonService singletonService(SingletonService::Get());
+ if(singletonService)
{
- Toolkit::StyleManager manager = Toolkit::StyleManager( new Internal::StyleManager() );
- singletonService.Register( typeid( manager ), manager );
+ Toolkit::StyleManager manager = Toolkit::StyleManager(new Internal::StyleManager());
+ singletonService.Register(typeid(manager), manager);
handle = manager;
}
}
return handle;
}
-DALI_TYPE_REGISTRATION_BEGIN_CREATE( Toolkit::StyleManager, Dali::BaseHandle, Create, true )
+DALI_TYPE_REGISTRATION_BEGIN_CREATE(Toolkit::StyleManager, Dali::BaseHandle, Create, true)
DALI_TYPE_REGISTRATION_END()
} // namespace
{
Toolkit::StyleManager manager;
- SingletonService singletonService( SingletonService::Get() );
- if ( singletonService )
+ SingletonService singletonService(SingletonService::Get());
+ if(singletonService)
{
// Check whether the style manager is already created
- Dali::BaseHandle handle = singletonService.GetSingleton( typeid( Toolkit::StyleManager ) );
- if( handle )
+ Dali::BaseHandle handle = singletonService.GetSingleton(typeid(Toolkit::StyleManager));
+ if(handle)
{
// If so, downcast the handle of singleton
- manager = Toolkit::StyleManager( dynamic_cast< StyleManager* >( handle.GetObjectPtr() ) );
+ manager = Toolkit::StyleManager(dynamic_cast<StyleManager*>(handle.GetObjectPtr()));
}
}
}
StyleManager::StyleManager()
-: mDefaultFontSize( -1 ),
+: mDefaultFontSize(-1),
mDefaultFontFamily(""),
mDefaultThemeFilePath(),
- mFeedbackStyle( nullptr )
+ mFeedbackStyle(nullptr)
{
// Add theme builder constants
- const std::string dataReadOnlyDir = AssetManager::GetDaliDataReadOnlyPath();
- mThemeBuilderConstants[ PACKAGE_PATH_KEY ] = dataReadOnlyDir + DEFAULT_TOOLKIT_PACKAGE_PATH;
- mThemeBuilderConstants[ APPLICATION_RESOURCE_PATH_KEY ] = Application::GetResourcePath();
+ const std::string dataReadOnlyDir = AssetManager::GetDaliDataReadOnlyPath();
+ mThemeBuilderConstants[PACKAGE_PATH_KEY] = dataReadOnlyDir + DEFAULT_TOOLKIT_PACKAGE_PATH;
+ mThemeBuilderConstants[APPLICATION_RESOURCE_PATH_KEY] = Application::GetResourcePath();
mStyleMonitor = StyleMonitor::Get();
- if( mStyleMonitor )
+ if(mStyleMonitor)
{
- mStyleMonitor.StyleChangeSignal().Connect( this, &StyleManager::StyleMonitorChange );
+ mStyleMonitor.StyleChangeSignal().Connect(this, &StyleManager::StyleMonitorChange);
mDefaultFontSize = mStyleMonitor.GetDefaultFontSize();
}
// Set the full path for the default style theme.
const std::string styleDirPath = AssetManager::GetDaliStylePath();
- mDefaultThemeFilePath = styleDirPath + DEFAULT_THEME_FILE_NAME;
+ mDefaultThemeFilePath = styleDirPath + DEFAULT_THEME_FILE_NAME;
// Sound & haptic style
mFeedbackStyle = new FeedbackStyle();
delete mFeedbackStyle;
}
-void StyleManager::ApplyTheme( const std::string& themeFile )
+void StyleManager::ApplyTheme(const std::string& themeFile)
{
- SetTheme( themeFile );
+ SetTheme(themeFile);
}
void StyleManager::ApplyDefaultTheme()
return mDefaultFontFamily;
}
-void StyleManager::SetStyleConstant( const std::string& key, const Property::Value& value )
+void StyleManager::SetStyleConstant(const std::string& key, const Property::Value& value)
{
- mStyleBuilderConstants[ key ] = value;
+ mStyleBuilderConstants[key] = value;
}
-bool StyleManager::GetStyleConstant( const std::string& key, Property::Value& valueOut )
+bool StyleManager::GetStyleConstant(const std::string& key, Property::Value& valueOut)
{
- Property::Value* value = mStyleBuilderConstants.Find( key );
- if( value )
+ Property::Value* value = mStyleBuilderConstants.Find(key);
+ if(value)
{
valueOut = *value;
return true;
return false;
}
-void StyleManager::ApplyThemeStyle( Toolkit::Control control )
+void StyleManager::ApplyThemeStyle(Toolkit::Control control)
{
- if( !mThemeBuilder )
+ if(!mThemeBuilder)
{
ApplyDefaultTheme();
}
- if( mThemeBuilder )
+ if(mThemeBuilder)
{
- ApplyStyle( mThemeBuilder, control );
+ ApplyStyle(mThemeBuilder, control);
}
}
-void StyleManager::ApplyThemeStyleAtInit( Toolkit::Control control )
+void StyleManager::ApplyThemeStyleAtInit(Toolkit::Control control)
{
- ApplyThemeStyle( control );
+ ApplyThemeStyle(control);
if(mFeedbackStyle)
{
- mFeedbackStyle->ObjectCreated( control );
+ mFeedbackStyle->ObjectCreated(control);
}
}
-void StyleManager::ApplyStyle( Toolkit::Control control, const std::string& jsonFileName, const std::string& styleName )
+void StyleManager::ApplyStyle(Toolkit::Control control, const std::string& jsonFileName, const std::string& styleName)
{
bool builderReady = false;
// First look in the cache
- Toolkit::Builder builder = FindCachedBuilder( jsonFileName );
- if( builder )
+ Toolkit::Builder builder = FindCachedBuilder(jsonFileName);
+ if(builder)
{
builderReady = true;
}
else
{
// Merge theme and style constants
- Property::Map constants( mThemeBuilderConstants );
- constants.Merge( mStyleBuilderConstants );
+ Property::Map constants(mThemeBuilderConstants);
+ constants.Merge(mStyleBuilderConstants);
// Create it
- builder = CreateBuilder( constants );
+ builder = CreateBuilder(constants);
- if( LoadJSON( builder, jsonFileName ) )
+ if(LoadJSON(builder, jsonFileName))
{
- CacheBuilder( builder, jsonFileName );
+ CacheBuilder(builder, jsonFileName);
builderReady = true;
}
}
// Apply the style to the control
- if( builderReady )
+ if(builderReady)
{
- builder.ApplyStyle( styleName, control );
+ builder.ApplyStyle(styleName, control);
}
}
return mControlStyleChangeSignal;
}
-void StyleManager::SetTheme( const std::string& themeFile )
+void StyleManager::SetTheme(const std::string& themeFile)
{
bool themeLoaded = false;
- bool loading = false;
+ bool loading = false;
// If we haven't loaded a theme, or the stored theme file is empty, or
// the previously loaded theme is different to the requested theme,
// first reset the builder and load the default theme.
- if( ! mThemeBuilder || mThemeFile.empty() || mThemeFile.compare( themeFile ) != 0 )
+ if(!mThemeBuilder || mThemeFile.empty() || mThemeFile.compare(themeFile) != 0)
{
- loading = true;
- mThemeBuilder = CreateBuilder( mThemeBuilderConstants );
- themeLoaded = LoadJSON( mThemeBuilder, mDefaultThemeFilePath ); // Sets themeLoaded to true if theme exists
+ loading = true;
+ mThemeBuilder = CreateBuilder(mThemeBuilderConstants);
+ themeLoaded = LoadJSON(mThemeBuilder, mDefaultThemeFilePath); // Sets themeLoaded to true if theme exists
}
- if( themeFile.compare(mDefaultThemeFilePath) != 0 )
+ if(themeFile.compare(mDefaultThemeFilePath) != 0)
{
// The theme is different to the default: Merge it
loading = true;
- themeLoaded |= LoadJSON( mThemeBuilder, themeFile );
+ themeLoaded |= LoadJSON(mThemeBuilder, themeFile);
}
- if( loading )
+ if(loading)
{
mThemeFile = themeFile;
- if( themeLoaded )
+ if(themeLoaded)
{
// We've successfully loaded the theme file
if(mFeedbackStyle)
{
- mFeedbackStyle->StyleChanged( mThemeFile, StyleChange::THEME_CHANGE );
+ mFeedbackStyle->StyleChanged(mThemeFile, StyleChange::THEME_CHANGE);
}
EmitStyleChangeSignals(StyleChange::THEME_CHANGE);
const Property::Map StyleManager::GetConfigurations()
{
- DALI_LOG_STREAM( gLogFilter, Debug::Concise, "GetConfigurations()\n On entry, mThemeBuilder: " << (bool(mThemeBuilder)?"Created":"Empty") << " mThemeFile: " << mThemeFile);
+ DALI_LOG_STREAM(gLogFilter, Debug::Concise, "GetConfigurations()\n On entry, mThemeBuilder: " << (bool(mThemeBuilder) ? "Created" : "Empty") << " mThemeFile: " << mThemeFile);
Property::Map result;
- if( mThemeBuilder )
+ if(mThemeBuilder)
{
result = mThemeBuilder.GetConfigurations();
}
else
{
- DALI_LOG_STREAM( gLogFilter, Debug::Concise, "GetConfigurations() Loading default theme" );
+ DALI_LOG_STREAM(gLogFilter, Debug::Concise, "GetConfigurations() Loading default theme");
bool themeLoaded = false;
- mThemeBuilder = CreateBuilder( mThemeBuilderConstants );
+ mThemeBuilder = CreateBuilder(mThemeBuilderConstants);
// Load default theme because this is first try to load stylesheet.
- themeLoaded = LoadJSON( mThemeBuilder, mDefaultThemeFilePath );
- mThemeFile = mDefaultThemeFilePath;
+ themeLoaded = LoadJSON(mThemeBuilder, mDefaultThemeFilePath);
+ mThemeFile = mDefaultThemeFilePath;
- if( themeLoaded )
+ if(themeLoaded)
{
result = mThemeBuilder.GetConfigurations();
}
- DALI_LOG_STREAM( gLogFilter, Debug::Concise, " themeLoaded" << (themeLoaded?"success":"failure") );
+ DALI_LOG_STREAM(gLogFilter, Debug::Concise, " themeLoaded" << (themeLoaded ? "success" : "failure"));
}
- DALI_LOG_STREAM( gLogFilter, Debug::Concise, "GetConfigurations()\n On exit, result Count: " << (result.Count() != 0) );
- DALI_LOG_STREAM( gLogFilter, Debug::Verbose, " result: " << result );
+ DALI_LOG_STREAM(gLogFilter, Debug::Concise, "GetConfigurations()\n On exit, result Count: " << (result.Count() != 0));
+ DALI_LOG_STREAM(gLogFilter, Debug::Verbose, " result: " << result);
return result;
}
-bool StyleManager::LoadFile( const std::string& filename, std::string& stringOut )
+bool StyleManager::LoadFile(const std::string& filename, std::string& stringOut)
{
- DALI_ASSERT_DEBUG( 0 != filename.length());
+ DALI_ASSERT_DEBUG(0 != filename.length());
// as toolkit is platform agnostic, it cannot load files from filesystem
// ask style monitor to load the style sheet
- if( mStyleMonitor )
+ if(mStyleMonitor)
{
- return mStyleMonitor.LoadThemeFile( filename, stringOut );
+ return mStyleMonitor.LoadThemeFile(filename, stringOut);
}
return false;
}
-Toolkit::Builder StyleManager::CreateBuilder( const Property::Map& constants )
+Toolkit::Builder StyleManager::CreateBuilder(const Property::Map& constants)
{
Toolkit::Builder builder = Toolkit::Builder::New();
- builder.AddConstants( constants );
+ builder.AddConstants(constants);
return builder;
}
-bool StyleManager::LoadJSON( Toolkit::Builder builder, const std::string& jsonFilePath )
+bool StyleManager::LoadJSON(Toolkit::Builder builder, const std::string& jsonFilePath)
{
std::string fileString;
- if( LoadFile( jsonFilePath, fileString ) )
+ if(LoadFile(jsonFilePath, fileString))
{
- builder.LoadFromString( fileString );
+ builder.LoadFromString(fileString);
return true;
}
else
}
}
-static void CollectQualifiers( std::vector<std::string>& qualifiersOut )
+static void CollectQualifiers(std::vector<std::string>& qualifiersOut)
{
// Append the relevant qualifier for orientation
// int orientation = 0; // Get the orientation from the system
orientation 90, 270 : LANDSCAPE_QUALIFIER
*/
- qualifiersOut.push_back( std::string( PORTRAIT_QUALIFIER ) );
-
+ qualifiersOut.push_back(std::string(PORTRAIT_QUALIFIER));
}
/**
* @param[out] qualifiedStyleOut The qualified style name
*/
static void BuildQualifiedStyleName(
- const std::string& styleName,
+ const std::string& styleName,
const std::vector<std::string>& qualifiers,
- std::string& qualifiedStyleOut )
+ std::string& qualifiedStyleOut)
{
- qualifiedStyleOut.append( styleName );
+ qualifiedStyleOut.append(styleName);
- for( std::vector<std::string>::const_iterator it = qualifiers.begin(),
- itEnd = qualifiers.end(); it != itEnd; ++it )
+ for(std::vector<std::string>::const_iterator it = qualifiers.begin(),
+ itEnd = qualifiers.end();
+ it != itEnd;
+ ++it)
{
const std::string& str = *it;
- qualifiedStyleOut.append( "-" );
- qualifiedStyleOut.append( str );
+ qualifiedStyleOut.append("-");
+ qualifiedStyleOut.append(str);
}
}
-static bool GetStyleNameForControl( Toolkit::Builder builder, Toolkit::Control control, std::string& styleName)
+static bool GetStyleNameForControl(Toolkit::Builder builder, Toolkit::Control control, std::string& styleName)
{
styleName = control.GetStyleName();
- if( styleName.empty() )
+ if(styleName.empty())
{
styleName = control.GetTypeName();
}
// Apply the style after choosing the correct actual style (e.g. landscape or portrait)
std::vector<std::string> qualifiers;
- CollectQualifiers( qualifiers );
+ CollectQualifiers(qualifiers);
- bool found = 0;
+ bool found = 0;
std::string qualifiedStyleName;
do
{
qualifiedStyleName.clear();
- BuildQualifiedStyleName( styleName, qualifiers, qualifiedStyleName );
+ BuildQualifiedStyleName(styleName, qualifiers, qualifiedStyleName);
// Break if style found or we have tried the root style name (qualifiers is empty)
- if( GetImpl(builder).LookupStyleName( qualifiedStyleName ) )
+ if(GetImpl(builder).LookupStyleName(qualifiedStyleName))
{
found = true;
break;
}
- if( qualifiers.size() == 0 )
+ if(qualifiers.size() == 0)
{
break;
}
// Remove the last qualifier in an attempt to find a style that is valid
qualifiers.pop_back();
- } while (!found);
+ } while(!found);
if(found)
{
return found;
}
-void StyleManager::ApplyStyle( Toolkit::Builder builder, Toolkit::Control control )
+void StyleManager::ApplyStyle(Toolkit::Builder builder, Toolkit::Control control)
{
std::string styleName = control.GetStyleName();
- if( GetStyleNameForControl( builder, control, styleName ) )
+ if(GetStyleNameForControl(builder, control, styleName))
{
- builder.ApplyStyle( styleName, control );
+ builder.ApplyStyle(styleName, control);
}
- if( mDefaultFontSize >= 0 )
+ if(mDefaultFontSize >= 0)
{
// Apply the style for logical font size
std::stringstream fontSizeQualifier;
fontSizeQualifier << styleName << FONT_SIZE_QUALIFIER << mDefaultFontSize;
- builder.ApplyStyle( fontSizeQualifier.str(), control );
+ builder.ApplyStyle(fontSizeQualifier.str(), control);
}
}
-const StylePtr StyleManager::GetRecordedStyle( Toolkit::Control control )
+const StylePtr StyleManager::GetRecordedStyle(Toolkit::Control control)
{
- if( mThemeBuilder )
+ if(mThemeBuilder)
{
std::string styleName = control.GetStyleName();
- if( GetStyleNameForControl( mThemeBuilder, control, styleName ) )
+ if(GetStyleNameForControl(mThemeBuilder, control, styleName))
{
- const StylePtr style = GetImpl(mThemeBuilder).GetStyle( styleName );
+ const StylePtr style = GetImpl(mThemeBuilder).GetStyle(styleName);
return style;
}
}
return StylePtr(NULL);
}
-Toolkit::Builder StyleManager::FindCachedBuilder( const std::string& key )
+Toolkit::Builder StyleManager::FindCachedBuilder(const std::string& key)
{
- BuilderMap::iterator builderIt = mBuilderCache.find( key );
- if( builderIt != mBuilderCache.end() )
+ BuilderMap::iterator builderIt = mBuilderCache.find(key);
+ if(builderIt != mBuilderCache.end())
{
return builderIt->second;
}
return Toolkit::Builder();
}
-void StyleManager::CacheBuilder( Toolkit::Builder builder, const std::string& key )
+void StyleManager::CacheBuilder(Toolkit::Builder builder, const std::string& key)
{
- mBuilderCache[ key ] = builder;
+ mBuilderCache[key] = builder;
}
-void StyleManager::StyleMonitorChange( StyleMonitor styleMonitor, StyleChange::Type styleChange )
+void StyleManager::StyleMonitorChange(StyleMonitor styleMonitor, StyleChange::Type styleChange)
{
- switch ( styleChange )
+ switch(styleChange)
{
case StyleChange::DEFAULT_FONT_CHANGE:
{
case StyleChange::THEME_CHANGE:
{
- SetTheme( styleMonitor.GetTheme() );
+ SetTheme(styleMonitor.GetTheme());
break;
}
}
- EmitStyleChangeSignals( styleChange );
+ EmitStyleChangeSignals(styleChange);
}
-void StyleManager::EmitStyleChangeSignals( StyleChange::Type styleChange )
+void StyleManager::EmitStyleChangeSignals(StyleChange::Type styleChange)
{
Toolkit::StyleManager styleManager = StyleManager::Get();
// Update Controls first
- mControlStyleChangeSignal.Emit( styleManager, styleChange );
+ mControlStyleChangeSignal.Emit(styleManager, styleChange);
// Inform application last
- mStyleChangedSignal.Emit( styleManager, styleChange );
+ mStyleChangedSignal.Emit(styleManager, styleChange);
}
-
} // namespace Internal
} // namespace Toolkit
#include <dali-toolkit/internal/text/bidirectional-support.h>
// EXTERNAL INCLUDES
-#include <memory.h>
#include <dali/devel-api/text-abstraction/bidirectional-support.h>
+#include <memory.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-void SetBidirectionalInfo( const Vector<Character>& text,
- const Vector<ScriptRun>& scripts,
- const Vector<LineBreakInfo>& lineBreakInfo,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo,
- bool matchSystemLanguageDirection,
- Dali::LayoutDirection::Type layoutDirection )
+void SetBidirectionalInfo(const Vector<Character>& text,
+ const Vector<ScriptRun>& scripts,
+ const Vector<LineBreakInfo>& lineBreakInfo,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo,
+ bool matchSystemLanguageDirection,
+ Dali::LayoutDirection::Type layoutDirection)
{
// Find where to insert the new paragraphs.
BidirectionalRunIndex bidiInfoIndex = 0u;
- for( Vector<BidirectionalParagraphInfoRun>::ConstIterator it = bidirectionalInfo.Begin(),
- endIt = bidirectionalInfo.End();
- it != endIt;
- ++it )
+ for(Vector<BidirectionalParagraphInfoRun>::ConstIterator it = bidirectionalInfo.Begin(),
+ endIt = bidirectionalInfo.End();
+ it != endIt;
+ ++it)
{
const BidirectionalParagraphInfoRun& run = *it;
- if( startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters )
+ if(startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters)
{
// Found where to insert the bidi info.
break;
bool hasRightToLeftScript = false;
- for( Vector<ScriptRun>::ConstIterator it = scripts.Begin(),
- endIt = scripts.End();
- it != endIt;
- ++it )
+ for(Vector<ScriptRun>::ConstIterator it = scripts.Begin(),
+ endIt = scripts.End();
+ it != endIt;
+ ++it)
{
- const ScriptRun& scriptRun = *it;
+ const ScriptRun& scriptRun = *it;
const CharacterIndex lastScriptRunIndex = scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters - 1u;
- if( startIndex > lastScriptRunIndex )
+ if(startIndex > lastScriptRunIndex)
{
// Skip the run as it has already been processed.
continue;
}
- if( lastCharacter <= scriptRun.characterRun.characterIndex )
+ if(lastCharacter <= scriptRun.characterRun.characterIndex)
{
// Do not get bidirectional info beyond startIndex + numberOfCharacters.
break;
}
- if( !hasRightToLeftScript && scriptRun.isRightToLeft )
+ if(!hasRightToLeftScript && scriptRun.isRightToLeft)
{
// The script is right to left.
hasRightToLeftScript = true;
}
- if( TextAbstraction::LINE_MUST_BREAK == *( lineBreakInfoBuffer + lastScriptRunIndex ) )
+ if(TextAbstraction::LINE_MUST_BREAK == *(lineBreakInfoBuffer + lastScriptRunIndex))
{
// A new paragraph has been found.
- if( hasRightToLeftScript )
+ if(hasRightToLeftScript)
{
// The Bidirectional run must have the same number of characters than the paragraph.
BidirectionalParagraphInfoRun bidirectionalRun;
- bidirectionalRun.characterRun.characterIndex = paragraphCharacterIndex;
- bidirectionalRun.characterRun.numberOfCharacters = ( lastScriptRunIndex - paragraphCharacterIndex ) + 1u; // The must break character is part of the paragrah.
+ bidirectionalRun.characterRun.characterIndex = paragraphCharacterIndex;
+ bidirectionalRun.characterRun.numberOfCharacters = (lastScriptRunIndex - paragraphCharacterIndex) + 1u; // The must break character is part of the paragrah.
// Create the bidirectional info for the whole paragraph and store the index to the table with this info in the run.
- bidirectionalRun.bidirectionalInfoIndex = bidirectionalSupport.CreateInfo( textBuffer + bidirectionalRun.characterRun.characterIndex,
- bidirectionalRun.characterRun.numberOfCharacters,
- matchSystemLanguageDirection,
- layoutDirection );
+ bidirectionalRun.bidirectionalInfoIndex = bidirectionalSupport.CreateInfo(textBuffer + bidirectionalRun.characterRun.characterIndex,
+ bidirectionalRun.characterRun.numberOfCharacters,
+ matchSystemLanguageDirection,
+ layoutDirection);
- bidirectionalRun.direction = bidirectionalSupport.GetParagraphDirection( bidirectionalRun.bidirectionalInfoIndex );
+ bidirectionalRun.direction = bidirectionalSupport.GetParagraphDirection(bidirectionalRun.bidirectionalInfoIndex);
- bidirectionalInfo.Insert( bidirectionalInfo.Begin() + bidiInfoIndex, bidirectionalRun );
+ bidirectionalInfo.Insert(bidirectionalInfo.Begin() + bidiInfoIndex, bidirectionalRun);
++bidiInfoIndex;
}
}
// Update indices of the bidi runs.
- for( Vector<BidirectionalParagraphInfoRun>::Iterator it = bidirectionalInfo.Begin() + bidiInfoIndex,
- endIt = bidirectionalInfo.End();
- it != endIt;
- ++it )
+ for(Vector<BidirectionalParagraphInfoRun>::Iterator it = bidirectionalInfo.Begin() + bidiInfoIndex,
+ endIt = bidirectionalInfo.End();
+ it != endIt;
+ ++it)
{
BidirectionalParagraphInfoRun& run = *it;
}
}
-void ReorderLine( const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo,
- Vector<BidirectionalLineInfoRun>& lineInfoRuns,
- BidirectionalLineRunIndex bidiLineIndex,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- CharacterDirection direction )
+void ReorderLine(const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo,
+ Vector<BidirectionalLineInfoRun>& lineInfoRuns,
+ BidirectionalLineRunIndex bidiLineIndex,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ CharacterDirection direction)
{
// Handle to the bidirectional info module in text-abstraction.
TextAbstraction::BidirectionalSupport bidirectionalSupport = TextAbstraction::BidirectionalSupport::Get();
// Creates a bidirectional info for the line run.
BidirectionalLineInfoRun lineInfoRun;
- lineInfoRun.characterRun.characterIndex = startIndex;
+ lineInfoRun.characterRun.characterIndex = startIndex;
lineInfoRun.characterRun.numberOfCharacters = numberOfCharacters;
- lineInfoRun.direction = direction;
- lineInfoRun.isIdentity = true;
+ lineInfoRun.direction = direction;
+ lineInfoRun.isIdentity = true;
// Allocate space for the conversion maps.
// The memory is freed after the visual to logical to visual conversion tables are built in the logical model.
- lineInfoRun.visualToLogicalMap = reinterpret_cast<CharacterIndex*>( malloc( numberOfCharacters * sizeof( CharacterIndex ) ) );
+ lineInfoRun.visualToLogicalMap = reinterpret_cast<CharacterIndex*>(malloc(numberOfCharacters * sizeof(CharacterIndex)));
- if( nullptr != lineInfoRun.visualToLogicalMap )
+ if(nullptr != lineInfoRun.visualToLogicalMap)
{
// Reorders the line.
- bidirectionalSupport.Reorder( bidirectionalParagraphInfo.bidirectionalInfoIndex,
- lineInfoRun.characterRun.characterIndex - bidirectionalParagraphInfo.characterRun.characterIndex,
- lineInfoRun.characterRun.numberOfCharacters,
- lineInfoRun.visualToLogicalMap );
+ bidirectionalSupport.Reorder(bidirectionalParagraphInfo.bidirectionalInfoIndex,
+ lineInfoRun.characterRun.characterIndex - bidirectionalParagraphInfo.characterRun.characterIndex,
+ lineInfoRun.characterRun.numberOfCharacters,
+ lineInfoRun.visualToLogicalMap);
// For those LTR lines inside a bidirectional paragraph.
// It will save to relayout the line after reordering.
- for( unsigned int i=0; i<numberOfCharacters; ++i )
+ for(unsigned int i = 0; i < numberOfCharacters; ++i)
{
- if( i != *( lineInfoRun.visualToLogicalMap + i ) )
+ if(i != *(lineInfoRun.visualToLogicalMap + i))
{
lineInfoRun.isIdentity = false;
break;
}
// Push the run into the vector.
- lineInfoRuns.Insert( lineInfoRuns.Begin() + bidiLineIndex, lineInfoRun );
+ lineInfoRuns.Insert(lineInfoRuns.Begin() + bidiLineIndex, lineInfoRun);
}
-bool GetMirroredText( const Vector<Character>& text,
- const Vector<CharacterDirection>& directions,
- const Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<Character>& mirroredText )
+bool GetMirroredText(const Vector<Character>& text,
+ const Vector<CharacterDirection>& directions,
+ const Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<Character>& mirroredText)
{
bool hasTextMirrored = false;
mirroredText = text;
- Character* mirroredTextBuffer = mirroredText.Begin();
- CharacterDirection* directionsBuffer = directions.Begin();
+ Character* mirroredTextBuffer = mirroredText.Begin();
+ CharacterDirection* directionsBuffer = directions.Begin();
- CharacterIndex index = startIndex;
+ CharacterIndex index = startIndex;
const CharacterIndex lastCharacter = startIndex + numberOfCharacters;
// Traverse the paragraphs and mirror the right to left ones.
- for( Vector<BidirectionalParagraphInfoRun>::ConstIterator it = bidirectionalInfo.Begin(),
- endIt = bidirectionalInfo.End();
- it != endIt;
- ++it )
+ for(Vector<BidirectionalParagraphInfoRun>::ConstIterator it = bidirectionalInfo.Begin(),
+ endIt = bidirectionalInfo.End();
+ it != endIt;
+ ++it)
{
const BidirectionalParagraphInfoRun& paragraph = *it;
- if( index >= paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters )
+ if(index >= paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters)
{
// Skip the paragraph as it has already been processed.
continue;
}
- if( lastCharacter <= paragraph.characterRun.characterIndex )
+ if(lastCharacter <= paragraph.characterRun.characterIndex)
{
// Do not get mirror characters beyond startIndex + numberOfCharacters.
break;
}
index += paragraph.characterRun.numberOfCharacters;
- const bool tmpMirrored = bidirectionalSupport.GetMirroredText( mirroredTextBuffer + paragraph.characterRun.characterIndex,
- directionsBuffer + paragraph.characterRun.characterIndex,
- paragraph.characterRun.numberOfCharacters );
+ const bool tmpMirrored = bidirectionalSupport.GetMirroredText(mirroredTextBuffer + paragraph.characterRun.characterIndex,
+ directionsBuffer + paragraph.characterRun.characterIndex,
+ paragraph.characterRun.numberOfCharacters);
hasTextMirrored = hasTextMirrored || tmpMirrored;
}
return hasTextMirrored;
}
-void GetCharactersDirection( const Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo,
- Length totalNumberOfCharacters,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<CharacterDirection>& directions )
+void GetCharactersDirection(const Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo,
+ Length totalNumberOfCharacters,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<CharacterDirection>& directions)
{
// Handle to the bidirectional info module in text-abstraction.
TextAbstraction::BidirectionalSupport bidirectionalSupport = TextAbstraction::BidirectionalSupport::Get();
// Resize the vector.
- directions.Resize( totalNumberOfCharacters );
+ directions.Resize(totalNumberOfCharacters);
// Whether the current buffer is being updated or is set from scratch.
const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters;
- CharacterDirection* directionsBuffer = NULL;
+ CharacterDirection* directionsBuffer = NULL;
Vector<CharacterDirection> newDirections;
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- newDirections.Resize( numberOfCharacters );
+ newDirections.Resize(numberOfCharacters);
directionsBuffer = newDirections.Begin();
}
else
}
const CharacterIndex lastCharacter = startIndex + numberOfCharacters;
- CharacterIndex index = startIndex;
+ CharacterIndex index = startIndex;
- for( Vector<BidirectionalParagraphInfoRun>::ConstIterator it = bidirectionalInfo.Begin(),
- endIt = bidirectionalInfo.End();
- it != endIt;
- ++it )
+ for(Vector<BidirectionalParagraphInfoRun>::ConstIterator it = bidirectionalInfo.Begin(),
+ endIt = bidirectionalInfo.End();
+ it != endIt;
+ ++it)
{
const BidirectionalParagraphInfoRun& paragraph = *it;
- if( index >= paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters )
+ if(index >= paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters)
{
// Skip the paragraph as it has already been processed.
continue;
}
- if( lastCharacter <= paragraph.characterRun.characterIndex )
+ if(lastCharacter <= paragraph.characterRun.characterIndex)
{
// Do not get the character directions beyond startIndex + numberOfCharacters.
break;
// Set the directions of any previous left to right characters.
const Length numberOfLeftToRightCharacters = paragraph.characterRun.characterIndex - index;
- if( numberOfLeftToRightCharacters > 0u )
+ if(numberOfLeftToRightCharacters > 0u)
{
- memset( directionsBuffer + index - startIndex, false, numberOfLeftToRightCharacters * sizeof( bool ) );
+ memset(directionsBuffer + index - startIndex, false, numberOfLeftToRightCharacters * sizeof(bool));
}
// Set the directions of the bidirectional text.
- bidirectionalSupport.GetCharactersDirection( paragraph.bidirectionalInfoIndex,
- directionsBuffer + paragraph.characterRun.characterIndex - startIndex,
- paragraph.characterRun.numberOfCharacters );
+ bidirectionalSupport.GetCharactersDirection(paragraph.bidirectionalInfoIndex,
+ directionsBuffer + paragraph.characterRun.characterIndex - startIndex,
+ paragraph.characterRun.numberOfCharacters);
// Update the index.
index += paragraph.characterRun.numberOfCharacters + numberOfLeftToRightCharacters;
}
// Fills with left to right those paragraphs without right to left characters.
- memset( directionsBuffer + index - startIndex, false, ( lastCharacter - index ) * sizeof( bool ) );
+ memset(directionsBuffer + index - startIndex, false, (lastCharacter - index) * sizeof(bool));
// If the direction info is updated, it needs to be inserted in the model.
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
// Insert the directions in the given buffer.
- directions.Insert( directions.Begin() + startIndex,
- newDirections.Begin(),
- newDirections.End() );
- directions.Resize( totalNumberOfCharacters );
+ directions.Insert(directions.Begin() + startIndex,
+ newDirections.Begin(),
+ newDirections.End());
+ directions.Resize(totalNumberOfCharacters);
}
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
- const static uint8_t U1 = 1u;
- const static uint8_t U2 = 2u;
- const static uint8_t U3 = 3u;
- const static uint8_t U4 = 4u;
- const static uint8_t U5 = 5u;
- const static uint8_t U6 = 6u;
- const static uint8_t U0 = 0u;
- const static uint8_t UTF8_LENGTH[256] = {
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // lead byte = 0xxx xxxx (U+0000 - U+007F + some extended ascii characters)
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
- U1, U1, //
-
- U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, //
- U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, // lead byte = 110x xxxx (U+0080 - U+07FF)
- U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, //
- U2, U2, //
-
- U3, U3, U3, U3, U3, U3, U3, U3, U3, U3, // lead byte = 1110 xxxx (U+0800 - U+FFFF)
- U3, U3, U3, U3, U3, U3, //
-
- U4, U4, U4, U4, U4, U4, U4, U4, // lead byte = 1111 0xxx (U+10000 - U+1FFFFF)
-
- U5, U5, U5, U5, // lead byte = 1111 10xx (U+200000 - U+3FFFFFF)
-
- U6, U6, // lead byte = 1111 110x (U+4000000 - U+7FFFFFFF)
-
- U0, U0, // Non valid.
- };
-
- const uint8_t CR = 0xd;
- const uint8_t LF = 0xa;
+// clang-format off
+constexpr uint8_t U1 = 1u;
+constexpr uint8_t U2 = 2u;
+constexpr uint8_t U3 = 3u;
+constexpr uint8_t U4 = 4u;
+constexpr uint8_t U5 = 5u;
+constexpr uint8_t U6 = 6u;
+constexpr uint8_t U0 = 0u;
+constexpr uint8_t UTF8_LENGTH[256] = {
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // lead byte = 0xxx xxxx (U+0000 - U+007F + some extended ascii characters)
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, //
+ U1, U1, //
+
+ U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, //
+ U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, // lead byte = 110x xxxx (U+0080 - U+07FF)
+ U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, //
+ U2, U2, //
+
+ U3, U3, U3, U3, U3, U3, U3, U3, U3, U3, // lead byte = 1110 xxxx (U+0800 - U+FFFF)
+ U3, U3, U3, U3, U3, U3, //
+
+ U4, U4, U4, U4, U4, U4, U4, U4, // lead byte = 1111 0xxx (U+10000 - U+1FFFFF)
+
+ U5, U5, U5, U5, // lead byte = 1111 10xx (U+200000 - U+3FFFFFF)
+
+ U6, U6, // lead byte = 1111 110x (U+4000000 - U+7FFFFFFF)
+
+ U0, U0, // Non valid.
+};
+
+constexpr uint8_t CR = 0xd;
+constexpr uint8_t LF = 0xa;
+// clang-format on
} // namespace
-uint8_t GetUtf8Length( uint8_t utf8LeadByte )
+uint8_t GetUtf8Length(uint8_t utf8LeadByte)
{
return UTF8_LENGTH[utf8LeadByte];
}
-uint32_t GetNumberOfUtf8Characters( const uint8_t* const utf8, uint32_t length )
+uint32_t GetNumberOfUtf8Characters(const uint8_t* const utf8, uint32_t length)
{
uint32_t numberOfCharacters = 0u;
const uint8_t* begin = utf8;
- const uint8_t* end = utf8 + length;
+ const uint8_t* end = utf8 + length;
- for( ; begin < end ; begin += UTF8_LENGTH[*begin], ++numberOfCharacters );
+ for(; begin < end; begin += UTF8_LENGTH[*begin])
+ {
+ ++numberOfCharacters;
+ }
return numberOfCharacters;
}
-uint32_t GetNumberOfUtf8Bytes( const uint32_t* const utf32, uint32_t numberOfCharacters )
+uint32_t GetNumberOfUtf8Bytes(const uint32_t* const utf32, uint32_t numberOfCharacters)
{
uint32_t numberOfBytes = 0u;
const uint32_t* begin = utf32;
- const uint32_t* end = utf32 + numberOfCharacters;
+ const uint32_t* end = utf32 + numberOfCharacters;
- for( ; begin < end; ++begin )
+ for(; begin < end; ++begin)
{
const uint32_t code = *begin;
- if( code < 0x80u )
+ if(code < 0x80u)
{
++numberOfBytes;
}
- else if( code < 0x800u )
+ else if(code < 0x800u)
{
numberOfBytes += U2;
}
- else if( code < 0x10000u )
+ else if(code < 0x10000u)
{
numberOfBytes += U3;
}
- else if( code < 0x200000u )
+ else if(code < 0x200000u)
{
numberOfBytes += U4;
}
- else if( code < 0x4000000u )
+ else if(code < 0x4000000u)
{
numberOfBytes += U5;
}
- else if( code < 0x80000000u )
+ else if(code < 0x80000000u)
{
numberOfBytes += U6;
}
return numberOfBytes;
}
-uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf32 )
+uint32_t Utf8ToUtf32(const uint8_t* const utf8, uint32_t length, uint32_t* utf32)
{
uint32_t numberOfCharacters = 0u;
const uint8_t* begin = utf8;
- const uint8_t* end = utf8 + length;
+ const uint8_t* end = utf8 + length;
- for( ; begin < end ; ++numberOfCharacters )
+ for(; begin < end; ++numberOfCharacters)
{
const uint8_t leadByte = *begin;
- switch( UTF8_LENGTH[leadByte] )
+ switch(UTF8_LENGTH[leadByte])
{
case U1:
{
- if( CR == leadByte )
+ if(CR == leadByte)
{
// Replace CR+LF or CR by LF
*utf32++ = LF;
// Look ahead if the next one is a LF.
++begin;
- if( begin < end )
+ if(begin < end)
{
- if( LF == *begin )
+ if(LF == *begin)
{
++begin;
}
case U2:
{
uint32_t& code = *utf32++;
- code = leadByte & 0x1fu;
+ code = leadByte & 0x1fu;
begin++;
code <<= 6u;
code |= *begin++ & 0x3fu;
case U3:
{
uint32_t& code = *utf32++;
- code = leadByte & 0x0fu;
+ code = leadByte & 0x0fu;
begin++;
code <<= 6u;
code |= *begin++ & 0x3fu;
case U4:
{
uint32_t& code = *utf32++;
- code = leadByte & 0x07u;
+ code = leadByte & 0x07u;
begin++;
code <<= 6u;
code |= *begin++ & 0x3fu;
case U5:
{
uint32_t& code = *utf32++;
- code = leadByte & 0x03u;
+ code = leadByte & 0x03u;
begin++;
code <<= 6u;
code |= *begin++ & 0x3fu;
case U6:
{
uint32_t& code = *utf32++;
- code = leadByte & 0x01u;
+ code = leadByte & 0x01u;
begin++;
code <<= 6u;
code |= *begin++ & 0x3fu;
break;
}
- case U0: // Invalid case
+ case U0: // Invalid case
{
begin++;
- *utf32++ = 0x20; // Use white space
+ *utf32++ = 0x20; // Use white space
break;
}
}
return numberOfCharacters;
}
-uint32_t Utf32ToUtf8( const uint32_t* const utf32, uint32_t numberOfCharacters, uint8_t* utf8 )
+uint32_t Utf32ToUtf8(const uint32_t* const utf32, uint32_t numberOfCharacters, uint8_t* utf8)
{
const uint32_t* begin = utf32;
- const uint32_t* end = utf32 + numberOfCharacters;
+ const uint32_t* end = utf32 + numberOfCharacters;
uint8_t* utf8Begin = utf8;
- for( ; begin < end; ++begin )
+ for(; begin < end; ++begin)
{
const uint32_t code = *begin;
+ // clang-format off
if( code < 0x80u )
{
*utf8++ = code;
}
else if( code < 0x800u )
{
- *utf8++ = static_cast<uint8_t>( code >> 6u ) | 0xc0u; // lead byte for 2 byte sequence
- *utf8++ = static_cast<uint8_t>( code & 0x3f ) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code >> 6u) | 0xc0u; // lead byte for 2 byte sequence
+ *utf8++ = static_cast<uint8_t>( code & 0x3f) | 0x80u; // continuation byte
}
else if( code < 0x10000u )
{
- *utf8++ = static_cast<uint8_t>( code >> 12u ) | 0xe0u; // lead byte for 3 byte sequence
- *utf8++ = static_cast<uint8_t>( ( code >> 6u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( code & 0x3f ) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code >> 12u) | 0xe0u; // lead byte for 3 byte sequence
+ *utf8++ = static_cast<uint8_t>((code >> 6u ) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code & 0x3f) | 0x80u; // continuation byte
}
else if( code < 0x200000u )
{
- *utf8++ = static_cast<uint8_t>( code >> 18u ) | 0xf0u; // lead byte for 4 byte sequence
- *utf8++ = static_cast<uint8_t>( ( code >> 12u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( ( code >> 6u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( code & 0x3f ) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code >> 18u) | 0xf0u; // lead byte for 4 byte sequence
+ *utf8++ = static_cast<uint8_t>((code >> 12u) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>((code >> 6u ) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code & 0x3f) | 0x80u; // continuation byte
}
else if( code < 0x4000000u )
{
- *utf8++ = static_cast<uint8_t>( code >> 24u ) | 0xf8u; // lead byte for 5 byte sequence
- *utf8++ = static_cast<uint8_t>( ( code >> 18u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( ( code >> 12u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( ( code >> 6u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( code & 0x3f ) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code >> 24u) | 0xf8u; // lead byte for 5 byte sequence
+ *utf8++ = static_cast<uint8_t>((code >> 18u) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>((code >> 12u) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>((code >> 6u ) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code & 0x3f) | 0x80u; // continuation byte
}
else if( code < 0x80000000u )
{
- *utf8++ = static_cast<uint8_t>( code >> 30u ) | 0xfcu; // lead byte for 6 byte sequence
- *utf8++ = static_cast<uint8_t>( ( code >> 24u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( ( code >> 18u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( ( code >> 12u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( ( code >> 6u ) & 0x3f ) | 0x80u; // continuation byte
- *utf8++ = static_cast<uint8_t>( code & 0x3f ) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code >> 30u) | 0xfcu; // lead byte for 6 byte sequence
+ *utf8++ = static_cast<uint8_t>((code >> 24u) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>((code >> 18u) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>((code >> 12u) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>((code >> 6u ) & 0x3f) | 0x80u; // continuation byte
+ *utf8++ = static_cast<uint8_t>( code & 0x3f) | 0x80u; // continuation byte
}
+ // clang-format on
}
return utf8 - utf8Begin;
}
-void Utf32ToUtf8( const uint32_t* const utf32, uint32_t numberOfCharacters, std::string& utf8 )
+void Utf32ToUtf8(const uint32_t* const utf32, uint32_t numberOfCharacters, std::string& utf8)
{
utf8.clear();
- uint32_t numberOfBytes = GetNumberOfUtf8Bytes( &utf32[0], numberOfCharacters );
- utf8.resize( numberOfBytes );
+ uint32_t numberOfBytes = GetNumberOfUtf8Bytes(&utf32[0], numberOfCharacters);
+ utf8.resize(numberOfBytes);
// This is a bit horrible but std::string returns a (signed) char*
- Utf32ToUtf8( utf32, numberOfCharacters, reinterpret_cast<uint8_t*>(&utf8[0]) );
+ Utf32ToUtf8(utf32, numberOfCharacters, reinterpret_cast<uint8_t*>(&utf8[0]));
}
} // namespace Text
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
/**
* @brief Finds a color in the vector of colors.
* It inserts the color in the vector if it's not in.
*
* @return The index + 1 where the color is in the vector. The index zero is reserved for the default color.
*/
-ColorIndex FindColor( Vector<Vector4>& colors,
- const Vector4& color )
+ColorIndex FindColor(Vector<Vector4>& colors,
+ const Vector4& color)
{
ColorIndex index = 1u; // The index zero is reserved for the default color.
- for( Vector<Vector4>::Iterator it = colors.Begin(),
- endIt = colors.End();
- it != endIt;
- ++it )
+ for(Vector<Vector4>::Iterator it = colors.Begin(),
+ endIt = colors.End();
+ it != endIt;
+ ++it)
{
- if( color == *it )
+ if(color == *it)
{
return index;
}
++index;
}
- colors.PushBack( color );
+ colors.PushBack(color);
return index;
}
-void SetColorSegmentationInfo( const Vector<ColorRun>& colorRuns,
- const Vector<GlyphIndex>& charactersToGlyph,
- const Vector<Length>& glyphsPerCharacter,
- CharacterIndex startCharacterIndex,
- GlyphIndex startGlyphIndex,
- Length numberOfCharacters,
- Vector<Vector4>& colors,
- Vector<ColorIndex>& colorIndices )
+void SetColorSegmentationInfo(const Vector<ColorRun>& colorRuns,
+ const Vector<GlyphIndex>& charactersToGlyph,
+ const Vector<Length>& glyphsPerCharacter,
+ CharacterIndex startCharacterIndex,
+ GlyphIndex startGlyphIndex,
+ Length numberOfCharacters,
+ Vector<Vector4>& colors,
+ Vector<ColorIndex>& colorIndices)
{
- if( 0u == charactersToGlyph.Count() )
+ if(0u == charactersToGlyph.Count())
{
// Nothing to do if there is no text.
return;
}
// Get pointers to the buffers.
- const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
- const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
+ const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
+ const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
// Calculate the number of glyphs to insert.
const CharacterIndex lastCharacterIndex = startCharacterIndex + numberOfCharacters - 1u;
- const Length numberOfNewGlyphs = *( charactersToGlyphBuffer + lastCharacterIndex ) + *( glyphsPerCharacterBuffer + lastCharacterIndex ) - *( charactersToGlyphBuffer + startCharacterIndex );
+ const Length numberOfNewGlyphs = *(charactersToGlyphBuffer + lastCharacterIndex) + *(glyphsPerCharacterBuffer + lastCharacterIndex) - *(charactersToGlyphBuffer + startCharacterIndex);
// Reserve space for the new color indices.
Vector<ColorIndex> newColorIndices;
- newColorIndices.Resize( numberOfNewGlyphs );
+ newColorIndices.Resize(numberOfNewGlyphs);
ColorIndex* newColorIndicesBuffer = newColorIndices.Begin();
// Convert from characters to glyphs.
Length index = 0u;
- for( Vector<ColorRun>::ConstIterator it = colorRuns.Begin(),
- endIt = colorRuns.End();
- it != endIt;
- ++it, ++index )
+ for(Vector<ColorRun>::ConstIterator it = colorRuns.Begin(),
+ endIt = colorRuns.End();
+ it != endIt;
+ ++it, ++index)
{
const ColorRun& colorRun = *it;
- if( ( startCharacterIndex < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters ) &&
- ( colorRun.characterRun.characterIndex < startCharacterIndex + numberOfCharacters ) )
+ if((startCharacterIndex < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters) &&
+ (colorRun.characterRun.characterIndex < startCharacterIndex + numberOfCharacters))
{
- if( 0u < colorRun.characterRun.numberOfCharacters )
+ if(0u < colorRun.characterRun.numberOfCharacters)
{
// Find the color index.
- const ColorIndex colorIndex = FindColor( colors, colorRun.color );
+ const ColorIndex colorIndex = FindColor(colors, colorRun.color);
// Get the index to the last character of the run.
const CharacterIndex lastIndex = colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters - 1u;
- const GlyphIndex glyphIndex = std::max( startGlyphIndex, *( charactersToGlyphBuffer + colorRun.characterRun.characterIndex ) ) - startGlyphIndex;
+ const GlyphIndex glyphIndex = std::max(startGlyphIndex, *(charactersToGlyphBuffer + colorRun.characterRun.characterIndex)) - startGlyphIndex;
// Get the number of glyphs of the run.
- const Length lastGlyphIndexPlusOne = std::min( numberOfNewGlyphs, *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex );
+ const Length lastGlyphIndexPlusOne = std::min(numberOfNewGlyphs, *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex);
// Set the indices.
- for( GlyphIndex i = glyphIndex; i < lastGlyphIndexPlusOne; ++i )
+ for(GlyphIndex i = glyphIndex; i < lastGlyphIndexPlusOne; ++i)
{
- *( newColorIndicesBuffer + i ) = colorIndex;
+ *(newColorIndicesBuffer + i) = colorIndex;
}
}
}
}
// Insert the new indices.
- colorIndices.Insert( colorIndices.Begin() + startGlyphIndex,
- newColorIndices.Begin(),
- newColorIndices.End() );
+ colorIndices.Insert(colorIndices.Begin() + startGlyphIndex,
+ newColorIndices.Begin(),
+ newColorIndices.End());
}
} // namespace Text
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace
{
-
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
const Dali::Toolkit::Text::CharacterDirection LTR = false; ///< Left To Right direction.
struct FindWordData
{
- FindWordData( const Dali::Toolkit::Text::Character* const textBuffer,
- Dali::Toolkit::Text::Length totalNumberOfCharacters,
- Dali::Toolkit::Text::CharacterIndex hitCharacter,
- bool isWhiteSpace,
- bool isNewParagraph )
- : textBuffer( textBuffer ),
- totalNumberOfCharacters( totalNumberOfCharacters ),
- hitCharacter( hitCharacter ),
- foundIndex( 0 ),
- isWhiteSpace( isWhiteSpace ),
- isNewParagraph( isNewParagraph )
- {}
+ FindWordData(const Dali::Toolkit::Text::Character* const textBuffer,
+ Dali::Toolkit::Text::Length totalNumberOfCharacters,
+ Dali::Toolkit::Text::CharacterIndex hitCharacter,
+ bool isWhiteSpace,
+ bool isNewParagraph)
+ : textBuffer(textBuffer),
+ totalNumberOfCharacters(totalNumberOfCharacters),
+ hitCharacter(hitCharacter),
+ foundIndex(0),
+ isWhiteSpace(isWhiteSpace),
+ isNewParagraph(isNewParagraph)
+ {
+ }
~FindWordData()
- {}
+ {
+ }
const Dali::Toolkit::Text::Character* const textBuffer;
Dali::Toolkit::Text::Length totalNumberOfCharacters;
Dali::Toolkit::Text::CharacterIndex hitCharacter;
Dali::Toolkit::Text::CharacterIndex foundIndex;
- bool isWhiteSpace : 1u;
+ bool isWhiteSpace : 1u;
bool isNewParagraph : 1u;
};
-bool IsWhiteSpaceOrNewParagraph( Dali::Toolkit::Text::Character character,
- bool isHitWhiteSpace,
- bool isHitWhiteSpaceOrNewParagraph )
+bool IsWhiteSpaceOrNewParagraph(Dali::Toolkit::Text::Character character,
+ bool isHitWhiteSpace,
+ bool isHitWhiteSpaceOrNewParagraph)
{
bool isWhiteSpaceOrNewParagraph = false;
- if( isHitWhiteSpaceOrNewParagraph )
+ if(isHitWhiteSpaceOrNewParagraph)
{
- if( isHitWhiteSpace )
+ if(isHitWhiteSpace)
{
// Whether the current character is a white space. Note a new paragraph character is a white space as well but here is not wanted.
- isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace( character ) && !Dali::TextAbstraction::IsNewParagraph( character );
+ isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace(character) && !Dali::TextAbstraction::IsNewParagraph(character);
}
else
{
// Whether the current character is a new paragraph character.
- isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsNewParagraph( character );
+ isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsNewParagraph(character);
}
}
else
{
// Whether the current character is a white space or a new paragraph character (note the new paragraph character is a white space as well).
- isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace( character );
+ isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace(character);
}
return isWhiteSpaceOrNewParagraph;
}
-void FindStartOfWord( FindWordData& data )
+void FindStartOfWord(FindWordData& data)
{
const bool isHitWhiteSpaceOrNewParagraph = data.isWhiteSpace || data.isNewParagraph;
- for( data.foundIndex = data.hitCharacter; data.foundIndex > 0; --data.foundIndex )
+ for(data.foundIndex = data.hitCharacter; data.foundIndex > 0; --data.foundIndex)
{
- const Dali::Toolkit::Text::Character character = *( data.textBuffer + data.foundIndex - 1u );
+ const Dali::Toolkit::Text::Character character = *(data.textBuffer + data.foundIndex - 1u);
- const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph( character,
- data.isWhiteSpace,
- isHitWhiteSpaceOrNewParagraph );
+ const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph(character,
+ data.isWhiteSpace,
+ isHitWhiteSpaceOrNewParagraph);
- if( isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph )
+ if(isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph)
{
break;
}
}
}
-void FindEndOfWord( FindWordData& data )
+void FindEndOfWord(FindWordData& data)
{
const bool isHitWhiteSpaceOrNewParagraph = data.isWhiteSpace || data.isNewParagraph;
- for( data.foundIndex = data.hitCharacter + 1u; data.foundIndex < data.totalNumberOfCharacters; ++data.foundIndex )
+ for(data.foundIndex = data.hitCharacter + 1u; data.foundIndex < data.totalNumberOfCharacters; ++data.foundIndex)
{
- const Dali::Toolkit::Text::Character character = *( data.textBuffer + data.foundIndex );
+ const Dali::Toolkit::Text::Character character = *(data.textBuffer + data.foundIndex);
- const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph( character,
- data.isWhiteSpace,
- isHitWhiteSpaceOrNewParagraph );
+ const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph(character,
+ data.isWhiteSpace,
+ isHitWhiteSpaceOrNewParagraph);
- if( isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph )
+ if(isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph)
{
break;
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-LineIndex GetClosestLine( VisualModelPtr visualModel,
- float visualY,
- bool& matchedLine )
+LineIndex GetClosestLine(VisualModelPtr visualModel,
+ float visualY,
+ bool& matchedLine)
{
- float totalHeight = 0.f;
- LineIndex lineIndex = 0;
- matchedLine = false;
+ float totalHeight = 0.f;
+ LineIndex lineIndex = 0;
+ matchedLine = false;
- if( visualY < 0.f )
+ if(visualY < 0.f)
{
return 0;
}
const Vector<LineRun>& lines = visualModel->mLines;
- for( Vector<LineRun>::ConstIterator it = lines.Begin(),
- endIt = lines.End();
- it != endIt;
- ++it, ++lineIndex )
+ for(Vector<LineRun>::ConstIterator it = lines.Begin(),
+ endIt = lines.End();
+ it != endIt;
+ ++it, ++lineIndex)
{
const LineRun& lineRun = *it;
// However, the line descender has a negative value, hence the subtraction.
totalHeight += lineRun.ascender - lineRun.descender;
- if( visualY < totalHeight )
+ if(visualY < totalHeight)
{
matchedLine = true;
return lineIndex;
}
}
- if( lineIndex == 0 )
+ if(lineIndex == 0)
{
return 0;
}
return lineIndex - 1u;
}
-float CalculateLineOffset( const Vector<LineRun>& lines,
- LineIndex lineIndex )
+float CalculateLineOffset(const Vector<LineRun>& lines,
+ LineIndex lineIndex)
{
float offset = 0.f;
- for( Vector<LineRun>::ConstIterator it = lines.Begin(),
- endIt = lines.Begin() + lineIndex;
- it != endIt;
- ++it )
+ for(Vector<LineRun>::ConstIterator it = lines.Begin(),
+ endIt = lines.Begin() + lineIndex;
+ it != endIt;
+ ++it)
{
const LineRun& lineRun = *it;
return offset;
}
-CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel,
- LogicalModelPtr logicalModel,
- MetricsPtr metrics,
- float visualX,
- float visualY,
- CharacterHitTest::Mode mode,
- bool& matchedCharacter )
+CharacterIndex GetClosestCursorIndex(VisualModelPtr visualModel,
+ LogicalModelPtr logicalModel,
+ MetricsPtr metrics,
+ float visualX,
+ float visualY,
+ CharacterHitTest::Mode mode,
+ bool& matchedCharacter)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GetClosestCursorIndex, closest visualX %f visualY %f\n", visualX, visualY );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GetClosestCursorIndex, closest visualX %f visualY %f\n", visualX, visualY);
// Whether there is a hit on a glyph.
matchedCharacter = false;
const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
const Length totalNumberOfLines = visualModel->mLines.Count();
- if( ( 0 == totalNumberOfGlyphs ) ||
- ( 0 == totalNumberOfLines ) )
+ if((0 == totalNumberOfGlyphs) ||
+ (0 == totalNumberOfLines))
{
return logicalIndex;
}
bool matchedLine = false;
// Find which line is closest.
- const LineIndex lineIndex = Text::GetClosestLine( visualModel,
- visualY,
- matchedLine );
+ const LineIndex lineIndex = Text::GetClosestLine(visualModel,
+ visualY,
+ matchedLine);
- if( !matchedLine && ( CharacterHitTest::TAP == mode ) )
+ if(!matchedLine && (CharacterHitTest::TAP == mode))
{
// Return the first or the last character if the touch point doesn't hit a line.
- return ( visualY < 0.f ) ? 0 : logicalModel->mText.Count();
+ return (visualY < 0.f) ? 0 : logicalModel->mText.Count();
}
// Convert from text's coords to line's coords.
- const LineRun& line = *( visualModel->mLines.Begin() + lineIndex );
+ const LineRun& line = *(visualModel->mLines.Begin() + lineIndex);
// Transform the tap point from text's coords to line's coords.
visualX -= line.alignmentOffset;
const CharacterIndex startCharacter = line.characterRun.characterIndex;
const CharacterIndex endCharacter = line.characterRun.characterIndex + line.characterRun.numberOfCharacters;
- DALI_ASSERT_DEBUG( endCharacter <= logicalModel->mText.Count() && "Invalid line info" );
+ DALI_ASSERT_DEBUG(endCharacter <= logicalModel->mText.Count() && "Invalid line info");
// Whether this line is a bidirectional line.
- const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo( startCharacter );
+ const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo(startCharacter);
// The character's direction buffer.
const CharacterDirection* const directionsBuffer = bidiLineFetched ? logicalModel->mCharacterDirections.Begin() : NULL;
bool isBeforeFirstGlyph = false;
// Traverses glyphs in visual order. To do that use the visual to logical conversion table.
- CharacterIndex visualIndex = startCharacter;
- Length numberOfVisualCharacters = 0;
- for( ; visualIndex < endCharacter; ++visualIndex )
+ CharacterIndex visualIndex = startCharacter;
+ Length numberOfVisualCharacters = 0;
+ for(; visualIndex < endCharacter; ++visualIndex)
{
// The character in logical order.
- const CharacterIndex characterLogicalOrderIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( visualIndex ) : visualIndex );
- const CharacterDirection direction = ( bidiLineFetched ? *( directionsBuffer + characterLogicalOrderIndex ) : LTR );
+ const CharacterIndex characterLogicalOrderIndex = (bidiLineFetched ? logicalModel->GetLogicalCharacterIndex(visualIndex) : visualIndex);
+ const CharacterDirection direction = (bidiLineFetched ? *(directionsBuffer + characterLogicalOrderIndex) : LTR);
// The number of glyphs for that character
- const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + characterLogicalOrderIndex );
+ const Length numberOfGlyphs = *(glyphsPerCharacterBuffer + characterLogicalOrderIndex);
++numberOfVisualCharacters;
- if( 0 != numberOfGlyphs )
+ if(0 != numberOfGlyphs)
{
// Get the first character/glyph of the group of glyphs.
- const CharacterIndex firstVisualCharacterIndex = 1u + visualIndex - numberOfVisualCharacters;
- const CharacterIndex firstLogicalCharacterIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( firstVisualCharacterIndex ) : firstVisualCharacterIndex );
- const GlyphIndex firstLogicalGlyphIndex = *( charactersToGlyphBuffer + firstLogicalCharacterIndex );
+ const CharacterIndex firstVisualCharacterIndex = 1u + visualIndex - numberOfVisualCharacters;
+ const CharacterIndex firstLogicalCharacterIndex = (bidiLineFetched ? logicalModel->GetLogicalCharacterIndex(firstVisualCharacterIndex) : firstVisualCharacterIndex);
+ const GlyphIndex firstLogicalGlyphIndex = *(charactersToGlyphBuffer + firstLogicalCharacterIndex);
// Get the metrics for the group of glyphs.
GlyphMetrics glyphMetrics;
- GetGlyphsMetrics( firstLogicalGlyphIndex,
- numberOfGlyphs,
- glyphMetrics,
- glyphInfoBuffer,
- metrics );
+ GetGlyphsMetrics(firstLogicalGlyphIndex,
+ numberOfGlyphs,
+ glyphMetrics,
+ glyphInfoBuffer,
+ metrics);
// Get the position of the first glyph.
- const Vector2& position = *( positionsBuffer + firstLogicalGlyphIndex );
+ const Vector2& position = *(positionsBuffer + firstLogicalGlyphIndex);
- if( startCharacter == visualIndex )
+ if(startCharacter == visualIndex)
{
const float glyphPosition = -glyphMetrics.xBearing + position.x;
- if( visualX < glyphPosition )
+ if(visualX < glyphPosition)
{
isBeforeFirstGlyph = true;
break;
}
// Whether the glyph can be split, like Latin ligatures fi, ff or Arabic (ل + ا).
- Length numberOfCharacters = *( charactersPerGlyphBuffer + firstLogicalGlyphIndex );
- if( direction != LTR )
+ Length numberOfCharacters = *(charactersPerGlyphBuffer + firstLogicalGlyphIndex);
+ if(direction != LTR)
{
// As characters are being traversed in visual order,
// for right to left ligatures, the character which contains the
// number of glyphs in the table is found first.
// Jump the number of characters to the next glyph is needed.
- if( 0 == numberOfCharacters )
+ if(0 == numberOfCharacters)
{
// TODO: This is a workaround to fix an issue with complex characters in the arabic
// script like i.e. رّ or الأَبْجَدِيَّة العَرَبِيَّة
// to hang in an infinite loop.
// Find the number of characters.
- for( GlyphIndex index = firstLogicalGlyphIndex + 1u;
- ( 0 == numberOfCharacters ) && ( index < totalNumberOfGlyphs );
- ++index )
+ for(GlyphIndex index = firstLogicalGlyphIndex + 1u;
+ (0 == numberOfCharacters) && (index < totalNumberOfGlyphs);
+ ++index)
{
- numberOfCharacters = *( charactersPerGlyphBuffer + index );
+ numberOfCharacters = *(charactersPerGlyphBuffer + index);
}
- if( 2u > numberOfCharacters )
+ if(2u > numberOfCharacters)
{
continue;
}
}
// Get the script of the character.
- const Script script = logicalModel->GetScript( characterLogicalOrderIndex );
+ const Script script = logicalModel->GetScript(characterLogicalOrderIndex);
- const bool isInterglyphIndex = ( numberOfCharacters > numberOfGlyphs ) && HasLigatureMustBreak( script );
- const Length numberOfBlocks = isInterglyphIndex ? numberOfCharacters : 1u;
- const float glyphAdvance = glyphMetrics.advance / static_cast<float>( numberOfBlocks );
+ const bool isInterglyphIndex = (numberOfCharacters > numberOfGlyphs) && HasLigatureMustBreak(script);
+ const Length numberOfBlocks = isInterglyphIndex ? numberOfCharacters : 1u;
+ const float glyphAdvance = glyphMetrics.advance / static_cast<float>(numberOfBlocks);
CharacterIndex index = 0;
- for( ; index < numberOfBlocks; ++index )
+ for(; index < numberOfBlocks; ++index)
{
// Find the mid-point of the area containing the glyph
- const float glyphCenter = -glyphMetrics.xBearing + position.x + ( static_cast<float>( index ) + 0.5f ) * glyphAdvance;
+ const float glyphCenter = -glyphMetrics.xBearing + position.x + (static_cast<float>(index) + 0.5f) * glyphAdvance;
- if( visualX < glyphCenter )
+ if(visualX < glyphCenter)
{
matchedCharacter = true;
break;
}
}
- if( matchedCharacter )
+ if(matchedCharacter)
{
// If the glyph is shaped from more than one character, it matches the character of the glyph.
visualIndex = firstVisualCharacterIndex + index;
// Return the logical position of the cursor in characters.
- if( !matchedCharacter )
+ if(!matchedCharacter)
{
- if( isBeforeFirstGlyph )
+ if(isBeforeFirstGlyph)
{
// If no character is matched, then the first character (in visual order) of the line is used.
visualIndex = startCharacter;
// Get the paragraph direction.
const CharacterDirection paragraphDirection = line.direction;
- if( totalNumberOfCharacters != visualIndex )
+ if(totalNumberOfCharacters != visualIndex)
{
// The visual index is not at the end of the text.
- if( LTR == paragraphDirection )
+ if(LTR == paragraphDirection)
{
// The paragraph direction is left to right.
- if( visualIndex == endCharacter )
+ if(visualIndex == endCharacter)
{
// It places the cursor just before the last character in visual order.
// i.e. it places the cursor just before the '\n' or before the last character
{
// The paragraph direction is right to left.
- if( ( lineIndex != totalNumberOfLines - 1u ) && // is not the last line.
- ( visualIndex == startCharacter ) )
+ if((lineIndex != totalNumberOfLines - 1u) && // is not the last line.
+ (visualIndex == startCharacter))
{
// It places the cursor just after the first character in visual order.
// i.e. it places the cursor just after the '\n' or after the last character
// This branch checks if the closest line is the one with the last '\n'. If it is, it decrements the visual index to place
// the cursor just before the last '\n'.
- if( ( lineIndex != totalNumberOfLines - 1u ) &&
- TextAbstraction::IsNewParagraph( *( logicalModel->mText.Begin() + visualIndex - 1u ) ) )
+ if((lineIndex != totalNumberOfLines - 1u) &&
+ TextAbstraction::IsNewParagraph(*(logicalModel->mText.Begin() + visualIndex - 1u)))
{
--visualIndex;
}
}
- logicalIndex = ( bidiLineFetched ? logicalModel->GetLogicalCursorIndex( visualIndex ) : visualIndex );
+ logicalIndex = (bidiLineFetched ? logicalModel->GetLogicalCursorIndex(visualIndex) : visualIndex);
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "closest visualIndex %d logicalIndex %d\n", visualIndex, logicalIndex );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "closest visualIndex %d logicalIndex %d\n", visualIndex, logicalIndex);
- DALI_ASSERT_DEBUG( ( logicalIndex <= logicalModel->mText.Count() && logicalIndex >= 0 ) && "GetClosestCursorIndex - Out of bounds index" );
+ DALI_ASSERT_DEBUG((logicalIndex <= logicalModel->mText.Count() && logicalIndex >= 0) && "GetClosestCursorIndex - Out of bounds index");
return logicalIndex;
}
-
-void GetCursorPosition( GetCursorPositionParameters& parameters,
- CursorInfo& cursorInfo )
+void GetCursorPosition(GetCursorPositionParameters& parameters,
+ CursorInfo& cursorInfo)
{
const LineRun* const modelLines = parameters.visualModel->mLines.Begin();
- if( NULL == modelLines )
+ if(NULL == modelLines)
{
// Nothing to do.
return;
const bool isLastPosition = parameters.logicalModel->mText.Count() == parameters.logical;
// Get the line where the character is laid-out.
- const CharacterIndex characterOfLine = isLastPosition ? ( parameters.logical - 1u ) : parameters.logical;
+ const CharacterIndex characterOfLine = isLastPosition ? (parameters.logical - 1u) : parameters.logical;
// Whether the cursor is in the last position and the last position is a new paragraph character.
- const bool isLastNewParagraph = parameters.isMultiline && isLastPosition && TextAbstraction::IsNewParagraph( *( parameters.logicalModel->mText.Begin() + characterOfLine ) );
+ const bool isLastNewParagraph = parameters.isMultiline && isLastPosition && TextAbstraction::IsNewParagraph(*(parameters.logicalModel->mText.Begin() + characterOfLine));
- const LineIndex lineIndex = parameters.visualModel->GetLineOfCharacter( characterOfLine );
- const LineRun& line = *( modelLines + lineIndex );
+ const LineIndex lineIndex = parameters.visualModel->GetLineOfCharacter(characterOfLine);
+ const LineRun& line = *(modelLines + lineIndex);
- if( isLastNewParagraph )
+ if(isLastNewParagraph)
{
// The cursor is in a new line with no characters. Place the cursor in that line.
const LineIndex newLineIndex = lineIndex + 1u;
- const LineRun& newLine = *( modelLines + newLineIndex );
+ const LineRun& newLine = *(modelLines + newLineIndex);
cursorInfo.isSecondaryCursor = false;
// Set the line offset and height.
- cursorInfo.lineOffset = CalculateLineOffset( parameters.visualModel->mLines,
- newLineIndex );
+ cursorInfo.lineOffset = CalculateLineOffset(parameters.visualModel->mLines,
+ newLineIndex);
// The line height is the addition of the line ascender and the line descender.
// However, the line descender has a negative value, hence the subtraction.
cursorInfo.primaryCursorHeight = cursorInfo.lineHeight;
// Set the primary cursor's position.
- cursorInfo.primaryPosition.x = ( LTR == line.direction ) ? newLine.alignmentOffset : parameters.visualModel->mControlSize.width - newLine.alignmentOffset;
+ cursorInfo.primaryPosition.x = (LTR == line.direction) ? newLine.alignmentOffset : parameters.visualModel->mControlSize.width - newLine.alignmentOffset;
cursorInfo.primaryPosition.y = cursorInfo.lineOffset;
}
else
{
// Whether this line is a bidirectional line.
- const bool bidiLineFetched = parameters.logicalModel->FetchBidirectionalLineInfo( characterOfLine );
+ const bool bidiLineFetched = parameters.logicalModel->FetchBidirectionalLineInfo(characterOfLine);
// Check if the logical position is the first or the last one of the line.
const bool isFirstPositionOfLine = line.characterRun.characterIndex == parameters.logical;
- const bool isLastPositionOfLine = line.characterRun.characterIndex + line.characterRun.numberOfCharacters == parameters.logical;
+ const bool isLastPositionOfLine = line.characterRun.characterIndex + line.characterRun.numberOfCharacters == parameters.logical;
// 'logical' is the logical 'cursor' index.
// Get the next and current logical 'character' index.
- const CharacterIndex characterIndex = isFirstPositionOfLine ? parameters.logical : parameters.logical - 1u;
+ const CharacterIndex characterIndex = isFirstPositionOfLine ? parameters.logical : parameters.logical - 1u;
const CharacterIndex nextCharacterIndex = isLastPositionOfLine ? characterIndex : parameters.logical;
// The character's direction buffer.
const CharacterDirection* const directionsBuffer = bidiLineFetched ? parameters.logicalModel->mCharacterDirections.Begin() : NULL;
CharacterDirection isCurrentRightToLeft = false;
- CharacterDirection isNextRightToLeft = false;
- if( bidiLineFetched ) // If bidiLineFetched is false, it means the whole text is left to right.
+ CharacterDirection isNextRightToLeft = false;
+ if(bidiLineFetched) // If bidiLineFetched is false, it means the whole text is left to right.
{
- isCurrentRightToLeft = *( directionsBuffer + characterIndex );
- isNextRightToLeft = *( directionsBuffer + nextCharacterIndex );
+ isCurrentRightToLeft = *(directionsBuffer + characterIndex);
+ isNextRightToLeft = *(directionsBuffer + nextCharacterIndex);
}
// Get the paragraph's direction.
const CharacterDirection isRightToLeftParagraph = line.direction;
// Check whether there is an alternative position:
- cursorInfo.isSecondaryCursor = ( ( !isLastPositionOfLine && ( isCurrentRightToLeft != isNextRightToLeft ) ) ||
- ( isLastPositionOfLine && ( isRightToLeftParagraph != isCurrentRightToLeft ) ) ||
- ( isFirstPositionOfLine && ( isRightToLeftParagraph != isCurrentRightToLeft ) ) );
+ cursorInfo.isSecondaryCursor = ((!isLastPositionOfLine && (isCurrentRightToLeft != isNextRightToLeft)) ||
+ (isLastPositionOfLine && (isRightToLeftParagraph != isCurrentRightToLeft)) ||
+ (isFirstPositionOfLine && (isRightToLeftParagraph != isCurrentRightToLeft)));
// Set the line offset and height.
- cursorInfo.lineOffset = CalculateLineOffset( parameters.visualModel->mLines,
- lineIndex );
+ cursorInfo.lineOffset = CalculateLineOffset(parameters.visualModel->mLines,
+ lineIndex);
// The line height is the addition of the line ascender and the line descender.
// However, the line descender has a negative value, hence the subtraction.
// Calculate the primary cursor.
CharacterIndex index = characterIndex;
- if( cursorInfo.isSecondaryCursor )
+ if(cursorInfo.isSecondaryCursor)
{
// If there is a secondary position, the primary cursor may be in a different place than the logical index.
- if( isLastPositionOfLine )
+ if(isLastPositionOfLine)
{
// The position of the cursor after the last character needs special
// care depending on its direction and the direction of the paragraph.
// i.e l0 l1 l2 r0 r1 should find r0.
index = isRightToLeftParagraph ? line.characterRun.characterIndex : line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u;
- if( bidiLineFetched )
+ if(bidiLineFetched)
{
- index = parameters.logicalModel->GetLogicalCharacterIndex( index );
+ index = parameters.logicalModel->GetLogicalCharacterIndex(index);
}
}
- else if( isFirstPositionOfLine )
+ else if(isFirstPositionOfLine)
{
index = isRightToLeftParagraph ? line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u : line.characterRun.characterIndex;
- if( bidiLineFetched )
+ if(bidiLineFetched)
{
- index = parameters.logicalModel->GetLogicalCharacterIndex( index );
+ index = parameters.logicalModel->GetLogicalCharacterIndex(index);
}
}
else
{
- index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? characterIndex : nextCharacterIndex;
+ index = (isRightToLeftParagraph == isCurrentRightToLeft) ? characterIndex : nextCharacterIndex;
}
}
- const GlyphIndex* const charactersToGlyphBuffer = parameters.visualModel->mCharactersToGlyph.Begin();
- const Length* const glyphsPerCharacterBuffer = parameters.visualModel->mGlyphsPerCharacter.Begin();
- const Length* const charactersPerGlyphBuffer = parameters.visualModel->mCharactersPerGlyph.Begin();
+ const GlyphIndex* const charactersToGlyphBuffer = parameters.visualModel->mCharactersToGlyph.Begin();
+ const Length* const glyphsPerCharacterBuffer = parameters.visualModel->mGlyphsPerCharacter.Begin();
+ const Length* const charactersPerGlyphBuffer = parameters.visualModel->mCharactersPerGlyph.Begin();
const CharacterIndex* const glyphsToCharactersBuffer = parameters.visualModel->mGlyphsToCharacters.Begin();
- const Vector2* const glyphPositionsBuffer = parameters.visualModel->mGlyphPositions.Begin();
- const GlyphInfo* const glyphInfoBuffer = parameters.visualModel->mGlyphs.Begin();
+ const Vector2* const glyphPositionsBuffer = parameters.visualModel->mGlyphPositions.Begin();
+ const GlyphInfo* const glyphInfoBuffer = parameters.visualModel->mGlyphs.Begin();
// Convert the cursor position into the glyph position.
- const GlyphIndex primaryGlyphIndex = *( charactersToGlyphBuffer + index );
- const Length primaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index );
- const Length primaryNumberOfCharacters = *( charactersPerGlyphBuffer + primaryGlyphIndex );
+ const GlyphIndex primaryGlyphIndex = *(charactersToGlyphBuffer + index);
+ const Length primaryNumberOfGlyphs = *(glyphsPerCharacterBuffer + index);
+ const Length primaryNumberOfCharacters = *(charactersPerGlyphBuffer + primaryGlyphIndex);
// Get the metrics for the group of glyphs.
GlyphMetrics glyphMetrics;
- GetGlyphsMetrics( primaryGlyphIndex,
- primaryNumberOfGlyphs,
- glyphMetrics,
- glyphInfoBuffer,
- parameters.metrics );
+ GetGlyphsMetrics(primaryGlyphIndex,
+ primaryNumberOfGlyphs,
+ glyphMetrics,
+ glyphInfoBuffer,
+ parameters.metrics);
// Whether to add the glyph's advance to the cursor position.
// i.e if the paragraph is left to right and the logical cursor is zero, the position is the position of the first glyph and the advance is not added,
// P -> isRightToLeftParagraph
// A -> Whether to add the glyph's advance.
- const bool addGlyphAdvance = ( ( isLastPositionOfLine && !isRightToLeftParagraph ) ||
- ( isFirstPositionOfLine && isRightToLeftParagraph ) ||
- ( !isFirstPositionOfLine && !isLastPosition && !isCurrentRightToLeft ) );
+ const bool addGlyphAdvance = ((isLastPositionOfLine && !isRightToLeftParagraph) ||
+ (isFirstPositionOfLine && isRightToLeftParagraph) ||
+ (!isFirstPositionOfLine && !isLastPosition && !isCurrentRightToLeft));
float glyphAdvance = addGlyphAdvance ? glyphMetrics.advance : 0.f;
- if( !isLastPositionOfLine &&
- ( primaryNumberOfCharacters > 1u ) )
+ if(!isLastPositionOfLine &&
+ (primaryNumberOfCharacters > 1u))
{
- const CharacterIndex firstIndex = *( glyphsToCharactersBuffer + primaryGlyphIndex );
+ const CharacterIndex firstIndex = *(glyphsToCharactersBuffer + primaryGlyphIndex);
bool isCurrentRightToLeft = false;
- if( bidiLineFetched ) // If bidiLineFetched is false, it means the whole text is left to right.
+ if(bidiLineFetched) // If bidiLineFetched is false, it means the whole text is left to right.
{
- isCurrentRightToLeft = *( directionsBuffer + index );
+ isCurrentRightToLeft = *(directionsBuffer + index);
}
- Length numberOfGlyphAdvance = ( isFirstPositionOfLine ? 0 : 1u ) + characterIndex - firstIndex;
- if( isCurrentRightToLeft )
+ Length numberOfGlyphAdvance = (isFirstPositionOfLine ? 0 : 1u) + characterIndex - firstIndex;
+ if(isCurrentRightToLeft)
{
numberOfGlyphAdvance = primaryNumberOfCharacters - numberOfGlyphAdvance;
}
- glyphAdvance = static_cast<float>( numberOfGlyphAdvance ) * glyphMetrics.advance / static_cast<float>( primaryNumberOfCharacters );
+ glyphAdvance = static_cast<float>(numberOfGlyphAdvance) * glyphMetrics.advance / static_cast<float>(primaryNumberOfCharacters);
}
// Get the glyph position and x bearing (in the line's coords).
- const Vector2& primaryPosition = *( glyphPositionsBuffer + primaryGlyphIndex );
+ const Vector2& primaryPosition = *(glyphPositionsBuffer + primaryGlyphIndex);
// Set the primary cursor's height.
cursorInfo.primaryCursorHeight = cursorInfo.isSecondaryCursor ? 0.5f * glyphMetrics.fontHeight : glyphMetrics.fontHeight;
cursorInfo.primaryPosition.x += line.alignmentOffset;
// Calculate the secondary cursor.
- if( cursorInfo.isSecondaryCursor )
+ if(cursorInfo.isSecondaryCursor)
{
// Set the secondary cursor's height.
cursorInfo.secondaryCursorHeight = 0.5f * glyphMetrics.fontHeight;
CharacterIndex index = characterIndex;
- if( !isLastPositionOfLine )
+ if(!isLastPositionOfLine)
{
- index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? nextCharacterIndex : characterIndex;
+ index = (isRightToLeftParagraph == isCurrentRightToLeft) ? nextCharacterIndex : characterIndex;
}
- const GlyphIndex secondaryGlyphIndex = *( charactersToGlyphBuffer + index );
- const Length secondaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index );
+ const GlyphIndex secondaryGlyphIndex = *(charactersToGlyphBuffer + index);
+ const Length secondaryNumberOfGlyphs = *(glyphsPerCharacterBuffer + index);
- const Vector2& secondaryPosition = *( glyphPositionsBuffer + secondaryGlyphIndex );
+ const Vector2& secondaryPosition = *(glyphPositionsBuffer + secondaryGlyphIndex);
- GetGlyphsMetrics( secondaryGlyphIndex,
- secondaryNumberOfGlyphs,
- glyphMetrics,
- glyphInfoBuffer,
- parameters.metrics );
+ GetGlyphsMetrics(secondaryGlyphIndex,
+ secondaryNumberOfGlyphs,
+ glyphMetrics,
+ glyphInfoBuffer,
+ parameters.metrics);
// Set the secondary cursor's position.
// P -> isRightToLeftParagraph
// A -> Whether to add the glyph's advance.
- const bool addGlyphAdvance = ( ( !isFirstPositionOfLine && !isCurrentRightToLeft ) ||
- ( isFirstPositionOfLine && !isRightToLeftParagraph ) );
+ const bool addGlyphAdvance = ((!isFirstPositionOfLine && !isCurrentRightToLeft) ||
+ (isFirstPositionOfLine && !isRightToLeftParagraph));
- cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + secondaryPosition.x + ( addGlyphAdvance ? glyphMetrics.advance : 0.f );
+ cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + secondaryPosition.x + (addGlyphAdvance ? glyphMetrics.advance : 0.f);
cursorInfo.secondaryPosition.y = cursorInfo.lineOffset + cursorInfo.lineHeight - cursorInfo.secondaryCursorHeight;
// Transform the cursor info from line's coords to text's coords.
}
}
-bool FindSelectionIndices( VisualModelPtr visualModel,
- LogicalModelPtr logicalModel,
- MetricsPtr metrics,
- float visualX,
- float visualY,
- CharacterIndex& startIndex,
- CharacterIndex& endIndex,
- CharacterIndex& noTextHitIndex )
+bool FindSelectionIndices(VisualModelPtr visualModel,
+ LogicalModelPtr logicalModel,
+ MetricsPtr metrics,
+ float visualX,
+ float visualY,
+ CharacterIndex& startIndex,
+ CharacterIndex& endIndex,
+ CharacterIndex& noTextHitIndex)
{
-/*
+ /*
Hit character Select
|-------------------------------------------------------|------------------------------------------|
| On a word | The word |
|-------------------------------------------------------|------------------------------------------|
*/
const Length totalNumberOfCharacters = logicalModel->mText.Count();
- startIndex = 0;
- endIndex = 0;
- noTextHitIndex = 0;
+ startIndex = 0;
+ endIndex = 0;
+ noTextHitIndex = 0;
- if( 0 == totalNumberOfCharacters )
+ if(0 == totalNumberOfCharacters)
{
// Nothing to do if the model is empty.
return false;
}
- bool matchedCharacter = false;
- CharacterIndex hitCharacter = Text::GetClosestCursorIndex( visualModel,
- logicalModel,
- metrics,
- visualX,
- visualY,
- CharacterHitTest::TAP,
- matchedCharacter );
+ bool matchedCharacter = false;
+ CharacterIndex hitCharacter = Text::GetClosestCursorIndex(visualModel,
+ logicalModel,
+ metrics,
+ visualX,
+ visualY,
+ CharacterHitTest::TAP,
+ matchedCharacter);
- if( !matchedCharacter )
+ if(!matchedCharacter)
{
noTextHitIndex = hitCharacter;
}
- DALI_ASSERT_DEBUG( ( hitCharacter <= totalNumberOfCharacters ) && "GetClosestCursorIndex returned out of bounds index" );
+ DALI_ASSERT_DEBUG((hitCharacter <= totalNumberOfCharacters) && "GetClosestCursorIndex returned out of bounds index");
- if( hitCharacter >= totalNumberOfCharacters )
+ if(hitCharacter >= totalNumberOfCharacters)
{
// Closest hit character is the last character.
- if( hitCharacter == totalNumberOfCharacters )
+ if(hitCharacter == totalNumberOfCharacters)
{
hitCharacter--; //Hit character index set to last character in logical model
}
const Character* const textBuffer = logicalModel->mText.Begin();
startIndex = hitCharacter;
- endIndex = hitCharacter;
+ endIndex = hitCharacter;
// Whether the hit character is a new paragraph character.
- const bool isHitCharacterNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + hitCharacter ) );
+ const bool isHitCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + hitCharacter));
// Whether the hit character is a white space. Note a new paragraph character is a white space as well but here is not wanted.
- const bool isHitCharacterWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + hitCharacter ) ) && !isHitCharacterNewParagraph;
+ const bool isHitCharacterWhiteSpace = TextAbstraction::IsWhiteSpace(*(textBuffer + hitCharacter)) && !isHitCharacterNewParagraph;
- FindWordData data( textBuffer,
- totalNumberOfCharacters,
- hitCharacter,
- isHitCharacterWhiteSpace,
- isHitCharacterNewParagraph );
+ FindWordData data(textBuffer,
+ totalNumberOfCharacters,
+ hitCharacter,
+ isHitCharacterWhiteSpace,
+ isHitCharacterNewParagraph);
- if( isHitCharacterNewParagraph )
+ if(isHitCharacterNewParagraph)
{
// Find the first character before the hit one which is not a new paragraph character.
- if( hitCharacter > 0 )
+ if(hitCharacter > 0)
{
endIndex = hitCharacter - 1u;
- for( ; endIndex > 0; --endIndex )
+ for(; endIndex > 0; --endIndex)
{
- const Dali::Toolkit::Text::Character character = *( data.textBuffer + endIndex );
+ const Dali::Toolkit::Text::Character character = *(data.textBuffer + endIndex);
- if( !Dali::TextAbstraction::IsNewParagraph( character ) )
+ if(!Dali::TextAbstraction::IsNewParagraph(character))
{
break;
}
}
}
- data.hitCharacter = endIndex;
+ data.hitCharacter = endIndex;
data.isNewParagraph = false;
- data.isWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + data.hitCharacter ) );
+ data.isWhiteSpace = TextAbstraction::IsWhiteSpace(*(textBuffer + data.hitCharacter));
}
// Find the start of the word.
- FindStartOfWord( data );
+ FindStartOfWord(data);
startIndex = data.foundIndex;
// Find the end of the word.
- FindEndOfWord( data );
+ FindEndOfWord(data);
endIndex = data.foundIndex;
- if( 1u == ( endIndex - startIndex ) )
+ if(1u == (endIndex - startIndex))
{
- if( isHitCharacterWhiteSpace )
+ if(isHitCharacterWhiteSpace)
{
// Select the word before or after the white space
- if( 0 == hitCharacter )
+ if(0 == hitCharacter)
{
data.isWhiteSpace = false;
- FindEndOfWord( data );
+ FindEndOfWord(data);
endIndex = data.foundIndex;
}
- else if( hitCharacter > 0 )
+ else if(hitCharacter > 0)
{
// Find the start of the word.
data.hitCharacter = hitCharacter - 1u;
data.isWhiteSpace = false;
- FindStartOfWord( data );
+ FindStartOfWord(data);
startIndex = data.foundIndex;
--endIndex;
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/decorator/text-decorator.h>
// EXTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/image-loading.h>
+#include <dali/devel-api/common/stage.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/actors/layer.h>
#include <dali/public-api/adaptor-framework/timer.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/public-api/events/touch-event.h>
#include <dali/public-api/events/pan-gesture.h>
+#include <dali/public-api/events/touch-event.h>
#include <dali/public-api/object/property-notification.h>
#include <dali/public-api/rendering/geometry.h>
#include <dali/public-api/rendering/renderer.h>
-#include <dali/devel-api/adaptor-framework/image-loading.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/internal/controls/image-view/image-view-impl.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#ifdef DEBUG_ENABLED
#define DECORATOR_DEBUG
namespace
{
#ifdef DECORATOR_DEBUG
-Integration::Log::Filter* gLogFilter( Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_TEXT_DECORATOR") );
+Integration::Log::Filter* gLogFilter(Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_TEXT_DECORATOR"));
#endif
-}
-}
-}
-
+} // namespace
+} // namespace Internal
+} // namespace Dali
// Local Data
namespace
{
-const Dali::Vector3 DEFAULT_GRAB_HANDLE_RELATIVE_SIZE( 1.25f, 1.5f, 1.0f );
-const Dali::Vector3 DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE( 1.25f, 1.5f, 1.0f );
-const Dali::Vector3 ACTIVE_LAYER_ANCHOR_POINT( 0.5f, 0.5f, 0.5f );
+const Dali::Vector3 DEFAULT_GRAB_HANDLE_RELATIVE_SIZE(1.25f, 1.5f, 1.0f);
+const Dali::Vector3 DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE(1.25f, 1.5f, 1.0f);
+const Dali::Vector3 ACTIVE_LAYER_ANCHOR_POINT(0.5f, 0.5f, 0.5f);
-const Dali::Vector4 LIGHT_BLUE( 0.75f, 0.96f, 1.f, 1.f ); // The text highlight color. TODO: due some problems, maybe with the blending function in the text clipping, the color is fully opaque.
+const Dali::Vector4 LIGHT_BLUE(0.75f, 0.96f, 1.f, 1.f); // The text highlight color. TODO: due some problems, maybe with the blending function in the text clipping, the color is fully opaque.
-const Dali::Vector4 HANDLE_COLOR( 0.0f, (183.0f / 255.0f), (229.0f / 255.0f), 1.0f );
+const Dali::Vector4 HANDLE_COLOR(0.0f, (183.0f / 255.0f), (229.0f / 255.0f), 1.0f);
-const unsigned int CURSOR_BLINK_INTERVAL = 500u; ///< Cursor blink interval in milliseconds.
-const float TO_MILLISECONDS = 1000.f; ///< Converts from seconds to milliseconds.
-const float TO_SECONDS = 1.f / TO_MILLISECONDS; ///< Converts from milliseconds to seconds.
+const unsigned int CURSOR_BLINK_INTERVAL = 500u; ///< Cursor blink interval in milliseconds.
+const float TO_MILLISECONDS = 1000.f; ///< Converts from seconds to milliseconds.
+const float TO_SECONDS = 1.f / TO_MILLISECONDS; ///< Converts from milliseconds to seconds.
-const unsigned int SCROLL_TICK_INTERVAL = 50u; ///< Scroll interval in milliseconds.
-const float SCROLL_THRESHOLD = 10.f; ///< Threshold in pixels close to the edges of the decorator boundaries from where the scroll timer starts to emit signals.
-const float SCROLL_SPEED = 300.f; ///< The scroll speed in pixels/second.
+const unsigned int SCROLL_TICK_INTERVAL = 50u; ///< Scroll interval in milliseconds.
+const float SCROLL_THRESHOLD = 10.f; ///< Threshold in pixels close to the edges of the decorator boundaries from where the scroll timer starts to emit signals.
+const float SCROLL_SPEED = 300.f; ///< The scroll speed in pixels/second.
const float SCROLL_DISTANCE = SCROLL_SPEED * SCROLL_TICK_INTERVAL * TO_SECONDS; ///< Distance in pixels scrolled in one second.
* @param[in] boundingRectangle local bounding
* @param[out] Vector4 World coordinate bounding Box.
*/
-void LocalToWorldCoordinatesBoundingBox( const Dali::Rect<int>& boundingRectangle, Dali::Vector4& boundingBox )
+void LocalToWorldCoordinatesBoundingBox(const Dali::Rect<int>& boundingRectangle, Dali::Vector4& boundingBox)
{
// Convert to world coordinates and store as a Vector4 to be compatible with Property Notifications.
Dali::Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
const float originX = boundingRectangle.x - 0.5f * stageSize.width;
const float originY = boundingRectangle.y - 0.5f * stageSize.height;
- boundingBox = Dali::Vector4( originX,
- originY,
- originX + boundingRectangle.width,
- originY + boundingRectangle.height );
+ boundingBox = Dali::Vector4(originX,
+ originY,
+ originX + boundingRectangle.width,
+ originY + boundingRectangle.height);
}
-void WorldToLocalCoordinatesBoundingBox( const Dali::Vector4& boundingBox, Dali::Rect<int>& boundingRectangle )
+void WorldToLocalCoordinatesBoundingBox(const Dali::Vector4& boundingBox, Dali::Rect<int>& boundingRectangle)
{
// Convert to local coordinates and store as a Dali::Rect.
Dali::Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
- boundingRectangle.x = boundingBox.x + 0.5f * stageSize.width;
- boundingRectangle.y = boundingBox.y + 0.5f * stageSize.height;
- boundingRectangle.width = boundingBox.z - boundingBox.x;
+ boundingRectangle.x = boundingBox.x + 0.5f * stageSize.width;
+ boundingRectangle.y = boundingBox.y + 0.5f * stageSize.height;
+ boundingRectangle.width = boundingBox.z - boundingBox.x;
boundingRectangle.height = boundingBox.w - boundingBox.y;
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
struct Decorator::Impl : public ConnectionTracker
{
enum ScrollDirection
struct CursorImpl
{
CursorImpl()
- : color( Dali::Color::BLACK ),
+ : color(Dali::Color::BLACK),
position(),
- cursorHeight( 0.0f ),
- lineHeight( 0.0f ),
- glyphOffset( 0.0f )
+ cursorHeight(0.0f),
+ lineHeight(0.0f),
+ glyphOffset(0.0f)
{
}
Vector4 color;
Vector2 position;
- float cursorHeight;
- float lineHeight;
- float glyphOffset;
+ float cursorHeight;
+ float lineHeight;
+ float glyphOffset;
};
struct HandleImpl
: position(),
globalPosition(),
size(),
- lineHeight( 0.0f ),
- grabDisplacementX( 0.f ),
- grabDisplacementY( 0.f ),
- active( false ),
- horizontallyVisible( false ),
- verticallyVisible( false ),
- pressed( false ),
- verticallyFlippedPreferred( false ),
- horizontallyFlipped( false ),
- verticallyFlipped( false ),
- verticallyFlippedOnTouch( false )
+ lineHeight(0.0f),
+ grabDisplacementX(0.f),
+ grabDisplacementY(0.f),
+ active(false),
+ horizontallyVisible(false),
+ verticallyVisible(false),
+ pressed(false),
+ verticallyFlippedPreferred(false),
+ horizontallyFlipped(false),
+ verticallyFlipped(false),
+ verticallyFlippedOnTouch(false)
{
}
ImageView actor;
- Actor grabArea;
+ Actor grabArea;
ImageView markerActor;
Vector2 position;
Vector2 globalPosition;
Size size;
- float lineHeight; ///< Not the handle height
+ float lineHeight; ///< Not the handle height
float grabDisplacementX;
float grabDisplacementY;
- bool active : 1;
- bool horizontallyVisible : 1;
- bool verticallyVisible : 1;
- bool pressed : 1;
+ bool active : 1;
+ bool horizontallyVisible : 1;
+ bool verticallyVisible : 1;
+ bool pressed : 1;
bool verticallyFlippedPreferred : 1; ///< Whether the handle is preferred to be vertically flipped.
- bool horizontallyFlipped : 1; ///< Whether the handle has been horizontally flipped.
- bool verticallyFlipped : 1; ///< Whether the handle has been vertically flipped.
- bool verticallyFlippedOnTouch : 1; ///< Whether the handle is vertically flipped on touch.
+ bool horizontallyFlipped : 1; ///< Whether the handle has been horizontally flipped.
+ bool verticallyFlipped : 1; ///< Whether the handle has been vertically flipped.
+ bool verticallyFlippedOnTouch : 1; ///< Whether the handle is vertically flipped on touch.
};
struct PopupImpl
}
TextSelectionPopup actor;
- Vector3 position;
+ Vector3 position;
};
- Impl( ControllerInterface& controller,
- TextSelectionPopupCallbackInterface& callbackInterface )
- : mController( controller ),
- mEnabledPopupButtons( TextSelectionPopup::NONE ),
- mTextSelectionPopupCallbackInterface( callbackInterface ),
- mHandleColor( HANDLE_COLOR ),
+ Impl(ControllerInterface& controller,
+ TextSelectionPopupCallbackInterface& callbackInterface)
+ : mController(controller),
+ mEnabledPopupButtons(TextSelectionPopup::NONE),
+ mTextSelectionPopupCallbackInterface(callbackInterface),
+ mHandleColor(HANDLE_COLOR),
mBoundingBox(),
- mHighlightColor( LIGHT_BLUE ),
- mHighlightPosition( Vector2::ZERO ),
- mHighlightSize( Vector2::ZERO ),
- mControlSize( Vector2::ZERO ),
- mHighlightOutlineOffset( 0.f ),
- mActiveCursor( ACTIVE_CURSOR_NONE ),
- mCursorBlinkInterval( CURSOR_BLINK_INTERVAL ),
- mCursorBlinkDuration( 0.0f ),
- mCursorWidth( CURSOR_WIDTH ),
- mHandleScrolling( HANDLE_TYPE_COUNT ),
- mHandleReleased( HANDLE_TYPE_COUNT ),
- mScrollDirection( SCROLL_NONE ),
- mScrollThreshold( SCROLL_THRESHOLD ),
- mScrollSpeed( SCROLL_SPEED ),
- mScrollDistance( SCROLL_DISTANCE ),
- mTextDepth( 0u ),
- mActiveCopyPastePopup( false ),
- mPopupSetNewPosition( true ),
- mCursorBlinkStatus( true ),
- mDelayCursorBlink( false ),
- mPrimaryCursorVisible( false ),
- mSecondaryCursorVisible( false ),
- mFlipSelectionHandlesOnCross( false ),
- mFlipLeftSelectionHandleDirection( false ),
- mFlipRightSelectionHandleDirection( false ),
- mIsHandlePanning( false ),
- mIsHandleCurrentlyCrossed( false ),
- mIsHandlePreviouslyCrossed( false ),
- mNotifyEndOfScroll( false ),
- mHorizontalScrollingEnabled( false ),
- mVerticalScrollingEnabled( false ),
- mSmoothHandlePanEnabled( false ),
- mIsHighlightBoxActive( false ),
- mHidePrimaryCursorAndGrabHandle( false )
+ mHighlightColor(LIGHT_BLUE),
+ mHighlightPosition(Vector2::ZERO),
+ mHighlightSize(Vector2::ZERO),
+ mControlSize(Vector2::ZERO),
+ mHighlightOutlineOffset(0.f),
+ mActiveCursor(ACTIVE_CURSOR_NONE),
+ mCursorBlinkInterval(CURSOR_BLINK_INTERVAL),
+ mCursorBlinkDuration(0.0f),
+ mCursorWidth(CURSOR_WIDTH),
+ mHandleScrolling(HANDLE_TYPE_COUNT),
+ mHandleReleased(HANDLE_TYPE_COUNT),
+ mScrollDirection(SCROLL_NONE),
+ mScrollThreshold(SCROLL_THRESHOLD),
+ mScrollSpeed(SCROLL_SPEED),
+ mScrollDistance(SCROLL_DISTANCE),
+ mTextDepth(0u),
+ mActiveCopyPastePopup(false),
+ mPopupSetNewPosition(true),
+ mCursorBlinkStatus(true),
+ mDelayCursorBlink(false),
+ mPrimaryCursorVisible(false),
+ mSecondaryCursorVisible(false),
+ mFlipSelectionHandlesOnCross(false),
+ mFlipLeftSelectionHandleDirection(false),
+ mFlipRightSelectionHandleDirection(false),
+ mIsHandlePanning(false),
+ mIsHandleCurrentlyCrossed(false),
+ mIsHandlePreviouslyCrossed(false),
+ mNotifyEndOfScroll(false),
+ mHorizontalScrollingEnabled(false),
+ mVerticalScrollingEnabled(false),
+ mSmoothHandlePanEnabled(false),
+ mIsHighlightBoxActive(false),
+ mHidePrimaryCursorAndGrabHandle(false)
{
- mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
- mHighlightShader = Shader::New( SHADER_TEXT_DECORATOR_SHADER_VERT, SHADER_TEXT_DECORATOR_SHADER_FRAG );
+ mQuadVertexFormat["aPosition"] = Property::VECTOR2;
+ mHighlightShader = Shader::New(SHADER_TEXT_DECORATOR_SHADER_VERT, SHADER_TEXT_DECORATOR_SHADER_FRAG);
SetupGestures();
}
* Relayout of the decorations owned by the decorator.
* @param[in] size The Size of the UI control the decorator is adding it's decorations to.
*/
- void Relayout( const Vector2& size )
+ void Relayout(const Vector2& size)
{
mControlSize = size;
// Show or hide the cursors
CreateCursors();
- if( mPrimaryCursor )
+ if(mPrimaryCursor)
{
const CursorImpl& cursor = mCursor[PRIMARY_CURSOR];
- mPrimaryCursorVisible = (!mHidePrimaryCursorAndGrabHandle) && ( ( mControlSize.width - ( cursor.position.x + mCursorWidth ) > -Math::MACHINE_EPSILON_1000 ) &&
- ( cursor.position.x > -Math::MACHINE_EPSILON_1000 ) &&
- ( mControlSize.height - ( cursor.position.y + cursor.cursorHeight ) > -Math::MACHINE_EPSILON_1000 ) &&
- ( cursor.position.y > -Math::MACHINE_EPSILON_1000 ) );
- if( mPrimaryCursorVisible )
+ mPrimaryCursorVisible = (!mHidePrimaryCursorAndGrabHandle) && ((mControlSize.width - (cursor.position.x + mCursorWidth) > -Math::MACHINE_EPSILON_1000) &&
+ (cursor.position.x > -Math::MACHINE_EPSILON_1000) &&
+ (mControlSize.height - (cursor.position.y + cursor.cursorHeight) > -Math::MACHINE_EPSILON_1000) &&
+ (cursor.position.y > -Math::MACHINE_EPSILON_1000));
+ if(mPrimaryCursorVisible)
{
- mPrimaryCursor.SetProperty( Actor::Property::POSITION, Vector2( cursor.position.x,
- cursor.position.y ) );
- mPrimaryCursor.SetProperty( Actor::Property::SIZE, Size( mCursorWidth, cursor.cursorHeight ) );
+ mPrimaryCursor.SetProperty(Actor::Property::POSITION, Vector2(cursor.position.x, cursor.position.y));
+ mPrimaryCursor.SetProperty(Actor::Property::SIZE, Size(mCursorWidth, cursor.cursorHeight));
}
- mPrimaryCursor.SetProperty( Actor::Property::VISIBLE, mPrimaryCursorVisible && mCursorBlinkStatus );
+ mPrimaryCursor.SetProperty(Actor::Property::VISIBLE, mPrimaryCursorVisible && mCursorBlinkStatus);
}
- if( mSecondaryCursor )
+ if(mSecondaryCursor)
{
const CursorImpl& cursor = mCursor[SECONDARY_CURSOR];
- mSecondaryCursorVisible = ( ( mControlSize.width - ( cursor.position.x + mCursorWidth ) > -Math::MACHINE_EPSILON_1000 ) &&
- ( cursor.position.x > -Math::MACHINE_EPSILON_1000 ) &&
- ( mControlSize.height - ( cursor.position.y + cursor.cursorHeight ) > -Math::MACHINE_EPSILON_1000 ) &&
- ( cursor.position.y > -Math::MACHINE_EPSILON_1000 ) );
- if( mSecondaryCursorVisible )
+ mSecondaryCursorVisible = ((mControlSize.width - (cursor.position.x + mCursorWidth) > -Math::MACHINE_EPSILON_1000) &&
+ (cursor.position.x > -Math::MACHINE_EPSILON_1000) &&
+ (mControlSize.height - (cursor.position.y + cursor.cursorHeight) > -Math::MACHINE_EPSILON_1000) &&
+ (cursor.position.y > -Math::MACHINE_EPSILON_1000));
+ if(mSecondaryCursorVisible)
{
- mSecondaryCursor.SetProperty( Actor::Property::POSITION, Vector2( cursor.position.x,
- cursor.position.y ) );
- mSecondaryCursor.SetProperty( Actor::Property::SIZE, Size( mCursorWidth, cursor.cursorHeight ) );
+ mSecondaryCursor.SetProperty(Actor::Property::POSITION, Vector2(cursor.position.x, cursor.position.y));
+ mSecondaryCursor.SetProperty(Actor::Property::SIZE, Size(mCursorWidth, cursor.cursorHeight));
}
- mSecondaryCursor.SetProperty( Actor::Property::VISIBLE, mSecondaryCursorVisible && mCursorBlinkStatus );
+ mSecondaryCursor.SetProperty(Actor::Property::VISIBLE, mSecondaryCursorVisible && mCursorBlinkStatus);
}
// Show or hide the grab handle
- HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
- bool newGrabHandlePosition = false;
- grabHandle.horizontallyVisible = false;
- grabHandle.verticallyVisible = false;
- if( grabHandle.active )
+ HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
+ bool newGrabHandlePosition = false;
+ grabHandle.horizontallyVisible = false;
+ grabHandle.verticallyVisible = false;
+ if(grabHandle.active)
{
- grabHandle.horizontallyVisible = ( ( mControlSize.width - ( grabHandle.position.x + floor( 0.5f * mCursorWidth ) ) > -Math::MACHINE_EPSILON_1000 ) &&
- ( grabHandle.position.x > -Math::MACHINE_EPSILON_1000 ) );
- grabHandle.verticallyVisible = ( ( ( mControlSize.height - grabHandle.lineHeight ) - grabHandle.position.y > -Math::MACHINE_EPSILON_1000 ) &&
- ( grabHandle.position.y > -Math::MACHINE_EPSILON_1000 ) );
+ grabHandle.horizontallyVisible = ((mControlSize.width - (grabHandle.position.x + floor(0.5f * mCursorWidth)) > -Math::MACHINE_EPSILON_1000) &&
+ (grabHandle.position.x > -Math::MACHINE_EPSILON_1000));
+ grabHandle.verticallyVisible = (((mControlSize.height - grabHandle.lineHeight) - grabHandle.position.y > -Math::MACHINE_EPSILON_1000) &&
+ (grabHandle.position.y > -Math::MACHINE_EPSILON_1000));
const bool isVisible = grabHandle.horizontallyVisible && grabHandle.verticallyVisible && (!mHidePrimaryCursorAndGrabHandle);
- if( isVisible )
+ if(isVisible)
{
CreateGrabHandle();
SetGrabHandlePosition();
// Sets the grab handle image according if it's pressed, flipped, etc.
- SetHandleImage( GRAB_HANDLE );
+ SetHandleImage(GRAB_HANDLE);
newGrabHandlePosition = true;
}
- if( grabHandle.actor )
+ if(grabHandle.actor)
{
- grabHandle.actor.SetProperty( Actor::Property::VISIBLE, isVisible );
+ grabHandle.actor.SetProperty(Actor::Property::VISIBLE, isVisible);
}
}
- else if( grabHandle.actor )
+ else if(grabHandle.actor)
{
grabHandle.actor.Unparent();
}
// Show or hide the selection handles/highlight
- HandleImpl& primary = mHandle[ LEFT_SELECTION_HANDLE ];
- HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ];
- bool newPrimaryHandlePosition = false;
- bool newSecondaryHandlePosition = false;
-
- primary.horizontallyVisible = ( ( mControlSize.width - primary.position.x > -Math::MACHINE_EPSILON_1000 ) &&
- ( primary.position.x > -Math::MACHINE_EPSILON_1000 ) );
- primary.verticallyVisible = ( ( ( mControlSize.height - primary.lineHeight ) - primary.position.y > -Math::MACHINE_EPSILON_1000 ) &&
- ( primary.position.y + ( primary.verticallyFlipped ? 0.f : primary.lineHeight ) > -Math::MACHINE_EPSILON_1000 ) );
- secondary.horizontallyVisible = ( ( mControlSize.width - secondary.position.x > -Math::MACHINE_EPSILON_1000 ) &&
- ( secondary.position.x > -Math::MACHINE_EPSILON_1000 ) );
- secondary.verticallyVisible = ( ( ( mControlSize.height - secondary.lineHeight ) - secondary.position.y > -Math::MACHINE_EPSILON_1000 ) &&
- ( secondary.position.y + ( secondary.verticallyFlipped ? 0.f : secondary.lineHeight ) > -Math::MACHINE_EPSILON_1000 ) );
-
- const bool primaryVisible = primary.horizontallyVisible && primary.verticallyVisible;
+ HandleImpl& primary = mHandle[LEFT_SELECTION_HANDLE];
+ HandleImpl& secondary = mHandle[RIGHT_SELECTION_HANDLE];
+ bool newPrimaryHandlePosition = false;
+ bool newSecondaryHandlePosition = false;
+
+ primary.horizontallyVisible = ((mControlSize.width - primary.position.x > -Math::MACHINE_EPSILON_1000) &&
+ (primary.position.x > -Math::MACHINE_EPSILON_1000));
+ primary.verticallyVisible = (((mControlSize.height - primary.lineHeight) - primary.position.y > -Math::MACHINE_EPSILON_1000) &&
+ (primary.position.y + (primary.verticallyFlipped ? 0.f : primary.lineHeight) > -Math::MACHINE_EPSILON_1000));
+ secondary.horizontallyVisible = ((mControlSize.width - secondary.position.x > -Math::MACHINE_EPSILON_1000) &&
+ (secondary.position.x > -Math::MACHINE_EPSILON_1000));
+ secondary.verticallyVisible = (((mControlSize.height - secondary.lineHeight) - secondary.position.y > -Math::MACHINE_EPSILON_1000) &&
+ (secondary.position.y + (secondary.verticallyFlipped ? 0.f : secondary.lineHeight) > -Math::MACHINE_EPSILON_1000));
+
+ const bool primaryVisible = primary.horizontallyVisible && primary.verticallyVisible;
const bool secondaryVisible = secondary.horizontallyVisible && secondary.verticallyVisible;
- if( primary.active || secondary.active )
+ if(primary.active || secondary.active)
{
- if( primaryVisible || secondaryVisible )
+ if(primaryVisible || secondaryVisible)
{
CreateSelectionHandles();
- if( primaryVisible )
+ if(primaryVisible)
{
- SetSelectionHandlePosition( LEFT_SELECTION_HANDLE );
+ SetSelectionHandlePosition(LEFT_SELECTION_HANDLE);
// Sets the primary handle image according if it's pressed, flipped, etc.
- SetHandleImage( LEFT_SELECTION_HANDLE );
+ SetHandleImage(LEFT_SELECTION_HANDLE);
- SetSelectionHandleMarkerSize( primary );
+ SetSelectionHandleMarkerSize(primary);
newPrimaryHandlePosition = true;
}
- if( secondaryVisible )
+ if(secondaryVisible)
{
- SetSelectionHandlePosition( RIGHT_SELECTION_HANDLE );
+ SetSelectionHandlePosition(RIGHT_SELECTION_HANDLE);
// Sets the secondary handle image according if it's pressed, flipped, etc.
- SetHandleImage( RIGHT_SELECTION_HANDLE );
+ SetHandleImage(RIGHT_SELECTION_HANDLE);
- SetSelectionHandleMarkerSize( secondary );
+ SetSelectionHandleMarkerSize(secondary);
newSecondaryHandlePosition = true;
}
}
- if( primary.actor )
+ if(primary.actor)
{
- primary.actor.SetProperty( Actor::Property::VISIBLE, primaryVisible );
+ primary.actor.SetProperty(Actor::Property::VISIBLE, primaryVisible);
}
- if( secondary.actor )
+ if(secondary.actor)
{
- secondary.actor.SetProperty( Actor::Property::VISIBLE, secondaryVisible );
+ secondary.actor.SetProperty(Actor::Property::VISIBLE, secondaryVisible);
}
-
}
else
{
- if( primary.actor )
+ if(primary.actor)
{
primary.actor.Unparent();
}
- if( secondary.actor )
+ if(secondary.actor)
{
secondary.actor.Unparent();
}
}
- if( mIsHighlightBoxActive )
+ if(mIsHighlightBoxActive)
{
CreateHighlight();
UpdateHighlight();
}
else
{
- if( mHighlightActor )
+ if(mHighlightActor)
{
mHighlightActor.Unparent();
}
}
- if( newGrabHandlePosition ||
- newPrimaryHandlePosition ||
- newSecondaryHandlePosition )
+ if(newGrabHandlePosition ||
+ newPrimaryHandlePosition ||
+ newSecondaryHandlePosition)
{
// Setup property notifications to find whether the handles leave the boundaries of the current display.
SetupActiveLayerPropertyNotifications();
}
- if( mActiveCopyPastePopup &&
- ( primaryVisible || secondaryVisible ) )
+ if(mActiveCopyPastePopup &&
+ (primaryVisible || secondaryVisible))
{
ShowPopup();
mPopupSetNewPosition = true;
}
else
{
- if( mCopyPastePopup.actor )
+ if(mCopyPastePopup.actor)
{
mCopyPastePopup.actor.HidePopup();
mPopupSetNewPosition = true;
}
}
- void UpdatePositions( const Vector2& scrollOffset )
+ void UpdatePositions(const Vector2& scrollOffset)
{
mCursor[PRIMARY_CURSOR].position += scrollOffset;
mCursor[SECONDARY_CURSOR].position += scrollOffset;
- mHandle[ GRAB_HANDLE ].position += scrollOffset;
- mHandle[ LEFT_SELECTION_HANDLE ].position += scrollOffset;
- mHandle[ RIGHT_SELECTION_HANDLE ].position += scrollOffset;
+ mHandle[GRAB_HANDLE].position += scrollOffset;
+ mHandle[LEFT_SELECTION_HANDLE].position += scrollOffset;
+ mHandle[RIGHT_SELECTION_HANDLE].position += scrollOffset;
mHighlightPosition += scrollOffset;
}
void ShowPopup()
{
- if( !mCopyPastePopup.actor )
+ if(!mCopyPastePopup.actor)
{
return;
}
- if( !mCopyPastePopup.actor.GetParent() )
+ if(!mCopyPastePopup.actor.GetParent())
{
- mActiveLayer.Add( mCopyPastePopup.actor );
+ mActiveLayer.Add(mCopyPastePopup.actor);
}
- mCopyPastePopup.actor.RaiseAbove( mActiveLayer );
+ mCopyPastePopup.actor.RaiseAbove(mActiveLayer);
mCopyPastePopup.actor.ShowPopup();
}
- float CalculateVerticalPopUpPosition( float halfHeight, bool preferBelow )
+ float CalculateVerticalPopUpPosition(float halfHeight, bool preferBelow)
{
float yPosition = 0.f;
- const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE];
+ const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE];
const HandleImpl& secondaryHandle = mHandle[RIGHT_SELECTION_HANDLE];
- const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
+ const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
- if( primaryHandle.active || secondaryHandle.active )
+ if(primaryHandle.active || secondaryHandle.active)
{
// The origin of the decorator's coordinate system in world coords.
- const Vector3 originWorldCoords = mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION ) - mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * ACTIVE_LAYER_ANCHOR_POINT;
+ const Vector3 originWorldCoords = mActiveLayer.GetCurrentProperty<Vector3>(Actor::Property::WORLD_POSITION) - mActiveLayer.GetCurrentProperty<Vector3>(Actor::Property::SIZE) * ACTIVE_LAYER_ANCHOR_POINT;
- if( preferBelow )
+ if(preferBelow)
{
// Find out if there is enough space for the popup at the bottom.
- const float primaryBelowY = primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height;
+ const float primaryBelowY = primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height;
const float secondaryBelowY = secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height;
- float maxY = std::max( primaryBelowY, secondaryBelowY );
+ float maxY = std::max(primaryBelowY, secondaryBelowY);
yPosition = halfHeight + maxY;
- if( originWorldCoords.y + yPosition + halfHeight > mBoundingBox.w )
+ if(originWorldCoords.y + yPosition + halfHeight > mBoundingBox.w)
{
// Does not fit below.
// Try to fit first below the non active handle. Otherwise above the active handle.
- if( RIGHT_SELECTION_HANDLE == mHandleReleased )
+ if(RIGHT_SELECTION_HANDLE == mHandleReleased)
{
- if( primaryBelowY < secondaryBelowY )
+ if(primaryBelowY < secondaryBelowY)
{
yPosition = halfHeight + primaryBelowY;
}
yPosition = primaryHandle.position.y - primaryHandle.size.height - halfHeight;
}
}
- else if( LEFT_SELECTION_HANDLE == mHandleReleased )
+ else if(LEFT_SELECTION_HANDLE == mHandleReleased)
{
- if( secondaryBelowY < primaryBelowY )
+ if(secondaryBelowY < primaryBelowY)
{
yPosition = halfHeight + secondaryBelowY;
}
}
// Check the handle is whithin the decoration box.
- if( originWorldCoords.y + yPosition < mBoundingBox.y )
+ if(originWorldCoords.y + yPosition < mBoundingBox.y)
{
yPosition = mBoundingBox.y - originWorldCoords.y + halfHeight;
}
- if( originWorldCoords.y + yPosition > mBoundingBox.w )
+ if(originWorldCoords.y + yPosition > mBoundingBox.w)
{
yPosition = mBoundingBox.w - originWorldCoords.y - halfHeight;
}
else
{
// Find out if there is enough space for the popup at the top.
- const float primaryTopY = primaryHandle.position.y - primaryHandle.size.height;
+ const float primaryTopY = primaryHandle.position.y - primaryHandle.size.height;
const float secondaryTopY = secondaryHandle.position.y - secondaryHandle.size.height;
- float minY = std::min( primaryTopY, secondaryTopY );
+ float minY = std::min(primaryTopY, secondaryTopY);
yPosition = -halfHeight + minY;
} // !preferBelow
- } // ( primaryHandle.active || secondaryHandle.active )
- else if( grabHandle.active )
+ } // ( primaryHandle.active || secondaryHandle.active )
+ else if(grabHandle.active)
{
- if( preferBelow )
+ if(preferBelow)
{
yPosition = halfHeight + grabHandle.lineHeight + grabHandle.size.height + grabHandle.position.y;
}
return yPosition;
}
- void ConstrainPopupPosition( const Vector3& popupHalfSize )
+ void ConstrainPopupPosition(const Vector3& popupHalfSize)
{
// Check if the popup is within the boundaries of the decoration box.
// Check first the horizontal dimension. If is not within the boundaries, it calculates the offset.
// The origin of the decorator's coordinate system in world coords.
- const Vector3 originWorldCoords = mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION ) - mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * ACTIVE_LAYER_ANCHOR_POINT;
+ const Vector3 originWorldCoords = mActiveLayer.GetCurrentProperty<Vector3>(Actor::Property::WORLD_POSITION) - mActiveLayer.GetCurrentProperty<Vector3>(Actor::Property::SIZE) * ACTIVE_LAYER_ANCHOR_POINT;
// The popup's position in world coords.
Vector3 popupPositionWorldCoords = originWorldCoords + mCopyPastePopup.position;
- if( popupPositionWorldCoords.x - popupHalfSize.width < mBoundingBox.x )
+ if(popupPositionWorldCoords.x - popupHalfSize.width < mBoundingBox.x)
{
- mCopyPastePopup.position.x += mBoundingBox.x - ( popupPositionWorldCoords.x - popupHalfSize.width );
+ mCopyPastePopup.position.x += mBoundingBox.x - (popupPositionWorldCoords.x - popupHalfSize.width);
}
- else if( popupPositionWorldCoords.x + popupHalfSize.width > mBoundingBox.z )
+ else if(popupPositionWorldCoords.x + popupHalfSize.width > mBoundingBox.z)
{
- mCopyPastePopup.position.x += mBoundingBox.z - ( popupPositionWorldCoords.x + popupHalfSize.width );
+ mCopyPastePopup.position.x += mBoundingBox.z - (popupPositionWorldCoords.x + popupHalfSize.width);
}
// Check the vertical dimension. If the popup doesn't fit above the handles, it looks for a valid position below.
- if( popupPositionWorldCoords.y - popupHalfSize.height < mBoundingBox.y )
+ if(popupPositionWorldCoords.y - popupHalfSize.height < mBoundingBox.y)
{
- mCopyPastePopup.position.y = CalculateVerticalPopUpPosition( popupHalfSize.height, true ); // true -> prefer to set the popup's position below.
+ mCopyPastePopup.position.y = CalculateVerticalPopUpPosition(popupHalfSize.height, true); // true -> prefer to set the popup's position below.
}
}
- void SetPopupPosition( Actor actor )
+ void SetPopupPosition(Actor actor)
{
- if( !mActiveCopyPastePopup )
+ if(!mActiveCopyPastePopup)
{
return;
}
// Retrieves the popup's size after relayout.
- const Vector3 popupSize( mCopyPastePopup.actor.GetRelayoutSize( Dimension::WIDTH ), mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT ), 0.0f );
+ const Vector3 popupSize(mCopyPastePopup.actor.GetRelayoutSize(Dimension::WIDTH), mCopyPastePopup.actor.GetRelayoutSize(Dimension::HEIGHT), 0.0f);
const Vector3 popupHalfSize = popupSize * 0.5f;
- if( mPopupSetNewPosition )
+ if(mPopupSetNewPosition)
{
- const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE];
+ const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE];
const HandleImpl& secondaryHandle = mHandle[RIGHT_SELECTION_HANDLE];
- const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
+ const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
- if( primaryHandle.active || secondaryHandle.active )
+ if(primaryHandle.active || secondaryHandle.active)
{
- const float minHandleXPosition = std::min( primaryHandle.position.x, secondaryHandle.position.x );
- const float maxHandleXPosition = std::max( primaryHandle.position.x, secondaryHandle.position.x );
+ const float minHandleXPosition = std::min(primaryHandle.position.x, secondaryHandle.position.x);
+ const float maxHandleXPosition = std::max(primaryHandle.position.x, secondaryHandle.position.x);
- mCopyPastePopup.position.x = minHandleXPosition + ( ( maxHandleXPosition - minHandleXPosition ) * 0.5f );
+ mCopyPastePopup.position.x = minHandleXPosition + ((maxHandleXPosition - minHandleXPosition) * 0.5f);
- const float primaryY = -popupHalfSize.height + primaryHandle.position.y - ( primaryHandle.verticallyFlipped ? primaryHandle.size.height : POPUP_PADDING );
- const float secondaryY = -popupHalfSize.height + secondaryHandle.position.y - ( secondaryHandle.verticallyFlipped ? secondaryHandle.size.height : POPUP_PADDING );
+ const float primaryY = -popupHalfSize.height + primaryHandle.position.y - (primaryHandle.verticallyFlipped ? primaryHandle.size.height : POPUP_PADDING);
+ const float secondaryY = -popupHalfSize.height + secondaryHandle.position.y - (secondaryHandle.verticallyFlipped ? secondaryHandle.size.height : POPUP_PADDING);
- mCopyPastePopup.position.y = std::min( primaryY, secondaryY );
+ mCopyPastePopup.position.y = std::min(primaryY, secondaryY);
}
- else if( grabHandle.active )
+ else if(grabHandle.active)
{
mCopyPastePopup.position.x = grabHandle.position.x;
- mCopyPastePopup.position.y = -popupHalfSize.height + grabHandle.position.y - ( grabHandle.verticallyFlipped ? grabHandle.size.height : POPUP_PADDING );
+ mCopyPastePopup.position.y = -popupHalfSize.height + grabHandle.position.y - (grabHandle.verticallyFlipped ? grabHandle.size.height : POPUP_PADDING);
}
} // mPopupSetNewPosition
// It may change the popup's position to fit within the decoration box.
- ConstrainPopupPosition( popupHalfSize );
+ ConstrainPopupPosition(popupHalfSize);
- SetUpPopupPositionNotifications( popupHalfSize );
+ SetUpPopupPositionNotifications(popupHalfSize);
// Prevent pixel mis-alignment by rounding down.
- mCopyPastePopup.position.x = floorf( mCopyPastePopup.position.x );
- mCopyPastePopup.position.y = floorf( mCopyPastePopup.position.y );
+ mCopyPastePopup.position.x = floorf(mCopyPastePopup.position.x);
+ mCopyPastePopup.position.y = floorf(mCopyPastePopup.position.y);
- mCopyPastePopup.actor.SetProperty( Actor::Property::POSITION, mCopyPastePopup.position );
+ mCopyPastePopup.actor.SetProperty(Actor::Property::POSITION, mCopyPastePopup.position);
mPopupSetNewPosition = false;
}
- void CreateCursor( Control& cursor, const Vector4& color )
+ void CreateCursor(Control& cursor, const Vector4& color)
{
cursor = Control::New();
- cursor.SetBackgroundColor( color );
- cursor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- cursor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
+ cursor.SetBackgroundColor(color);
+ cursor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ cursor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
}
// Add or Remove cursor(s) from parent
void CreateCursors()
{
- if( mActiveCursor == ACTIVE_CURSOR_NONE )
+ if(mActiveCursor == ACTIVE_CURSOR_NONE)
{
- if( mPrimaryCursor )
+ if(mPrimaryCursor)
{
mPrimaryCursor.Unparent();
}
- if( mSecondaryCursor )
+ if(mSecondaryCursor)
{
mSecondaryCursor.Unparent();
}
else
{
// Create Primary and or Secondary Cursor(s) if active and add to parent
- if ( mActiveCursor == ACTIVE_CURSOR_PRIMARY ||
- mActiveCursor == ACTIVE_CURSOR_BOTH )
+ if(mActiveCursor == ACTIVE_CURSOR_PRIMARY ||
+ mActiveCursor == ACTIVE_CURSOR_BOTH)
{
- if ( !mPrimaryCursor )
+ if(!mPrimaryCursor)
{
- CreateCursor( mPrimaryCursor, mCursor[PRIMARY_CURSOR].color );
+ CreateCursor(mPrimaryCursor, mCursor[PRIMARY_CURSOR].color);
#ifdef DECORATOR_DEBUG
- mPrimaryCursor.SetProperty( Dali::Actor::Property::NAME, "PrimaryCursorActor" );
+ mPrimaryCursor.SetProperty(Dali::Actor::Property::NAME, "PrimaryCursorActor");
#endif
}
- if( !mPrimaryCursor.GetParent() )
+ if(!mPrimaryCursor.GetParent())
{
- mActiveLayer.Add( mPrimaryCursor );
+ mActiveLayer.Add(mPrimaryCursor);
}
}
- if ( mActiveCursor == ACTIVE_CURSOR_BOTH )
+ if(mActiveCursor == ACTIVE_CURSOR_BOTH)
{
- if ( !mSecondaryCursor )
+ if(!mSecondaryCursor)
{
- CreateCursor( mSecondaryCursor, mCursor[SECONDARY_CURSOR].color );
+ CreateCursor(mSecondaryCursor, mCursor[SECONDARY_CURSOR].color);
#ifdef DECORATOR_DEBUG
- mSecondaryCursor.SetProperty( Dali::Actor::Property::NAME, "SecondaryCursorActor" );
+ mSecondaryCursor.SetProperty(Dali::Actor::Property::NAME, "SecondaryCursorActor");
#endif
}
- if( !mSecondaryCursor.GetParent() )
+ if(!mSecondaryCursor.GetParent())
{
- mActiveLayer.Add( mSecondaryCursor );
+ mActiveLayer.Add(mSecondaryCursor);
}
}
else
{
- if( mSecondaryCursor )
+ if(mSecondaryCursor)
{
mSecondaryCursor.Unparent();
}
bool OnCursorBlinkTimerTick()
{
- if( !mDelayCursorBlink )
+ if(!mDelayCursorBlink)
{
// Cursor blinking
- if ( mPrimaryCursor )
+ if(mPrimaryCursor)
{
- mPrimaryCursor.SetProperty( Actor::Property::VISIBLE, mPrimaryCursorVisible && mCursorBlinkStatus );
+ mPrimaryCursor.SetProperty(Actor::Property::VISIBLE, mPrimaryCursorVisible && mCursorBlinkStatus);
}
- if ( mSecondaryCursor )
+ if(mSecondaryCursor)
{
- mSecondaryCursor.SetProperty( Actor::Property::VISIBLE, mSecondaryCursorVisible && mCursorBlinkStatus );
+ mSecondaryCursor.SetProperty(Actor::Property::VISIBLE, mSecondaryCursorVisible && mCursorBlinkStatus);
}
mCursorBlinkStatus = !mCursorBlinkStatus;
mTapDetector = TapGestureDetector::New();
// Will consume double tap gestures on handles.
- mTapDetector.SetMaximumTapsRequired( 2u );
+ mTapDetector.SetMaximumTapsRequired(2u);
// Will consume long press gestures on handles.
mLongPressDetector = LongPressGestureDetector::New();
// Detects pan gestures on handles.
mPanDetector = PanGestureDetector::New();
- mPanDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnPan );
+ mPanDetector.DetectedSignal().Connect(this, &Decorator::Impl::OnPan);
}
void CreateActiveLayer()
{
- if( !mActiveLayer )
+ if(!mActiveLayer)
{
mActiveLayer = Actor::New();
#ifdef DECORATOR_DEBUG
- mActiveLayer.SetProperty( Actor::Property::NAME, "ActiveLayerActor" );
+ mActiveLayer.SetProperty(Actor::Property::NAME, "ActiveLayerActor");
#endif
- mActiveLayer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mActiveLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
+ mActiveLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mActiveLayer.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
// Add the active layer telling the controller it doesn't need clipping.
- mController.AddDecoration( mActiveLayer, false );
+ mController.AddDecoration(mActiveLayer, false);
}
mActiveLayer.RaiseToTop();
}
- void SetSelectionHandleMarkerSize( HandleImpl& handle )
+ void SetSelectionHandleMarkerSize(HandleImpl& handle)
{
- if( handle.markerActor )
+ if(handle.markerActor)
{
- handle.markerActor.SetProperty( Actor::Property::SIZE, Vector2( 0, handle.lineHeight ) );
+ handle.markerActor.SetProperty(Actor::Property::SIZE, Vector2(0, handle.lineHeight));
}
}
void CreateGrabHandle()
{
HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
- if( !grabHandle.actor )
+ if(!grabHandle.actor)
{
- if( mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED].size() )
+ if(mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED].size())
{
- grabHandle.actor = ImageView::New( mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED] );
- GetImpl( grabHandle.actor).SetDepthIndex( DepthIndex::DECORATION );
- grabHandle.actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER );
+ grabHandle.actor = ImageView::New(mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED]);
+ GetImpl(grabHandle.actor).SetDepthIndex(DepthIndex::DECORATION);
+ grabHandle.actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER);
// Area that Grab handle responds to, larger than actual handle so easier to move
#ifdef DECORATOR_DEBUG
- grabHandle.actor.SetProperty( Dali::Actor::Property::NAME, "GrabHandleActor" );
- if ( Dali::Internal::gLogFilter->IsEnabledFor( Debug::Verbose ) )
+ grabHandle.actor.SetProperty(Dali::Actor::Property::NAME, "GrabHandleActor");
+ if(Dali::Internal::gLogFilter->IsEnabledFor(Debug::Verbose))
{
- grabHandle.grabArea = Control::New();
- Toolkit::Control control = Toolkit::Control::DownCast( grabHandle.grabArea );
- control.SetBackgroundColor( Vector4( 1.0f, 1.0f, 1.0f, 0.5f ) );
- grabHandle.grabArea.SetProperty( Dali::Actor::Property::NAME, "GrabArea" );
+ grabHandle.grabArea = Control::New();
+ Toolkit::Control control = Toolkit::Control::DownCast(grabHandle.grabArea);
+ control.SetBackgroundColor(Vector4(1.0f, 1.0f, 1.0f, 0.5f));
+ grabHandle.grabArea.SetProperty(Dali::Actor::Property::NAME, "GrabArea");
}
else
{
grabHandle.grabArea = Actor::New();
- grabHandle.grabArea.SetProperty( Dali::Actor::Property::NAME, "GrabArea" );
+ grabHandle.grabArea.SetProperty(Dali::Actor::Property::NAME, "GrabArea");
}
#else
grabHandle.grabArea = Actor::New();
#endif
- grabHandle.grabArea.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER );
- grabHandle.grabArea.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER );
- grabHandle.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
- grabHandle.grabArea.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_GRAB_HANDLE_RELATIVE_SIZE );
- grabHandle.actor.Add( grabHandle.grabArea );
- grabHandle.actor.SetProperty( Actor::Property::COLOR, mHandleColor );
+ grabHandle.grabArea.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER);
+ grabHandle.grabArea.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER);
+ grabHandle.grabArea.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS);
+ grabHandle.grabArea.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_GRAB_HANDLE_RELATIVE_SIZE);
+ grabHandle.actor.Add(grabHandle.grabArea);
+ grabHandle.actor.SetProperty(Actor::Property::COLOR, mHandleColor);
- grabHandle.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnGrabHandleTouched );
+ grabHandle.grabArea.TouchedSignal().Connect(this, &Decorator::Impl::OnGrabHandleTouched);
// The grab handle's actor is attached to the tap and long press detectors in order to consume these events.
// Note that no callbacks are connected to any signal emitted by the tap and long press detectors.
- mTapDetector.Attach( grabHandle.actor );
- mLongPressDetector.Attach( grabHandle.actor );
+ mTapDetector.Attach(grabHandle.actor);
+ mLongPressDetector.Attach(grabHandle.actor);
// The grab handle's area is attached to the pan detector.
// The OnPan() method is connected to the signals emitted by the pan detector.
- mPanDetector.Attach( grabHandle.grabArea );
+ mPanDetector.Attach(grabHandle.grabArea);
- mActiveLayer.Add( grabHandle.actor );
+ mActiveLayer.Add(grabHandle.actor);
}
}
- if( grabHandle.actor && !grabHandle.actor.GetParent() )
+ if(grabHandle.actor && !grabHandle.actor.GetParent())
{
- mActiveLayer.Add( grabHandle.actor );
+ mActiveLayer.Add(grabHandle.actor);
}
}
- void CreateHandleMarker( HandleImpl& handle, const std::string& image, HandleType handleType )
+ void CreateHandleMarker(HandleImpl& handle, const std::string& image, HandleType handleType)
{
- if( image.size() )
+ if(image.size())
{
- handle.markerActor = ImageView::New( image );
- handle.markerActor.SetProperty( Actor::Property::COLOR, mHandleColor );
- handle.actor.Add( handle.markerActor );
+ handle.markerActor = ImageView::New(image);
+ handle.markerActor.SetProperty(Actor::Property::COLOR, mHandleColor);
+ handle.actor.Add(handle.markerActor);
- handle.markerActor.SetResizePolicy ( ResizePolicy::FIXED, Dimension::HEIGHT );
+ handle.markerActor.SetResizePolicy(ResizePolicy::FIXED, Dimension::HEIGHT);
- if( LEFT_SELECTION_HANDLE == handleType )
+ if(LEFT_SELECTION_HANDLE == handleType)
{
- handle.markerActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_RIGHT );
- handle.markerActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT );
+ handle.markerActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_RIGHT);
+ handle.markerActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT);
}
- else if( RIGHT_SELECTION_HANDLE == handleType )
+ else if(RIGHT_SELECTION_HANDLE == handleType)
{
- handle.markerActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_LEFT );
- handle.markerActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
+ handle.markerActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_LEFT);
+ handle.markerActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
}
}
}
void CreateSelectionHandles()
{
- HandleImpl& primary = mHandle[ LEFT_SELECTION_HANDLE ];
- if( !primary.actor )
+ HandleImpl& primary = mHandle[LEFT_SELECTION_HANDLE];
+ if(!primary.actor)
{
- if( mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED].size() )
+ if(mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED].size())
{
- primary.actor = ImageView::New( mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] );
+ primary.actor = ImageView::New(mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED]);
#ifdef DECORATOR_DEBUG
- primary.actor.SetProperty( Dali::Actor::Property::NAME,"SelectionHandleOne");
+ primary.actor.SetProperty(Dali::Actor::Property::NAME, "SelectionHandleOne");
#endif
- primary.actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT ); // Change to BOTTOM_RIGHT if Look'n'Feel requires handle above text.
- GetImpl( primary.actor ).SetDepthIndex( DepthIndex::DECORATION );
- primary.actor.SetProperty( Actor::Property::COLOR, mHandleColor );
+ primary.actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT); // Change to BOTTOM_RIGHT if Look'n'Feel requires handle above text.
+ GetImpl(primary.actor).SetDepthIndex(DepthIndex::DECORATION);
+ primary.actor.SetProperty(Actor::Property::COLOR, mHandleColor);
primary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
#ifdef DECORATOR_DEBUG
- primary.grabArea.SetProperty( Dali::Actor::Property::NAME,"SelectionHandleOneGrabArea");
+ primary.grabArea.SetProperty(Dali::Actor::Property::NAME, "SelectionHandleOneGrabArea");
#endif
- primary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
- primary.grabArea.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER );
- primary.grabArea.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER );
- primary.grabArea.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
+ primary.grabArea.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS);
+ primary.grabArea.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER);
+ primary.grabArea.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER);
+ primary.grabArea.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE);
- primary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleOneTouched );
+ primary.grabArea.TouchedSignal().Connect(this, &Decorator::Impl::OnHandleOneTouched);
// The handle's actor is attached to the tap and long press detectors in order to consume these events.
// Note that no callbacks are connected to any signal emitted by the tap and long press detectors.
- mTapDetector.Attach( primary.actor );
- mLongPressDetector.Attach( primary.actor );
+ mTapDetector.Attach(primary.actor);
+ mLongPressDetector.Attach(primary.actor);
// The handle's area is attached to the pan detector.
// The OnPan() method is connected to the signals emitted by the pan detector.
- mPanDetector.Attach( primary.grabArea );
+ mPanDetector.Attach(primary.grabArea);
- primary.actor.Add( primary.grabArea );
+ primary.actor.Add(primary.grabArea);
- CreateHandleMarker( primary, mHandleImages[LEFT_SELECTION_HANDLE_MARKER][HANDLE_IMAGE_RELEASED], LEFT_SELECTION_HANDLE );
+ CreateHandleMarker(primary, mHandleImages[LEFT_SELECTION_HANDLE_MARKER][HANDLE_IMAGE_RELEASED], LEFT_SELECTION_HANDLE);
}
}
- if( primary.actor && !primary.actor.GetParent() )
+ if(primary.actor && !primary.actor.GetParent())
{
- mActiveLayer.Add( primary.actor );
+ mActiveLayer.Add(primary.actor);
}
- HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ];
- if( !secondary.actor )
+ HandleImpl& secondary = mHandle[RIGHT_SELECTION_HANDLE];
+ if(!secondary.actor)
{
- if( mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED].size() )
+ if(mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED].size())
{
- secondary.actor = ImageView::New( mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] );
+ secondary.actor = ImageView::New(mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED]);
#ifdef DECORATOR_DEBUG
- secondary.actor.SetProperty( Dali::Actor::Property::NAME,"SelectionHandleTwo");
+ secondary.actor.SetProperty(Dali::Actor::Property::NAME, "SelectionHandleTwo");
#endif
- secondary.actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text.
- GetImpl( secondary.actor ).SetDepthIndex( DepthIndex::DECORATION );
- secondary.actor.SetProperty( Actor::Property::COLOR, mHandleColor );
+ secondary.actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text.
+ GetImpl(secondary.actor).SetDepthIndex(DepthIndex::DECORATION);
+ secondary.actor.SetProperty(Actor::Property::COLOR, mHandleColor);
secondary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
#ifdef DECORATOR_DEBUG
- secondary.grabArea.SetProperty( Dali::Actor::Property::NAME,"SelectionHandleTwoGrabArea");
+ secondary.grabArea.SetProperty(Dali::Actor::Property::NAME, "SelectionHandleTwoGrabArea");
#endif
- secondary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
- secondary.grabArea.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER );
- secondary.grabArea.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER );
- secondary.grabArea.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
+ secondary.grabArea.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS);
+ secondary.grabArea.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER);
+ secondary.grabArea.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER);
+ secondary.grabArea.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE);
- secondary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleTwoTouched );
+ secondary.grabArea.TouchedSignal().Connect(this, &Decorator::Impl::OnHandleTwoTouched);
// The handle's actor is attached to the tap and long press detectors in order to consume these events.
// Note that no callbacks are connected to any signal emitted by the tap and long press detectors.
- mTapDetector.Attach( secondary.actor );
- mLongPressDetector.Attach( secondary.actor );
+ mTapDetector.Attach(secondary.actor);
+ mLongPressDetector.Attach(secondary.actor);
// The handle's area is attached to the pan detector.
// The OnPan() method is connected to the signals emitted by the pan detector.
- mPanDetector.Attach( secondary.grabArea );
+ mPanDetector.Attach(secondary.grabArea);
- secondary.actor.Add( secondary.grabArea );
+ secondary.actor.Add(secondary.grabArea);
- CreateHandleMarker( secondary, mHandleImages[RIGHT_SELECTION_HANDLE_MARKER][HANDLE_IMAGE_RELEASED], RIGHT_SELECTION_HANDLE );
+ CreateHandleMarker(secondary, mHandleImages[RIGHT_SELECTION_HANDLE_MARKER][HANDLE_IMAGE_RELEASED], RIGHT_SELECTION_HANDLE);
}
}
- if( secondary.actor && !secondary.actor.GetParent() )
+ if(secondary.actor && !secondary.actor.GetParent())
{
- mActiveLayer.Add( secondary.actor );
+ mActiveLayer.Add(secondary.actor);
}
}
- void CalculateHandleWorldCoordinates( HandleImpl& handle, Vector2& position )
+ void CalculateHandleWorldCoordinates(HandleImpl& handle, Vector2& position)
{
// Gets the world position of the active layer. The active layer is where the handles are added.
- const Vector3 parentWorldPosition = mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION );
+ const Vector3 parentWorldPosition = mActiveLayer.GetCurrentProperty<Vector3>(Actor::Property::WORLD_POSITION);
// The grab handle position in world coords.
// The active layer's world position is the center of the active layer. The origin of the
// coord system of the handles is the top left of the active layer.
- position.x = parentWorldPosition.x - 0.5f * mControlSize.width + handle.position.x + ( mSmoothHandlePanEnabled ? handle.grabDisplacementX : 0.f );
- position.y = parentWorldPosition.y - 0.5f * mControlSize.height + handle.position.y + ( mSmoothHandlePanEnabled ? handle.grabDisplacementY : 0.f );
+ position.x = parentWorldPosition.x - 0.5f * mControlSize.width + handle.position.x + (mSmoothHandlePanEnabled ? handle.grabDisplacementX : 0.f);
+ position.y = parentWorldPosition.y - 0.5f * mControlSize.height + handle.position.y + (mSmoothHandlePanEnabled ? handle.grabDisplacementY : 0.f);
}
void SetGrabHandlePosition()
// retrieves the position of the center of the actor but the handle's position set
// by the text controller is not the center of the actor.
Vector2 grabHandleWorldPosition;
- CalculateHandleWorldCoordinates( grabHandle, grabHandleWorldPosition );
+ CalculateHandleWorldCoordinates(grabHandle, grabHandleWorldPosition);
// Check if the grab handle exceeds the boundaries of the decoration box.
// At the moment only the height is checked for the grab handle.
- grabHandle.verticallyFlipped = ( grabHandle.verticallyFlippedPreferred &&
- ( ( grabHandleWorldPosition.y - grabHandle.size.height ) > mBoundingBox.y ) ) ||
- ( grabHandleWorldPosition.y + grabHandle.lineHeight + grabHandle.size.height > mBoundingBox.w );
+ grabHandle.verticallyFlipped = (grabHandle.verticallyFlippedPreferred &&
+ ((grabHandleWorldPosition.y - grabHandle.size.height) > mBoundingBox.y)) ||
+ (grabHandleWorldPosition.y + grabHandle.lineHeight + grabHandle.size.height > mBoundingBox.w);
// The grab handle 'y' position in local coords.
// If the grab handle exceeds the bottom of the decoration box,
// The SetGrabHandleImage() method will change the orientation.
const float yLocalPosition = grabHandle.verticallyFlipped ? grabHandle.position.y : grabHandle.position.y + grabHandle.lineHeight;
- if( grabHandle.actor )
+ if(grabHandle.actor)
{
- grabHandle.actor.SetProperty( Actor::Property::POSITION, Vector2( grabHandle.position.x + floor( 0.5f * mCursorWidth ) + ( mSmoothHandlePanEnabled ? grabHandle.grabDisplacementX : 0.f ),
- yLocalPosition + ( mSmoothHandlePanEnabled ? grabHandle.grabDisplacementY : 0.f ) ) );
+ grabHandle.actor.SetProperty(Actor::Property::POSITION, Vector2(grabHandle.position.x + floor(0.5f * mCursorWidth) + (mSmoothHandlePanEnabled ? grabHandle.grabDisplacementX : 0.f), yLocalPosition + (mSmoothHandlePanEnabled ? grabHandle.grabDisplacementY : 0.f)));
}
}
- void SetSelectionHandlePosition( HandleType type )
+ void SetSelectionHandlePosition(HandleType type)
{
const bool isPrimaryHandle = LEFT_SELECTION_HANDLE == type;
// retrieves the position of the center of the actor but the handle's position set
// by the text controller is not the center of the actor.
Vector2 handleWorldPosition;
- CalculateHandleWorldCoordinates( handle, handleWorldPosition );
+ CalculateHandleWorldCoordinates(handle, handleWorldPosition);
// Whether to flip the handle (horizontally).
bool flipHandle = isPrimaryHandle ? mFlipLeftSelectionHandleDirection : mFlipRightSelectionHandleDirection;
// Whether to flip the handles if they are crossed.
bool crossFlip = false;
- if( mFlipSelectionHandlesOnCross || !mIsHandlePanning )
+ if(mFlipSelectionHandlesOnCross || !mIsHandlePanning)
{
crossFlip = mIsHandleCurrentlyCrossed;
}
const bool isHandlePreviouslyCrossed = mFlipSelectionHandlesOnCross ? false : mIsHandlePreviouslyCrossed;
// Does not flip if both conditions are true (double flip)
- flipHandle = flipHandle != ( crossFlip || isHandlePreviouslyCrossed );
+ flipHandle = flipHandle != (crossFlip || isHandlePreviouslyCrossed);
// Will flip the handles vertically if the user prefers it.
bool verticallyFlippedPreferred = handle.verticallyFlippedPreferred;
- if( crossFlip || isHandlePreviouslyCrossed )
+ if(crossFlip || isHandlePreviouslyCrossed)
{
- if( isPrimaryHandle )
+ if(isPrimaryHandle)
{
verticallyFlippedPreferred = mHandle[RIGHT_SELECTION_HANDLE].verticallyFlippedPreferred;
}
}
// Check if the selection handle exceeds the boundaries of the decoration box.
- const bool exceedsLeftEdge = ( isPrimaryHandle ? !flipHandle : flipHandle ) && ( handleWorldPosition.x - handle.size.width < mBoundingBox.x );
- const bool exceedsRightEdge = ( isPrimaryHandle ? flipHandle : !flipHandle ) && ( handleWorldPosition.x + handle.size.width > mBoundingBox.z );
+ const bool exceedsLeftEdge = (isPrimaryHandle ? !flipHandle : flipHandle) && (handleWorldPosition.x - handle.size.width < mBoundingBox.x);
+ const bool exceedsRightEdge = (isPrimaryHandle ? flipHandle : !flipHandle) && (handleWorldPosition.x + handle.size.width > mBoundingBox.z);
// Does not flip if both conditions are true (double flip)
- flipHandle = flipHandle != ( exceedsLeftEdge || exceedsRightEdge );
+ flipHandle = flipHandle != (exceedsLeftEdge || exceedsRightEdge);
- if( flipHandle )
+ if(flipHandle)
{
- if( handle.actor && !handle.horizontallyFlipped )
+ if(handle.actor && !handle.horizontallyFlipped)
{
// Change the anchor point to flip the image.
- handle.actor.SetProperty( Actor::Property::ANCHOR_POINT, isPrimaryHandle ? AnchorPoint::TOP_LEFT : AnchorPoint::TOP_RIGHT );
+ handle.actor.SetProperty(Actor::Property::ANCHOR_POINT, isPrimaryHandle ? AnchorPoint::TOP_LEFT : AnchorPoint::TOP_RIGHT);
handle.horizontallyFlipped = true;
}
}
else
{
- if( handle.actor && handle.horizontallyFlipped )
+ if(handle.actor && handle.horizontallyFlipped)
{
// Reset the anchor point.
- handle.actor.SetProperty( Actor::Property::ANCHOR_POINT, isPrimaryHandle ? AnchorPoint::TOP_RIGHT : AnchorPoint::TOP_LEFT );
+ handle.actor.SetProperty(Actor::Property::ANCHOR_POINT, isPrimaryHandle ? AnchorPoint::TOP_RIGHT : AnchorPoint::TOP_LEFT);
handle.horizontallyFlipped = false;
}
}
// Whether to flip the handle vertically.
- handle.verticallyFlipped = ( verticallyFlippedPreferred &&
- ( ( handleWorldPosition.y - handle.size.height ) > mBoundingBox.y ) ) ||
- ( handleWorldPosition.y + handle.lineHeight + handle.size.height > mBoundingBox.w );
+ handle.verticallyFlipped = (verticallyFlippedPreferred &&
+ ((handleWorldPosition.y - handle.size.height) > mBoundingBox.y)) ||
+ (handleWorldPosition.y + handle.lineHeight + handle.size.height > mBoundingBox.w);
// The primary selection handle 'y' position in local coords.
// If the handle exceeds the bottom of the decoration box,
// The SetHandleImage() method will change the orientation.
const float yLocalPosition = handle.verticallyFlipped ? handle.position.y : handle.position.y + handle.lineHeight;
- if( handle.actor )
+ if(handle.actor)
{
- handle.actor.SetProperty( Actor::Property::POSITION, Vector2( handle.position.x + ( mSmoothHandlePanEnabled ? handle.grabDisplacementX : 0.f ),
- yLocalPosition + ( mSmoothHandlePanEnabled ? handle.grabDisplacementY : 0.f ) ) );
+ handle.actor.SetProperty(Actor::Property::POSITION, Vector2(handle.position.x + (mSmoothHandlePanEnabled ? handle.grabDisplacementX : 0.f), yLocalPosition + (mSmoothHandlePanEnabled ? handle.grabDisplacementY : 0.f)));
}
}
- void SetHandleImage( HandleType type )
+ void SetHandleImage(HandleType type)
{
HandleImpl& handle = mHandle[type];
HandleType markerType = HANDLE_TYPE_COUNT;
// If the selection handle is flipped it chooses the image of the other selection handle. Does nothing for the grab handle.
- if( LEFT_SELECTION_HANDLE == type )
+ if(LEFT_SELECTION_HANDLE == type)
{
- type = handle.horizontallyFlipped ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE;
+ type = handle.horizontallyFlipped ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE;
markerType = handle.horizontallyFlipped ? RIGHT_SELECTION_HANDLE_MARKER : LEFT_SELECTION_HANDLE_MARKER;
}
- else if( RIGHT_SELECTION_HANDLE == type )
+ else if(RIGHT_SELECTION_HANDLE == type)
{
- type = handle.horizontallyFlipped ? LEFT_SELECTION_HANDLE : RIGHT_SELECTION_HANDLE;
+ type = handle.horizontallyFlipped ? LEFT_SELECTION_HANDLE : RIGHT_SELECTION_HANDLE;
markerType = handle.horizontallyFlipped ? LEFT_SELECTION_HANDLE_MARKER : RIGHT_SELECTION_HANDLE_MARKER;
}
// Chooses between the released or pressed image. It checks whether the pressed image exists.
- if( handle.actor )
+ if(handle.actor)
{
- const HandleImageType imageType = ( handle.pressed ? ( mHandleImages[type][HANDLE_IMAGE_PRESSED].size() ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED ) : HANDLE_IMAGE_RELEASED );
+ const HandleImageType imageType = (handle.pressed ? (mHandleImages[type][HANDLE_IMAGE_PRESSED].size() ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED) : HANDLE_IMAGE_RELEASED);
- handle.actor.SetImage( mHandleImages[type][imageType] );
+ handle.actor.SetImage(mHandleImages[type][imageType]);
}
- if( HANDLE_TYPE_COUNT != markerType )
+ if(HANDLE_TYPE_COUNT != markerType)
{
- if( handle.markerActor )
+ if(handle.markerActor)
{
- const HandleImageType markerImageType = ( handle.pressed ? ( mHandleImages[markerType][HANDLE_IMAGE_PRESSED].size() ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED ) : HANDLE_IMAGE_RELEASED );
- handle.markerActor.SetImage( mHandleImages[markerType][markerImageType] );
+ const HandleImageType markerImageType = (handle.pressed ? (mHandleImages[markerType][HANDLE_IMAGE_PRESSED].size() ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED) : HANDLE_IMAGE_RELEASED);
+ handle.markerActor.SetImage(mHandleImages[markerType][markerImageType]);
}
}
// Whether to flip the handle vertically.
- if( handle.actor )
+ if(handle.actor)
{
- handle.actor.SetProperty( Actor::Property::ORIENTATION, Quaternion( handle.verticallyFlipped ? ANGLE_180 : ANGLE_0, Vector3::XAXIS ) );
+ handle.actor.SetProperty(Actor::Property::ORIENTATION, Quaternion(handle.verticallyFlipped ? ANGLE_180 : ANGLE_0, Vector3::XAXIS));
}
}
void CreateHighlight()
{
- if( !mHighlightActor )
+ if(!mHighlightActor)
{
mHighlightActor = Actor::New();
- mHighlightActor.SetProperty( Dali::Actor::Property::NAME, "HighlightActor" );
- mHighlightActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- mHighlightActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- mHighlightActor.SetProperty( Actor::Property::COLOR, mHighlightColor );
- mHighlightActor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_COLOR );
+ mHighlightActor.SetProperty(Dali::Actor::Property::NAME, "HighlightActor");
+ mHighlightActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ mHighlightActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ mHighlightActor.SetProperty(Actor::Property::COLOR, mHighlightColor);
+ mHighlightActor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_COLOR);
}
// Add the highlight box telling the controller it needs clipping.
- mController.AddDecoration( mHighlightActor, true );
+ mController.AddDecoration(mHighlightActor, true);
}
void UpdateHighlight()
{
- if ( mHighlightActor )
+ if(mHighlightActor)
{
// Sets the position of the highlight actor inside the decorator.
- mHighlightActor.SetProperty( Actor::Property::POSITION, Vector2( mHighlightPosition.x + mHighlightOutlineOffset,
- mHighlightPosition.y + mHighlightOutlineOffset ) );
+ mHighlightActor.SetProperty(Actor::Property::POSITION, Vector2(mHighlightPosition.x + mHighlightOutlineOffset, mHighlightPosition.y + mHighlightOutlineOffset));
const unsigned int numberOfQuads = mHighlightQuadList.Count();
- if( 0u != numberOfQuads )
+ if(0u != numberOfQuads)
{
// Set the size of the highlighted text to the actor.
- mHighlightActor.SetProperty( Actor::Property::SIZE, mHighlightSize );
+ mHighlightActor.SetProperty(Actor::Property::SIZE, mHighlightSize);
// Used to translate the vertices given in decorator's coords to the mHighlightActor's local coords.
const float offsetX = mHighlightPosition.x + 0.5f * mHighlightSize.width;
const float offsetY = mHighlightPosition.y + 0.5f * mHighlightSize.height;
- Vector<Vector2> vertices;
+ Vector<Vector2> vertices;
Vector<unsigned short> indices;
- vertices.Reserve( 4u * numberOfQuads );
- indices.Reserve( 6u * numberOfQuads );
+ vertices.Reserve(4u * numberOfQuads);
+ indices.Reserve(6u * numberOfQuads);
// Index to the vertex.
unsigned int v = 0u;
// Traverse all quads.
- for( Vector<Vector4>::ConstIterator it = mHighlightQuadList.Begin(),
- endIt = mHighlightQuadList.End();
- it != endIt;
- ++it, v += 4u )
+ for(Vector<Vector4>::ConstIterator it = mHighlightQuadList.Begin(),
+ endIt = mHighlightQuadList.End();
+ it != endIt;
+ ++it, v += 4u)
{
const Vector4& quad = *it;
// top-left (v+0)
vertex.x = quad.x - offsetX;
vertex.y = quad.y - offsetY;
- vertices.PushBack( vertex );
+ vertices.PushBack(vertex);
// top-right (v+1)
vertex.x = quad.z - offsetX;
vertex.y = quad.y - offsetY;
- vertices.PushBack( vertex );
+ vertices.PushBack(vertex);
// bottom-left (v+2)
vertex.x = quad.x - offsetX;
vertex.y = quad.w - offsetY;
- vertices.PushBack( vertex );
+ vertices.PushBack(vertex);
// bottom-right (v+3)
vertex.x = quad.z - offsetX;
vertex.y = quad.w - offsetY;
- vertices.PushBack( vertex );
+ vertices.PushBack(vertex);
// triangle A (3, 1, 0)
- indices.PushBack( v + 3 );
- indices.PushBack( v + 1 );
- indices.PushBack( v );
+ indices.PushBack(v + 3);
+ indices.PushBack(v + 1);
+ indices.PushBack(v);
// triangle B (0, 2, 3)
- indices.PushBack( v );
- indices.PushBack( v + 2 );
- indices.PushBack( v + 3 );
+ indices.PushBack(v);
+ indices.PushBack(v + 2);
+ indices.PushBack(v + 3);
}
- if( ! mQuadVertices )
+ if(!mQuadVertices)
{
- mQuadVertices = VertexBuffer::New( mQuadVertexFormat );
+ mQuadVertices = VertexBuffer::New(mQuadVertexFormat);
}
- mQuadVertices.SetData( &vertices[ 0 ], vertices.Size() );
+ mQuadVertices.SetData(&vertices[0], vertices.Size());
- if( !mQuadGeometry )
+ if(!mQuadGeometry)
{
mQuadGeometry = Geometry::New();
- mQuadGeometry.AddVertexBuffer( mQuadVertices );
+ mQuadGeometry.AddVertexBuffer(mQuadVertices);
}
- mQuadGeometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
+ mQuadGeometry.SetIndexBuffer(&indices[0], indices.Size());
- if( !mHighlightRenderer )
+ if(!mHighlightRenderer)
{
- mHighlightRenderer = Dali::Renderer::New( mQuadGeometry, mHighlightShader );
- mHighlightActor.AddRenderer( mHighlightRenderer );
+ mHighlightRenderer = Dali::Renderer::New(mQuadGeometry, mHighlightShader);
+ mHighlightActor.AddRenderer(mHighlightRenderer);
}
}
mHighlightQuadList.Clear();
- if( mHighlightRenderer )
+ if(mHighlightRenderer)
{
- mHighlightRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, mTextDepth - 2 ); // text is rendered at mTextDepth and text's shadow at mTextDepth -1u.
+ mHighlightRenderer.SetProperty(Renderer::Property::DEPTH_INDEX, mTextDepth - 2); // text is rendered at mTextDepth and text's shadow at mTextDepth -1u.
}
}
}
- void DoPan( HandleImpl& handle, HandleType type, const PanGesture& gesture )
+ void DoPan(HandleImpl& handle, HandleType type, const PanGesture& gesture)
{
GestureState state = gesture.GetState();
- if( GestureState::STARTED == state )
+ if(GestureState::STARTED == state)
{
handle.grabDisplacementX = handle.grabDisplacementY = 0.f;
const Vector2& displacement = gesture.GetDisplacement();
handle.grabDisplacementX += displacement.x;
- handle.grabDisplacementY += ( handle.verticallyFlipped ? -displacement.y : displacement.y );
+ handle.grabDisplacementY += (handle.verticallyFlipped ? -displacement.y : displacement.y);
- const float x = handle.globalPosition.x + handle.grabDisplacementX;
- const float y = handle.globalPosition.y + handle.grabDisplacementY + 0.5f * handle.lineHeight;
- const float yVerticallyFlippedCorrected = y - ( handle.verticallyFlippedOnTouch ? handle.lineHeight : 0.f );
+ const float x = handle.globalPosition.x + handle.grabDisplacementX;
+ const float y = handle.globalPosition.y + handle.grabDisplacementY + 0.5f * handle.lineHeight;
+ const float yVerticallyFlippedCorrected = y - (handle.verticallyFlippedOnTouch ? handle.lineHeight : 0.f);
- if( ( GestureState::STARTED == state ) ||
- ( GestureState::CONTINUING == state ) )
+ if((GestureState::STARTED == state) ||
+ (GestureState::CONTINUING == state))
{
Vector2 targetSize;
- mController.GetTargetSize( targetSize );
+ mController.GetTargetSize(targetSize);
- if( mHorizontalScrollingEnabled &&
- ( x < mScrollThreshold ) )
+ if(mHorizontalScrollingEnabled &&
+ (x < mScrollThreshold))
{
mScrollDirection = SCROLL_RIGHT;
mHandleScrolling = type;
StartScrollTimer();
}
- else if( mHorizontalScrollingEnabled &&
- ( x > targetSize.width - mScrollThreshold ) )
+ else if(mHorizontalScrollingEnabled &&
+ (x > targetSize.width - mScrollThreshold))
{
mScrollDirection = SCROLL_LEFT;
mHandleScrolling = type;
StartScrollTimer();
}
- else if( mVerticalScrollingEnabled &&
- ( yVerticallyFlippedCorrected < mScrollThreshold ) )
+ else if(mVerticalScrollingEnabled &&
+ (yVerticallyFlippedCorrected < mScrollThreshold))
{
mScrollDirection = SCROLL_TOP;
mHandleScrolling = type;
StartScrollTimer();
}
- else if( mVerticalScrollingEnabled &&
- ( yVerticallyFlippedCorrected + handle.lineHeight > targetSize.height - mScrollThreshold ) )
+ else if(mVerticalScrollingEnabled &&
+ (yVerticallyFlippedCorrected + handle.lineHeight > targetSize.height - mScrollThreshold))
{
mScrollDirection = SCROLL_BOTTOM;
mHandleScrolling = type;
{
mHandleScrolling = HANDLE_TYPE_COUNT;
StopScrollTimer();
- mController.DecorationEvent( type, HANDLE_PRESSED, x, y );
+ mController.DecorationEvent(type, HANDLE_PRESSED, x, y);
}
mIsHandlePanning = true;
}
- else if( ( GestureState::FINISHED == state ) ||
- ( GestureState::CANCELLED == state ) )
+ else if((GestureState::FINISHED == state) ||
+ (GestureState::CANCELLED == state))
{
- if( mScrollTimer &&
- ( mScrollTimer.IsRunning() || mNotifyEndOfScroll ) )
+ if(mScrollTimer &&
+ (mScrollTimer.IsRunning() || mNotifyEndOfScroll))
{
mNotifyEndOfScroll = false;
- mHandleScrolling = HANDLE_TYPE_COUNT;
+ mHandleScrolling = HANDLE_TYPE_COUNT;
StopScrollTimer();
- mController.DecorationEvent( type, HANDLE_STOP_SCROLLING, x, y );
+ mController.DecorationEvent(type, HANDLE_STOP_SCROLLING, x, y);
}
else
{
- mController.DecorationEvent( type, HANDLE_RELEASED, x, y );
+ mController.DecorationEvent(type, HANDLE_RELEASED, x, y);
}
- if( handle.actor )
+ if(handle.actor)
{
- handle.actor.SetImage( mHandleImages[type][HANDLE_IMAGE_RELEASED] );
+ handle.actor.SetImage(mHandleImages[type][HANDLE_IMAGE_RELEASED]);
}
handle.pressed = false;
}
}
- void OnPan( Actor actor, const PanGesture& gesture )
+ void OnPan(Actor actor, const PanGesture& gesture)
{
- HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
- HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE];
+ HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
+ HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE];
HandleImpl& secondarySelectionHandle = mHandle[RIGHT_SELECTION_HANDLE];
- if( actor == grabHandle.grabArea )
+ if(actor == grabHandle.grabArea)
{
- DoPan( grabHandle, GRAB_HANDLE, gesture );
+ DoPan(grabHandle, GRAB_HANDLE, gesture);
}
- else if( actor == primarySelectionHandle.grabArea )
+ else if(actor == primarySelectionHandle.grabArea)
{
- DoPan( primarySelectionHandle, LEFT_SELECTION_HANDLE, gesture );
+ DoPan(primarySelectionHandle, LEFT_SELECTION_HANDLE, gesture);
}
- else if( actor == secondarySelectionHandle.grabArea )
+ else if(actor == secondarySelectionHandle.grabArea)
{
- DoPan( secondarySelectionHandle, RIGHT_SELECTION_HANDLE, gesture );
+ DoPan(secondarySelectionHandle, RIGHT_SELECTION_HANDLE, gesture);
}
}
- bool OnGrabHandleTouched( Actor actor, const TouchEvent& touch )
+ bool OnGrabHandleTouched(Actor actor, const TouchEvent& touch)
{
HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
// Switch between pressed/release grab-handle images
- if( touch.GetPointCount() > 0 &&
- grabHandle.actor )
+ if(touch.GetPointCount() > 0 &&
+ grabHandle.actor)
{
- const PointState::Type state = touch.GetState( 0 );
+ const PointState::Type state = touch.GetState(0);
- if( PointState::DOWN == state )
+ if(PointState::DOWN == state)
{
grabHandle.pressed = true;
}
- else if( ( PointState::UP == state ) ||
- ( PointState::INTERRUPTED == state ) )
+ else if((PointState::UP == state) ||
+ (PointState::INTERRUPTED == state))
{
grabHandle.pressed = false;
}
- SetHandleImage( GRAB_HANDLE );
+ SetHandleImage(GRAB_HANDLE);
}
return false;
}
- bool OnHandleOneTouched( Actor actor, const TouchEvent& touch )
+ bool OnHandleOneTouched(Actor actor, const TouchEvent& touch)
{
HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE];
// Switch between pressed/release selection handle images
- if( touch.GetPointCount() > 0 &&
- primarySelectionHandle.actor )
+ if(touch.GetPointCount() > 0 &&
+ primarySelectionHandle.actor)
{
- const PointState::Type state = touch.GetState( 0 );
+ const PointState::Type state = touch.GetState(0);
- if( PointState::DOWN == state )
+ if(PointState::DOWN == state)
{
- primarySelectionHandle.pressed = true;
+ primarySelectionHandle.pressed = true;
primarySelectionHandle.verticallyFlippedOnTouch = primarySelectionHandle.verticallyFlipped;
}
- else if( ( PointState::UP == state ) ||
- ( PointState::INTERRUPTED == state ) )
+ else if((PointState::UP == state) ||
+ (PointState::INTERRUPTED == state))
{
primarySelectionHandle.pressed = false;
- mIsHandlePreviouslyCrossed = mIsHandleCurrentlyCrossed;
- mIsHandlePanning = false;
- mHandleReleased = LEFT_SELECTION_HANDLE;
+ mIsHandlePreviouslyCrossed = mIsHandleCurrentlyCrossed;
+ mIsHandlePanning = false;
+ mHandleReleased = LEFT_SELECTION_HANDLE;
}
- SetHandleImage( LEFT_SELECTION_HANDLE );
+ SetHandleImage(LEFT_SELECTION_HANDLE);
}
return false;
}
- bool OnHandleTwoTouched( Actor actor, const TouchEvent& touch )
+ bool OnHandleTwoTouched(Actor actor, const TouchEvent& touch)
{
HandleImpl& secondarySelectionHandle = mHandle[RIGHT_SELECTION_HANDLE];
// Switch between pressed/release selection handle images
- if( touch.GetPointCount() > 0 &&
- secondarySelectionHandle.actor )
+ if(touch.GetPointCount() > 0 &&
+ secondarySelectionHandle.actor)
{
- const PointState::Type state = touch.GetState( 0 );
+ const PointState::Type state = touch.GetState(0);
- if( PointState::DOWN == state )
+ if(PointState::DOWN == state)
{
- secondarySelectionHandle.pressed = true;
+ secondarySelectionHandle.pressed = true;
secondarySelectionHandle.verticallyFlippedOnTouch = secondarySelectionHandle.verticallyFlipped;
}
- else if( ( PointState::UP == state ) ||
- ( PointState::INTERRUPTED == state ) )
+ else if((PointState::UP == state) ||
+ (PointState::INTERRUPTED == state))
{
secondarySelectionHandle.pressed = false;
- mIsHandlePreviouslyCrossed = mIsHandleCurrentlyCrossed;
- mIsHandlePanning = false;
- mHandleReleased = RIGHT_SELECTION_HANDLE;
+ mIsHandlePreviouslyCrossed = mIsHandleCurrentlyCrossed;
+ mIsHandlePanning = false;
+ mHandleReleased = RIGHT_SELECTION_HANDLE;
}
- SetHandleImage( RIGHT_SELECTION_HANDLE );
+ SetHandleImage(RIGHT_SELECTION_HANDLE);
}
return false;
}
- void HandleResetPosition( PropertyNotification& source )
+ void HandleResetPosition(PropertyNotification& source)
{
const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
- if( grabHandle.active )
+ if(grabHandle.active)
{
// Sets the grab handle position and calculates if it needs to be vertically flipped if it exceeds the boundary box.
SetGrabHandlePosition();
// Sets the grab handle image according if it's pressed, flipped, etc.
- SetHandleImage( GRAB_HANDLE );
+ SetHandleImage(GRAB_HANDLE);
}
else
{
// Sets the primary selection handle position and calculates if it needs to be vertically flipped if it exceeds the boundary box.
- SetSelectionHandlePosition( LEFT_SELECTION_HANDLE );
+ SetSelectionHandlePosition(LEFT_SELECTION_HANDLE);
// Sets the primary handle image according if it's pressed, flipped, etc.
- SetHandleImage( LEFT_SELECTION_HANDLE );
+ SetHandleImage(LEFT_SELECTION_HANDLE);
// Sets the secondary selection handle position and calculates if it needs to be vertically flipped if it exceeds the boundary box.
- SetSelectionHandlePosition( RIGHT_SELECTION_HANDLE );
+ SetSelectionHandlePosition(RIGHT_SELECTION_HANDLE);
// Sets the secondary handle image according if it's pressed, flipped, etc.
- SetHandleImage( RIGHT_SELECTION_HANDLE );
+ SetHandleImage(RIGHT_SELECTION_HANDLE);
}
}
void SetupActiveLayerPropertyNotifications()
{
- if( !mActiveLayer )
+ if(!mActiveLayer)
{
return;
}
// Vertical notifications.
// Disconnect any previous connected callback.
- if( mHandleVerticalLessThanNotification )
+ if(mHandleVerticalLessThanNotification)
{
- mHandleVerticalLessThanNotification.NotifySignal().Disconnect( this, &Decorator::Impl::HandleResetPosition );
- mActiveLayer.RemovePropertyNotification( mHandleVerticalLessThanNotification );
+ mHandleVerticalLessThanNotification.NotifySignal().Disconnect(this, &Decorator::Impl::HandleResetPosition);
+ mActiveLayer.RemovePropertyNotification(mHandleVerticalLessThanNotification);
}
- if( mHandleVerticalGreaterThanNotification )
+ if(mHandleVerticalGreaterThanNotification)
{
- mHandleVerticalGreaterThanNotification.NotifySignal().Disconnect( this, &Decorator::Impl::HandleResetPosition );
- mActiveLayer.RemovePropertyNotification( mHandleVerticalGreaterThanNotification );
+ mHandleVerticalGreaterThanNotification.NotifySignal().Disconnect(this, &Decorator::Impl::HandleResetPosition);
+ mActiveLayer.RemovePropertyNotification(mHandleVerticalGreaterThanNotification);
}
- const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
- const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE];
+ const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
+ const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE];
const HandleImpl& secondaryHandle = mHandle[RIGHT_SELECTION_HANDLE];
- if( grabHandle.active )
+ if(grabHandle.active)
{
- if( grabHandle.verticallyFlipped )
+ if(grabHandle.verticallyFlipped)
{
// The grab handle is vertically flipped. Never is going to exceed the bottom edje of the display.
mHandleVerticalGreaterThanNotification.Reset();
// The vertical distance from the center of the active layer to the top edje of the display.
const float topHeight = 0.5f * mControlSize.height - grabHandle.position.y + grabHandle.size.height;
- mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
- LessThanCondition( mBoundingBox.y + topHeight ) );
+ mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y,
+ LessThanCondition(mBoundingBox.y + topHeight));
// Notifies the change from false to true and from true to false.
- mHandleVerticalLessThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mHandleVerticalLessThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
// Connects the signals with the callbacks.
- mHandleVerticalLessThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition );
+ mHandleVerticalLessThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition);
}
else
{
// The vertical distance from the center of the active layer to the bottom edje of the display.
const float bottomHeight = -0.5f * mControlSize.height + grabHandle.position.y + grabHandle.lineHeight + grabHandle.size.height;
- mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
- GreaterThanCondition( mBoundingBox.w - bottomHeight ) );
+ mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y,
+ GreaterThanCondition(mBoundingBox.w - bottomHeight));
// Notifies the change from false to true and from true to false.
- mHandleVerticalGreaterThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mHandleVerticalGreaterThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
// Connects the signals with the callbacks.
- mHandleVerticalGreaterThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition );
+ mHandleVerticalGreaterThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition);
}
}
else // The selection handles are active
{
- if( primaryHandle.verticallyFlipped && secondaryHandle.verticallyFlipped )
+ if(primaryHandle.verticallyFlipped && secondaryHandle.verticallyFlipped)
{
// Both selection handles are vertically flipped. Never are going to exceed the bottom edje of the display.
mHandleVerticalGreaterThanNotification.Reset();
// The vertical distance from the center of the active layer to the top edje of the display.
- const float topHeight = 0.5f * mControlSize.height + std::max( -primaryHandle.position.y + primaryHandle.size.height, -secondaryHandle.position.y + secondaryHandle.size.height );
+ const float topHeight = 0.5f * mControlSize.height + std::max(-primaryHandle.position.y + primaryHandle.size.height, -secondaryHandle.position.y + secondaryHandle.size.height);
- mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
- LessThanCondition( mBoundingBox.y + topHeight ) );
+ mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y,
+ LessThanCondition(mBoundingBox.y + topHeight));
// Notifies the change from false to true and from true to false.
- mHandleVerticalLessThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mHandleVerticalLessThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
// Connects the signals with the callbacks.
- mHandleVerticalLessThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition );
+ mHandleVerticalLessThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition);
}
- else if( !primaryHandle.verticallyFlipped && !secondaryHandle.verticallyFlipped )
+ else if(!primaryHandle.verticallyFlipped && !secondaryHandle.verticallyFlipped)
{
// Both selection handles aren't vertically flipped. Never are going to exceed the top edje of the display.
mHandleVerticalLessThanNotification.Reset();
// The vertical distance from the center of the active layer to the bottom edje of the display.
- const float bottomHeight = -0.5f * mControlSize.height + std::max( primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height,
- secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height );
+ const float bottomHeight = -0.5f * mControlSize.height + std::max(primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height,
+ secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height);
- mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
- GreaterThanCondition( mBoundingBox.w - bottomHeight ) );
+ mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y,
+ GreaterThanCondition(mBoundingBox.w - bottomHeight));
// Notifies the change from false to true and from true to false.
- mHandleVerticalGreaterThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mHandleVerticalGreaterThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
// Connects the signals with the callbacks.
- mHandleVerticalGreaterThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition );
+ mHandleVerticalGreaterThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition);
}
else
{
// Only one of the selection handles is vertically flipped. Both vertical notifications are needed.
// The vertical distance from the center of the active layer to the top edje of the display.
- const float topHeight = 0.5f * mControlSize.height + ( primaryHandle.verticallyFlipped ?
- -primaryHandle.position.y + primaryHandle.size.height :
- -secondaryHandle.position.y + secondaryHandle.size.height );
+ const float topHeight = 0.5f * mControlSize.height + (primaryHandle.verticallyFlipped ? -primaryHandle.position.y + primaryHandle.size.height : -secondaryHandle.position.y + secondaryHandle.size.height);
- mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
- LessThanCondition( mBoundingBox.y + topHeight ) );
+ mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y,
+ LessThanCondition(mBoundingBox.y + topHeight));
// Notifies the change from false to true and from true to false.
- mHandleVerticalLessThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mHandleVerticalLessThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
// Connects the signals with the callbacks.
- mHandleVerticalLessThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition );
+ mHandleVerticalLessThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition);
// The vertical distance from the center of the active layer to the bottom edje of the display.
- const float bottomHeight = -0.5f * mControlSize.height + ( primaryHandle.verticallyFlipped ?
- secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height :
- primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height );
+ const float bottomHeight = -0.5f * mControlSize.height + (primaryHandle.verticallyFlipped ? secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height : primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height);
- mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
- GreaterThanCondition( mBoundingBox.w - bottomHeight ) );
+ mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y,
+ GreaterThanCondition(mBoundingBox.w - bottomHeight));
// Notifies the change from false to true and from true to false.
- mHandleVerticalGreaterThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mHandleVerticalGreaterThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
// Connects the signals with the callbacks.
- mHandleVerticalGreaterThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition );
+ mHandleVerticalGreaterThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition);
}
}
// Horizontal notifications.
// Disconnect any previous connected callback.
- if( mHandleHorizontalLessThanNotification )
+ if(mHandleHorizontalLessThanNotification)
{
- mHandleHorizontalLessThanNotification.NotifySignal().Disconnect( this, &Decorator::Impl::HandleResetPosition );
- mActiveLayer.RemovePropertyNotification( mHandleHorizontalLessThanNotification );
+ mHandleHorizontalLessThanNotification.NotifySignal().Disconnect(this, &Decorator::Impl::HandleResetPosition);
+ mActiveLayer.RemovePropertyNotification(mHandleHorizontalLessThanNotification);
}
- if( mHandleHorizontalGreaterThanNotification )
+ if(mHandleHorizontalGreaterThanNotification)
{
- mHandleHorizontalGreaterThanNotification.NotifySignal().Disconnect( this, &Decorator::Impl::HandleResetPosition );
- mActiveLayer.RemovePropertyNotification( mHandleHorizontalGreaterThanNotification );
+ mHandleHorizontalGreaterThanNotification.NotifySignal().Disconnect(this, &Decorator::Impl::HandleResetPosition);
+ mActiveLayer.RemovePropertyNotification(mHandleHorizontalGreaterThanNotification);
}
- if( primaryHandle.active || secondaryHandle.active )
+ if(primaryHandle.active || secondaryHandle.active)
{
// The horizontal distance from the center of the active layer to the left edje of the display.
- const float leftWidth = 0.5f * mControlSize.width + std::max( -primaryHandle.position.x + primaryHandle.size.width,
- -secondaryHandle.position.x + secondaryHandle.size.width );
+ const float leftWidth = 0.5f * mControlSize.width + std::max(-primaryHandle.position.x + primaryHandle.size.width,
+ -secondaryHandle.position.x + secondaryHandle.size.width);
- mHandleHorizontalLessThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_X,
- LessThanCondition( mBoundingBox.x + leftWidth ) );
+ mHandleHorizontalLessThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_X,
+ LessThanCondition(mBoundingBox.x + leftWidth));
// Notifies the change from false to true and from true to false.
- mHandleHorizontalLessThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mHandleHorizontalLessThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
// Connects the signals with the callbacks.
- mHandleHorizontalLessThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition );
+ mHandleHorizontalLessThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition);
// The horizontal distance from the center of the active layer to the right edje of the display.
- const float rightWidth = -0.5f * mControlSize.width + std::max( primaryHandle.position.x + primaryHandle.size.width,
- secondaryHandle.position.x + secondaryHandle.size.width );
+ const float rightWidth = -0.5f * mControlSize.width + std::max(primaryHandle.position.x + primaryHandle.size.width,
+ secondaryHandle.position.x + secondaryHandle.size.width);
- mHandleHorizontalGreaterThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_X,
- GreaterThanCondition( mBoundingBox.z - rightWidth ) );
+ mHandleHorizontalGreaterThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_X,
+ GreaterThanCondition(mBoundingBox.z - rightWidth));
// Notifies the change from false to true and from true to false.
- mHandleHorizontalGreaterThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mHandleHorizontalGreaterThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
// Connects the signals with the callbacks.
- mHandleHorizontalGreaterThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition );
+ mHandleHorizontalGreaterThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition);
}
}
// Popup
- float AlternatePopUpPositionRelativeToCursor( bool topBottom )
+ float AlternatePopUpPositionRelativeToCursor(bool topBottom)
{
float alternativePosition = 0.0f;
- const float halfPopupHeight = 0.5f * mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT );
+ const float halfPopupHeight = 0.5f * mCopyPastePopup.actor.GetRelayoutSize(Dimension::HEIGHT);
- const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE];
+ const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE];
const HandleImpl& secondaryHandle = mHandle[RIGHT_SELECTION_HANDLE];
- const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
- const CursorImpl& cursor = mCursor[PRIMARY_CURSOR];
+ const HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
+ const CursorImpl& cursor = mCursor[PRIMARY_CURSOR];
- if( primaryHandle.active || secondaryHandle.active )
+ if(primaryHandle.active || secondaryHandle.active)
{
- float handleY = 0.f;
+ float handleY = 0.f;
float maxHandleHeight = 0.f;
- const bool primaryVisible = primaryHandle.horizontallyVisible && primaryHandle.verticallyVisible;
+ const bool primaryVisible = primaryHandle.horizontallyVisible && primaryHandle.verticallyVisible;
const bool secondaryVisible = secondaryHandle.horizontallyVisible && secondaryHandle.verticallyVisible;
- if( primaryVisible && secondaryVisible )
+ if(primaryVisible && secondaryVisible)
{
- handleY = std::max( primaryHandle.position.y, secondaryHandle.position.y );
- maxHandleHeight = std::max( primaryHandle.size.height, secondaryHandle.size.height );
+ handleY = std::max(primaryHandle.position.y, secondaryHandle.position.y);
+ maxHandleHeight = std::max(primaryHandle.size.height, secondaryHandle.size.height);
}
- else if( primaryVisible && !secondaryVisible )
+ else if(primaryVisible && !secondaryVisible)
{
- handleY = primaryHandle.position.y;
+ handleY = primaryHandle.position.y;
maxHandleHeight = primaryHandle.size.height;
}
- else if( !primaryVisible && secondaryVisible )
+ else if(!primaryVisible && secondaryVisible)
{
- handleY = secondaryHandle.position.y;
+ handleY = secondaryHandle.position.y;
maxHandleHeight = secondaryHandle.size.height;
}
- alternativePosition = handleY + ( topBottom ? halfPopupHeight + maxHandleHeight + cursor.lineHeight : -halfPopupHeight - maxHandleHeight );
+ alternativePosition = handleY + (topBottom ? halfPopupHeight + maxHandleHeight + cursor.lineHeight : -halfPopupHeight - maxHandleHeight);
}
else
{
- alternativePosition = cursor.position.y + ( topBottom ? halfPopupHeight + grabHandle.size.height + cursor.lineHeight : -halfPopupHeight - grabHandle.size.height );
+ alternativePosition = cursor.position.y + (topBottom ? halfPopupHeight + grabHandle.size.height + cursor.lineHeight : -halfPopupHeight - grabHandle.size.height);
}
return alternativePosition;
}
- void PopUpLeavesTopBoundary( PropertyNotification& source )
+ void PopUpLeavesTopBoundary(PropertyNotification& source)
{
- const float popupHeight = mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT );
+ const float popupHeight = mCopyPastePopup.actor.GetRelayoutSize(Dimension::HEIGHT);
// Sets the position of the popup below.
- mCopyPastePopup.actor.SetProperty( Actor::Property::POSITION_Y, floorf( CalculateVerticalPopUpPosition( 0.5f * popupHeight, true ) ) );
+ mCopyPastePopup.actor.SetProperty(Actor::Property::POSITION_Y, floorf(CalculateVerticalPopUpPosition(0.5f * popupHeight, true)));
}
- void PopUpLeavesBottomBoundary( PropertyNotification& source )
+ void PopUpLeavesBottomBoundary(PropertyNotification& source)
{
- const float popupHeight = mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT );
+ const float popupHeight = mCopyPastePopup.actor.GetRelayoutSize(Dimension::HEIGHT);
// Sets the position of the popup above.
- mCopyPastePopup.actor.SetProperty( Actor::Property::POSITION_Y, floorf( CalculateVerticalPopUpPosition( 0.5f * popupHeight, false ) ) );
+ mCopyPastePopup.actor.SetProperty(Actor::Property::POSITION_Y, floorf(CalculateVerticalPopUpPosition(0.5f * popupHeight, false)));
}
- void SetUpPopupPositionNotifications( const Vector3& popupHalfSize )
+ void SetUpPopupPositionNotifications(const Vector3& popupHalfSize)
{
// Disconnect any previous connected callback.
- if( mPopupTopExceedNotification )
+ if(mPopupTopExceedNotification)
{
- mPopupTopExceedNotification.NotifySignal().Disconnect( this, &Decorator::Impl::PopUpLeavesTopBoundary );
- mCopyPastePopup.actor.RemovePropertyNotification( mPopupTopExceedNotification );
+ mPopupTopExceedNotification.NotifySignal().Disconnect(this, &Decorator::Impl::PopUpLeavesTopBoundary);
+ mCopyPastePopup.actor.RemovePropertyNotification(mPopupTopExceedNotification);
}
- if( mPopupBottomExceedNotification )
+ if(mPopupBottomExceedNotification)
{
- mPopupBottomExceedNotification.NotifySignal().Disconnect( this, &Decorator::Impl::PopUpLeavesBottomBoundary );
- mCopyPastePopup.actor.RemovePropertyNotification( mPopupBottomExceedNotification );
+ mPopupBottomExceedNotification.NotifySignal().Disconnect(this, &Decorator::Impl::PopUpLeavesBottomBoundary);
+ mCopyPastePopup.actor.RemovePropertyNotification(mPopupBottomExceedNotification);
}
// Note Property notifications ignore any set anchor point so conditions must allow for this. Default is Top Left.
// Exceeding vertical boundary
- mPopupTopExceedNotification = mCopyPastePopup.actor.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
- LessThanCondition( mBoundingBox.y + popupHalfSize.height ) );
+ mPopupTopExceedNotification = mCopyPastePopup.actor.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y,
+ LessThanCondition(mBoundingBox.y + popupHalfSize.height));
- mPopupBottomExceedNotification = mCopyPastePopup.actor.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
- GreaterThanCondition( mBoundingBox.w - popupHalfSize.height ) );
+ mPopupBottomExceedNotification = mCopyPastePopup.actor.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y,
+ GreaterThanCondition(mBoundingBox.w - popupHalfSize.height));
// Notifies the change from false to true and from true to false.
- mPopupTopExceedNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
- mPopupBottomExceedNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED );
+ mPopupTopExceedNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
+ mPopupBottomExceedNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED);
- mPopupTopExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesTopBoundary );
- mPopupBottomExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesBottomBoundary );
+ mPopupTopExceedNotification.NotifySignal().Connect(this, &Decorator::Impl::PopUpLeavesTopBoundary);
+ mPopupBottomExceedNotification.NotifySignal().Connect(this, &Decorator::Impl::PopUpLeavesBottomBoundary);
}
- void SetHandleImage( HandleType handleType, HandleImageType handleImageType, const std::string& imageFileName )
+ void SetHandleImage(HandleType handleType, HandleImageType handleImageType, const std::string& imageFileName)
{
- ImageDimensions dimensions = Dali::GetOriginalImageSize( imageFileName );
+ ImageDimensions dimensions = Dali::GetOriginalImageSize(imageFileName);
HandleImpl& handle = mHandle[handleType];
- handle.size = Size( dimensions.GetWidth(), dimensions.GetHeight() );
+ handle.size = Size(dimensions.GetWidth(), dimensions.GetHeight());
mHandleImages[handleType][handleImageType] = imageFileName;
}
- void SetScrollThreshold( float threshold )
+ void SetScrollThreshold(float threshold)
{
mScrollThreshold = threshold;
}
return mScrollThreshold;
}
- void SetScrollSpeed( float speed )
+ void SetScrollSpeed(float speed)
{
- mScrollSpeed = speed;
+ mScrollSpeed = speed;
mScrollDistance = speed * SCROLL_TICK_INTERVAL * TO_SECONDS;
}
{
StopScrollTimer();
- if( mScrollTimer )
+ if(mScrollTimer)
{
mNotifyEndOfScroll = true;
}
*/
void StartScrollTimer()
{
- if( !mScrollTimer )
+ if(!mScrollTimer)
{
- mScrollTimer = Timer::New( SCROLL_TICK_INTERVAL );
- mScrollTimer.TickSignal().Connect( this, &Decorator::Impl::OnScrollTimerTick );
+ mScrollTimer = Timer::New(SCROLL_TICK_INTERVAL);
+ mScrollTimer.TickSignal().Connect(this, &Decorator::Impl::OnScrollTimerTick);
}
- if( !mScrollTimer.IsRunning() )
+ if(!mScrollTimer.IsRunning())
{
mScrollTimer.Start();
}
*/
void StopScrollTimer()
{
- if( mScrollTimer )
+ if(mScrollTimer)
{
mScrollTimer.Stop();
}
*/
bool OnScrollTimerTick()
{
- if( HANDLE_TYPE_COUNT != mHandleScrolling )
+ if(HANDLE_TYPE_COUNT != mHandleScrolling)
{
float x = 0.f;
float y = 0.f;
- switch( mScrollDirection )
+ switch(mScrollDirection)
{
case SCROLL_RIGHT:
{
break;
}
- mController.DecorationEvent( mHandleScrolling,
- HANDLE_SCROLLING,
- x,
- y );
+ mController.DecorationEvent(mHandleScrolling,
+ HANDLE_SCROLLING,
+ x,
+ y);
}
return true;
PanGestureDetector mPanDetector;
LongPressGestureDetector mLongPressDetector;
- Timer mCursorBlinkTimer; ///< Timer to signal cursor to blink
- Timer mScrollTimer; ///< Timer used to scroll the text when the grab handle is moved close to the edges.
+ Timer mCursorBlinkTimer; ///< Timer to signal cursor to blink
+ Timer mScrollTimer; ///< Timer used to scroll the text when the grab handle is moved close to the edges.
Actor mActiveLayer; ///< Actor for active handles and alike that ensures they are above all else.
PropertyNotification mHandleVerticalLessThanNotification; ///< Notifies when the 'y' coord of the active layer is less than a given value.
Control mPrimaryCursor;
Control mSecondaryCursor;
- Actor mHighlightActor; ///< Actor to display highlight
- Renderer mHighlightRenderer;
- Shader mHighlightShader; ///< Shader used for highlight
- Property::Map mQuadVertexFormat;
- PopupImpl mCopyPastePopup;
- TextSelectionPopup::Buttons mEnabledPopupButtons; /// Bit mask of currently enabled Popup buttons
+ Actor mHighlightActor; ///< Actor to display highlight
+ Renderer mHighlightRenderer;
+ Shader mHighlightShader; ///< Shader used for highlight
+ Property::Map mQuadVertexFormat;
+ PopupImpl mCopyPastePopup;
+ TextSelectionPopup::Buttons mEnabledPopupButtons; /// Bit mask of currently enabled Popup buttons
TextSelectionPopupCallbackInterface& mTextSelectionPopupCallbackInterface;
- std::string mHandleImages[HANDLE_TYPE_COUNT][HANDLE_IMAGE_TYPE_COUNT];
- Vector4 mHandleColor;
-
- CursorImpl mCursor[CURSOR_COUNT];
- HandleImpl mHandle[HANDLE_TYPE_COUNT];
-
- VertexBuffer mQuadVertices;
- Geometry mQuadGeometry;
- QuadContainer mHighlightQuadList; ///< Sub-selections that combine to create the complete selection highlight.
-
- Vector4 mBoundingBox; ///< The bounding box in world coords.
- Vector4 mHighlightColor; ///< Color of the highlight
- Vector2 mHighlightPosition; ///< The position of the highlight actor.
- Size mHighlightSize; ///< The size of the highlighted text.
- Size mControlSize; ///< The control's size. Set by the Relayout.
- float mHighlightOutlineOffset; ///< The outline's offset.
-
- unsigned int mActiveCursor;
- unsigned int mCursorBlinkInterval;
- float mCursorBlinkDuration;
- float mCursorWidth; ///< The width of the cursors in pixels.
- HandleType mHandleScrolling; ///< The handle which is scrolling.
- HandleType mHandleReleased; ///< The last handle released.
- ScrollDirection mScrollDirection; ///< The direction of the scroll.
- float mScrollThreshold; ///< Defines a square area inside the control, close to the edge. A cursor entering this area will trigger scroll events.
- float mScrollSpeed; ///< The scroll speed in pixels per second.
- float mScrollDistance; ///< Distance the text scrolls during a scroll interval.
- int mTextDepth; ///< The depth used to render the text.
-
- bool mActiveCopyPastePopup : 1;
- bool mPopupSetNewPosition : 1;
- bool mCursorBlinkStatus : 1; ///< Flag to switch between blink on and blink off.
- bool mDelayCursorBlink : 1; ///< Used to avoid cursor blinking when entering text.
- bool mPrimaryCursorVisible : 1; ///< Whether the primary cursor is visible.
- bool mSecondaryCursorVisible : 1; ///< Whether the secondary cursor is visible.
- bool mFlipSelectionHandlesOnCross : 1; ///< Whether to flip the selection handles as soon as they cross.
- bool mFlipLeftSelectionHandleDirection : 1; ///< Whether to flip the left selection handle image because of the character's direction.
- bool mFlipRightSelectionHandleDirection : 1; ///< Whether to flip the right selection handle image because of the character's direction.
- bool mIsHandlePanning : 1; ///< Whether any of the handles is moving.
- bool mIsHandleCurrentlyCrossed : 1; ///< Whether the handles are crossed.
- bool mIsHandlePreviouslyCrossed : 1; ///< Whether the handles where crossed at the last handle touch up.
- bool mNotifyEndOfScroll : 1; ///< Whether to notify the end of the scroll.
- bool mHorizontalScrollingEnabled : 1; ///< Whether the horizontal scrolling is enabled.
- bool mVerticalScrollingEnabled : 1; ///< Whether the vertical scrolling is enabled.
- bool mSmoothHandlePanEnabled : 1; ///< Whether to pan smoothly the handles.
- bool mIsHighlightBoxActive : 1; ///< Whether the highlight box is active.
- bool mHidePrimaryCursorAndGrabHandle : 1; ///< Whether the primary cursor and grab are hidden always.
+ std::string mHandleImages[HANDLE_TYPE_COUNT][HANDLE_IMAGE_TYPE_COUNT];
+ Vector4 mHandleColor;
+
+ CursorImpl mCursor[CURSOR_COUNT];
+ HandleImpl mHandle[HANDLE_TYPE_COUNT];
+
+ VertexBuffer mQuadVertices;
+ Geometry mQuadGeometry;
+ QuadContainer mHighlightQuadList; ///< Sub-selections that combine to create the complete selection highlight.
+
+ Vector4 mBoundingBox; ///< The bounding box in world coords.
+ Vector4 mHighlightColor; ///< Color of the highlight
+ Vector2 mHighlightPosition; ///< The position of the highlight actor.
+ Size mHighlightSize; ///< The size of the highlighted text.
+ Size mControlSize; ///< The control's size. Set by the Relayout.
+ float mHighlightOutlineOffset; ///< The outline's offset.
+
+ unsigned int mActiveCursor;
+ unsigned int mCursorBlinkInterval;
+ float mCursorBlinkDuration;
+ float mCursorWidth; ///< The width of the cursors in pixels.
+ HandleType mHandleScrolling; ///< The handle which is scrolling.
+ HandleType mHandleReleased; ///< The last handle released.
+ ScrollDirection mScrollDirection; ///< The direction of the scroll.
+ float mScrollThreshold; ///< Defines a square area inside the control, close to the edge. A cursor entering this area will trigger scroll events.
+ float mScrollSpeed; ///< The scroll speed in pixels per second.
+ float mScrollDistance; ///< Distance the text scrolls during a scroll interval.
+ int mTextDepth; ///< The depth used to render the text.
+
+ bool mActiveCopyPastePopup : 1;
+ bool mPopupSetNewPosition : 1;
+ bool mCursorBlinkStatus : 1; ///< Flag to switch between blink on and blink off.
+ bool mDelayCursorBlink : 1; ///< Used to avoid cursor blinking when entering text.
+ bool mPrimaryCursorVisible : 1; ///< Whether the primary cursor is visible.
+ bool mSecondaryCursorVisible : 1; ///< Whether the secondary cursor is visible.
+ bool mFlipSelectionHandlesOnCross : 1; ///< Whether to flip the selection handles as soon as they cross.
+ bool mFlipLeftSelectionHandleDirection : 1; ///< Whether to flip the left selection handle image because of the character's direction.
+ bool mFlipRightSelectionHandleDirection : 1; ///< Whether to flip the right selection handle image because of the character's direction.
+ bool mIsHandlePanning : 1; ///< Whether any of the handles is moving.
+ bool mIsHandleCurrentlyCrossed : 1; ///< Whether the handles are crossed.
+ bool mIsHandlePreviouslyCrossed : 1; ///< Whether the handles where crossed at the last handle touch up.
+ bool mNotifyEndOfScroll : 1; ///< Whether to notify the end of the scroll.
+ bool mHorizontalScrollingEnabled : 1; ///< Whether the horizontal scrolling is enabled.
+ bool mVerticalScrollingEnabled : 1; ///< Whether the vertical scrolling is enabled.
+ bool mSmoothHandlePanEnabled : 1; ///< Whether to pan smoothly the handles.
+ bool mIsHighlightBoxActive : 1; ///< Whether the highlight box is active.
+ bool mHidePrimaryCursorAndGrabHandle : 1; ///< Whether the primary cursor and grab are hidden always.
};
-DecoratorPtr Decorator::New( ControllerInterface& controller,
- TextSelectionPopupCallbackInterface& callbackInterface )
+DecoratorPtr Decorator::New(ControllerInterface& controller,
+ TextSelectionPopupCallbackInterface& callbackInterface)
{
- return DecoratorPtr( new Decorator( controller,
- callbackInterface ) );
+ return DecoratorPtr(new Decorator(controller,
+ callbackInterface));
}
-void Decorator::SetBoundingBox( const Rect<int>& boundingBox )
+void Decorator::SetBoundingBox(const Rect<int>& boundingBox)
{
- LocalToWorldCoordinatesBoundingBox( boundingBox, mImpl->mBoundingBox );
+ LocalToWorldCoordinatesBoundingBox(boundingBox, mImpl->mBoundingBox);
}
-void Decorator::GetBoundingBox( Rect<int>& boundingBox ) const
+void Decorator::GetBoundingBox(Rect<int>& boundingBox) const
{
- WorldToLocalCoordinatesBoundingBox( mImpl->mBoundingBox, boundingBox );
+ WorldToLocalCoordinatesBoundingBox(mImpl->mBoundingBox, boundingBox);
}
-void Decorator::Relayout( const Vector2& size )
+void Decorator::Relayout(const Vector2& size)
{
- mImpl->Relayout( size );
+ mImpl->Relayout(size);
}
-void Decorator::UpdatePositions( const Vector2& scrollOffset )
+void Decorator::UpdatePositions(const Vector2& scrollOffset)
{
- mImpl->UpdatePositions( scrollOffset );
+ mImpl->UpdatePositions(scrollOffset);
}
/** Cursor **/
-void Decorator::SetActiveCursor( ActiveCursor activeCursor )
+void Decorator::SetActiveCursor(ActiveCursor activeCursor)
{
mImpl->mActiveCursor = activeCursor;
}
return mImpl->mActiveCursor;
}
-void Decorator::SetPosition( Cursor cursor, float x, float y, float cursorHeight, float lineHeight )
+void Decorator::SetPosition(Cursor cursor, float x, float y, float cursorHeight, float lineHeight)
{
Impl::CursorImpl& cursorImpl = mImpl->mCursor[cursor];
- cursorImpl.position.x = x;
- cursorImpl.position.y = y;
+ cursorImpl.position.x = x;
+ cursorImpl.position.y = y;
cursorImpl.cursorHeight = cursorHeight;
- cursorImpl.lineHeight = lineHeight;
+ cursorImpl.lineHeight = lineHeight;
}
-void Decorator::GetPosition( Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight ) const
+void Decorator::GetPosition(Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight) const
{
const Impl::CursorImpl& cursorImpl = mImpl->mCursor[cursor];
- x = cursorImpl.position.x;
- y = cursorImpl.position.y;
+ x = cursorImpl.position.x;
+ y = cursorImpl.position.y;
cursorHeight = cursorImpl.cursorHeight;
- lineHeight = cursorImpl.lineHeight;
+ lineHeight = cursorImpl.lineHeight;
}
-const Vector2& Decorator::GetPosition( Cursor cursor ) const
+const Vector2& Decorator::GetPosition(Cursor cursor) const
{
return mImpl->mCursor[cursor].position;
}
-void Decorator::SetGlyphOffset( Cursor cursor, float glyphOffset )
+void Decorator::SetGlyphOffset(Cursor cursor, float glyphOffset)
{
Impl::CursorImpl& cursorImpl = mImpl->mCursor[cursor];
cursorImpl.glyphOffset = glyphOffset;
}
-const float Decorator::GetGlyphOffset( Cursor cursor) const
+const float Decorator::GetGlyphOffset(Cursor cursor) const
{
return mImpl->mCursor[cursor].glyphOffset;
}
-void Decorator::SetCursorColor( Cursor cursor, const Dali::Vector4& color )
+void Decorator::SetCursorColor(Cursor cursor, const Dali::Vector4& color)
{
mImpl->mCursor[cursor].color = color;
}
-const Dali::Vector4& Decorator::GetColor( Cursor cursor ) const
+const Dali::Vector4& Decorator::GetColor(Cursor cursor) const
{
return mImpl->mCursor[cursor].color;
}
void Decorator::StartCursorBlink()
{
- if ( !mImpl->mCursorBlinkTimer )
+ if(!mImpl->mCursorBlinkTimer)
{
- mImpl->mCursorBlinkTimer = Timer::New( mImpl->mCursorBlinkInterval );
- mImpl->mCursorBlinkTimer.TickSignal().Connect( mImpl, &Decorator::Impl::OnCursorBlinkTimerTick );
+ mImpl->mCursorBlinkTimer = Timer::New(mImpl->mCursorBlinkInterval);
+ mImpl->mCursorBlinkTimer.TickSignal().Connect(mImpl, &Decorator::Impl::OnCursorBlinkTimerTick);
}
- if ( !mImpl->mCursorBlinkTimer.IsRunning() )
+ if(!mImpl->mCursorBlinkTimer.IsRunning())
{
mImpl->mCursorBlinkTimer.Start();
}
void Decorator::StopCursorBlink()
{
- if ( mImpl->mCursorBlinkTimer )
+ if(mImpl->mCursorBlinkTimer)
{
mImpl->mCursorBlinkTimer.Stop();
}
void Decorator::DelayCursorBlink()
{
mImpl->mCursorBlinkStatus = true; // Show cursor for a bit longer
- mImpl->mDelayCursorBlink = true;
+ mImpl->mDelayCursorBlink = true;
}
-void Decorator::SetCursorBlinkInterval( float seconds )
+void Decorator::SetCursorBlinkInterval(float seconds)
{
- mImpl->mCursorBlinkInterval = static_cast<unsigned int>( seconds * TO_MILLISECONDS ); // Convert to milliseconds
+ mImpl->mCursorBlinkInterval = static_cast<unsigned int>(seconds * TO_MILLISECONDS); // Convert to milliseconds
}
float Decorator::GetCursorBlinkInterval() const
{
- return static_cast<float>( mImpl->mCursorBlinkInterval ) * TO_SECONDS;
+ return static_cast<float>(mImpl->mCursorBlinkInterval) * TO_SECONDS;
}
-void Decorator::SetCursorBlinkDuration( float seconds )
+void Decorator::SetCursorBlinkDuration(float seconds)
{
mImpl->mCursorBlinkDuration = seconds;
}
return mImpl->mCursorBlinkDuration;
}
-void Decorator::SetCursorWidth( int width )
+void Decorator::SetCursorWidth(int width)
{
- mImpl->mCursorWidth = static_cast<float>( width );
+ mImpl->mCursorWidth = static_cast<float>(width);
}
int Decorator::GetCursorWidth() const
{
- return static_cast<int>( mImpl->mCursorWidth );
+ return static_cast<int>(mImpl->mCursorWidth);
}
-void Decorator::SetEditable( bool editable )
+void Decorator::SetEditable(bool editable)
{
mImpl->mHidePrimaryCursorAndGrabHandle = !editable;
- mImpl->Relayout( mImpl->mControlSize );
+ mImpl->Relayout(mImpl->mControlSize);
}
/** Handles **/
-void Decorator::SetHandleActive( HandleType handleType, bool active )
+void Decorator::SetHandleActive(HandleType handleType, bool active)
{
mImpl->mHandle[handleType].active = active;
- if( !active )
+ if(!active)
{
- if( ( LEFT_SELECTION_HANDLE == handleType ) || ( RIGHT_SELECTION_HANDLE == handleType ) )
+ if((LEFT_SELECTION_HANDLE == handleType) || (RIGHT_SELECTION_HANDLE == handleType))
{
mImpl->mIsHandlePreviouslyCrossed = false;
}
// The problem is the handle actor does not receive the touch event with the Interrupt
// state when the power button is pressed and the application goes to background.
mImpl->mHandle[handleType].pressed = false;
- const bool imageReleased = mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED].size();
- ImageView imageView = mImpl->mHandle[handleType].actor;
- if( imageReleased && imageView )
+ const bool imageReleased = mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED].size();
+ ImageView imageView = mImpl->mHandle[handleType].actor;
+ if(imageReleased && imageView)
{
- imageView.SetImage( mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED] );
+ imageView.SetImage(mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED]);
}
}
-
}
-bool Decorator::IsHandleActive( HandleType handleType ) const
+bool Decorator::IsHandleActive(HandleType handleType) const
{
- return mImpl->mHandle[handleType].active ;
+ return mImpl->mHandle[handleType].active;
}
-void Decorator::SetHandleImage( HandleType handleType, HandleImageType handleImageType, const std::string& imageFileName )
+void Decorator::SetHandleImage(HandleType handleType, HandleImageType handleImageType, const std::string& imageFileName)
{
- mImpl->SetHandleImage( handleType, handleImageType, imageFileName );
+ mImpl->SetHandleImage(handleType, handleImageType, imageFileName);
}
-const std::string& Decorator::GetHandleImage( HandleType handleType, HandleImageType handleImageType ) const
+const std::string& Decorator::GetHandleImage(HandleType handleType, HandleImageType handleImageType) const
{
return mImpl->mHandleImages[handleType][handleImageType];
}
-void Decorator::SetHandleColor( const Vector4& color )
+void Decorator::SetHandleColor(const Vector4& color)
{
mImpl->mHandleColor = color;
}
return mImpl->mHandleColor;
}
-void Decorator::SetPosition( HandleType handleType, float x, float y, float height )
+void Decorator::SetPosition(HandleType handleType, float x, float y, float height)
{
// Adjust handle's displacement
Impl::HandleImpl& handle = mImpl->mHandle[handleType];
handle.position.y = y;
handle.lineHeight = height;
- if( mImpl->mSmoothHandlePanEnabled )
+ if(mImpl->mSmoothHandlePanEnabled)
{
handle.grabDisplacementX = 0.f;
handle.grabDisplacementY = 0.f;
}
}
-void Decorator::GetPosition( HandleType handleType, float& x, float& y, float& height ) const
+void Decorator::GetPosition(HandleType handleType, float& x, float& y, float& height) const
{
Impl::HandleImpl& handle = mImpl->mHandle[handleType];
- x = handle.position.x;
- y = handle.position.y;
+ x = handle.position.x;
+ y = handle.position.y;
height = handle.lineHeight;
}
-const Vector2& Decorator::GetPosition( HandleType handleType ) const
+const Vector2& Decorator::GetPosition(HandleType handleType) const
{
return mImpl->mHandle[handleType].position;
}
-void Decorator::FlipHandleVertically( HandleType handleType, bool flip )
+void Decorator::FlipHandleVertically(HandleType handleType, bool flip)
{
mImpl->mHandle[handleType].verticallyFlippedPreferred = flip;
}
-bool Decorator::IsHandleVerticallyFlipped( HandleType handleType ) const
+bool Decorator::IsHandleVerticallyFlipped(HandleType handleType) const
{
return mImpl->mHandle[handleType].verticallyFlippedPreferred;
}
-void Decorator::FlipSelectionHandlesOnCrossEnabled( bool enable )
+void Decorator::FlipSelectionHandlesOnCrossEnabled(bool enable)
{
mImpl->mFlipSelectionHandlesOnCross = enable;
}
-void Decorator::SetSelectionHandleFlipState( bool indicesSwapped, bool left, bool right )
+void Decorator::SetSelectionHandleFlipState(bool indicesSwapped, bool left, bool right)
{
- mImpl->mIsHandleCurrentlyCrossed = indicesSwapped;
- mImpl->mFlipLeftSelectionHandleDirection = left;
+ mImpl->mIsHandleCurrentlyCrossed = indicesSwapped;
+ mImpl->mFlipLeftSelectionHandleDirection = left;
mImpl->mFlipRightSelectionHandleDirection = right;
}
-void Decorator::AddHighlight( unsigned int index, const Vector4& quad )
+void Decorator::AddHighlight(unsigned int index, const Vector4& quad)
{
- *( mImpl->mHighlightQuadList.Begin() + index ) = quad;
+ *(mImpl->mHighlightQuadList.Begin() + index) = quad;
}
-void Decorator::SetHighLightBox( const Vector2& position, const Size& size, float outlineOffset )
+void Decorator::SetHighLightBox(const Vector2& position, const Size& size, float outlineOffset)
{
- mImpl->mHighlightPosition = position;
- mImpl->mHighlightSize = size;
+ mImpl->mHighlightPosition = position;
+ mImpl->mHighlightSize = size;
mImpl->mHighlightOutlineOffset = outlineOffset;
}
void Decorator::ClearHighlights()
{
mImpl->mHighlightQuadList.Clear();
- mImpl->mHighlightPosition = Vector2::ZERO;
+ mImpl->mHighlightPosition = Vector2::ZERO;
mImpl->mHighlightOutlineOffset = 0.f;
}
-void Decorator::ResizeHighlightQuads( unsigned int numberOfQuads )
+void Decorator::ResizeHighlightQuads(unsigned int numberOfQuads)
{
- mImpl->mHighlightQuadList.Resize( numberOfQuads );
+ mImpl->mHighlightQuadList.Resize(numberOfQuads);
}
-void Decorator::SetHighlightColor( const Vector4& color )
+void Decorator::SetHighlightColor(const Vector4& color)
{
mImpl->mHighlightColor = color;
}
return mImpl->mHighlightColor;
}
-void Decorator::SetHighlightActive( bool active )
+void Decorator::SetHighlightActive(bool active)
{
mImpl->mIsHighlightBoxActive = active;
}
bool Decorator::IsHighlightVisible() const
{
- return ( mImpl->mHighlightActor && mImpl->mHighlightActor.GetParent() );
+ return (mImpl->mHighlightActor && mImpl->mHighlightActor.GetParent());
}
-void Decorator::SetTextDepth( int textDepth )
+void Decorator::SetTextDepth(int textDepth)
{
mImpl->mTextDepth = textDepth;
}
-void Decorator::SetPopupActive( bool active )
+void Decorator::SetPopupActive(bool active)
{
mImpl->mActiveCopyPastePopup = active;
}
return mImpl->mActiveCopyPastePopup;
}
-void Decorator::SetEnabledPopupButtons( TextSelectionPopup::Buttons& enabledButtonsBitMask )
+void Decorator::SetEnabledPopupButtons(TextSelectionPopup::Buttons& enabledButtonsBitMask)
{
mImpl->mEnabledPopupButtons = enabledButtonsBitMask;
- if ( !mImpl->mCopyPastePopup.actor )
+ if(!mImpl->mCopyPastePopup.actor)
{
- mImpl->mCopyPastePopup.actor = TextSelectionPopup::New( &mImpl->mTextSelectionPopupCallbackInterface );
+ mImpl->mCopyPastePopup.actor = TextSelectionPopup::New(&mImpl->mTextSelectionPopupCallbackInterface);
#ifdef DECORATOR_DEBUG
- mImpl->mCopyPastePopup.actor.SetProperty( Dali::Actor::Property::NAME,"mCopyPastePopup");
+ mImpl->mCopyPastePopup.actor.SetProperty(Dali::Actor::Property::NAME, "mCopyPastePopup");
#endif
- mImpl->mCopyPastePopup.actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- mImpl->mCopyPastePopup.actor.OnRelayoutSignal().Connect( mImpl, &Decorator::Impl::SetPopupPosition ); // Position popup after size negotiation
+ mImpl->mCopyPastePopup.actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ mImpl->mCopyPastePopup.actor.OnRelayoutSignal().Connect(mImpl, &Decorator::Impl::SetPopupPosition); // Position popup after size negotiation
}
- mImpl->mCopyPastePopup.actor.EnableButtons( mImpl->mEnabledPopupButtons );
+ mImpl->mCopyPastePopup.actor.EnableButtons(mImpl->mEnabledPopupButtons);
}
TextSelectionPopup::Buttons& Decorator::GetEnabledPopupButtons()
/** Scroll **/
-void Decorator::SetScrollThreshold( float threshold )
+void Decorator::SetScrollThreshold(float threshold)
{
- mImpl->SetScrollThreshold( threshold );
+ mImpl->SetScrollThreshold(threshold);
}
float Decorator::GetScrollThreshold() const
return mImpl->GetScrollThreshold();
}
-void Decorator::SetScrollSpeed( float speed )
+void Decorator::SetScrollSpeed(float speed)
{
- mImpl->SetScrollSpeed( speed );
+ mImpl->SetScrollSpeed(speed);
}
float Decorator::GetScrollSpeed() const
mImpl->NotifyEndOfScroll();
}
-void Decorator::SetHorizontalScrollEnabled( bool enable )
+void Decorator::SetHorizontalScrollEnabled(bool enable)
{
mImpl->mHorizontalScrollingEnabled = enable;
}
return mImpl->mHorizontalScrollingEnabled;
}
-void Decorator::SetVerticalScrollEnabled( bool enable )
+void Decorator::SetVerticalScrollEnabled(bool enable)
{
mImpl->mVerticalScrollingEnabled = enable;
}
return mImpl->mVerticalScrollingEnabled;
}
-void Decorator::SetSmoothHandlePanEnabled( bool enable )
+void Decorator::SetSmoothHandlePanEnabled(bool enable)
{
mImpl->mSmoothHandlePanEnabled = enable;
}
delete mImpl;
}
-Decorator::Decorator( ControllerInterface& controller,
- TextSelectionPopupCallbackInterface& callbackInterface )
-: mImpl( NULL )
+Decorator::Decorator(ControllerInterface& controller,
+ TextSelectionPopupCallbackInterface& callbackInterface)
+: mImpl(NULL)
{
- mImpl = new Decorator::Impl( controller, callbackInterface );
+ mImpl = new Decorator::Impl(controller, callbackInterface);
}
} // namespace Text
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-Length GetNumberOfGlyphsOfGroup( GlyphIndex glyphIndex,
- GlyphIndex lastGlyphPlusOne,
- const Length* const charactersPerGlyphBuffer )
+Length GetNumberOfGlyphsOfGroup(GlyphIndex glyphIndex,
+ GlyphIndex lastGlyphPlusOne,
+ const Length* const charactersPerGlyphBuffer)
{
Length numberOfGLyphsInGroup = 1u;
- for( GlyphIndex index = glyphIndex; index < lastGlyphPlusOne; ++index )
+ for(GlyphIndex index = glyphIndex; index < lastGlyphPlusOne; ++index)
{
- if( 0u == *( charactersPerGlyphBuffer + index ) )
+ if(0u == *(charactersPerGlyphBuffer + index))
{
++numberOfGLyphsInGroup;
}
return numberOfGLyphsInGroup;
}
-void GetGlyphsMetrics( GlyphIndex glyphIndex,
- Length numberOfGlyphs,
- GlyphMetrics& glyphMetrics,
- const GlyphInfo* const glyphsBuffer,
- MetricsPtr& metrics )
+void GetGlyphsMetrics(GlyphIndex glyphIndex,
+ Length numberOfGlyphs,
+ GlyphMetrics& glyphMetrics,
+ const GlyphInfo* const glyphsBuffer,
+ MetricsPtr& metrics)
{
- const GlyphInfo& firstGlyph = *( glyphsBuffer + glyphIndex );
+ const GlyphInfo& firstGlyph = *(glyphsBuffer + glyphIndex);
Text::FontMetrics fontMetrics;
- if( 0u != firstGlyph.fontId )
+ if(0u != firstGlyph.fontId)
{
- metrics->GetFontMetrics( firstGlyph.fontId, fontMetrics );
+ metrics->GetFontMetrics(firstGlyph.fontId, fontMetrics);
}
- else if( 0u != firstGlyph.index )
+ else if(0u != firstGlyph.index)
{
// It may be an embedded image.
- fontMetrics.ascender = firstGlyph.height;
+ fontMetrics.ascender = firstGlyph.height;
fontMetrics.descender = 0.f;
- fontMetrics.height = fontMetrics.ascender;
+ fontMetrics.height = fontMetrics.ascender;
}
- const bool isItalicFont = metrics->HasItalicStyle( firstGlyph.fontId );
+ const bool isItalicFont = metrics->HasItalicStyle(firstGlyph.fontId);
- glyphMetrics.fontId = firstGlyph.fontId;
+ glyphMetrics.fontId = firstGlyph.fontId;
glyphMetrics.fontHeight = fontMetrics.height;
- glyphMetrics.width = firstGlyph.width;
- glyphMetrics.advance = firstGlyph.advance;
- glyphMetrics.ascender = fontMetrics.ascender;
- glyphMetrics.xBearing = firstGlyph.xBearing;
+ glyphMetrics.width = firstGlyph.width;
+ glyphMetrics.advance = firstGlyph.advance;
+ glyphMetrics.ascender = fontMetrics.ascender;
+ glyphMetrics.xBearing = firstGlyph.xBearing;
- if( 1u < numberOfGlyphs )
+ if(1u < numberOfGlyphs)
{
- float maxWidthEdge = firstGlyph.xBearing + firstGlyph.width;
+ float maxWidthEdge = firstGlyph.xBearing + firstGlyph.width;
- for( unsigned int i = 1u; i < numberOfGlyphs; ++i )
+ for(unsigned int i = 1u; i < numberOfGlyphs; ++i)
{
- const GlyphInfo& glyphInfo = *( glyphsBuffer + glyphIndex + i );
+ const GlyphInfo& glyphInfo = *(glyphsBuffer + glyphIndex + i);
// update the initial xBearing if smaller.
- glyphMetrics.xBearing = std::min( glyphMetrics.xBearing, glyphMetrics.advance + glyphInfo.xBearing );
+ glyphMetrics.xBearing = std::min(glyphMetrics.xBearing, glyphMetrics.advance + glyphInfo.xBearing);
// update the max width edge if bigger.
const float currentMaxGlyphWidthEdge = glyphMetrics.advance + glyphInfo.xBearing + glyphInfo.width;
- maxWidthEdge = std::max( maxWidthEdge, currentMaxGlyphWidthEdge );
+ maxWidthEdge = std::max(maxWidthEdge, currentMaxGlyphWidthEdge);
glyphMetrics.advance += glyphInfo.advance;
}
glyphMetrics.width = maxWidthEdge - glyphMetrics.xBearing;
}
- glyphMetrics.width += ( firstGlyph.isItalicRequired && !isItalicFont ) ? TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE * firstGlyph.height : 0.f;
+ glyphMetrics.width += (firstGlyph.isItalicRequired && !isItalicFont) ? TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE * firstGlyph.height : 0.f;
}
} // namespace Text
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
using namespace Dali::Toolkit;
-const uint32_t STAR = 0x2A; // Set default substitute character as '*'
-const int DEFAULT_SHOW_DURATION = 1000;
+const uint32_t STAR = 0x2A; // Set default substitute character as '*'
+const int DEFAULT_SHOW_DURATION = 1000;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-const char * const PROPERTY_MODE = "mode";
-const char * const PROPERTY_SUBSTITUTE_CHARACTER = "substituteCharacter";
-const char * const PROPERTY_SUBSTITUTE_COUNT = "substituteCount";
-const char * const PROPERTY_SHOW_DURATION = "showDuration";
-
-HiddenText::HiddenText( Observer* observer )
-: mObserver( observer ),
- mHideMode( static_cast< int >( Toolkit::HiddenInput::Mode::HIDE_NONE ) ),
- mSubstituteText( STAR ),
- mDisplayDuration( DEFAULT_SHOW_DURATION ),
- mSubstituteCount( 0 ),
- mPreviousTextCount( 0 )
+const char* const PROPERTY_MODE = "mode";
+const char* const PROPERTY_SUBSTITUTE_CHARACTER = "substituteCharacter";
+const char* const PROPERTY_SUBSTITUTE_COUNT = "substituteCount";
+const char* const PROPERTY_SHOW_DURATION = "showDuration";
+
+HiddenText::HiddenText(Observer* observer)
+: mObserver(observer),
+ mHideMode(static_cast<int>(Toolkit::HiddenInput::Mode::HIDE_NONE)),
+ mSubstituteText(STAR),
+ mDisplayDuration(DEFAULT_SHOW_DURATION),
+ mSubstituteCount(0),
+ mPreviousTextCount(0)
{
- mTimer = Timer::New( mDisplayDuration );
- mTimer.TickSignal().Connect( this, &HiddenText::OnTick );
+ mTimer = Timer::New(mDisplayDuration);
+ mTimer.TickSignal().Connect(this, &HiddenText::OnTick);
}
-void HiddenText::SetProperties( const Property::Map& map )
+void HiddenText::SetProperties(const Property::Map& map)
{
- const Property::Map::SizeType count = map.Count();
+ const Property::Map::SizeType count = map.Count();
- for ( Property::Map::SizeType position = 0; position < count; ++position )
- {
- KeyValuePair keyValue = map.GetKeyValue( position );
- Property::Key& key = keyValue.first;
- Property::Value& value = keyValue.second;
+ for(Property::Map::SizeType position = 0; position < count; ++position)
+ {
+ KeyValuePair keyValue = map.GetKeyValue(position);
+ Property::Key& key = keyValue.first;
+ Property::Value& value = keyValue.second;
- if( key == Toolkit::HiddenInput::Property::MODE || key == PROPERTY_MODE )
- {
- value.Get( mHideMode );
- }
- else if( key == Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER || key == PROPERTY_SUBSTITUTE_CHARACTER )
- {
- value.Get( mSubstituteText );
- }
- else if( key == Toolkit::HiddenInput::Property::SUBSTITUTE_COUNT || key == PROPERTY_SUBSTITUTE_COUNT )
- {
- value.Get( mSubstituteCount );
- }
- else if( key == Toolkit::HiddenInput::Property::SHOW_LAST_CHARACTER_DURATION || key == PROPERTY_SHOW_DURATION )
- {
- value.Get( mDisplayDuration );
- }
+ if(key == Toolkit::HiddenInput::Property::MODE || key == PROPERTY_MODE)
+ {
+ value.Get(mHideMode);
+ }
+ else if(key == Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER || key == PROPERTY_SUBSTITUTE_CHARACTER)
+ {
+ value.Get(mSubstituteText);
}
+ else if(key == Toolkit::HiddenInput::Property::SUBSTITUTE_COUNT || key == PROPERTY_SUBSTITUTE_COUNT)
+ {
+ value.Get(mSubstituteCount);
+ }
+ else if(key == Toolkit::HiddenInput::Property::SHOW_LAST_CHARACTER_DURATION || key == PROPERTY_SHOW_DURATION)
+ {
+ value.Get(mDisplayDuration);
+ }
+ }
}
-void HiddenText::GetProperties( Property::Map& map )
+void HiddenText::GetProperties(Property::Map& map)
{
- map[Toolkit::HiddenInput::Property::MODE] = mHideMode;
- map[Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER] = mSubstituteText;
- map[Toolkit::HiddenInput::Property::SUBSTITUTE_COUNT] = mSubstituteCount;
+ map[Toolkit::HiddenInput::Property::MODE] = mHideMode;
+ map[Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER] = mSubstituteText;
+ map[Toolkit::HiddenInput::Property::SUBSTITUTE_COUNT] = mSubstituteCount;
map[Toolkit::HiddenInput::Property::SHOW_LAST_CHARACTER_DURATION] = mDisplayDuration;
}
-void HiddenText::Substitute( const Vector<Character>& source, Vector<Character>& destination )
+void HiddenText::Substitute(const Vector<Character>& source, Vector<Character>& destination)
{
const Length characterCount = source.Count();
- destination.Resize( characterCount );
+ destination.Resize(characterCount);
- uint32_t* begin = destination.Begin();
- uint32_t* end = begin + characterCount;
+ uint32_t* begin = destination.Begin();
+ uint32_t* end = begin + characterCount;
uint32_t* hideStart = NULL;
- uint32_t* hideEnd = NULL;
+ uint32_t* hideEnd = NULL;
uint32_t* sourcePos = source.Begin();
- switch ( mHideMode )
+ switch(mHideMode)
{
case Toolkit::HiddenInput::Mode::HIDE_NONE:
{
hideStart = NULL;
- hideEnd = NULL;
+ hideEnd = NULL;
break;
}
case Toolkit::HiddenInput::Mode::HIDE_ALL:
{
hideStart = begin;
- hideEnd = end;
+ hideEnd = end;
break;
}
case Toolkit::HiddenInput::Mode::HIDE_COUNT:
{
hideStart = begin;
- hideEnd = begin + mSubstituteCount;
+ hideEnd = begin + mSubstituteCount;
break;
}
case Toolkit::HiddenInput::Mode::SHOW_COUNT:
{
hideStart = begin + mSubstituteCount;
- hideEnd = end;
+ hideEnd = end;
break;
}
case Toolkit::HiddenInput::Mode::SHOW_LAST_CHARACTER:
{
- if (mPreviousTextCount < characterCount)
+ if(mPreviousTextCount < characterCount)
{
hideStart = begin;
- hideEnd = end-1;
- if ( mDisplayDuration > 0 )
+ hideEnd = end - 1;
+ if(mDisplayDuration > 0)
{
- mTimer.SetInterval( mDisplayDuration );
+ mTimer.SetInterval(mDisplayDuration);
mTimer.Start();
}
else
else
{
hideStart = begin;
- hideEnd = end;
+ hideEnd = end;
}
break;
}
}
- for (; begin < end; ++begin )
+ for(; begin < end; ++begin)
{
- if (begin >= hideStart && begin < hideEnd)
+ if(begin >= hideStart && begin < hideEnd)
{
*begin = static_cast<uint32_t>(mSubstituteText);
sourcePos++;
bool HiddenText::OnTick()
{
- if( mObserver != NULL )
+ if(mObserver != NULL)
{
mObserver->DisplayTimeExpired();
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/layouts/layout-engine.h>
// EXTERNAL INCLUDES
-#include <limits>
-#include <cmath>
-#include <dali/integration-api/debug.h>
#include <dali/devel-api/text-abstraction/font-client.h>
+#include <dali/integration-api/debug.h>
+#include <cmath>
+#include <limits>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/bidirectional-support.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace Layout
{
-
namespace
{
-
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_LAYOUT");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_LAYOUT");
#endif
-const float MAX_FLOAT = std::numeric_limits<float>::max();
-const CharacterDirection LTR = false;
-const CharacterDirection RTL = !LTR;
-const float LINE_SPACING = 0.f;
-const float MIN_LINE_SIZE = 0.f;
+const float MAX_FLOAT = std::numeric_limits<float>::max();
+const CharacterDirection LTR = false;
+const CharacterDirection RTL = !LTR;
+const float LINE_SPACING = 0.f;
+const float MIN_LINE_SIZE = 0.f;
-inline bool isEmptyLineAtLast( const Vector<LineRun>& lines, const Vector<LineRun>::Iterator& line )
+inline bool isEmptyLineAtLast(const Vector<LineRun>& lines, const Vector<LineRun>::Iterator& line)
{
- return ( (*line).characterRun.numberOfCharacters == 0 && line + 1u == lines.End() );
+ return ((*line).characterRun.numberOfCharacters == 0 && line + 1u == lines.End());
}
} //namespace
struct LineLayout
{
LineLayout()
- : glyphIndex{ 0u },
- characterIndex{ 0u },
- numberOfGlyphs{ 0u },
- numberOfCharacters{ 0u },
- ascender{ -MAX_FLOAT },
- descender{ MAX_FLOAT },
- lineSpacing{ 0.f },
- penX{ 0.f },
- previousAdvance{ 0.f },
- length{ 0.f },
- whiteSpaceLengthEndOfLine{ 0.f },
- direction{ LTR }
- {}
+ : glyphIndex{0u},
+ characterIndex{0u},
+ numberOfGlyphs{0u},
+ numberOfCharacters{0u},
+ ascender{-MAX_FLOAT},
+ descender{MAX_FLOAT},
+ lineSpacing{0.f},
+ penX{0.f},
+ previousAdvance{0.f},
+ length{0.f},
+ whiteSpaceLengthEndOfLine{0.f},
+ direction{LTR}
+ {
+ }
~LineLayout()
- {}
+ {
+ }
void Clear()
{
- glyphIndex = 0u;
- characterIndex = 0u;
- numberOfGlyphs = 0u;
+ glyphIndex = 0u;
+ characterIndex = 0u;
+ numberOfGlyphs = 0u;
numberOfCharacters = 0u;
- ascender = -MAX_FLOAT;
- descender = MAX_FLOAT;
- direction = LTR;
+ ascender = -MAX_FLOAT;
+ descender = MAX_FLOAT;
+ direction = LTR;
}
GlyphIndex glyphIndex; ///< Index of the first glyph to be laid-out.
{
paragraphDirection = LTR;
bidiParagraphIndex = 0u;
- bidiLineIndex = 0u;
- isBidirectional = false;
+ bidiLineIndex = 0u;
+ isBidirectional = false;
}
- CharacterDirection paragraphDirection = LTR; ///< The paragraph's direction.
- BidirectionalRunIndex bidiParagraphIndex = 0u; ///< Index to the paragraph's bidi info.
- BidirectionalLineRunIndex bidiLineIndex = 0u; ///< Index where to insert the next bidi line info.
- bool isBidirectional = false; ///< Whether the text is bidirectional.
+ CharacterDirection paragraphDirection = LTR; ///< The paragraph's direction.
+ BidirectionalRunIndex bidiParagraphIndex = 0u; ///< Index to the paragraph's bidi info.
+ BidirectionalLineRunIndex bidiLineIndex = 0u; ///< Index where to insert the next bidi line info.
+ bool isBidirectional = false; ///< Whether the text is bidirectional.
};
struct Engine::Impl
{
Impl()
- : mLayout{ Layout::Engine::SINGLE_LINE_BOX },
- mCursorWidth{ 0.f },
- mDefaultLineSpacing{ LINE_SPACING },
- mDefaultLineSize{ MIN_LINE_SIZE }
+ : mLayout{Layout::Engine::SINGLE_LINE_BOX},
+ mCursorWidth{0.f},
+ mDefaultLineSpacing{LINE_SPACING},
+ mDefaultLineSize{MIN_LINE_SIZE}
{
}
* @param[in] glyphMetrics The metrics of the new font.
* @param[in,out] lineLayout The line layout.
*/
- void UpdateLineHeight( const GlyphMetrics& glyphMetrics, LineLayout& lineLayout )
+ void UpdateLineHeight(const GlyphMetrics& glyphMetrics, LineLayout& lineLayout)
{
Text::FontMetrics fontMetrics;
- if( 0u != glyphMetrics.fontId )
+ if(0u != glyphMetrics.fontId)
{
- mMetrics->GetFontMetrics( glyphMetrics.fontId, fontMetrics );
+ mMetrics->GetFontMetrics(glyphMetrics.fontId, fontMetrics);
}
else
{
- fontMetrics.ascender = glyphMetrics.fontHeight;
- fontMetrics.descender = 0.f;
- fontMetrics.height = fontMetrics.ascender;
- fontMetrics.underlinePosition = 0.f;
+ fontMetrics.ascender = glyphMetrics.fontHeight;
+ fontMetrics.descender = 0.f;
+ fontMetrics.height = fontMetrics.ascender;
+ fontMetrics.underlinePosition = 0.f;
fontMetrics.underlineThickness = 1.f;
}
// Sets the maximum ascender.
- lineLayout.ascender = std::max( lineLayout.ascender, fontMetrics.ascender );
+ lineLayout.ascender = std::max(lineLayout.ascender, fontMetrics.ascender);
// Sets the minimum descender.
- lineLayout.descender = std::min( lineLayout.descender, fontMetrics.descender );
+ lineLayout.descender = std::min(lineLayout.descender, fontMetrics.descender);
// Sets the line size
- lineLayout.lineSpacing = mDefaultLineSize - ( lineLayout.ascender + -lineLayout.descender );
+ lineLayout.lineSpacing = mDefaultLineSize - (lineLayout.ascender + -lineLayout.descender);
lineLayout.lineSpacing = lineLayout.lineSpacing < 0.f ? 0.f : lineLayout.lineSpacing;
// Add the line spacing
* @param[in,out] lineLayout The line layout.
* @param[in] tmpLineLayout A temporary line layout.
*/
- void MergeLineLayout( LineLayout& lineLayout,
- const LineLayout& tmpLineLayout )
+ void MergeLineLayout(LineLayout& lineLayout,
+ const LineLayout& tmpLineLayout)
{
lineLayout.numberOfCharacters += tmpLineLayout.numberOfCharacters;
lineLayout.numberOfGlyphs += tmpLineLayout.numberOfGlyphs;
- lineLayout.penX = tmpLineLayout.penX;
+ lineLayout.penX = tmpLineLayout.penX;
lineLayout.previousAdvance = tmpLineLayout.previousAdvance;
- lineLayout.length = tmpLineLayout.length;
+ lineLayout.length = tmpLineLayout.length;
lineLayout.whiteSpaceLengthEndOfLine = tmpLineLayout.whiteSpaceLengthEndOfLine;
// Sets the maximum ascender.
- lineLayout.ascender = std::max( lineLayout.ascender, tmpLineLayout.ascender );
+ lineLayout.ascender = std::max(lineLayout.ascender, tmpLineLayout.ascender);
// Sets the minimum descender.
- lineLayout.descender = std::min( lineLayout.descender, tmpLineLayout.descender );
+ lineLayout.descender = std::min(lineLayout.descender, tmpLineLayout.descender);
}
- void LayoutRightToLeft( const Parameters& parameters,
- const BidirectionalLineInfoRun& bidirectionalLineInfo,
- float& length,
- float& whiteSpaceLengthEndOfLine )
+ void LayoutRightToLeft(const Parameters& parameters,
+ const BidirectionalLineInfoRun& bidirectionalLineInfo,
+ float& length,
+ float& whiteSpaceLengthEndOfLine)
{
- const Character* const textBuffer = parameters.textModel->mLogicalModel->mText.Begin();
- const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin();
- const GlyphInfo* const glyphsBuffer = parameters.textModel->mVisualModel->mGlyphs.Begin();
+ const Character* const textBuffer = parameters.textModel->mLogicalModel->mText.Begin();
+ const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin();
+ const GlyphInfo* const glyphsBuffer = parameters.textModel->mVisualModel->mGlyphs.Begin();
const GlyphIndex* const charactersToGlyphsBuffer = parameters.textModel->mVisualModel->mCharactersToGlyph.Begin();
- const float outlineWidth = static_cast<float>( parameters.textModel->GetOutlineWidth() );
+ const float outlineWidth = static_cast<float>(parameters.textModel->GetOutlineWidth());
const GlyphIndex lastGlyphOfParagraphPlusOne = parameters.startGlyphIndex + parameters.numberOfGlyphs;
CharacterIndex characterLogicalIndex = 0u;
- CharacterIndex characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *( bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex );
+ CharacterIndex characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *(bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex);
- if( RTL == bidirectionalLineInfo.direction )
+ if(RTL == bidirectionalLineInfo.direction)
{
- while( TextAbstraction::IsWhiteSpace( *( textBuffer + characterVisualIndex ) ) )
+ while(TextAbstraction::IsWhiteSpace(*(textBuffer + characterVisualIndex)))
{
- const GlyphInfo& glyphInfo = *( glyphsBuffer + *( charactersToGlyphsBuffer + characterVisualIndex ) );
+ const GlyphInfo& glyphInfo = *(glyphsBuffer + *(charactersToGlyphsBuffer + characterVisualIndex));
whiteSpaceLengthEndOfLine += glyphInfo.advance;
++characterLogicalIndex;
- characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *( bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex );
+ characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *(bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex);
}
}
- const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex );
+ const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex);
// Check whether the first glyph comes from a character that is shaped in multiple glyphs.
- const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( glyphIndex,
- lastGlyphOfParagraphPlusOne,
- charactersPerGlyphBuffer );
+ const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(glyphIndex,
+ lastGlyphOfParagraphPlusOne,
+ charactersPerGlyphBuffer);
GlyphMetrics glyphMetrics;
- GetGlyphsMetrics( glyphIndex,
- numberOfGLyphsInGroup,
- glyphMetrics,
- glyphsBuffer,
- mMetrics );
+ GetGlyphsMetrics(glyphIndex,
+ numberOfGLyphsInGroup,
+ glyphMetrics,
+ glyphsBuffer,
+ mMetrics);
float penX = -glyphMetrics.xBearing + mCursorWidth + outlineWidth;
// Traverses the characters of the right to left paragraph.
- for( ; characterLogicalIndex < bidirectionalLineInfo.characterRun.numberOfCharacters; )
+ for(; characterLogicalIndex < bidirectionalLineInfo.characterRun.numberOfCharacters;)
{
// Convert the character in the logical order into the character in the visual order.
- const CharacterIndex characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *( bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex );
- const bool isWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + characterVisualIndex ) );
+ const CharacterIndex characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *(bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex);
+ const bool isWhiteSpace = TextAbstraction::IsWhiteSpace(*(textBuffer + characterVisualIndex));
- const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex );
+ const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex);
// Check whether this glyph comes from a character that is shaped in multiple glyphs.
- const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( glyphIndex,
- lastGlyphOfParagraphPlusOne,
- charactersPerGlyphBuffer );
+ const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(glyphIndex,
+ lastGlyphOfParagraphPlusOne,
+ charactersPerGlyphBuffer);
- characterLogicalIndex += *( charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u );
+ characterLogicalIndex += *(charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u);
GlyphMetrics glyphMetrics;
- GetGlyphsMetrics( glyphIndex,
- numberOfGLyphsInGroup,
- glyphMetrics,
- glyphsBuffer,
- mMetrics );
+ GetGlyphsMetrics(glyphIndex,
+ numberOfGLyphsInGroup,
+ glyphMetrics,
+ glyphsBuffer,
+ mMetrics);
- if( isWhiteSpace )
+ if(isWhiteSpace)
{
- if( RTL == bidirectionalLineInfo.direction )
+ if(RTL == bidirectionalLineInfo.direction)
{
length += glyphMetrics.advance;
}
}
else
{
- if( LTR == bidirectionalLineInfo.direction )
+ if(LTR == bidirectionalLineInfo.direction)
{
whiteSpaceLengthEndOfLine = 0.f;
}
- length = std::max( length, penX + glyphMetrics.xBearing + glyphMetrics.width );
- penX += ( glyphMetrics.advance + parameters.interGlyphExtraAdvance );
+ length = std::max(length, penX + glyphMetrics.xBearing + glyphMetrics.width);
+ penX += (glyphMetrics.advance + parameters.interGlyphExtraAdvance);
}
}
}
- void ReorderBiDiLayout( const Parameters& parameters,
- LayoutBidiParameters& bidiParameters,
- const LineLayout& currentLineLayout,
- LineLayout& lineLayout,
- bool breakInCharacters )
+ void ReorderBiDiLayout(const Parameters& parameters,
+ LayoutBidiParameters& bidiParameters,
+ const LineLayout& currentLineLayout,
+ LineLayout& lineLayout,
+ bool breakInCharacters)
{
const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin();
const Vector<BidirectionalParagraphInfoRun>& bidirectionalParagraphsInfo = parameters.textModel->mLogicalModel->mBidirectionalParagraphInfo;
const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo = bidirectionalParagraphsInfo[bidiParameters.bidiParagraphIndex];
- if( ( lineLayout.characterIndex >= bidirectionalParagraphInfo.characterRun.characterIndex ) &&
- ( lineLayout.characterIndex < bidirectionalParagraphInfo.characterRun.characterIndex + bidirectionalParagraphInfo.characterRun.numberOfCharacters ) )
+ if((lineLayout.characterIndex >= bidirectionalParagraphInfo.characterRun.characterIndex) &&
+ (lineLayout.characterIndex < bidirectionalParagraphInfo.characterRun.characterIndex + bidirectionalParagraphInfo.characterRun.numberOfCharacters))
{
Vector<BidirectionalLineInfoRun>& bidirectionalLinesInfo = parameters.textModel->mLogicalModel->mBidirectionalLineInfo;
// Sets the visual to logical map tables needed to reorder the text.
- ReorderLine( bidirectionalParagraphInfo,
- bidirectionalLinesInfo,
- bidiParameters.bidiLineIndex,
- lineLayout.characterIndex,
- lineLayout.numberOfCharacters,
- bidiParameters.paragraphDirection );
+ ReorderLine(bidirectionalParagraphInfo,
+ bidirectionalLinesInfo,
+ bidiParameters.bidiLineIndex,
+ lineLayout.characterIndex,
+ lineLayout.numberOfCharacters,
+ bidiParameters.paragraphDirection);
// Recalculate the length of the line and update the layout.
- const BidirectionalLineInfoRun& bidirectionalLineInfo = *( bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex );
+ const BidirectionalLineInfoRun& bidirectionalLineInfo = *(bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex);
- if( !bidirectionalLineInfo.isIdentity )
+ if(!bidirectionalLineInfo.isIdentity)
{
- float length = 0.f;
+ float length = 0.f;
float whiteSpaceLengthEndOfLine = 0.f;
- LayoutRightToLeft( parameters,
- bidirectionalLineInfo,
- length,
- whiteSpaceLengthEndOfLine );
+ LayoutRightToLeft(parameters,
+ bidirectionalLineInfo,
+ length,
+ whiteSpaceLengthEndOfLine);
lineLayout.whiteSpaceLengthEndOfLine = whiteSpaceLengthEndOfLine;
- if( !Equals( length, lineLayout.length ) )
+ if(!Equals(length, lineLayout.length))
{
const bool isMultiline = mLayout == MULTI_LINE_BOX;
- if( isMultiline && ( length > parameters.boundingBox.width ) )
+ if(isMultiline && (length > parameters.boundingBox.width))
{
- if( breakInCharacters || ( isMultiline && ( 0u == currentLineLayout.numberOfGlyphs ) ) )
+ if(breakInCharacters || (isMultiline && (0u == currentLineLayout.numberOfGlyphs)))
{
// The word doesn't fit in one line. It has to be split by character.
// Remove the last laid out glyph(s) as they doesn't fit.
- for( GlyphIndex glyphIndex = lineLayout.glyphIndex + lineLayout.numberOfGlyphs - 1u; glyphIndex >= lineLayout.glyphIndex; )
+ for(GlyphIndex glyphIndex = lineLayout.glyphIndex + lineLayout.numberOfGlyphs - 1u; glyphIndex >= lineLayout.glyphIndex;)
{
- const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( glyphIndex,
- lastGlyphOfParagraphPlusOne,
- charactersPerGlyphBuffer );
+ const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(glyphIndex,
+ lastGlyphOfParagraphPlusOne,
+ charactersPerGlyphBuffer);
- const Length numberOfCharacters = *( charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u );
+ const Length numberOfCharacters = *(charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u);
lineLayout.numberOfGlyphs -= numberOfGLyphsInGroup;
lineLayout.numberOfCharacters -= numberOfCharacters;
- AdjustLayout( parameters,
- bidiParameters,
- bidirectionalParagraphInfo,
- lineLayout );
+ AdjustLayout(parameters,
+ bidiParameters,
+ bidirectionalParagraphInfo,
+ lineLayout);
- if( lineLayout.length < parameters.boundingBox.width )
+ if(lineLayout.length < parameters.boundingBox.width)
{
break;
}
- if( glyphIndex < numberOfGLyphsInGroup )
+ if(glyphIndex < numberOfGLyphsInGroup)
{
// avoids go under zero for an unsigned int.
break;
}
else
{
- lineLayout = currentLineLayout;
+ lineLayout = currentLineLayout;
- AdjustLayout( parameters,
- bidiParameters,
- bidirectionalParagraphInfo,
- lineLayout );
+ AdjustLayout(parameters,
+ bidiParameters,
+ bidirectionalParagraphInfo,
+ lineLayout);
}
}
else
{
- lineLayout.length = std::max( length, lineLayout.length );
+ lineLayout.length = std::max(length, lineLayout.length);
}
}
}
}
}
- void AdjustLayout( const Parameters& parameters,
- LayoutBidiParameters& bidiParameters,
- const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo,
- LineLayout& lineLayout )
+ void AdjustLayout(const Parameters& parameters,
+ LayoutBidiParameters& bidiParameters,
+ const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo,
+ LineLayout& lineLayout)
{
Vector<BidirectionalLineInfoRun>& bidirectionalLinesInfo = parameters.textModel->mLogicalModel->mBidirectionalLineInfo;
// Remove current reordered line.
- bidirectionalLinesInfo.Erase( bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex );
+ bidirectionalLinesInfo.Erase(bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex);
// Re-build the conversion table without the removed glyphs.
- ReorderLine( bidirectionalParagraphInfo,
- bidirectionalLinesInfo,
- bidiParameters.bidiLineIndex,
- lineLayout.characterIndex,
- lineLayout.numberOfCharacters,
- bidiParameters.paragraphDirection );
+ ReorderLine(bidirectionalParagraphInfo,
+ bidirectionalLinesInfo,
+ bidiParameters.bidiLineIndex,
+ lineLayout.characterIndex,
+ lineLayout.numberOfCharacters,
+ bidiParameters.paragraphDirection);
- const BidirectionalLineInfoRun& bidirectionalLineInfo = *( bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex );
+ const BidirectionalLineInfoRun& bidirectionalLineInfo = *(bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex);
- float length = 0.f;
+ float length = 0.f;
float whiteSpaceLengthEndOfLine = 0.f;
- LayoutRightToLeft( parameters,
- bidirectionalLineInfo,
- length,
- whiteSpaceLengthEndOfLine );
+ LayoutRightToLeft(parameters,
+ bidirectionalLineInfo,
+ length,
+ whiteSpaceLengthEndOfLine);
- lineLayout.length = length;
+ lineLayout.length = length;
lineLayout.whiteSpaceLengthEndOfLine = whiteSpaceLengthEndOfLine;
}
* @param[out] lineLayout The line layout.
* @param[in] completelyFill Whether to completely fill the line ( even if the last word exceeds the boundaries ).
*/
- void GetLineLayoutForBox( const Parameters& parameters,
- LayoutBidiParameters& bidiParameters,
- LineLayout& lineLayout,
- bool completelyFill )
+ void GetLineLayoutForBox(const Parameters& parameters,
+ LayoutBidiParameters& bidiParameters,
+ LineLayout& lineLayout,
+ bool completelyFill)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->GetLineLayoutForBox\n" );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " initial glyph index : %d\n", lineLayout.glyphIndex );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->GetLineLayoutForBox\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " initial glyph index : %d\n", lineLayout.glyphIndex);
- const Character* const textBuffer = parameters.textModel->mLogicalModel->mText.Begin();
- const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin();
- const GlyphInfo* const glyphsBuffer = parameters.textModel->mVisualModel->mGlyphs.Begin();
+ const Character* const textBuffer = parameters.textModel->mLogicalModel->mText.Begin();
+ const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin();
+ const GlyphInfo* const glyphsBuffer = parameters.textModel->mVisualModel->mGlyphs.Begin();
const CharacterIndex* const glyphsToCharactersBuffer = parameters.textModel->mVisualModel->mGlyphsToCharacters.Begin();
- const LineBreakInfo* const lineBreakInfoBuffer = parameters.textModel->mLogicalModel->mLineBreakInfo.Begin();
+ const LineBreakInfo* const lineBreakInfoBuffer = parameters.textModel->mLogicalModel->mLineBreakInfo.Begin();
- const float outlineWidth = static_cast<float>( parameters.textModel->GetOutlineWidth() );
+ const float outlineWidth = static_cast<float>(parameters.textModel->GetOutlineWidth());
const Length totalNumberOfGlyphs = parameters.textModel->mVisualModel->mGlyphs.Count();
- const bool isMultiline = mLayout == MULTI_LINE_BOX;
+ const bool isMultiline = mLayout == MULTI_LINE_BOX;
const bool isWordLaidOut = parameters.textModel->mLineWrapMode == Text::LineWrap::WORD;
// The last glyph to be laid-out.
// the difference needs to be added to the line length.
// Check whether the first glyph comes from a character that is shaped in multiple glyphs.
- const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( lineLayout.glyphIndex,
- lastGlyphOfParagraphPlusOne,
- charactersPerGlyphBuffer );
+ const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(lineLayout.glyphIndex,
+ lastGlyphOfParagraphPlusOne,
+ charactersPerGlyphBuffer);
GlyphMetrics glyphMetrics;
- GetGlyphsMetrics( lineLayout.glyphIndex,
- numberOfGLyphsInGroup,
- glyphMetrics,
- glyphsBuffer,
- mMetrics );
+ GetGlyphsMetrics(lineLayout.glyphIndex,
+ numberOfGLyphsInGroup,
+ glyphMetrics,
+ glyphsBuffer,
+ mMetrics);
// Set the direction of the first character of the line.
- lineLayout.characterIndex = *( glyphsToCharactersBuffer + lineLayout.glyphIndex );
+ lineLayout.characterIndex = *(glyphsToCharactersBuffer + lineLayout.glyphIndex);
// Stores temporary line layout which has not been added to the final line layout.
LineLayout tmpLineLayout;
// Calculate the line height if there is no characters.
FontId lastFontId = glyphMetrics.fontId;
- UpdateLineHeight( glyphMetrics, tmpLineLayout );
+ UpdateLineHeight(glyphMetrics, tmpLineLayout);
bool oneWordLaidOut = false;
- for( GlyphIndex glyphIndex = lineLayout.glyphIndex;
- glyphIndex < lastGlyphOfParagraphPlusOne; )
+ for(GlyphIndex glyphIndex = lineLayout.glyphIndex;
+ glyphIndex < lastGlyphOfParagraphPlusOne;)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " glyph index : %d\n", glyphIndex );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " glyph index : %d\n", glyphIndex);
// Check whether this glyph comes from a character that is shaped in multiple glyphs.
- const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( glyphIndex,
- lastGlyphOfParagraphPlusOne,
- charactersPerGlyphBuffer );
+ const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(glyphIndex,
+ lastGlyphOfParagraphPlusOne,
+ charactersPerGlyphBuffer);
GlyphMetrics glyphMetrics;
- GetGlyphsMetrics( glyphIndex,
- numberOfGLyphsInGroup,
- glyphMetrics,
- glyphsBuffer,
- mMetrics );
+ GetGlyphsMetrics(glyphIndex,
+ numberOfGLyphsInGroup,
+ glyphMetrics,
+ glyphsBuffer,
+ mMetrics);
- const bool isLastGlyph = glyphIndex + numberOfGLyphsInGroup == totalNumberOfGlyphs;
+ const bool isLastGlyph = glyphIndex + numberOfGLyphsInGroup == totalNumberOfGlyphs;
// Check if the font of the current glyph is the same of the previous one.
// If it's different the ascender and descender need to be updated.
- if( lastFontId != glyphMetrics.fontId )
+ if(lastFontId != glyphMetrics.fontId)
{
- UpdateLineHeight( glyphMetrics, tmpLineLayout );
+ UpdateLineHeight(glyphMetrics, tmpLineLayout);
lastFontId = glyphMetrics.fontId;
}
// Get the character indices for the current glyph. The last character index is needed
// because there are glyphs formed by more than one character but their break info is
// given only for the last character.
- const Length charactersPerGlyph = *( charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u );
- const bool hasCharacters = charactersPerGlyph > 0u;
- const CharacterIndex characterFirstIndex = *( glyphsToCharactersBuffer + glyphIndex );
- const CharacterIndex characterLastIndex = characterFirstIndex + ( hasCharacters ? charactersPerGlyph - 1u : 0u );
+ const Length charactersPerGlyph = *(charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u);
+ const bool hasCharacters = charactersPerGlyph > 0u;
+ const CharacterIndex characterFirstIndex = *(glyphsToCharactersBuffer + glyphIndex);
+ const CharacterIndex characterLastIndex = characterFirstIndex + (hasCharacters ? charactersPerGlyph - 1u : 0u);
// Get the line break info for the current character.
- const LineBreakInfo lineBreakInfo = hasCharacters ? *( lineBreakInfoBuffer + characterLastIndex ) : TextAbstraction::LINE_NO_BREAK;
+ const LineBreakInfo lineBreakInfo = hasCharacters ? *(lineBreakInfoBuffer + characterLastIndex) : TextAbstraction::LINE_NO_BREAK;
// Increase the number of characters.
tmpLineLayout.numberOfCharacters += charactersPerGlyph;
tmpLineLayout.numberOfGlyphs += numberOfGLyphsInGroup;
// Check whether is a white space.
- const Character character = *( textBuffer + characterFirstIndex );
- const bool isWhiteSpace = TextAbstraction::IsWhiteSpace( character );
+ const Character character = *(textBuffer + characterFirstIndex);
+ const bool isWhiteSpace = TextAbstraction::IsWhiteSpace(character);
// Calculate the length of the line.
// Used to restore the temporal line layout when a single word does not fit in the control's width and is split by character.
- const float previousTmpPenX = tmpLineLayout.penX;
- const float previousTmpAdvance = tmpLineLayout.previousAdvance;
- const float previousTmpLength = tmpLineLayout.length;
+ const float previousTmpPenX = tmpLineLayout.penX;
+ const float previousTmpAdvance = tmpLineLayout.previousAdvance;
+ const float previousTmpLength = tmpLineLayout.length;
const float previousTmpWhiteSpaceLengthEndOfLine = tmpLineLayout.whiteSpaceLengthEndOfLine;
- if( isWhiteSpace )
+ if(isWhiteSpace)
{
// Add the length to the length of white spaces at the end of the line.
tmpLineLayout.whiteSpaceLengthEndOfLine += glyphMetrics.advance; // The advance is used as the width is always zero for the white spaces.
else
{
tmpLineLayout.penX += tmpLineLayout.previousAdvance + tmpLineLayout.whiteSpaceLengthEndOfLine;
- tmpLineLayout.previousAdvance = ( glyphMetrics.advance + parameters.interGlyphExtraAdvance );
+ tmpLineLayout.previousAdvance = (glyphMetrics.advance + parameters.interGlyphExtraAdvance);
- tmpLineLayout.length = std::max( tmpLineLayout.length, tmpLineLayout.penX + glyphMetrics.xBearing + glyphMetrics.width );
+ tmpLineLayout.length = std::max(tmpLineLayout.length, tmpLineLayout.penX + glyphMetrics.xBearing + glyphMetrics.width);
// Clear the white space length at the end of the line.
tmpLineLayout.whiteSpaceLengthEndOfLine = 0.f;
}
// Check if the accumulated length fits in the width of the box.
- if( ( completelyFill || isMultiline ) && !isWhiteSpace &&
- ( tmpLineLayout.length > parameters.boundingBox.width ) )
+ if((completelyFill || isMultiline) && !isWhiteSpace &&
+ (tmpLineLayout.length > parameters.boundingBox.width))
{
// Current word does not fit in the box's width.
- if( !oneWordLaidOut || completelyFill )
+ if(!oneWordLaidOut || completelyFill)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Break the word by character\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " Break the word by character\n");
// The word doesn't fit in the control's width. It needs to be split by character.
- if( tmpLineLayout.numberOfGlyphs > 0u )
+ if(tmpLineLayout.numberOfGlyphs > 0u)
{
tmpLineLayout.numberOfCharacters -= charactersPerGlyph;
tmpLineLayout.numberOfGlyphs -= numberOfGLyphsInGroup;
- tmpLineLayout.penX = previousTmpPenX;
- tmpLineLayout.previousAdvance = previousTmpAdvance;
- tmpLineLayout.length = previousTmpLength;
+ tmpLineLayout.penX = previousTmpPenX;
+ tmpLineLayout.previousAdvance = previousTmpAdvance;
+ tmpLineLayout.length = previousTmpLength;
tmpLineLayout.whiteSpaceLengthEndOfLine = previousTmpWhiteSpaceLengthEndOfLine;
}
// Add part of the word to the line layout.
- MergeLineLayout( lineLayout, tmpLineLayout );
+ MergeLineLayout(lineLayout, tmpLineLayout);
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Current word does not fit.\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " Current word does not fit.\n");
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox.\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox.\n");
// Reorder the RTL line.
- if( bidiParameters.isBidirectional )
+ if(bidiParameters.isBidirectional)
{
- ReorderBiDiLayout( parameters,
- bidiParameters,
- lineLayout,
- lineLayout,
- true );
+ ReorderBiDiLayout(parameters,
+ bidiParameters,
+ lineLayout,
+ lineLayout,
+ true);
}
return;
}
- if( ( isMultiline || isLastGlyph ) &&
- ( TextAbstraction::LINE_MUST_BREAK == lineBreakInfo ) )
+ if((isMultiline || isLastGlyph) &&
+ (TextAbstraction::LINE_MUST_BREAK == lineBreakInfo))
{
LineLayout currentLineLayout = lineLayout;
// Must break the line. Update the line layout and return.
- MergeLineLayout( lineLayout, tmpLineLayout );
+ MergeLineLayout(lineLayout, tmpLineLayout);
- // Reorder the RTL line.
- if( bidiParameters.isBidirectional )
+ // Reorder the RTL line.
+ if(bidiParameters.isBidirectional)
{
- ReorderBiDiLayout( parameters,
- bidiParameters,
- currentLineLayout,
- lineLayout,
- false );
+ ReorderBiDiLayout(parameters,
+ bidiParameters,
+ currentLineLayout,
+ lineLayout,
+ false);
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Must break\n" );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " Must break\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n");
return;
}
- if( isMultiline &&
- ( TextAbstraction::LINE_ALLOW_BREAK == lineBreakInfo ) )
+ if(isMultiline &&
+ (TextAbstraction::LINE_ALLOW_BREAK == lineBreakInfo))
{
oneWordLaidOut = isWordLaidOut;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " One word laid-out\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " One word laid-out\n");
// Current glyph is the last one of the current word.
// Add the temporal layout to the current one.
- MergeLineLayout( lineLayout, tmpLineLayout );
+ MergeLineLayout(lineLayout, tmpLineLayout);
tmpLineLayout.Clear();
}
glyphIndex += numberOfGLyphsInGroup;
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n");
}
- void SetGlyphPositions( const GlyphInfo* const glyphsBuffer,
- Length numberOfGlyphs,
- float outlineWidth,
- float interGlyphExtraAdvance,
- Vector2* glyphPositionsBuffer )
+ void SetGlyphPositions(const GlyphInfo* const glyphsBuffer,
+ Length numberOfGlyphs,
+ float outlineWidth,
+ float interGlyphExtraAdvance,
+ Vector2* glyphPositionsBuffer)
{
// Traverse the glyphs and set the positions.
// so the penX position needs to be moved to the right.
const GlyphInfo& glyph = *glyphsBuffer;
- float penX = -glyph.xBearing + mCursorWidth + outlineWidth;
+ float penX = -glyph.xBearing + mCursorWidth + outlineWidth;
- for( GlyphIndex i = 0u; i < numberOfGlyphs; ++i )
+ for(GlyphIndex i = 0u; i < numberOfGlyphs; ++i)
{
- const GlyphInfo& glyph = *( glyphsBuffer + i );
- Vector2& position = *( glyphPositionsBuffer + i );
+ const GlyphInfo& glyph = *(glyphsBuffer + i);
+ Vector2& position = *(glyphPositionsBuffer + i);
position.x = penX + glyph.xBearing;
position.y = -glyph.yBearing;
- penX += ( glyph.advance + interGlyphExtraAdvance );
+ penX += (glyph.advance + interGlyphExtraAdvance);
}
}
- void SetGlyphPositions( const Parameters& layoutParameters,
- Vector2* glyphPositionsBuffer,
- LayoutBidiParameters& layoutBidiParameters,
- const LineLayout& layout )
+ void SetGlyphPositions(const Parameters& layoutParameters,
+ Vector2* glyphPositionsBuffer,
+ LayoutBidiParameters& layoutBidiParameters,
+ const LineLayout& layout)
{
- const Character* const textBuffer = layoutParameters.textModel->mLogicalModel->mText.Begin();
- const BidirectionalLineInfoRun& bidiLine = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo[layoutBidiParameters.bidiLineIndex];
- const GlyphInfo* const glyphsBuffer = layoutParameters.textModel->mVisualModel->mGlyphs.Begin();
- const GlyphIndex* const charactersToGlyphsBuffer = layoutParameters.textModel->mVisualModel->mCharactersToGlyph.Begin();
- const Length* const glyphsPerCharacterBuffer = layoutParameters.textModel->mVisualModel->mGlyphsPerCharacter.Begin();
+ const Character* const textBuffer = layoutParameters.textModel->mLogicalModel->mText.Begin();
+ const BidirectionalLineInfoRun& bidiLine = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo[layoutBidiParameters.bidiLineIndex];
+ const GlyphInfo* const glyphsBuffer = layoutParameters.textModel->mVisualModel->mGlyphs.Begin();
+ const GlyphIndex* const charactersToGlyphsBuffer = layoutParameters.textModel->mVisualModel->mCharactersToGlyph.Begin();
+ const Length* const glyphsPerCharacterBuffer = layoutParameters.textModel->mVisualModel->mGlyphsPerCharacter.Begin();
CharacterIndex characterLogicalIndex = 0u;
- CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *( bidiLine.visualToLogicalMap + characterLogicalIndex );
+ CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *(bidiLine.visualToLogicalMap + characterLogicalIndex);
float penX = 0.f;
- while( TextAbstraction::IsWhiteSpace( *( textBuffer + characterVisualIndex ) ) )
+ while(TextAbstraction::IsWhiteSpace(*(textBuffer + characterVisualIndex)))
{
- const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex );
- const GlyphInfo& glyph = *( glyphsBuffer + glyphIndex );
+ const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex);
+ const GlyphInfo& glyph = *(glyphsBuffer + glyphIndex);
- Vector2& position = *( glyphPositionsBuffer + glyphIndex - layoutParameters.startGlyphIndex );
- position.x = penX;
- position.y = -glyph.yBearing;
+ Vector2& position = *(glyphPositionsBuffer + glyphIndex - layoutParameters.startGlyphIndex);
+ position.x = penX;
+ position.y = -glyph.yBearing;
penX += glyph.advance;
++characterLogicalIndex;
- characterVisualIndex = bidiLine.characterRun.characterIndex + *( bidiLine.visualToLogicalMap + characterLogicalIndex );
+ characterVisualIndex = bidiLine.characterRun.characterIndex + *(bidiLine.visualToLogicalMap + characterLogicalIndex);
}
- const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex );
- const GlyphInfo& glyph = *( glyphsBuffer + glyphIndex );
+ const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex);
+ const GlyphInfo& glyph = *(glyphsBuffer + glyphIndex);
penX += -glyph.xBearing;
// Traverses the characters of the right to left paragraph.
- for( ; characterLogicalIndex < bidiLine.characterRun.numberOfCharacters;
- ++characterLogicalIndex )
+ for(; characterLogicalIndex < bidiLine.characterRun.numberOfCharacters;
+ ++characterLogicalIndex)
{
// Convert the character in the logical order into the character in the visual order.
- const CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *( bidiLine.visualToLogicalMap + characterLogicalIndex );
+ const CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *(bidiLine.visualToLogicalMap + characterLogicalIndex);
// Get the number of glyphs of the character.
- const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + characterVisualIndex );
+ const Length numberOfGlyphs = *(glyphsPerCharacterBuffer + characterVisualIndex);
- for( GlyphIndex index = 0u; index < numberOfGlyphs; ++index )
+ for(GlyphIndex index = 0u; index < numberOfGlyphs; ++index)
{
// Convert the character in the visual order into the glyph in the visual order.
- const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex ) + index;
+ const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex) + index;
- DALI_ASSERT_DEBUG( glyphIndex < layoutParameters.textModel->mVisualModel->mGlyphs.Count() );
+ DALI_ASSERT_DEBUG(glyphIndex < layoutParameters.textModel->mVisualModel->mGlyphs.Count());
- const GlyphInfo& glyph = *( glyphsBuffer + glyphIndex );
- Vector2& position = *( glyphPositionsBuffer + glyphIndex - layoutParameters.startGlyphIndex );
+ const GlyphInfo& glyph = *(glyphsBuffer + glyphIndex);
+ Vector2& position = *(glyphPositionsBuffer + glyphIndex - layoutParameters.startGlyphIndex);
position.x = penX + glyph.xBearing;
position.y = -glyph.yBearing;
- penX += ( glyph.advance + layoutParameters.interGlyphExtraAdvance );
+ penX += (glyph.advance + layoutParameters.interGlyphExtraAdvance);
}
}
}
*
* @return Pointer to either lines or newLines.
*/
- LineRun* ResizeLinesBuffer( Vector<LineRun>& lines,
- Vector<LineRun>& newLines,
- Length& linesCapacity,
- bool updateCurrentBuffer )
+ LineRun* ResizeLinesBuffer(Vector<LineRun>& lines,
+ Vector<LineRun>& newLines,
+ Length& linesCapacity,
+ bool updateCurrentBuffer)
{
LineRun* linesBuffer = nullptr;
// Reserve more space for the next lines.
linesCapacity *= 2u;
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- newLines.Resize( linesCapacity );
+ newLines.Resize(linesCapacity);
linesBuffer = newLines.Begin();
}
else
{
- lines.Resize( linesCapacity );
+ lines.Resize(linesCapacity);
linesBuffer = lines.Begin();
}
*
* return Whether the line is ellipsized.
*/
- bool EllipsisLine( const Parameters& layoutParameters,
- LayoutBidiParameters& layoutBidiParameters,
- const LineLayout& layout,
- Size& layoutSize,
- LineRun* linesBuffer,
- Vector2* glyphPositionsBuffer,
- Length& numberOfLines,
- float penY,
- bool& isAutoScrollEnabled )
+ bool EllipsisLine(const Parameters& layoutParameters,
+ LayoutBidiParameters& layoutBidiParameters,
+ const LineLayout& layout,
+ Size& layoutSize,
+ LineRun* linesBuffer,
+ Vector2* glyphPositionsBuffer,
+ Length& numberOfLines,
+ float penY,
+ bool& isAutoScrollEnabled)
{
- const bool ellipsis = isAutoScrollEnabled ? ( penY - layout.descender > layoutParameters.boundingBox.height ) :
- ( ( penY - layout.descender > layoutParameters.boundingBox.height ) ||
- ( ( mLayout == SINGLE_LINE_BOX ) &&
- ( layout.length > layoutParameters.boundingBox.width ) ) );
+ const bool ellipsis = isAutoScrollEnabled ? (penY - layout.descender > layoutParameters.boundingBox.height) : ((penY - layout.descender > layoutParameters.boundingBox.height) || ((mLayout == SINGLE_LINE_BOX) && (layout.length > layoutParameters.boundingBox.width)));
- if( ellipsis )
+ if(ellipsis)
{
isAutoScrollEnabled = false;
// Do not layout more lines if ellipsis is enabled.
// The last line needs to be completely filled with characters.
// Part of a word may be used.
- LineRun* lineRun = nullptr;
+ LineRun* lineRun = nullptr;
LineLayout ellipsisLayout;
- if( 0u != numberOfLines )
+ if(0u != numberOfLines)
{
// Get the last line and layout it again with the 'completelyFill' flag to true.
- lineRun = linesBuffer + ( numberOfLines - 1u );
+ lineRun = linesBuffer + (numberOfLines - 1u);
penY -= layout.ascender - lineRun->descender + lineRun->lineSpacing;
lineRun = linesBuffer;
lineRun->glyphRun.glyphIndex = 0u;
- ellipsisLayout.glyphIndex = 0u;
+ ellipsisLayout.glyphIndex = 0u;
++numberOfLines;
}
- GetLineLayoutForBox( layoutParameters,
- layoutBidiParameters,
- ellipsisLayout,
- true );
+ GetLineLayoutForBox(layoutParameters,
+ layoutBidiParameters,
+ ellipsisLayout,
+ true);
- lineRun->glyphRun.numberOfGlyphs = ellipsisLayout.numberOfGlyphs;
- lineRun->characterRun.characterIndex = ellipsisLayout.characterIndex;
+ lineRun->glyphRun.numberOfGlyphs = ellipsisLayout.numberOfGlyphs;
+ lineRun->characterRun.characterIndex = ellipsisLayout.characterIndex;
lineRun->characterRun.numberOfCharacters = ellipsisLayout.numberOfCharacters;
- lineRun->width = ellipsisLayout.length;
- lineRun->extraLength = std::ceil( ellipsisLayout.whiteSpaceLengthEndOfLine );
- lineRun->ascender = ellipsisLayout.ascender;
- lineRun->descender = ellipsisLayout.descender;
- lineRun->ellipsis = true;
+ lineRun->width = ellipsisLayout.length;
+ lineRun->extraLength = std::ceil(ellipsisLayout.whiteSpaceLengthEndOfLine);
+ lineRun->ascender = ellipsisLayout.ascender;
+ lineRun->descender = ellipsisLayout.descender;
+ lineRun->ellipsis = true;
layoutSize.width = layoutParameters.boundingBox.width;
- if( layoutSize.height < Math::MACHINE_EPSILON_1000 )
+ if(layoutSize.height < Math::MACHINE_EPSILON_1000)
{
- layoutSize.height += ( lineRun->ascender + -lineRun->descender ) + lineRun->lineSpacing;
+ layoutSize.height += (lineRun->ascender + -lineRun->descender) + lineRun->lineSpacing;
}
const GlyphInfo* const glyphsBuffer = layoutParameters.textModel->mVisualModel->mGlyphs.Begin();
- const float outlineWidth = static_cast<float>( layoutParameters.textModel->GetOutlineWidth() );
+ const float outlineWidth = static_cast<float>(layoutParameters.textModel->GetOutlineWidth());
const Vector<BidirectionalLineInfoRun>& bidirectionalLinesInfo = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo;
- if( layoutBidiParameters.isBidirectional )
+ if(layoutBidiParameters.isBidirectional)
{
layoutBidiParameters.bidiLineIndex = 0u;
- for( Vector<BidirectionalLineInfoRun>::ConstIterator it = bidirectionalLinesInfo.Begin(),
- endIt = bidirectionalLinesInfo.End();
- it != endIt;
- ++it, ++layoutBidiParameters.bidiLineIndex )
+ for(Vector<BidirectionalLineInfoRun>::ConstIterator it = bidirectionalLinesInfo.Begin(),
+ endIt = bidirectionalLinesInfo.End();
+ it != endIt;
+ ++it, ++layoutBidiParameters.bidiLineIndex)
{
const BidirectionalLineInfoRun& run = *it;
- if( ellipsisLayout.characterIndex == run.characterRun.characterIndex )
+ if(ellipsisLayout.characterIndex == run.characterRun.characterIndex)
{
// Found where to insert the bidi line info.
break;
}
}
- const BidirectionalLineInfoRun* const bidirectionalLineInfo = ( layoutBidiParameters.isBidirectional && !bidirectionalLinesInfo.Empty() ) ? &bidirectionalLinesInfo[layoutBidiParameters.bidiLineIndex] : nullptr;
+ const BidirectionalLineInfoRun* const bidirectionalLineInfo = (layoutBidiParameters.isBidirectional && !bidirectionalLinesInfo.Empty()) ? &bidirectionalLinesInfo[layoutBidiParameters.bidiLineIndex] : nullptr;
- if( ( nullptr != bidirectionalLineInfo ) &&
- !bidirectionalLineInfo->isIdentity &&
- ( ellipsisLayout.characterIndex == bidirectionalLineInfo->characterRun.characterIndex ) )
+ if((nullptr != bidirectionalLineInfo) &&
+ !bidirectionalLineInfo->isIdentity &&
+ (ellipsisLayout.characterIndex == bidirectionalLineInfo->characterRun.characterIndex))
{
lineRun->direction = RTL;
- SetGlyphPositions( layoutParameters,
- glyphPositionsBuffer,
- layoutBidiParameters,
- ellipsisLayout );
+ SetGlyphPositions(layoutParameters,
+ glyphPositionsBuffer,
+ layoutBidiParameters,
+ ellipsisLayout);
}
else
{
lineRun->direction = LTR;
- SetGlyphPositions( glyphsBuffer + lineRun->glyphRun.glyphIndex,
- ellipsisLayout.numberOfGlyphs,
- outlineWidth,
- layoutParameters.interGlyphExtraAdvance,
- glyphPositionsBuffer + lineRun->glyphRun.glyphIndex - layoutParameters.startGlyphIndex );
+ SetGlyphPositions(glyphsBuffer + lineRun->glyphRun.glyphIndex,
+ ellipsisLayout.numberOfGlyphs,
+ outlineWidth,
+ layoutParameters.interGlyphExtraAdvance,
+ glyphPositionsBuffer + lineRun->glyphRun.glyphIndex - layoutParameters.startGlyphIndex);
}
}
* @param[in,out] numberOfLines The number of laid-out lines.
* @param[in] isLastLine Whether the laid-out line is the last one.
*/
- void UpdateTextLayout( const Parameters& layoutParameters,
- const LineLayout& layout,
- Size& layoutSize,
- LineRun* linesBuffer,
- GlyphIndex index,
- Length& numberOfLines,
- bool isLastLine )
+ void UpdateTextLayout(const Parameters& layoutParameters,
+ const LineLayout& layout,
+ Size& layoutSize,
+ LineRun* linesBuffer,
+ GlyphIndex index,
+ Length& numberOfLines,
+ bool isLastLine)
{
- LineRun& lineRun = *( linesBuffer + numberOfLines );
+ LineRun& lineRun = *(linesBuffer + numberOfLines);
++numberOfLines;
- lineRun.glyphRun.glyphIndex = index;
- lineRun.glyphRun.numberOfGlyphs = layout.numberOfGlyphs;
- lineRun.characterRun.characterIndex = layout.characterIndex;
+ lineRun.glyphRun.glyphIndex = index;
+ lineRun.glyphRun.numberOfGlyphs = layout.numberOfGlyphs;
+ lineRun.characterRun.characterIndex = layout.characterIndex;
lineRun.characterRun.numberOfCharacters = layout.numberOfCharacters;
- lineRun.width = layout.length;
- lineRun.extraLength = std::ceil( layout.whiteSpaceLengthEndOfLine );
-
+ lineRun.width = layout.length;
+ lineRun.extraLength = std::ceil(layout.whiteSpaceLengthEndOfLine);
// Rounds upward to avoid a non integer size.
- lineRun.width = std::ceil( lineRun.width );
+ lineRun.width = std::ceil(lineRun.width);
- lineRun.ascender = layout.ascender;
+ lineRun.ascender = layout.ascender;
lineRun.descender = layout.descender;
lineRun.direction = layout.direction;
- lineRun.ellipsis = false;
+ lineRun.ellipsis = false;
- lineRun.lineSpacing = mDefaultLineSize - ( lineRun.ascender + -lineRun.descender );
+ lineRun.lineSpacing = mDefaultLineSize - (lineRun.ascender + -lineRun.descender);
lineRun.lineSpacing = lineRun.lineSpacing < 0.f ? 0.f : lineRun.lineSpacing;
lineRun.lineSpacing += mDefaultLineSpacing;
-
// Update the actual size.
- if( lineRun.width > layoutSize.width )
+ if(lineRun.width > layoutSize.width)
{
layoutSize.width = lineRun.width;
}
- layoutSize.height += ( lineRun.ascender + -lineRun.descender ) + lineRun.lineSpacing;
+ layoutSize.height += (lineRun.ascender + -lineRun.descender) + lineRun.lineSpacing;
}
/**
* @param[in,out] linesBuffer Pointer to the line's buffer.
* @param[in,out] numberOfLines The number of laid-out lines.
*/
- void UpdateTextLayout( const Parameters& layoutParameters,
- CharacterIndex characterIndex,
- GlyphIndex glyphIndex,
- Size& layoutSize,
- LineRun* linesBuffer,
- Length& numberOfLines )
+ void UpdateTextLayout(const Parameters& layoutParameters,
+ CharacterIndex characterIndex,
+ GlyphIndex glyphIndex,
+ Size& layoutSize,
+ LineRun* linesBuffer,
+ Length& numberOfLines)
{
const Vector<GlyphInfo>& glyphs = layoutParameters.textModel->mVisualModel->mGlyphs;
const GlyphInfo& glyphInfo = glyphs[glyphs.Count() - 1u];
Text::FontMetrics fontMetrics;
- if( 0u != glyphInfo.fontId )
+ if(0u != glyphInfo.fontId)
{
- mMetrics->GetFontMetrics( glyphInfo.fontId, fontMetrics );
+ mMetrics->GetFontMetrics(glyphInfo.fontId, fontMetrics);
}
- LineRun& lineRun = *( linesBuffer + numberOfLines );
+ LineRun& lineRun = *(linesBuffer + numberOfLines);
++numberOfLines;
- lineRun.glyphRun.glyphIndex = glyphIndex;
- lineRun.glyphRun.numberOfGlyphs = 0u;
- lineRun.characterRun.characterIndex = characterIndex;
+ lineRun.glyphRun.glyphIndex = glyphIndex;
+ lineRun.glyphRun.numberOfGlyphs = 0u;
+ lineRun.characterRun.characterIndex = characterIndex;
lineRun.characterRun.numberOfCharacters = 0u;
- lineRun.width = 0.f;
- lineRun.ascender = fontMetrics.ascender;
- lineRun.descender = fontMetrics.descender;
- lineRun.extraLength = 0.f;
- lineRun.alignmentOffset = 0.f;
- lineRun.direction = LTR;
- lineRun.ellipsis = false;
-
- lineRun.lineSpacing = mDefaultLineSize - ( lineRun.ascender + -lineRun.descender );
+ lineRun.width = 0.f;
+ lineRun.ascender = fontMetrics.ascender;
+ lineRun.descender = fontMetrics.descender;
+ lineRun.extraLength = 0.f;
+ lineRun.alignmentOffset = 0.f;
+ lineRun.direction = LTR;
+ lineRun.ellipsis = false;
+
+ lineRun.lineSpacing = mDefaultLineSize - (lineRun.ascender + -lineRun.descender);
lineRun.lineSpacing = lineRun.lineSpacing < 0.f ? 0.f : lineRun.lineSpacing;
lineRun.lineSpacing += mDefaultLineSpacing;
- layoutSize.height += ( lineRun.ascender + -lineRun.descender ) + lineRun.lineSpacing;
+ layoutSize.height += (lineRun.ascender + -lineRun.descender) + lineRun.lineSpacing;
}
/**
* @param[in] lines The vector of lines (before the new laid-out lines are inserted).
* @param[in,out] layoutSize The text's layout size.
*/
- void UpdateLayoutSize( const Vector<LineRun>& lines,
- Size& layoutSize )
+ void UpdateLayoutSize(const Vector<LineRun>& lines,
+ Size& layoutSize)
{
- for( Vector<LineRun>::ConstIterator it = lines.Begin(),
- endIt = lines.End();
- it != endIt;
- ++it )
+ for(Vector<LineRun>::ConstIterator it = lines.Begin(),
+ endIt = lines.End();
+ it != endIt;
+ ++it)
{
const LineRun& line = *it;
- if( line.width > layoutSize.width )
+ if(line.width > layoutSize.width)
{
layoutSize.width = line.width;
}
- layoutSize.height += ( line.ascender + -line.descender ) + line.lineSpacing;
+ layoutSize.height += (line.ascender + -line.descender) + line.lineSpacing;
}
}
* @param[in] characterOffset The offset to be added to the runs of characters.
* @param[in] glyphOffset The offset to be added to the runs of glyphs.
*/
- void UpdateLineIndexOffsets( const Parameters& layoutParameters,
- Vector<LineRun>& lines,
- Length characterOffset,
- Length glyphOffset )
+ void UpdateLineIndexOffsets(const Parameters& layoutParameters,
+ Vector<LineRun>& lines,
+ Length characterOffset,
+ Length glyphOffset)
{
// Update the glyph and character runs.
- for( Vector<LineRun>::Iterator it = lines.Begin() + layoutParameters.startLineIndex,
- endIt = lines.End();
- it != endIt;
- ++it )
+ for(Vector<LineRun>::Iterator it = lines.Begin() + layoutParameters.startLineIndex,
+ endIt = lines.End();
+ it != endIt;
+ ++it)
{
LineRun& line = *it;
- line.glyphRun.glyphIndex = glyphOffset;
+ line.glyphRun.glyphIndex = glyphOffset;
line.characterRun.characterIndex = characterOffset;
glyphOffset += line.glyphRun.numberOfGlyphs;
}
}
- bool LayoutText( Parameters& layoutParameters,
- Size& layoutSize,
- bool elideTextEnabled,
- bool& isAutoScrollEnabled )
+ bool LayoutText(Parameters& layoutParameters,
+ Size& layoutSize,
+ bool elideTextEnabled,
+ bool& isAutoScrollEnabled)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->LayoutText\n" );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " box size %f, %f\n", layoutParameters.boundingBox.width, layoutParameters.boundingBox.height );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->LayoutText\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " box size %f, %f\n", layoutParameters.boundingBox.width, layoutParameters.boundingBox.height);
Vector<LineRun>& lines = layoutParameters.textModel->mVisualModel->mLines;
- if( 0u == layoutParameters.numberOfGlyphs )
+ if(0u == layoutParameters.numberOfGlyphs)
{
// Add an extra line if the last character is a new paragraph character and the last line doesn't have zero characters.
- if( layoutParameters.isLastNewParagraph )
+ if(layoutParameters.isLastNewParagraph)
{
Length numberOfLines = lines.Count();
- if( 0u != numberOfLines )
+ if(0u != numberOfLines)
{
- const LineRun& lastLine = *( lines.End() - 1u );
+ const LineRun& lastLine = *(lines.End() - 1u);
- if( 0u != lastLine.characterRun.numberOfCharacters )
+ if(0u != lastLine.characterRun.numberOfCharacters)
{
// Need to add a new line with no characters but with height to increase the layoutSize.height
LineRun newLine;
- Initialize( newLine );
- lines.PushBack( newLine );
-
- UpdateTextLayout( layoutParameters,
- lastLine.characterRun.characterIndex + lastLine.characterRun.numberOfCharacters,
- lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs,
- layoutSize,
- lines.Begin(),
- numberOfLines );
+ Initialize(newLine);
+ lines.PushBack(newLine);
+
+ UpdateTextLayout(layoutParameters,
+ lastLine.characterRun.characterIndex + lastLine.characterRun.numberOfCharacters,
+ lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs,
+ layoutSize,
+ lines.Begin(),
+ numberOfLines);
}
}
}
// Calculates the layout size.
- UpdateLayoutSize( lines,
- layoutSize );
+ UpdateLayoutSize(lines,
+ layoutSize);
// Rounds upward to avoid a non integer size.
- layoutSize.height = std::ceil( layoutSize.height );
+ layoutSize.height = std::ceil(layoutSize.height);
// Nothing else do if there are no glyphs to layout.
return false;
}
- const GlyphIndex lastGlyphPlusOne = layoutParameters.startGlyphIndex + layoutParameters.numberOfGlyphs;
- const Length totalNumberOfGlyphs = layoutParameters.textModel->mVisualModel->mGlyphs.Count();
- Vector<Vector2>& glyphPositions = layoutParameters.textModel->mVisualModel->mGlyphPositions;
+ const GlyphIndex lastGlyphPlusOne = layoutParameters.startGlyphIndex + layoutParameters.numberOfGlyphs;
+ const Length totalNumberOfGlyphs = layoutParameters.textModel->mVisualModel->mGlyphs.Count();
+ Vector<Vector2>& glyphPositions = layoutParameters.textModel->mVisualModel->mGlyphPositions;
// In a previous layout, an extra line with no characters may have been added if the text ended with a new paragraph character.
// This extra line needs to be removed.
- if( 0u != lines.Count() )
+ if(0u != lines.Count())
{
Vector<LineRun>::Iterator lastLine = lines.End() - 1u;
- if( ( 0u == lastLine->characterRun.numberOfCharacters ) &&
- ( lastGlyphPlusOne == totalNumberOfGlyphs ) )
+ if((0u == lastLine->characterRun.numberOfCharacters) &&
+ (lastGlyphPlusOne == totalNumberOfGlyphs))
{
- lines.Remove( lastLine );
+ lines.Remove(lastLine);
}
}
// Retrieve BiDi info.
const bool hasBidiParagraphs = !layoutParameters.textModel->mLogicalModel->mBidirectionalParagraphInfo.Empty();
- const CharacterIndex* const glyphsToCharactersBuffer = hasBidiParagraphs ? layoutParameters.textModel->mVisualModel->mGlyphsToCharacters.Begin() : nullptr;
+ const CharacterIndex* const glyphsToCharactersBuffer = hasBidiParagraphs ? layoutParameters.textModel->mVisualModel->mGlyphsToCharacters.Begin() : nullptr;
const Vector<BidirectionalParagraphInfoRun>& bidirectionalParagraphsInfo = layoutParameters.textModel->mLogicalModel->mBidirectionalParagraphInfo;
- const Vector<BidirectionalLineInfoRun>& bidirectionalLinesInfo = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo;
+ const Vector<BidirectionalLineInfoRun>& bidirectionalLinesInfo = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo;
// Set the layout bidirectional paramters.
LayoutBidiParameters layoutBidiParameters;
// Whether the layout is being updated or set from scratch.
const bool updateCurrentBuffer = layoutParameters.numberOfGlyphs < totalNumberOfGlyphs;
- Vector2* glyphPositionsBuffer = nullptr;
+ Vector2* glyphPositionsBuffer = nullptr;
Vector<Vector2> newGlyphPositions;
- LineRun* linesBuffer = nullptr;
+ LineRun* linesBuffer = nullptr;
Vector<LineRun> newLines;
// Estimate the number of lines.
- Length linesCapacity = std::max( 1u, layoutParameters.estimatedNumberOfLines );
+ Length linesCapacity = std::max(1u, layoutParameters.estimatedNumberOfLines);
Length numberOfLines = 0u;
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- newGlyphPositions.Resize( layoutParameters.numberOfGlyphs );
+ newGlyphPositions.Resize(layoutParameters.numberOfGlyphs);
glyphPositionsBuffer = newGlyphPositions.Begin();
- newLines.Resize( linesCapacity );
+ newLines.Resize(linesCapacity);
linesBuffer = newLines.Begin();
}
else
{
glyphPositionsBuffer = glyphPositions.Begin();
- lines.Resize( linesCapacity );
+ lines.Resize(linesCapacity);
linesBuffer = lines.Begin();
}
- float penY = CalculateLineOffset( lines,
- layoutParameters.startLineIndex );
- for( GlyphIndex index = layoutParameters.startGlyphIndex; index < lastGlyphPlusOne; )
+ float penY = CalculateLineOffset(lines,
+ layoutParameters.startLineIndex);
+ for(GlyphIndex index = layoutParameters.startGlyphIndex; index < lastGlyphPlusOne;)
{
layoutBidiParameters.Clear();
- if( hasBidiParagraphs )
+ if(hasBidiParagraphs)
{
- const CharacterIndex startCharacterIndex = *( glyphsToCharactersBuffer + index );
+ const CharacterIndex startCharacterIndex = *(glyphsToCharactersBuffer + index);
- for( Vector<BidirectionalParagraphInfoRun>::ConstIterator it = bidirectionalParagraphsInfo.Begin(),
- endIt = bidirectionalParagraphsInfo.End();
- it != endIt;
- ++it, ++layoutBidiParameters.bidiParagraphIndex )
+ for(Vector<BidirectionalParagraphInfoRun>::ConstIterator it = bidirectionalParagraphsInfo.Begin(),
+ endIt = bidirectionalParagraphsInfo.End();
+ it != endIt;
+ ++it, ++layoutBidiParameters.bidiParagraphIndex)
{
const BidirectionalParagraphInfoRun& run = *it;
const CharacterIndex lastCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters;
- if( lastCharacterIndex <= startCharacterIndex )
+ if(lastCharacterIndex <= startCharacterIndex)
{
// Do not process, the paragraph has already been processed.
continue;
}
- if( startCharacterIndex >= run.characterRun.characterIndex && startCharacterIndex < lastCharacterIndex )
+ if(startCharacterIndex >= run.characterRun.characterIndex && startCharacterIndex < lastCharacterIndex)
{
layoutBidiParameters.paragraphDirection = run.direction;
- layoutBidiParameters.isBidirectional = true;
+ layoutBidiParameters.isBidirectional = true;
}
// Has already been found.
break;
}
- if( layoutBidiParameters.isBidirectional )
+ if(layoutBidiParameters.isBidirectional)
{
- for( Vector<BidirectionalLineInfoRun>::ConstIterator it = bidirectionalLinesInfo.Begin(),
- endIt = bidirectionalLinesInfo.End();
- it != endIt;
- ++it, ++layoutBidiParameters.bidiLineIndex )
+ for(Vector<BidirectionalLineInfoRun>::ConstIterator it = bidirectionalLinesInfo.Begin(),
+ endIt = bidirectionalLinesInfo.End();
+ it != endIt;
+ ++it, ++layoutBidiParameters.bidiLineIndex)
{
const BidirectionalLineInfoRun& run = *it;
const CharacterIndex lastCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters;
- if( lastCharacterIndex <= startCharacterIndex )
+ if(lastCharacterIndex <= startCharacterIndex)
{
// skip
continue;
}
- if( startCharacterIndex < lastCharacterIndex )
+ if(startCharacterIndex < lastCharacterIndex)
{
// Found where to insert the bidi line info.
break;
// Get the layout for the line.
LineLayout layout;
- layout.direction = layoutBidiParameters.paragraphDirection;
+ layout.direction = layoutBidiParameters.paragraphDirection;
layout.glyphIndex = index;
- GetLineLayoutForBox( layoutParameters,
- layoutBidiParameters,
- layout,
- false );
-
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " glyph index %d\n", layout.glyphIndex );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " character index %d\n", layout.characterIndex );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of glyphs %d\n", layout.numberOfGlyphs );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of characters %d\n", layout.numberOfCharacters );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " length %f\n", layout.length );
-
- if( 0u == layout.numberOfGlyphs )
+ GetLineLayoutForBox(layoutParameters,
+ layoutBidiParameters,
+ layout,
+ false);
+
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " glyph index %d\n", layout.glyphIndex);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " character index %d\n", layout.characterIndex);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " number of glyphs %d\n", layout.numberOfGlyphs);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " number of characters %d\n", layout.numberOfCharacters);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " length %f\n", layout.length);
+
+ if(0u == layout.numberOfGlyphs)
{
// The width is too small and no characters are laid-out.
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--LayoutText width too small!\n\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--LayoutText width too small!\n\n");
- lines.Resize( numberOfLines );
+ lines.Resize(numberOfLines);
// Rounds upward to avoid a non integer size.
- layoutSize.height = std::ceil( layoutSize.height );
+ layoutSize.height = std::ceil(layoutSize.height);
return false;
}
// of the box.
penY += layout.ascender;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " pen y %f\n", penY );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " pen y %f\n", penY);
bool ellipsis = false;
- if( elideTextEnabled )
+ if(elideTextEnabled)
{
layoutBidiParameters.paragraphDirection = currentParagraphDirection;
// Does the ellipsis of the last line.
- ellipsis = EllipsisLine( layoutParameters,
- layoutBidiParameters,
- layout,
- layoutSize,
- linesBuffer,
- glyphPositionsBuffer,
- numberOfLines,
- penY,
- isAutoScrollEnabled );
+ ellipsis = EllipsisLine(layoutParameters,
+ layoutBidiParameters,
+ layout,
+ layoutSize,
+ linesBuffer,
+ glyphPositionsBuffer,
+ numberOfLines,
+ penY,
+ isAutoScrollEnabled);
}
- if( ellipsis )
+ if(ellipsis)
{
// No more lines to layout.
break;
// Whether the last line has been laid-out.
const bool isLastLine = index + layout.numberOfGlyphs == totalNumberOfGlyphs;
- if( numberOfLines == linesCapacity )
+ if(numberOfLines == linesCapacity)
{
-
// Reserve more space for the next lines.
- linesBuffer = ResizeLinesBuffer( lines,
- newLines,
- linesCapacity,
- updateCurrentBuffer );
+ linesBuffer = ResizeLinesBuffer(lines,
+ newLines,
+ linesCapacity,
+ updateCurrentBuffer);
}
// Updates the current text's layout with the line's layout.
- UpdateTextLayout( layoutParameters,
- layout,
- layoutSize,
- linesBuffer,
- index,
- numberOfLines,
- isLastLine );
+ UpdateTextLayout(layoutParameters,
+ layout,
+ layoutSize,
+ linesBuffer,
+ index,
+ numberOfLines,
+ isLastLine);
const GlyphIndex nextIndex = index + layout.numberOfGlyphs;
- if( ( nextIndex == totalNumberOfGlyphs ) &&
- layoutParameters.isLastNewParagraph &&
- ( mLayout == MULTI_LINE_BOX ) )
+ if((nextIndex == totalNumberOfGlyphs) &&
+ layoutParameters.isLastNewParagraph &&
+ (mLayout == MULTI_LINE_BOX))
{
// The last character of the text is a new paragraph character.
// An extra line with no characters is added to increase the text's height
// in order to place the cursor.
- if( numberOfLines == linesCapacity )
+ if(numberOfLines == linesCapacity)
{
// Reserve more space for the next lines.
- linesBuffer = ResizeLinesBuffer( lines,
- newLines,
- linesCapacity,
- updateCurrentBuffer );
+ linesBuffer = ResizeLinesBuffer(lines,
+ newLines,
+ linesCapacity,
+ updateCurrentBuffer);
}
- UpdateTextLayout( layoutParameters,
- layout.characterIndex + layout.numberOfCharacters,
- index + layout.numberOfGlyphs,
- layoutSize,
- linesBuffer,
- numberOfLines );
+ UpdateTextLayout(layoutParameters,
+ layout.characterIndex + layout.numberOfCharacters,
+ index + layout.numberOfGlyphs,
+ layoutSize,
+ linesBuffer,
+ numberOfLines);
} // whether to add a last line.
const GlyphInfo* const glyphsBuffer = layoutParameters.textModel->mVisualModel->mGlyphs.Begin();
- const float outlineWidth = static_cast<float>( layoutParameters.textModel->GetOutlineWidth() );
+ const float outlineWidth = static_cast<float>(layoutParameters.textModel->GetOutlineWidth());
- const BidirectionalLineInfoRun* const bidirectionalLineInfo = ( layoutBidiParameters.isBidirectional && !bidirectionalLinesInfo.Empty() ) ? &bidirectionalLinesInfo[layoutBidiParameters.bidiLineIndex] : nullptr;
+ const BidirectionalLineInfoRun* const bidirectionalLineInfo = (layoutBidiParameters.isBidirectional && !bidirectionalLinesInfo.Empty()) ? &bidirectionalLinesInfo[layoutBidiParameters.bidiLineIndex] : nullptr;
- if( ( nullptr != bidirectionalLineInfo ) &&
- !bidirectionalLineInfo->isIdentity &&
- ( layout.characterIndex == bidirectionalLineInfo->characterRun.characterIndex ) )
+ if((nullptr != bidirectionalLineInfo) &&
+ !bidirectionalLineInfo->isIdentity &&
+ (layout.characterIndex == bidirectionalLineInfo->characterRun.characterIndex))
{
- SetGlyphPositions( layoutParameters,
- glyphPositionsBuffer,
- layoutBidiParameters,
- layout );
+ SetGlyphPositions(layoutParameters,
+ glyphPositionsBuffer,
+ layoutBidiParameters,
+ layout);
}
else
{
-
// Sets the positions of the glyphs.
- SetGlyphPositions( glyphsBuffer + index,
- layout.numberOfGlyphs,
- outlineWidth,
- layoutParameters.interGlyphExtraAdvance,
- glyphPositionsBuffer + index - layoutParameters.startGlyphIndex );
+ SetGlyphPositions(glyphsBuffer + index,
+ layout.numberOfGlyphs,
+ outlineWidth,
+ layoutParameters.interGlyphExtraAdvance,
+ glyphPositionsBuffer + index - layoutParameters.startGlyphIndex);
}
// Updates the vertical pen's position.
penY += -layout.descender + layout.lineSpacing + mDefaultLineSpacing;
// If there is a defaultLineSize, updates the pen's position.
- if( mDefaultLineSize > 0.f )
+ if(mDefaultLineSize > 0.f)
{
- float lineSpacing = mDefaultLineSize - ( layout.ascender + -layout.descender );
- lineSpacing = lineSpacing < 0.f ? 0.f : lineSpacing;
+ float lineSpacing = mDefaultLineSize - (layout.ascender + -layout.descender);
+ lineSpacing = lineSpacing < 0.f ? 0.f : lineSpacing;
penY += lineSpacing;
}
// Increase the glyph index.
index = nextIndex;
} // no ellipsis
- } // end for() traversing glyphs.
+ } // end for() traversing glyphs.
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- glyphPositions.Insert( glyphPositions.Begin() + layoutParameters.startGlyphIndex,
- newGlyphPositions.Begin(),
- newGlyphPositions.End() );
- glyphPositions.Resize( totalNumberOfGlyphs );
+ glyphPositions.Insert(glyphPositions.Begin() + layoutParameters.startGlyphIndex,
+ newGlyphPositions.Begin(),
+ newGlyphPositions.End());
+ glyphPositions.Resize(totalNumberOfGlyphs);
- newLines.Resize( numberOfLines );
+ newLines.Resize(numberOfLines);
// Current text's layout size adds only the newly laid-out lines.
// Updates the layout size with the previously laid-out lines.
- UpdateLayoutSize( lines,
- layoutSize );
+ UpdateLayoutSize(lines,
+ layoutSize);
- if( 0u != newLines.Count() )
+ if(0u != newLines.Count())
{
- const LineRun& lastLine = *( newLines.End() - 1u );
+ const LineRun& lastLine = *(newLines.End() - 1u);
const Length characterOffset = lastLine.characterRun.characterIndex + lastLine.characterRun.numberOfCharacters;
- const Length glyphOffset = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs;
+ const Length glyphOffset = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs;
// Update the indices of the runs before the new laid-out lines are inserted.
- UpdateLineIndexOffsets( layoutParameters,
- lines,
- characterOffset,
- glyphOffset );
+ UpdateLineIndexOffsets(layoutParameters,
+ lines,
+ characterOffset,
+ glyphOffset);
// Insert the lines.
- lines.Insert( lines.Begin() + layoutParameters.startLineIndex,
- newLines.Begin(),
- newLines.End() );
+ lines.Insert(lines.Begin() + layoutParameters.startLineIndex,
+ newLines.Begin(),
+ newLines.End());
}
}
else
{
- lines.Resize( numberOfLines );
+ lines.Resize(numberOfLines);
}
// Rounds upward to avoid a non integer size.
- layoutSize.height = std::ceil( layoutSize.height );
+ layoutSize.height = std::ceil(layoutSize.height);
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--LayoutText\n\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--LayoutText\n\n");
return true;
}
- void Align( const Size& size,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Text::HorizontalAlignment::Type horizontalAlignment,
- Vector<LineRun>& lines,
- float& alignmentOffset,
- Dali::LayoutDirection::Type layoutDirection,
- bool matchSystemLanguageDirection )
+ void Align(const Size& size,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Text::HorizontalAlignment::Type horizontalAlignment,
+ Vector<LineRun>& lines,
+ float& alignmentOffset,
+ Dali::LayoutDirection::Type layoutDirection,
+ bool matchSystemLanguageDirection)
{
const CharacterIndex lastCharacterPlusOne = startIndex + numberOfCharacters;
alignmentOffset = MAX_FLOAT;
// Traverse all lines and align the glyphs.
- for( Vector<LineRun>::Iterator it = lines.Begin(), endIt = lines.End();
- it != endIt;
- ++it )
+ for(Vector<LineRun>::Iterator it = lines.Begin(), endIt = lines.End();
+ it != endIt;
+ ++it)
{
LineRun& line = *it;
- if( line.characterRun.characterIndex < startIndex )
+ if(line.characterRun.characterIndex < startIndex)
{
// Do not align lines which have already been aligned.
continue;
}
- if( line.characterRun.characterIndex > lastCharacterPlusOne )
+ if(line.characterRun.characterIndex > lastCharacterPlusOne)
{
// Do not align lines beyond the last laid-out character.
break;
}
- if( line.characterRun.characterIndex == lastCharacterPlusOne && !isEmptyLineAtLast( lines, it ) )
+ if(line.characterRun.characterIndex == lastCharacterPlusOne && !isEmptyLineAtLast(lines, it))
{
// Do not align lines beyond the last laid-out character unless the line is last and empty.
break;
// Calculate the line's alignment offset accordingly with the align option,
// the box width, line length, and the paragraph's direction.
- CalculateHorizontalAlignment( size.width,
- horizontalAlignment,
- line,
- layoutDirection,
- matchSystemLanguageDirection );
+ CalculateHorizontalAlignment(size.width,
+ horizontalAlignment,
+ line,
+ layoutDirection,
+ matchSystemLanguageDirection);
// Updates the alignment offset.
- alignmentOffset = std::min( alignmentOffset, line.alignmentOffset );
+ alignmentOffset = std::min(alignmentOffset, line.alignmentOffset);
}
}
- void CalculateHorizontalAlignment( float boxWidth,
- HorizontalAlignment::Type horizontalAlignment,
- LineRun& line,
- Dali::LayoutDirection::Type layoutDirection,
- bool matchSystemLanguageDirection )
+ void CalculateHorizontalAlignment(float boxWidth,
+ HorizontalAlignment::Type horizontalAlignment,
+ LineRun& line,
+ Dali::LayoutDirection::Type layoutDirection,
+ bool matchSystemLanguageDirection)
{
line.alignmentOffset = 0.f;
const bool isLineRTL = RTL == line.direction;
// Whether to swap the alignment.
// Swap if the line is RTL and is not required to match the direction of the system's language or if it's required to match the direction of the system's language and it's RTL.
- bool isLayoutRTL = isLineRTL;
- float lineLength = line.width;
+ bool isLayoutRTL = isLineRTL;
+ float lineLength = line.width;
// match align for system language direction
- if( matchSystemLanguageDirection )
+ if(matchSystemLanguageDirection)
{
// Swap the alignment type if the line is right to left.
isLayoutRTL = layoutDirection == LayoutDirection::RIGHT_TO_LEFT;
}
// Calculate the horizontal line offset.
- switch( horizontalAlignment )
+ switch(horizontalAlignment)
{
case HorizontalAlignment::BEGIN:
{
- if( isLayoutRTL )
+ if(isLayoutRTL)
{
- if( isLineRTL )
+ if(isLineRTL)
{
lineLength += line.extraLength;
}
{
line.alignmentOffset = 0.f;
- if( isLineRTL )
+ if(isLineRTL)
{
// 'Remove' the white spaces at the end of the line (which are at the beginning in visual order)
line.alignmentOffset -= line.extraLength;
}
case HorizontalAlignment::CENTER:
{
- line.alignmentOffset = 0.5f * ( boxWidth - lineLength );
+ line.alignmentOffset = 0.5f * (boxWidth - lineLength);
- if( isLineRTL )
+ if(isLineRTL)
{
line.alignmentOffset -= line.extraLength;
}
- line.alignmentOffset = std::floor( line.alignmentOffset ); // floor() avoids pixel alignment issues.
+ line.alignmentOffset = std::floor(line.alignmentOffset); // floor() avoids pixel alignment issues.
break;
}
case HorizontalAlignment::END:
{
- if( isLayoutRTL )
+ if(isLayoutRTL)
{
line.alignmentOffset = 0.f;
- if( isLineRTL )
+ if(isLineRTL)
{
// 'Remove' the white spaces at the end of the line (which are at the beginning in visual order)
line.alignmentOffset -= line.extraLength;
}
else
{
- if( isLineRTL )
+ if(isLineRTL)
{
lineLength += line.extraLength;
}
}
}
- void Initialize( LineRun& line )
+ void Initialize(LineRun& line)
{
- line.glyphRun.glyphIndex = 0u;
- line.glyphRun.numberOfGlyphs = 0u;
- line.characterRun.characterIndex = 0u;
+ line.glyphRun.glyphIndex = 0u;
+ line.glyphRun.numberOfGlyphs = 0u;
+ line.characterRun.characterIndex = 0u;
line.characterRun.numberOfCharacters = 0u;
- line.width = 0.f;
- line.ascender = 0.f;
- line.descender = 0.f;
- line.extraLength = 0.f;
- line.alignmentOffset = 0.f;
- line.direction = LTR;
- line.ellipsis = false;
- line.lineSpacing = mDefaultLineSpacing;
+ line.width = 0.f;
+ line.ascender = 0.f;
+ line.descender = 0.f;
+ line.extraLength = 0.f;
+ line.alignmentOffset = 0.f;
+ line.direction = LTR;
+ line.ellipsis = false;
+ line.lineSpacing = mDefaultLineSpacing;
}
- Type mLayout;
+ Type mLayout;
float mCursorWidth;
float mDefaultLineSpacing;
float mDefaultLineSize;
};
Engine::Engine()
-: mImpl{ nullptr }
+: mImpl{nullptr}
{
mImpl = new Engine::Impl();
}
delete mImpl;
}
-void Engine::SetMetrics( MetricsPtr& metrics )
+void Engine::SetMetrics(MetricsPtr& metrics)
{
mImpl->mMetrics = metrics;
}
-void Engine::SetLayout( Type layout )
+void Engine::SetLayout(Type layout)
{
mImpl->mLayout = layout;
}
Engine::Type Engine::GetLayout() const
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GetLayout[%d]\n", mImpl->mLayout);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GetLayout[%d]\n", mImpl->mLayout);
return mImpl->mLayout;
}
-void Engine::SetCursorWidth( int width )
+void Engine::SetCursorWidth(int width)
{
- mImpl->mCursorWidth = static_cast<float>( width );
+ mImpl->mCursorWidth = static_cast<float>(width);
}
int Engine::GetCursorWidth() const
{
- return static_cast<int>( mImpl->mCursorWidth );
+ return static_cast<int>(mImpl->mCursorWidth);
}
-bool Engine::LayoutText( Parameters& layoutParameters,
- Size& layoutSize,
- bool elideTextEnabled,
- bool& isAutoScrollEnabled )
+bool Engine::LayoutText(Parameters& layoutParameters,
+ Size& layoutSize,
+ bool elideTextEnabled,
+ bool& isAutoScrollEnabled)
{
- return mImpl->LayoutText( layoutParameters,
- layoutSize,
- elideTextEnabled,
- isAutoScrollEnabled );
+ return mImpl->LayoutText(layoutParameters,
+ layoutSize,
+ elideTextEnabled,
+ isAutoScrollEnabled);
}
-void Engine::Align( const Size& size,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Text::HorizontalAlignment::Type horizontalAlignment,
- Vector<LineRun>& lines,
- float& alignmentOffset,
- Dali::LayoutDirection::Type layoutDirection,
- bool matchSystemLanguageDirection )
+void Engine::Align(const Size& size,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Text::HorizontalAlignment::Type horizontalAlignment,
+ Vector<LineRun>& lines,
+ float& alignmentOffset,
+ Dali::LayoutDirection::Type layoutDirection,
+ bool matchSystemLanguageDirection)
{
- mImpl->Align( size,
- startIndex,
- numberOfCharacters,
- horizontalAlignment,
- lines,
- alignmentOffset,
- layoutDirection,
- matchSystemLanguageDirection );
+ mImpl->Align(size,
+ startIndex,
+ numberOfCharacters,
+ horizontalAlignment,
+ lines,
+ alignmentOffset,
+ layoutDirection,
+ matchSystemLanguageDirection);
}
-void Engine::SetDefaultLineSpacing( float lineSpacing )
+void Engine::SetDefaultLineSpacing(float lineSpacing)
{
mImpl->mDefaultLineSpacing = lineSpacing;
}
return mImpl->mDefaultLineSpacing;
}
-void Engine::SetDefaultLineSize( float lineSize )
+void Engine::SetDefaultLineSize(float lineSize)
{
mImpl->mDefaultLineSize = lineSize;
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-void FreeFontFamilyNames( Vector<FontDescriptionRun>& fontDescriptionRuns )
+void FreeFontFamilyNames(Vector<FontDescriptionRun>& fontDescriptionRuns)
{
- for( Vector<FontDescriptionRun>::Iterator it = fontDescriptionRuns.Begin(),
- endIt = fontDescriptionRuns.End();
- it != endIt;
- ++it )
+ for(Vector<FontDescriptionRun>::Iterator it = fontDescriptionRuns.Begin(),
+ endIt = fontDescriptionRuns.End();
+ it != endIt;
+ ++it)
{
- delete[] (*it).familyName;
+ delete[](*it).familyName;
}
fontDescriptionRuns.Clear();
}
-void FreeEmbeddedItems( Vector<EmbeddedItem>& embeddedItem )
+void FreeEmbeddedItems(Vector<EmbeddedItem>& embeddedItem)
{
- for( Vector<EmbeddedItem>::Iterator it = embeddedItem.Begin(),
- endIt = embeddedItem.End();
- it != endIt;
- ++it )
+ for(Vector<EmbeddedItem>::Iterator it = embeddedItem.Begin(),
+ endIt = embeddedItem.End();
+ it != endIt;
+ ++it)
{
EmbeddedItem& item = *it;
delete[] item.url;
LogicalModelPtr LogicalModel::New()
{
- return LogicalModelPtr( new LogicalModel() );
+ return LogicalModelPtr(new LogicalModel());
}
-Script LogicalModel::GetScript( CharacterIndex characterIndex ) const
+Script LogicalModel::GetScript(CharacterIndex characterIndex) const
{
// If this operation is too slow, consider a binary search.
const ScriptRun* const scriptRunBuffer = mScriptRuns.Begin();
- for( Length index = 0u, length = mScriptRuns.Count(); index < length; ++index )
+ for(Length index = 0u, length = mScriptRuns.Count(); index < length; ++index)
{
const ScriptRun* const scriptRun = scriptRunBuffer + index;
- if( ( scriptRun->characterRun.characterIndex <= characterIndex ) &&
- ( characterIndex < scriptRun->characterRun.characterIndex + scriptRun->characterRun.numberOfCharacters ) )
+ if((scriptRun->characterRun.characterIndex <= characterIndex) &&
+ (characterIndex < scriptRun->characterRun.characterIndex + scriptRun->characterRun.numberOfCharacters))
{
return scriptRun->script;
}
return TextAbstraction::UNKNOWN;
}
-CharacterDirection LogicalModel::GetCharacterDirection( CharacterIndex characterIndex ) const
+CharacterDirection LogicalModel::GetCharacterDirection(CharacterIndex characterIndex) const
{
- if( characterIndex >= mCharacterDirections.Count() )
+ if(characterIndex >= mCharacterDirections.Count())
{
// The model has no right to left characters, so the vector of directions is void.
return false;
}
- return *( mCharacterDirections.Begin() + characterIndex );
+ return *(mCharacterDirections.Begin() + characterIndex);
}
-CharacterIndex LogicalModel::GetLogicalCursorIndex( CharacterIndex visualCursorIndex )
+CharacterIndex LogicalModel::GetLogicalCursorIndex(CharacterIndex visualCursorIndex)
{
// The character's directions buffer.
const CharacterDirection* const modelCharacterDirections = mCharacterDirections.Begin();
CharacterIndex logicalCursorIndex = 0u;
- if( bidirectionalLineInfo->characterRun.characterIndex == visualCursorIndex )
+ if(bidirectionalLineInfo->characterRun.characterIndex == visualCursorIndex)
{
- if( isRightToLeftParagraph )
+ if(isRightToLeftParagraph)
{
logicalCursorIndex = lastCharacterIndex;
}
logicalCursorIndex = bidirectionalLineInfo->characterRun.characterIndex;
}
}
- else if( lastCharacterIndex == visualCursorIndex )
+ else if(lastCharacterIndex == visualCursorIndex)
{
- if( isRightToLeftParagraph )
+ if(isRightToLeftParagraph)
{
logicalCursorIndex = bidirectionalLineInfo->characterRun.characterIndex;
}
// and calculate the logical position according the directions of
// both characters and the direction of the paragraph.
- const CharacterIndex previousVisualCursorIndex = visualCursorIndex - 1u;
- const CharacterIndex previousLogicalCursorIndex = *( bidirectionalLineInfo->visualToLogicalMap + previousVisualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex ) + bidirectionalLineInfo->characterRun.characterIndex;
- const CharacterIndex currentLogicalCursorIndex = *( bidirectionalLineInfo->visualToLogicalMap + visualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex ) + bidirectionalLineInfo->characterRun.characterIndex;
+ const CharacterIndex previousVisualCursorIndex = visualCursorIndex - 1u;
+ const CharacterIndex previousLogicalCursorIndex = *(bidirectionalLineInfo->visualToLogicalMap + previousVisualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex;
+ const CharacterIndex currentLogicalCursorIndex = *(bidirectionalLineInfo->visualToLogicalMap + visualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex;
- const CharacterDirection previousCharacterDirection = *( modelCharacterDirections + previousLogicalCursorIndex );
- const CharacterDirection currentCharacterDirection = *( modelCharacterDirections + currentLogicalCursorIndex );
+ const CharacterDirection previousCharacterDirection = *(modelCharacterDirections + previousLogicalCursorIndex);
+ const CharacterDirection currentCharacterDirection = *(modelCharacterDirections + currentLogicalCursorIndex);
- if( previousCharacterDirection == currentCharacterDirection )
+ if(previousCharacterDirection == currentCharacterDirection)
{
// Both glyphs have the same direction.
- if( previousCharacterDirection )
+ if(previousCharacterDirection)
{
logicalCursorIndex = previousLogicalCursorIndex;
}
}
else
{
- if( isRightToLeftParagraph )
+ if(isRightToLeftParagraph)
{
- if( currentCharacterDirection )
+ if(currentCharacterDirection)
{
logicalCursorIndex = currentLogicalCursorIndex + 1u;
}
}
else
{
- if( previousCharacterDirection )
+ if(previousCharacterDirection)
{
logicalCursorIndex = currentLogicalCursorIndex;
}
return logicalCursorIndex;
}
-CharacterIndex LogicalModel::GetLogicalCharacterIndex( CharacterIndex visualCharacterIndex )
+CharacterIndex LogicalModel::GetLogicalCharacterIndex(CharacterIndex visualCharacterIndex)
{
// The bidirectional line info.
const BidirectionalLineInfoRun* const bidirectionalLineInfo = mBidirectionalLineInfo.Begin() + mBidirectionalLineIndex;
- return *( bidirectionalLineInfo->visualToLogicalMap + visualCharacterIndex - bidirectionalLineInfo->characterRun.characterIndex ) + bidirectionalLineInfo->characterRun.characterIndex;
+ return *(bidirectionalLineInfo->visualToLogicalMap + visualCharacterIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex;
}
-bool LogicalModel::FetchBidirectionalLineInfo( CharacterIndex characterIndex )
+bool LogicalModel::FetchBidirectionalLineInfo(CharacterIndex characterIndex)
{
// The number of bidirectional lines.
const Length numberOfBidirectionalLines = mBidirectionalLineInfo.Count();
- if( 0u == numberOfBidirectionalLines )
+ if(0u == numberOfBidirectionalLines)
{
// If there is no bidirectional info.
return false;
// Check first if the character is in the previously fetched line.
- BidirectionalLineRunIndex bidiLineIndex = 0u;
- CharacterIndex lastCharacterOfRightToLeftRun = 0u;
- if( mBidirectionalLineIndex < numberOfBidirectionalLines )
+ BidirectionalLineRunIndex bidiLineIndex = 0u;
+ CharacterIndex lastCharacterOfRightToLeftRun = 0u;
+ if(mBidirectionalLineIndex < numberOfBidirectionalLines)
{
- const BidirectionalLineInfoRun& bidiLineRun = *( bidirectionalLineInfoBuffer + mBidirectionalLineIndex );
+ const BidirectionalLineInfoRun& bidiLineRun = *(bidirectionalLineInfoBuffer + mBidirectionalLineIndex);
const CharacterIndex lastCharacterOfRunPlusOne = bidiLineRun.characterRun.characterIndex + bidiLineRun.characterRun.numberOfCharacters;
- if( ( bidiLineRun.characterRun.characterIndex <= characterIndex ) &&
- ( characterIndex < lastCharacterOfRunPlusOne ) )
+ if((bidiLineRun.characterRun.characterIndex <= characterIndex) &&
+ (characterIndex < lastCharacterOfRunPlusOne))
{
// The character is in the previously fetched bidi line.
return true;
// The character is not in the previously fetched line.
// Set the bidi line index from where to start the fetch.
- if( characterIndex < bidiLineRun.characterRun.characterIndex )
+ if(characterIndex < bidiLineRun.characterRun.characterIndex)
{
// Start the fetch from the beginning.
bidiLineIndex = 0u;
else
{
// Start the fetch from the next line.
- bidiLineIndex = mBidirectionalLineIndex + 1u;
+ bidiLineIndex = mBidirectionalLineIndex + 1u;
lastCharacterOfRightToLeftRun = lastCharacterOfRunPlusOne - 1u;
}
}
}
// The character has not been found in the previously fetched bidi line.
- for( Vector<BidirectionalLineInfoRun>::ConstIterator it = bidirectionalLineInfoBuffer + bidiLineIndex,
- endIt = mBidirectionalLineInfo.End();
- it != endIt;
- ++it, ++bidiLineIndex )
+ for(Vector<BidirectionalLineInfoRun>::ConstIterator it = bidirectionalLineInfoBuffer + bidiLineIndex,
+ endIt = mBidirectionalLineInfo.End();
+ it != endIt;
+ ++it, ++bidiLineIndex)
{
const BidirectionalLineInfoRun& bidiLineRun = *it;
- if( ( lastCharacterOfRightToLeftRun < characterIndex ) &&
- ( characterIndex < bidiLineRun.characterRun.characterIndex ) )
+ if((lastCharacterOfRightToLeftRun < characterIndex) &&
+ (characterIndex < bidiLineRun.characterRun.characterIndex))
{
// The character is not inside a bidi line.
return false;
}
const CharacterIndex lastCharacterOfRunPlusOne = bidiLineRun.characterRun.characterIndex + bidiLineRun.characterRun.numberOfCharacters;
- lastCharacterOfRightToLeftRun = lastCharacterOfRunPlusOne - 1u;
- if( ( bidiLineRun.characterRun.characterIndex <= characterIndex ) &&
- ( characterIndex < lastCharacterOfRunPlusOne ) )
+ lastCharacterOfRightToLeftRun = lastCharacterOfRunPlusOne - 1u;
+ if((bidiLineRun.characterRun.characterIndex <= characterIndex) &&
+ (characterIndex < lastCharacterOfRunPlusOne))
{
// Bidi line found. Fetch the line.
mBidirectionalLineIndex = bidiLineIndex;
return mBidirectionalLineIndex;
}
-void LogicalModel::UpdateTextStyleRuns( CharacterIndex index, int numberOfCharacters )
+void LogicalModel::UpdateTextStyleRuns(CharacterIndex index, int numberOfCharacters)
{
const Length totalNumberOfCharacters = mText.Count();
// Process the color runs.
Vector<ColorRun> removedColorRuns;
- UpdateCharacterRuns<ColorRun>( index,
- numberOfCharacters,
- totalNumberOfCharacters,
- mColorRuns,
- removedColorRuns );
+ UpdateCharacterRuns<ColorRun>(index,
+ numberOfCharacters,
+ totalNumberOfCharacters,
+ mColorRuns,
+ removedColorRuns);
// Process the background color runs.
Vector<ColorRun> removedBackgroundColorRuns;
- UpdateCharacterRuns<ColorRun>( index,
- numberOfCharacters,
- totalNumberOfCharacters,
- mBackgroundColorRuns,
- removedBackgroundColorRuns );
+ UpdateCharacterRuns<ColorRun>(index,
+ numberOfCharacters,
+ totalNumberOfCharacters,
+ mBackgroundColorRuns,
+ removedBackgroundColorRuns);
// Process the font description runs.
Vector<FontDescriptionRun> removedFontDescriptionRuns;
- UpdateCharacterRuns<FontDescriptionRun>( index,
- numberOfCharacters,
- totalNumberOfCharacters,
- mFontDescriptionRuns,
- removedFontDescriptionRuns );
+ UpdateCharacterRuns<FontDescriptionRun>(index,
+ numberOfCharacters,
+ totalNumberOfCharacters,
+ mFontDescriptionRuns,
+ removedFontDescriptionRuns);
// Free memory allocated for the font family name.
- FreeFontFamilyNames( removedFontDescriptionRuns );
+ FreeFontFamilyNames(removedFontDescriptionRuns);
}
-void LogicalModel::RetrieveStyle( CharacterIndex index, InputStyle& style )
+void LogicalModel::RetrieveStyle(CharacterIndex index, InputStyle& style)
{
unsigned int runIndex = 0u;
// Set the text color.
- bool colorOverriden = false;
- unsigned int colorIndex = 0u;
+ bool colorOverriden = false;
+ unsigned int colorIndex = 0u;
const ColorRun* const colorRunsBuffer = mColorRuns.Begin();
- for( Vector<ColorRun>::ConstIterator it = colorRunsBuffer,
- endIt = mColorRuns.End();
- it != endIt;
- ++it, ++runIndex )
+ for(Vector<ColorRun>::ConstIterator it = colorRunsBuffer,
+ endIt = mColorRuns.End();
+ it != endIt;
+ ++it, ++runIndex)
{
const ColorRun& colorRun = *it;
- if( ( colorRun.characterRun.characterIndex <= index ) &&
- ( index < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters ) )
+ if((colorRun.characterRun.characterIndex <= index) &&
+ (index < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters))
{
- colorIndex = runIndex;
+ colorIndex = runIndex;
colorOverriden = true;
}
}
// Set the text's color if it's overriden.
- if( colorOverriden )
+ if(colorOverriden)
{
- style.textColor = ( *( colorRunsBuffer + colorIndex ) ).color;
+ style.textColor = (*(colorRunsBuffer + colorIndex)).color;
style.isDefaultColor = false;
}
runIndex = 0u;
// Set the font's parameters.
- bool nameOverriden = false;
- bool weightOverriden = false;
- bool widthOverriden = false;
- bool slantOverriden = false;
- bool sizeOverriden = false;
- unsigned int nameIndex = 0u;
- unsigned int weightIndex = 0u;
- unsigned int widthIndex = 0u;
- unsigned int slantIndex = 0u;
- unsigned int sizeIndex = 0u;
+ bool nameOverriden = false;
+ bool weightOverriden = false;
+ bool widthOverriden = false;
+ bool slantOverriden = false;
+ bool sizeOverriden = false;
+ unsigned int nameIndex = 0u;
+ unsigned int weightIndex = 0u;
+ unsigned int widthIndex = 0u;
+ unsigned int slantIndex = 0u;
+ unsigned int sizeIndex = 0u;
const FontDescriptionRun* const fontDescriptionRunsBuffer = mFontDescriptionRuns.Begin();
- for( Vector<FontDescriptionRun>::ConstIterator it = fontDescriptionRunsBuffer,
- endIt = mFontDescriptionRuns.End();
- it != endIt;
- ++it, ++runIndex )
+ for(Vector<FontDescriptionRun>::ConstIterator it = fontDescriptionRunsBuffer,
+ endIt = mFontDescriptionRuns.End();
+ it != endIt;
+ ++it, ++runIndex)
{
const FontDescriptionRun& fontDescriptionRun = *it;
- if( ( fontDescriptionRun.characterRun.characterIndex <= index ) &&
- ( index < fontDescriptionRun.characterRun.characterIndex + fontDescriptionRun.characterRun.numberOfCharacters ) )
+ if((fontDescriptionRun.characterRun.characterIndex <= index) &&
+ (index < fontDescriptionRun.characterRun.characterIndex + fontDescriptionRun.characterRun.numberOfCharacters))
{
- if( fontDescriptionRun.familyDefined )
+ if(fontDescriptionRun.familyDefined)
{
- nameIndex = runIndex;
+ nameIndex = runIndex;
nameOverriden = true;
}
- if( fontDescriptionRun.weightDefined )
+ if(fontDescriptionRun.weightDefined)
{
- weightIndex = runIndex;
+ weightIndex = runIndex;
weightOverriden = true;
}
- if( fontDescriptionRun.widthDefined )
+ if(fontDescriptionRun.widthDefined)
{
- widthIndex = runIndex;
+ widthIndex = runIndex;
widthOverriden = true;
}
- if( fontDescriptionRun.slantDefined )
+ if(fontDescriptionRun.slantDefined)
{
- slantIndex = runIndex;
+ slantIndex = runIndex;
slantOverriden = true;
}
- if( fontDescriptionRun.sizeDefined )
+ if(fontDescriptionRun.sizeDefined)
{
- sizeIndex = runIndex;
+ sizeIndex = runIndex;
sizeOverriden = true;
}
}
}
// Set the font's family name if it's overriden.
- if( nameOverriden )
+ if(nameOverriden)
{
- const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + nameIndex );
+ const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + nameIndex);
- style.familyName = std::string( fontDescriptionRun.familyName, fontDescriptionRun.familyLength );
+ style.familyName = std::string(fontDescriptionRun.familyName, fontDescriptionRun.familyLength);
style.isFamilyDefined = true;
}
// Set the font's weight if it's overriden.
- if( weightOverriden )
+ if(weightOverriden)
{
- const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + weightIndex );
+ const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + weightIndex);
- style.weight = fontDescriptionRun.weight;
+ style.weight = fontDescriptionRun.weight;
style.isWeightDefined = true;
}
// Set the font's width if it's overriden.
- if( widthOverriden )
+ if(widthOverriden)
{
- const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + widthIndex );
+ const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + widthIndex);
- style.width = fontDescriptionRun.width;
+ style.width = fontDescriptionRun.width;
style.isWidthDefined = true;
}
// Set the font's slant if it's overriden.
- if( slantOverriden )
+ if(slantOverriden)
{
- const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + slantIndex );
+ const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + slantIndex);
- style.slant = fontDescriptionRun.slant;
+ style.slant = fontDescriptionRun.slant;
style.isSlantDefined = true;
}
// Set the font's size if it's overriden.
- if( sizeOverriden )
+ if(sizeOverriden)
{
- const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + sizeIndex );
+ const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + sizeIndex);
- style.size = static_cast<float>( fontDescriptionRun.size ) / 64.f;
+ style.size = static_cast<float>(fontDescriptionRun.size) / 64.f;
style.isSizeDefined = true;
}
}
void LogicalModel::ClearFontDescriptionRuns()
{
- FreeFontFamilyNames( mFontDescriptionRuns );
+ FreeFontFamilyNames(mFontDescriptionRuns);
}
-void LogicalModel::CreateParagraphInfo( CharacterIndex startIndex,
- Length numberOfCharacters )
+void LogicalModel::CreateParagraphInfo(CharacterIndex startIndex,
+ Length numberOfCharacters)
{
const Length totalNumberOfCharacters = mLineBreakInfo.Count();
// Count the number of LINE_MUST_BREAK to reserve some space for the vector of paragraph's info.
Vector<CharacterIndex> paragraphs;
- paragraphs.Reserve( numberOfCharacters );
- const TextAbstraction::LineBreakInfo* lineBreakInfoBuffer = mLineBreakInfo.Begin();
- const CharacterIndex lastCharacterIndexPlusOne = startIndex + numberOfCharacters;
- for( Length index = startIndex; index < lastCharacterIndexPlusOne; ++index )
+ paragraphs.Reserve(numberOfCharacters);
+ const TextAbstraction::LineBreakInfo* lineBreakInfoBuffer = mLineBreakInfo.Begin();
+ const CharacterIndex lastCharacterIndexPlusOne = startIndex + numberOfCharacters;
+ for(Length index = startIndex; index < lastCharacterIndexPlusOne; ++index)
{
- if( TextAbstraction::LINE_MUST_BREAK == *( lineBreakInfoBuffer + index ) )
+ if(TextAbstraction::LINE_MUST_BREAK == *(lineBreakInfoBuffer + index))
{
- paragraphs.PushBack( index );
+ paragraphs.PushBack(index);
}
}
const bool updateCurrentParagraphs = numberOfCharacters < totalNumberOfCharacters;
// Reserve space for current paragraphs plus new ones.
- const Length numberOfNewParagraphs = paragraphs.Count();
+ const Length numberOfNewParagraphs = paragraphs.Count();
const Length totalNumberOfParagraphs = mParagraphInfo.Count() + numberOfNewParagraphs;
- mParagraphInfo.Resize( totalNumberOfParagraphs );
+ mParagraphInfo.Resize(totalNumberOfParagraphs);
- ParagraphRun* paragraphInfoBuffer = NULL;
+ ParagraphRun* paragraphInfoBuffer = NULL;
Vector<ParagraphRun> newParagraphs;
- if( updateCurrentParagraphs )
+ if(updateCurrentParagraphs)
{
- newParagraphs.Resize( numberOfNewParagraphs );
+ newParagraphs.Resize(numberOfNewParagraphs);
paragraphInfoBuffer = newParagraphs.Begin();
}
else
// Find where to insert the new paragraphs.
ParagraphRunIndex paragraphIndex = 0u;
- CharacterIndex firstIndex = startIndex;
+ CharacterIndex firstIndex = startIndex;
- if( updateCurrentParagraphs )
+ if(updateCurrentParagraphs)
{
- for( Vector<ParagraphRun>::ConstIterator it = mParagraphInfo.Begin(),
- endIt = mParagraphInfo.Begin() + totalNumberOfParagraphs - numberOfNewParagraphs;
- it != endIt;
- ++it )
+ for(Vector<ParagraphRun>::ConstIterator it = mParagraphInfo.Begin(),
+ endIt = mParagraphInfo.Begin() + totalNumberOfParagraphs - numberOfNewParagraphs;
+ it != endIt;
+ ++it)
{
- const ParagraphRun& paragraph( *it );
+ const ParagraphRun& paragraph(*it);
- if( startIndex < paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters )
+ if(startIndex < paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters)
{
firstIndex = paragraph.characterRun.characterIndex;
break;
// Create the paragraph info.
ParagraphRunIndex newParagraphIndex = 0u;
- for( Vector<CharacterIndex>::ConstIterator it = paragraphs.Begin(),
- endIt = paragraphs.End();
- it != endIt;
- ++it, ++newParagraphIndex )
+ for(Vector<CharacterIndex>::ConstIterator it = paragraphs.Begin(),
+ endIt = paragraphs.End();
+ it != endIt;
+ ++it, ++newParagraphIndex)
{
const CharacterIndex index = *it;
- ParagraphRun& paragraph = *( paragraphInfoBuffer + newParagraphIndex );
- paragraph.characterRun.characterIndex = firstIndex;
+ ParagraphRun& paragraph = *(paragraphInfoBuffer + newParagraphIndex);
+ paragraph.characterRun.characterIndex = firstIndex;
paragraph.characterRun.numberOfCharacters = 1u + index - firstIndex;
firstIndex += paragraph.characterRun.numberOfCharacters;
}
-
// Insert the new paragraphs.
- if( updateCurrentParagraphs )
+ if(updateCurrentParagraphs)
{
- mParagraphInfo.Insert( mParagraphInfo.Begin() + paragraphIndex,
- newParagraphs.Begin(),
- newParagraphs.End() );
+ mParagraphInfo.Insert(mParagraphInfo.Begin() + paragraphIndex,
+ newParagraphs.Begin(),
+ newParagraphs.End());
- mParagraphInfo.Resize( totalNumberOfParagraphs );
+ mParagraphInfo.Resize(totalNumberOfParagraphs);
// Update the next paragraph indices.
- for( Vector<ParagraphRun>::Iterator it = mParagraphInfo.Begin() + paragraphIndex + newParagraphs.Count(),
- endIt = mParagraphInfo.End();
- it != endIt;
- ++it )
+ for(Vector<ParagraphRun>::Iterator it = mParagraphInfo.Begin() + paragraphIndex + newParagraphs.Count(),
+ endIt = mParagraphInfo.End();
+ it != endIt;
+ ++it)
{
- ParagraphRun& paragraph( *it );
+ ParagraphRun& paragraph(*it);
paragraph.characterRun.characterIndex += numberOfCharacters;
}
}
}
-void LogicalModel::FindParagraphs( CharacterIndex index,
- Length numberOfCharacters,
- Vector<ParagraphRunIndex>& paragraphs )
+void LogicalModel::FindParagraphs(CharacterIndex index,
+ Length numberOfCharacters,
+ Vector<ParagraphRunIndex>& paragraphs)
{
// Reserve som space for the paragraph indices.
- paragraphs.Reserve( mParagraphInfo.Count() );
+ paragraphs.Reserve(mParagraphInfo.Count());
// Traverse the paragraphs to find which ones contain the given characters.
ParagraphRunIndex paragraphIndex = 0u;
- for( Vector<ParagraphRun>::ConstIterator it = mParagraphInfo.Begin(),
- endIt = mParagraphInfo.End();
- it != endIt;
- ++it, ++paragraphIndex )
+ for(Vector<ParagraphRun>::ConstIterator it = mParagraphInfo.Begin(),
+ endIt = mParagraphInfo.End();
+ it != endIt;
+ ++it, ++paragraphIndex)
{
- const ParagraphRun& paragraph( *it );
+ const ParagraphRun& paragraph(*it);
- if( ( paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters > index ) &&
- ( paragraph.characterRun.characterIndex < index + numberOfCharacters ) )
+ if((paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters > index) &&
+ (paragraph.characterRun.characterIndex < index + numberOfCharacters))
{
- paragraphs.PushBack( paragraphIndex );
+ paragraphs.PushBack(paragraphIndex);
}
}
}
void LogicalModel::ClearEmbeddedImages()
{
- FreeEmbeddedItems( mEmbeddedItems );
+ FreeEmbeddedItems(mEmbeddedItems);
}
LogicalModel::~LogicalModel()
}
LogicalModel::LogicalModel()
-: mBidirectionalLineIndex( 0u )
+: mBidirectionalLineIndex(0u)
{
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
const std::string XHTML_VALUE_ATTRIBUTE("value");
}
-void ProcessColorTag( const Tag& tag, ColorRun& colorRun )
+void ProcessColorTag(const Tag& tag, ColorRun& colorRun)
{
- for( Vector<Attribute>::ConstIterator it = tag.attributes.Begin(),
- endIt = tag.attributes.End();
- it != endIt;
- ++it )
+ for(Vector<Attribute>::ConstIterator it = tag.attributes.Begin(),
+ endIt = tag.attributes.End();
+ it != endIt;
+ ++it)
{
- const Attribute& attribute( *it );
- if( TokenComparison( XHTML_VALUE_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) )
+ const Attribute& attribute(*it);
+ if(TokenComparison(XHTML_VALUE_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
- ColorStringToVector4( attribute.valueBuffer, attribute.valueLength, colorRun.color );
+ ColorStringToVector4(attribute.valueBuffer, attribute.valueLength, colorRun.color);
}
}
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
const std::string XHTML_URL_ATTRIBUTE("url");
const std::string NONE("none");
const std::string MULTIPLY("multiply");
-}
+} // namespace
-void ProcessEmbeddedItem( const Tag& tag, EmbeddedItem& embeddedItem )
+void ProcessEmbeddedItem(const Tag& tag, EmbeddedItem& embeddedItem)
{
- embeddedItem.url = nullptr;
- embeddedItem.urlLength = 0u;
- embeddedItem.width = 0u;
- embeddedItem.height = 0u;
+ embeddedItem.url = nullptr;
+ embeddedItem.urlLength = 0u;
+ embeddedItem.width = 0u;
+ embeddedItem.height = 0u;
embeddedItem.colorBlendingMode = ColorBlendingMode::NONE;
- for( Vector<Attribute>::ConstIterator it = tag.attributes.Begin(),
- endIt = tag.attributes.End();
- it != endIt;
- ++it )
+ for(Vector<Attribute>::ConstIterator it = tag.attributes.Begin(),
+ endIt = tag.attributes.End();
+ it != endIt;
+ ++it)
{
- const Attribute& attribute( *it );
- if( TokenComparison(XHTML_URL_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) )
+ const Attribute& attribute(*it);
+ if(TokenComparison(XHTML_URL_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
embeddedItem.urlLength = attribute.valueLength;
- embeddedItem.url = new char[embeddedItem.urlLength];
+ embeddedItem.url = new char[embeddedItem.urlLength];
memcpy(embeddedItem.url, attribute.valueBuffer, embeddedItem.urlLength);
// The memory is freed when the font run is removed from the logical model.
}
- else if (TokenComparison(XHTML_WIDTH_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
+ else if(TokenComparison(XHTML_WIDTH_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
embeddedItem.width = StringToUint(attribute.valueBuffer);
}
- else if (TokenComparison(XHTML_HEIGHT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
+ else if(TokenComparison(XHTML_HEIGHT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
embeddedItem.height = StringToUint(attribute.valueBuffer);
}
- else if (TokenComparison(XHTML_COLOR_BLENDING_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
+ else if(TokenComparison(XHTML_COLOR_BLENDING_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
- if (TokenComparison(MULTIPLY, attribute.valueBuffer, attribute.valueLength))
+ if(TokenComparison(MULTIPLY, attribute.valueBuffer, attribute.valueLength))
{
embeddedItem.colorBlendingMode = ColorBlendingMode::MULTIPLY;
}
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
const std::string XHTML_FAMILY_ATTRIBUTE("family");
const std::string XHTML_SLANT_ATTRIBUTE("slant");
const unsigned int MAX_FONT_ATTRIBUTE_SIZE = 15u; ///< The maximum length of any of the possible 'weight', 'width' or 'slant' values.
-}
+} // namespace
-void ProcessFontTag( const Tag& tag, FontDescriptionRun& fontRun )
+void ProcessFontTag(const Tag& tag, FontDescriptionRun& fontRun)
{
- for( Vector<Attribute>::ConstIterator it = tag.attributes.Begin(),
- endIt = tag.attributes.End();
- it != endIt;
- ++it )
+ for(Vector<Attribute>::ConstIterator it = tag.attributes.Begin(),
+ endIt = tag.attributes.End();
+ it != endIt;
+ ++it)
{
- const Attribute& attribute( *it );
- if( TokenComparison( XHTML_FAMILY_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) )
+ const Attribute& attribute(*it);
+ if(TokenComparison(XHTML_FAMILY_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
fontRun.familyDefined = true;
- fontRun.familyLength = attribute.valueLength;
- fontRun.familyName = new char[fontRun.familyLength];
- memcpy( fontRun.familyName, attribute.valueBuffer, fontRun.familyLength );
+ fontRun.familyLength = attribute.valueLength;
+ fontRun.familyName = new char[fontRun.familyLength];
+ memcpy(fontRun.familyName, attribute.valueBuffer, fontRun.familyLength);
// The memory is freed when the font run is removed from the logical model.
}
- else if( TokenComparison( XHTML_SIZE_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) )
+ else if(TokenComparison(XHTML_SIZE_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
// 64.f is used to convert from point size to 26.6 pixel format.
- fontRun.size = static_cast<PointSize26Dot6>( StringToFloat( attribute.valueBuffer ) * 64.f );
+ fontRun.size = static_cast<PointSize26Dot6>(StringToFloat(attribute.valueBuffer) * 64.f);
fontRun.sizeDefined = true;
}
- else if( TokenComparison( XHTML_WEIGHT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) )
+ else if(TokenComparison(XHTML_WEIGHT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
// The StringToWeight() uses the Scripting::GetEnumeration() function which requires the input string to end with a '\0' char.
- char value[MAX_FONT_ATTRIBUTE_SIZE+1u];
+ char value[MAX_FONT_ATTRIBUTE_SIZE + 1u];
const Length length = attribute.valueLength > MAX_FONT_ATTRIBUTE_SIZE ? MAX_FONT_ATTRIBUTE_SIZE : attribute.valueLength;
- memcpy( value, attribute.valueBuffer, length );
+ memcpy(value, attribute.valueBuffer, length);
value[length] = 0;
- fontRun.weight = StringToWeight( value );
+ fontRun.weight = StringToWeight(value);
fontRun.weightDefined = true;
}
- else if( TokenComparison( XHTML_WIDTH_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) )
+ else if(TokenComparison(XHTML_WIDTH_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
// The StringToWidth() uses the Scripting::GetEnumeration() function which requires the input string to end with a '\0' char.
- char value[MAX_FONT_ATTRIBUTE_SIZE+1u];
+ char value[MAX_FONT_ATTRIBUTE_SIZE + 1u];
const Length length = attribute.valueLength > MAX_FONT_ATTRIBUTE_SIZE ? MAX_FONT_ATTRIBUTE_SIZE : attribute.valueLength;
- memcpy( value, attribute.valueBuffer, length );
+ memcpy(value, attribute.valueBuffer, length);
value[length] = 0;
- fontRun.width = StringToWidth( value );
+ fontRun.width = StringToWidth(value);
fontRun.widthDefined = true;
}
- else if( TokenComparison( XHTML_SLANT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) )
+ else if(TokenComparison(XHTML_SLANT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength))
{
// The StringToSlant() uses the Scripting::GetEnumeration() function which requires the input string to end with a '\0' char.
- char value[MAX_FONT_ATTRIBUTE_SIZE+1u];
+ char value[MAX_FONT_ATTRIBUTE_SIZE + 1u];
const Length length = attribute.valueLength > MAX_FONT_ATTRIBUTE_SIZE ? MAX_FONT_ATTRIBUTE_SIZE : attribute.valueLength;
- memcpy( value, attribute.valueBuffer, length );
+ memcpy(value, attribute.valueBuffer, length);
value[length] = 0;
- fontRun.slant = StringToSlant( value );
+ fontRun.slant = StringToSlant(value);
fontRun.slantDefined = true;
}
}
#include <dali/public-api/common/constants.h>
#include <dali/public-api/math/vector2.h>
#include <stdlib.h>
-#include <sstream>
#include <iomanip>
+#include <sstream>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
const char WHITE_SPACE = 0x20; // ASCII value of the white space.
const char LAST_UPPER_CASE = 0x5b; // ASCII value of the one after the last upper case character (Z).
const char TO_LOWER_CASE = 32; // Value to add to a upper case character to transform it into a lower case.
-const char WEB_COLOR_TOKEN( '#' );
-const char* const HEX_COLOR_TOKEN( "0x" );
-const char* const ALPHA_ONE( "FF" );
-
-const std::string BLACK_COLOR( "black" );
-const std::string WHITE_COLOR( "white" );
-const std::string RED_COLOR( "red" );
-const std::string GREEN_COLOR( "green" );
-const std::string BLUE_COLOR( "blue" );
-const std::string YELLOW_COLOR( "yellow" );
-const std::string MAGENTA_COLOR( "magenta" );
-const std::string CYAN_COLOR( "cyan" );
-const std::string TRANSPARENT_COLOR( "transparent" );
-}
-
-bool TokenComparison( const std::string& string1, const char* const stringBuffer2, Length length )
+const char WEB_COLOR_TOKEN('#');
+const char* const HEX_COLOR_TOKEN("0x");
+const char* const ALPHA_ONE("FF");
+
+const std::string BLACK_COLOR("black");
+const std::string WHITE_COLOR("white");
+const std::string RED_COLOR("red");
+const std::string GREEN_COLOR("green");
+const std::string BLUE_COLOR("blue");
+const std::string YELLOW_COLOR("yellow");
+const std::string MAGENTA_COLOR("magenta");
+const std::string CYAN_COLOR("cyan");
+const std::string TRANSPARENT_COLOR("transparent");
+} // namespace
+
+bool TokenComparison(const std::string& string1, const char* const stringBuffer2, Length length)
{
const Length stringSize = string1.size();
- if( stringSize != length )
+ if(stringSize != length)
{
// Early return. Strings have different sizes.
return false;
const char* const stringBuffer1 = string1.c_str();
- for( std::size_t index = 0; index < stringSize; ++index )
+ for(std::size_t index = 0; index < stringSize; ++index)
{
- const char character = *( stringBuffer2 + index );
- const bool toLower = ( character < LAST_UPPER_CASE ) && ( character >= FIRST_UPPER_CASE );
- if( *( stringBuffer1 + index ) != ( toLower ? character + TO_LOWER_CASE : character ) )
+ const char character = *(stringBuffer2 + index);
+ const bool toLower = (character < LAST_UPPER_CASE) && (character >= FIRST_UPPER_CASE);
+ if(*(stringBuffer1 + index) != (toLower ? character + TO_LOWER_CASE : character))
{
return false;
}
return true;
}
-void SkipWhiteSpace( const char*& stringBuffer,
- const char* const stringEndBuffer )
+void SkipWhiteSpace(const char*& stringBuffer,
+ const char* const stringEndBuffer)
{
- for( ; ( WHITE_SPACE >= *stringBuffer ) && ( stringBuffer < stringEndBuffer ); ++stringBuffer );
+ for(; (WHITE_SPACE >= *stringBuffer) && (stringBuffer < stringEndBuffer); ++stringBuffer)
+ ;
}
-void JumpToWhiteSpace( const char*& stringBuffer,
- const char* const stringEndBuffer )
+void JumpToWhiteSpace(const char*& stringBuffer,
+ const char* const stringEndBuffer)
{
- for( ; ( WHITE_SPACE != *stringBuffer ) && ( stringBuffer < stringEndBuffer ); ++stringBuffer );
+ for(; (WHITE_SPACE != *stringBuffer) && (stringBuffer < stringEndBuffer); ++stringBuffer)
+ ;
}
-unsigned int StringToUint( const char* const uintStr )
+unsigned int StringToUint(const char* const uintStr)
{
- return static_cast<unsigned int>( strtoul( uintStr, NULL, 10 ) );
+ return static_cast<unsigned int>(strtoul(uintStr, NULL, 10));
}
-unsigned int StringToHex( const char* const uintStr )
+unsigned int StringToHex(const char* const uintStr)
{
- return static_cast<unsigned int>( strtoul( uintStr, NULL, 16 ) );
+ return static_cast<unsigned int>(strtoul(uintStr, NULL, 16));
}
-float StringToFloat( const char* const floatStr )
+float StringToFloat(const char* const floatStr)
{
- return static_cast<float>( strtod( floatStr, NULL ) );
+ return static_cast<float>(strtod(floatStr, NULL));
}
-void FloatToString( float value, std::string& floatStr )
+void FloatToString(float value, std::string& floatStr)
{
std::stringstream ss;
ss << value;
floatStr = ss.str();
}
-void UintToString( unsigned int value, std::string& uIntStr )
+void UintToString(unsigned int value, std::string& uIntStr)
{
std::stringstream ss;
ss << value;
uIntStr = ss.str();
}
-void UintColorToVector4( unsigned int color, Vector4& retColor )
+void UintColorToVector4(unsigned int color, Vector4& retColor)
{
- retColor.a = static_cast<float>( ( color & 0xFF000000 ) >> 24u ) / 255.f;
- retColor.r = static_cast<float>( ( color & 0x00FF0000 ) >> 16u ) / 255.f;
- retColor.g = static_cast<float>( ( color & 0x0000FF00 ) >> 8u ) / 255.f;
- retColor.b = static_cast<float>( color & 0x000000FF ) / 255.f;
+ retColor.a = static_cast<float>((color & 0xFF000000) >> 24u) / 255.f;
+ retColor.r = static_cast<float>((color & 0x00FF0000) >> 16u) / 255.f;
+ retColor.g = static_cast<float>((color & 0x0000FF00) >> 8u) / 255.f;
+ retColor.b = static_cast<float>(color & 0x000000FF) / 255.f;
}
-void ColorStringToVector4( const char* const colorStr, Length length, Vector4& retColor )
+void ColorStringToVector4(const char* const colorStr, Length length, Vector4& retColor)
{
- if( WEB_COLOR_TOKEN == *colorStr )
+ if(WEB_COLOR_TOKEN == *colorStr)
{
- std::string webColor( colorStr + 1u, length - 1u );
- if( 4u == length ) // 3 component web color #F00 (red)
+ std::string webColor(colorStr + 1u, length - 1u);
+ if(4u == length) // 3 component web color #F00 (red)
{
- webColor.insert( 2u, &( webColor[2] ), 1u );
- webColor.insert( 1u, &( webColor[1] ), 1u );
- webColor.insert( 0u, &( webColor[0] ), 1u );
- webColor.insert( 0u, ALPHA_ONE );
+ webColor.insert(2u, &(webColor[2]), 1u);
+ webColor.insert(1u, &(webColor[1]), 1u);
+ webColor.insert(0u, &(webColor[0]), 1u);
+ webColor.insert(0u, ALPHA_ONE);
}
- else if( 7u == length ) // 6 component web color #FF0000 (red)
+ else if(7u == length) // 6 component web color #FF0000 (red)
{
- webColor.insert( 0u, ALPHA_ONE );
+ webColor.insert(0u, ALPHA_ONE);
}
- UintColorToVector4( StringToHex( webColor.c_str() ), retColor );
+ UintColorToVector4(StringToHex(webColor.c_str()), retColor);
}
- else if( TokenComparison( HEX_COLOR_TOKEN, colorStr, 2u ) )
+ else if(TokenComparison(HEX_COLOR_TOKEN, colorStr, 2u))
{
- UintColorToVector4( StringToHex( colorStr + 2u ), retColor );
+ UintColorToVector4(StringToHex(colorStr + 2u), retColor);
}
- else if( TokenComparison( BLACK_COLOR, colorStr, length ) )
+ else if(TokenComparison(BLACK_COLOR, colorStr, length))
{
retColor = Color::BLACK;
}
- else if( TokenComparison( WHITE_COLOR, colorStr, length ) )
+ else if(TokenComparison(WHITE_COLOR, colorStr, length))
{
retColor = Color::WHITE;
}
- else if( TokenComparison( RED_COLOR, colorStr, length ) )
+ else if(TokenComparison(RED_COLOR, colorStr, length))
{
retColor = Color::RED;
}
- else if( TokenComparison( GREEN_COLOR, colorStr, length ) )
+ else if(TokenComparison(GREEN_COLOR, colorStr, length))
{
retColor = Color::GREEN;
}
- else if( TokenComparison( BLUE_COLOR, colorStr, length ) )
+ else if(TokenComparison(BLUE_COLOR, colorStr, length))
{
retColor = Color::BLUE;
}
- else if( TokenComparison( YELLOW_COLOR, colorStr, length ) )
+ else if(TokenComparison(YELLOW_COLOR, colorStr, length))
{
retColor = Color::YELLOW;
}
- else if( TokenComparison( MAGENTA_COLOR, colorStr, length ) )
+ else if(TokenComparison(MAGENTA_COLOR, colorStr, length))
{
retColor = Color::MAGENTA;
}
- else if( TokenComparison( CYAN_COLOR, colorStr, length ) )
+ else if(TokenComparison(CYAN_COLOR, colorStr, length))
{
retColor = Color::CYAN;
}
- else if( TokenComparison( TRANSPARENT_COLOR, colorStr, length ) )
+ else if(TokenComparison(TRANSPARENT_COLOR, colorStr, length))
{
retColor = Color::TRANSPARENT;
}
}
-void Vector4ToColorString( const Vector4& value, std::string& vector2Str )
+void Vector4ToColorString(const Vector4& value, std::string& vector2Str)
{
- if( Color::BLACK == value )
+ if(Color::BLACK == value)
{
vector2Str = BLACK_COLOR;
return;
}
- if( Color::WHITE == value )
+ if(Color::WHITE == value)
{
vector2Str = WHITE_COLOR;
return;
}
- if( Color::RED == value )
+ if(Color::RED == value)
{
vector2Str = RED_COLOR;
return;
}
- if( Color::GREEN == value )
+ if(Color::GREEN == value)
{
vector2Str = GREEN_COLOR;
return;
}
- if( Color::BLUE == value )
+ if(Color::BLUE == value)
{
vector2Str = BLUE_COLOR;
return;
}
- if( Color::YELLOW == value )
+ if(Color::YELLOW == value)
{
vector2Str = YELLOW_COLOR;
return;
}
- if( Color::MAGENTA == value )
+ if(Color::MAGENTA == value)
{
vector2Str = MAGENTA_COLOR;
return;
}
- if( Color::CYAN == value )
+ if(Color::CYAN == value)
{
vector2Str = CYAN_COLOR;
return;
}
- if( Color::TRANSPARENT == value )
+ if(Color::TRANSPARENT == value)
{
vector2Str = TRANSPARENT_COLOR;
return;
}
- const unsigned int alpha = static_cast<unsigned int>( 255.f * value.a );
- const unsigned int red = static_cast<unsigned int>( 255.f * value.r );
- const unsigned int green = static_cast<unsigned int>( 255.f * value.g );
- const unsigned int blue = static_cast<unsigned int>( 255.f * value.b );
+ const unsigned int alpha = static_cast<unsigned int>(255.f * value.a);
+ const unsigned int red = static_cast<unsigned int>(255.f * value.r);
+ const unsigned int green = static_cast<unsigned int>(255.f * value.g);
+ const unsigned int blue = static_cast<unsigned int>(255.f * value.b);
- std::stringstream ss;
- const unsigned int size = 2u * sizeof( unsigned char );
+ std::stringstream ss;
+ const unsigned int size = 2u * sizeof(unsigned char);
ss << "0x"
- << std::setfill('0') << std::setw( size )
+ << std::setfill('0') << std::setw(size)
<< std::hex << alpha
- << std::setfill('0') << std::setw( size )
+ << std::setfill('0') << std::setw(size)
<< std::hex << red
- << std::setfill('0') << std::setw( size )
+ << std::setfill('0') << std::setw(size)
<< std::hex << green
- << std::setfill('0') << std::setw( size )
+ << std::setfill('0') << std::setw(size)
<< std::hex << blue;
vector2Str = ss.str();
}
-void StringToVector2( const char* const vectorStr, Length length, Vector2& vector2 )
+void StringToVector2(const char* const vectorStr, Length length, Vector2& vector2)
{
// Points to the first character of the string.
const char* strBuffer = vectorStr;
const char* const xBuffer = strBuffer;
// Jumps to the next white space.
- JumpToWhiteSpace( strBuffer, strBuffer + length );
+ JumpToWhiteSpace(strBuffer, strBuffer + length);
// Points to the first character of the 'y' value.
const char* const yBuffer = strBuffer;
// Converts the shadow's offset to float.
- vector2.x = StringToFloat( xBuffer );
- vector2.y = StringToFloat( yBuffer );
+ vector2.x = StringToFloat(xBuffer);
+ vector2.y = StringToFloat(yBuffer);
}
-void Vector2ToString( const Vector2& value, std::string& vector2Str )
+void Vector2ToString(const Vector2& value, std::string& vector2Str)
{
- FloatToString( value.x, vector2Str );
+ FloatToString(value.x, vector2Str);
vector2Str += " ";
std::string yStr;
- FloatToString( value.y, yStr );
+ FloatToString(value.y, yStr);
vector2Str += yStr;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/markup-processor.h>
// EXTERNAL INCLUDES
-#include <climits> // for ULONG_MAX
-#include <functional>
#include <dali/integration-api/debug.h>
+#include <climits> // for ULONG_MAX
+#include <functional>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/character-set-conversion.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
// HTML-ISH tag and attribute constants.
const char CHAR_ARRAY_END = '\0';
const char HEX_CODE = 'x';
-const char WHITE_SPACE = 0x20; // ASCII value of the white space.
+const char WHITE_SPACE = 0x20; // ASCII value of the white space.
// Range 1 0x0u < XHTML_DECIMAL_ENTITY_RANGE <= 0xD7FFu
// Range 2 0xE000u < XHTML_DECIMAL_ENTITY_RANGE <= 0xFFFDu
// Range 3 0x10000u < XHTML_DECIMAL_ENTITY_RANGE <= 0x10FFFFu
-const unsigned long XHTML_DECIMAL_ENTITY_RANGE[] = { 0x0u, 0xD7FFu, 0xE000u, 0xFFFDu, 0x10000u, 0x10FFFFu };
+const unsigned long XHTML_DECIMAL_ENTITY_RANGE[] = {0x0u, 0xD7FFu, 0xE000u, 0xFFFDu, 0x10000u, 0x10FFFFu};
-const unsigned int MAX_NUM_OF_ATTRIBUTES = 5u; ///< The font tag has the 'family', 'size' 'weight', 'width' and 'slant' attrubutes.
+const unsigned int MAX_NUM_OF_ATTRIBUTES = 5u; ///< The font tag has the 'family', 'size' 'weight', 'width' and 'slant' attrubutes.
const unsigned int DEFAULT_VECTOR_SIZE = 16u; ///< Default size of run vectors.
#if defined(DEBUG_ENABLED)
{
typedef VectorBase::SizeType RunIndex;
- Vector<RunIndex> stack; ///< Use a vector as a style stack. Stores the indices pointing where the run is stored inside the logical model.
- unsigned int topIndex; ///< Points the top of the stack.
+ Vector<RunIndex> stack; ///< Use a vector as a style stack. Stores the indices pointing where the run is stored inside the logical model.
+ unsigned int topIndex; ///< Points the top of the stack.
StyleStack()
: stack(),
- topIndex( 0u )
+ topIndex(0u)
{
- stack.Resize( DEFAULT_VECTOR_SIZE );
+ stack.Resize(DEFAULT_VECTOR_SIZE);
}
- void Push( RunIndex index )
+ void Push(RunIndex index)
{
// Check if there is space inside the style stack.
const VectorBase::SizeType size = stack.Count();
- if( topIndex >= size )
+ if(topIndex >= size)
{
// Resize the style stack.
- stack.Resize( 2u * size );
+ stack.Resize(2u * size);
}
// Set the run index in the top of the stack.
- *( stack.Begin() + topIndex ) = index;
+ *(stack.Begin() + topIndex) = index;
// Reposition the pointer to the top of the stack.
++topIndex;
{
// Pop the top of the stack.
--topIndex;
- return *( stack.Begin() + topIndex );
+ return *(stack.Begin() + topIndex);
}
};
*
* @param[in,out] fontRun The font description run to initialize.
*/
-void Initialize( FontDescriptionRun& fontRun )
+void Initialize(FontDescriptionRun& fontRun)
{
- fontRun.characterRun.characterIndex = 0u;
+ fontRun.characterRun.characterIndex = 0u;
fontRun.characterRun.numberOfCharacters = 0u;
- fontRun.familyName = NULL;
- fontRun.familyLength = 0u;
- fontRun.weight = TextAbstraction::FontWeight::NORMAL;
- fontRun.width = TextAbstraction::FontWidth::NORMAL;
- fontRun.slant = TextAbstraction::FontSlant::NORMAL;
- fontRun.size = 0u;
- fontRun.familyDefined = false;
- fontRun.weightDefined = false;
- fontRun.widthDefined = false;
- fontRun.slantDefined = false;
- fontRun.sizeDefined = false;
+ fontRun.familyName = NULL;
+ fontRun.familyLength = 0u;
+ fontRun.weight = TextAbstraction::FontWeight::NORMAL;
+ fontRun.width = TextAbstraction::FontWidth::NORMAL;
+ fontRun.slant = TextAbstraction::FontSlant::NORMAL;
+ fontRun.size = 0u;
+ fontRun.familyDefined = false;
+ fontRun.weightDefined = false;
+ fontRun.widthDefined = false;
+ fontRun.slantDefined = false;
+ fontRun.sizeDefined = false;
}
/**
*
* @param[in,out] colorRun The font description run to initialize.
*/
-void Initialize( ColorRun& colorRun )
+void Initialize(ColorRun& colorRun)
{
- colorRun.characterRun.characterIndex = 0u;
+ colorRun.characterRun.characterIndex = 0u;
colorRun.characterRun.numberOfCharacters = 0u;
}
*
* @param[in,out] tag The tag.
*/
-void ParseAttributes( Tag& tag )
+void ParseAttributes(Tag& tag)
{
- if( tag.buffer == NULL )
+ if(tag.buffer == NULL)
{
return;
}
- tag.attributes.Resize( MAX_NUM_OF_ATTRIBUTES );
+ tag.attributes.Resize(MAX_NUM_OF_ATTRIBUTES);
// Find first the tag name.
bool isQuotationOpen = false;
- const char* tagBuffer = tag.buffer;
+ const char* tagBuffer = tag.buffer;
const char* const tagEndBuffer = tagBuffer + tag.length;
- tag.length = 0u;
- for( ; tagBuffer < tagEndBuffer; ++tagBuffer )
+ tag.length = 0u;
+ for(; tagBuffer < tagEndBuffer; ++tagBuffer)
{
const char character = *tagBuffer;
- if( WHITE_SPACE < character )
+ if(WHITE_SPACE < character)
{
++tag.length;
}
break;
}
}
- SkipWhiteSpace( tagBuffer, tagEndBuffer );
+ SkipWhiteSpace(tagBuffer, tagEndBuffer);
// Find the attributes.
unsigned int attributeIndex = 0u;
- const char* nameBuffer = NULL;
- const char* valueBuffer = NULL;
- Length nameLength = 0u;
- Length valueLength = 0u;
+ const char* nameBuffer = NULL;
+ const char* valueBuffer = NULL;
+ Length nameLength = 0u;
+ Length valueLength = 0u;
- bool addToNameValue = true;
+ bool addToNameValue = true;
Length numberOfWhiteSpace = 0u;
- for( ; tagBuffer < tagEndBuffer; ++tagBuffer )
+ for(; tagBuffer < tagEndBuffer; ++tagBuffer)
{
const char character = *tagBuffer;
- if( ( WHITE_SPACE >= character ) && !isQuotationOpen )
+ if((WHITE_SPACE >= character) && !isQuotationOpen)
{
- if( NULL != valueBuffer )
+ if(NULL != valueBuffer)
{
// Remove white spaces at the end of the value.
valueLength -= numberOfWhiteSpace;
}
- if( ( NULL != nameBuffer ) && ( NULL != valueBuffer ) )
+ if((NULL != nameBuffer) && (NULL != valueBuffer))
{
// Every time a white space is found, a new attribute is created and stored in the attributes vector.
- Attribute& attribute = *( tag.attributes.Begin() + attributeIndex );
+ Attribute& attribute = *(tag.attributes.Begin() + attributeIndex);
++attributeIndex;
- attribute.nameBuffer = nameBuffer;
+ attribute.nameBuffer = nameBuffer;
attribute.valueBuffer = valueBuffer;
- attribute.nameLength = nameLength;
+ attribute.nameLength = nameLength;
attribute.valueLength = valueLength;
- nameBuffer = NULL;
+ nameBuffer = NULL;
valueBuffer = NULL;
- nameLength = 0u;
+ nameLength = 0u;
valueLength = 0u;
addToNameValue = true; // next read characters will be added to the name.
}
}
- else if( EQUAL == character ) // '='
+ else if(EQUAL == character) // '='
{
addToNameValue = false; // next read characters will be added to the value.
- SkipWhiteSpace( tagBuffer, tagEndBuffer );
+ SkipWhiteSpace(tagBuffer, tagEndBuffer);
}
- else if( QUOTATION_MARK == character ) // '\''
+ else if(QUOTATION_MARK == character) // '\''
{
// Do not add quotation marks to neither name nor value.
isQuotationOpen = !isQuotationOpen;
- if( isQuotationOpen )
+ if(isQuotationOpen)
{
++tagBuffer;
- SkipWhiteSpace( tagBuffer, tagEndBuffer );
+ SkipWhiteSpace(tagBuffer, tagEndBuffer);
--tagBuffer;
}
}
else
{
// Adds characters to the name or the value.
- if( addToNameValue )
+ if(addToNameValue)
{
- if( NULL == nameBuffer )
+ if(NULL == nameBuffer)
{
nameBuffer = tagBuffer;
}
}
else
{
- if( isQuotationOpen )
+ if(isQuotationOpen)
{
- if( WHITE_SPACE >= character )
+ if(WHITE_SPACE >= character)
{
++numberOfWhiteSpace;
}
numberOfWhiteSpace = 0u;
}
}
- if( NULL == valueBuffer )
+ if(NULL == valueBuffer)
{
valueBuffer = tagBuffer;
}
}
}
- if( NULL != valueBuffer )
+ if(NULL != valueBuffer)
{
// Remove white spaces at the end of the value.
valueLength -= numberOfWhiteSpace;
}
- if( ( NULL != nameBuffer ) && ( NULL != valueBuffer ) )
+ if((NULL != nameBuffer) && (NULL != valueBuffer))
{
// Checks if the last attribute needs to be added.
- Attribute& attribute = *( tag.attributes.Begin() + attributeIndex );
+ Attribute& attribute = *(tag.attributes.Begin() + attributeIndex);
++attributeIndex;
- attribute.nameBuffer = nameBuffer;
+ attribute.nameBuffer = nameBuffer;
attribute.valueBuffer = valueBuffer;
- attribute.nameLength = nameLength;
+ attribute.nameLength = nameLength;
attribute.valueLength = valueLength;
}
// Resize the vector of attributes.
- tag.attributes.Resize( attributeIndex );
+ tag.attributes.Resize(attributeIndex);
}
/**
*
* @return @e true if the iterator @e it is pointing a mark-up tag. Otherwise @e false.
*/
-bool IsTag( const char*& markupStringBuffer,
- const char* const markupStringEndBuffer,
- Tag& tag )
+bool IsTag(const char*& markupStringBuffer,
+ const char* const markupStringEndBuffer,
+ Tag& tag)
{
- bool isTag = false;
- bool isQuotationOpen = false;
- bool attributesFound = false;
- tag.isEndTag = false;
+ bool isTag = false;
+ bool isQuotationOpen = false;
+ bool attributesFound = false;
+ tag.isEndTag = false;
bool isPreviousLessThan = false;
- bool isPreviousSlash = false;
+ bool isPreviousSlash = false;
const char character = *markupStringBuffer;
- if( LESS_THAN == character ) // '<'
+ if(LESS_THAN == character) // '<'
{
- tag.buffer = NULL;
- tag.length = 0u;
+ tag.buffer = NULL;
+ tag.length = 0u;
isPreviousLessThan = true;
// if the iterator is pointing to a '<' character, then check if it's a mark-up tag is needed.
++markupStringBuffer;
- if( markupStringBuffer < markupStringEndBuffer )
+ if(markupStringBuffer < markupStringEndBuffer)
{
- SkipWhiteSpace( markupStringBuffer, markupStringEndBuffer );
+ SkipWhiteSpace(markupStringBuffer, markupStringEndBuffer);
- for( ; ( !isTag ) && ( markupStringBuffer < markupStringEndBuffer ); ++markupStringBuffer )
+ for(; (!isTag) && (markupStringBuffer < markupStringEndBuffer); ++markupStringBuffer)
{
const char character = *markupStringBuffer;
- if( !isQuotationOpen && ( SLASH == character ) ) // '/'
+ if(!isQuotationOpen && (SLASH == character)) // '/'
{
- if (isPreviousLessThan)
+ if(isPreviousLessThan)
{
tag.isEndTag = true;
}
}
isPreviousLessThan = false;
- if( ( markupStringBuffer + 1u < markupStringEndBuffer ) && ( WHITE_SPACE >= *( markupStringBuffer + 1u ) ) )
+ if((markupStringBuffer + 1u < markupStringEndBuffer) && (WHITE_SPACE >= *(markupStringBuffer + 1u)))
{
++markupStringBuffer;
- SkipWhiteSpace( markupStringBuffer, markupStringEndBuffer );
+ SkipWhiteSpace(markupStringBuffer, markupStringEndBuffer);
--markupStringBuffer;
}
}
- else if( GREATER_THAN == character ) // '>'
+ else if(GREATER_THAN == character) // '>'
{
isTag = true;
- if (isPreviousSlash)
+ if(isPreviousSlash)
{
tag.isEndTag = true;
}
- isPreviousSlash = false;
+ isPreviousSlash = false;
isPreviousLessThan = false;
}
- else if( QUOTATION_MARK == character )
+ else if(QUOTATION_MARK == character)
{
isQuotationOpen = !isQuotationOpen;
++tag.length;
- isPreviousSlash = false;
+ isPreviousSlash = false;
isPreviousLessThan = false;
}
- else if( WHITE_SPACE >= character ) // ' '
+ else if(WHITE_SPACE >= character) // ' '
{
// If the tag contains white spaces then it may have attributes.
- if( !isQuotationOpen )
+ if(!isQuotationOpen)
{
attributesFound = true;
}
}
else
{
- if( NULL == tag.buffer )
+ if(NULL == tag.buffer)
{
tag.buffer = markupStringBuffer;
}
// If it's not any of the 'special' characters then just add it to the tag string.
++tag.length;
- isPreviousSlash = false;
+ isPreviousSlash = false;
isPreviousLessThan = false;
}
}
}
// If the tag string has white spaces, then parse the attributes is needed.
- if( attributesFound )
+ if(attributesFound)
{
- ParseAttributes( tag );
+ ParseAttributes(tag);
}
}
*
* @return Length of markupText in case of XHTML entity otherwise return 0.
*/
-unsigned int GetXHTMLEntityLength( const char*& markupStringBuffer,
- const char* const markupStringEndBuffer )
+unsigned int GetXHTMLEntityLength(const char*& markupStringBuffer,
+ const char* const markupStringEndBuffer)
{
char character = *markupStringBuffer;
- if( AMPERSAND == character ) // '&'
+ if(AMPERSAND == character) // '&'
{
// if the iterator is pointing to a '&' character, then check for ';' to find end to XHTML entity.
++markupStringBuffer;
- if( markupStringBuffer < markupStringEndBuffer )
+ if(markupStringBuffer < markupStringEndBuffer)
{
unsigned int len = 1u;
- for( ; markupStringBuffer < markupStringEndBuffer ; ++markupStringBuffer )
+ for(; markupStringBuffer < markupStringEndBuffer; ++markupStringBuffer)
{
character = *markupStringBuffer;
++len;
- if( SEMI_COLON == character ) // ';'
+ if(SEMI_COLON == character) // ';'
{
// found end of XHTML entity
++markupStringBuffer;
return len;
}
- else if( ( AMPERSAND == character ) || ( BACK_SLASH == character ) || ( LESS_THAN == character ))
+ else if((AMPERSAND == character) || (BACK_SLASH == character) || (LESS_THAN == character))
{
return 0;
}
*
* @return true if string is successfully parsed otherwise false
*/
-bool XHTMLNumericEntityToUtf8 ( const char* markupText, char* utf8 )
+bool XHTMLNumericEntityToUtf8(const char* markupText, char* utf8)
{
bool result = false;
- if( NULL != markupText )
+ if(NULL != markupText)
{
bool isHex = false;
// check if hex or decimal entity
- if( ( CHAR_ARRAY_END != *markupText ) && ( HEX_CODE == *markupText ) )
+ if((CHAR_ARRAY_END != *markupText) && (HEX_CODE == *markupText))
{
isHex = true;
++markupText;
}
- char* end = NULL;
- unsigned long l = strtoul( markupText, &end, ( isHex ? 16 : 10 ) ); // l contains UTF-32 code in case of correct XHTML entity
+ char* end = NULL;
+ unsigned long l = strtoul(markupText, &end, (isHex ? 16 : 10)); // l contains UTF-32 code in case of correct XHTML entity
// check for valid XHTML numeric entities (between '#' or "#x" and ';')
- if( ( l > 0 ) && ( l < ULONG_MAX ) && ( *end == SEMI_COLON ) ) // in case wrong XHTML entity is set eg. "abcdefs;" in that case *end will be 'a'
+ if((l > 0) && (l < ULONG_MAX) && (*end == SEMI_COLON)) // in case wrong XHTML entity is set eg. "abcdefs;" in that case *end will be 'a'
{
/* characters XML 1.1 permits */
- if( ( ( XHTML_DECIMAL_ENTITY_RANGE[0] < l ) && ( l <= XHTML_DECIMAL_ENTITY_RANGE[1] ) ) ||
- ( ( XHTML_DECIMAL_ENTITY_RANGE[2] <= l ) && ( l <= XHTML_DECIMAL_ENTITY_RANGE[3] ) ) ||
- ( ( XHTML_DECIMAL_ENTITY_RANGE[4] <= l ) && ( l <= XHTML_DECIMAL_ENTITY_RANGE[5] ) ) )
+ if(((XHTML_DECIMAL_ENTITY_RANGE[0] < l) && (l <= XHTML_DECIMAL_ENTITY_RANGE[1])) ||
+ ((XHTML_DECIMAL_ENTITY_RANGE[2] <= l) && (l <= XHTML_DECIMAL_ENTITY_RANGE[3])) ||
+ ((XHTML_DECIMAL_ENTITY_RANGE[4] <= l) && (l <= XHTML_DECIMAL_ENTITY_RANGE[5])))
{
// Convert UTF32 code to UTF8
- Utf32ToUtf8( reinterpret_cast<const uint32_t* const>( &l ), 1, reinterpret_cast<uint8_t*>( utf8 ) );
+ Utf32ToUtf8(reinterpret_cast<const uint32_t* const>(&l), 1, reinterpret_cast<uint8_t*>(utf8));
result = true;
- }
+ }
}
}
return result;
* @param[in/out] tagReference The tagReference we should increment/decrement
* @param[in] parameterSettingFunction This function will be called to set run specific parameters
*/
-template <typename RunType>
+template<typename RunType>
void ProcessTagForRun(
- Vector<RunType>& runsContainer,
- StyleStack& styleStack,
- const Tag& tag,
- const CharacterIndex characterIndex,
- StyleStack::RunIndex& runIndex,
- int& tagReference,
- std::function<void (const Tag&, RunType&)> parameterSettingFunction)
+ Vector<RunType>& runsContainer,
+ StyleStack& styleStack,
+ const Tag& tag,
+ const CharacterIndex characterIndex,
+ StyleStack::RunIndex& runIndex,
+ int& tagReference,
+ std::function<void(const Tag&, RunType&)> parameterSettingFunction)
{
- if( !tag.isEndTag )
+ if(!tag.isEndTag)
{
// Create a new run.
RunType run;
}
else
{
- if( tagReference > 0 )
+ if(tagReference > 0)
{
// Pop the top of the stack and set the number of characters of the run.
- RunType& run = *( runsContainer.Begin() + styleStack.Pop() );
+ RunType& run = *(runsContainer.Begin() + styleStack.Pop());
run.characterRun.numberOfCharacters = characterIndex - run.characterRun.characterIndex;
--tagReference;
}
* @param[in/out] characterIndex The current character index
*/
void ProcessItemTag(
- MarkupProcessData& markupProcessData,
- const Tag tag,
- CharacterIndex& characterIndex)
+ MarkupProcessData& markupProcessData,
+ const Tag tag,
+ CharacterIndex& characterIndex)
{
- if (tag.isEndTag)
+ if(tag.isEndTag)
{
// Create an embedded item instance.
EmbeddedItem item;
markupProcessData.items.PushBack(item);
// Insert white space character that will be replaced by the item.
- markupProcessData.markupProcessedText.append( 1u, WHITE_SPACE );
+ markupProcessData.markupProcessedText.append(1u, WHITE_SPACE);
++characterIndex;
}
}
*/
void ResizeModelVectors(MarkupProcessData& markupProcessData, const StyleStack::RunIndex fontRunIndex, const StyleStack::RunIndex colorRunIndex)
{
- markupProcessData.fontRuns.Resize( fontRunIndex );
- markupProcessData.colorRuns.Resize( colorRunIndex );
+ markupProcessData.fontRuns.Resize(fontRunIndex);
+ markupProcessData.colorRuns.Resize(colorRunIndex);
#ifdef DEBUG_ENABLED
- for( unsigned int i=0; i<colorRunIndex; ++i )
+ for(unsigned int i = 0; i < colorRunIndex; ++i)
{
ColorRun& run = markupProcessData.colorRuns[i];
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "run[%d] index: %d, length: %d, color %f,%f,%f,%f\n", i, run.characterRun.characterIndex, run.characterRun.numberOfCharacters, run.color.r, run.color.g, run.color.b, run.color.a );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "run[%d] index: %d, length: %d, color %f,%f,%f,%f\n", i, run.characterRun.characterIndex, run.characterRun.numberOfCharacters, run.color.r, run.color.g, run.color.b, run.color.a);
}
#endif
}
* @param[in/out] characterIndex The current character index
*/
void ProcessMarkupStringBuffer(
- MarkupProcessData& markupProcessData,
- const char*& markupStringBuffer,
- const char* const markupStringEndBuffer,
- CharacterIndex& characterIndex)
+ MarkupProcessData& markupProcessData,
+ const char*& markupStringBuffer,
+ const char* const markupStringEndBuffer,
+ CharacterIndex& characterIndex)
{
- unsigned char character = *markupStringBuffer;
- const char* markupBuffer = markupStringBuffer;
- unsigned char count = GetUtf8Length( character );
- char utf8[8];
+ unsigned char character = *markupStringBuffer;
+ const char* markupBuffer = markupStringBuffer;
+ unsigned char count = GetUtf8Length(character);
+ char utf8[8];
- if( ( BACK_SLASH == character ) && ( markupStringBuffer + 1u < markupStringEndBuffer ) )
+ if((BACK_SLASH == character) && (markupStringBuffer + 1u < markupStringEndBuffer))
{
// Adding < , > or & special character.
- const unsigned char nextCharacter = *( markupStringBuffer + 1u );
- if( ( LESS_THAN == nextCharacter ) || ( GREATER_THAN == nextCharacter ) || ( AMPERSAND == nextCharacter ) )
+ const unsigned char nextCharacter = *(markupStringBuffer + 1u);
+ if((LESS_THAN == nextCharacter) || (GREATER_THAN == nextCharacter) || (AMPERSAND == nextCharacter))
{
character = nextCharacter;
++markupStringBuffer;
- count = GetUtf8Length( character );
+ count = GetUtf8Length(character);
markupBuffer = markupStringBuffer;
}
}
- else // checking if contains XHTML entity or not
+ else // checking if contains XHTML entity or not
{
- const unsigned int len = GetXHTMLEntityLength( markupStringBuffer, markupStringEndBuffer);
+ const unsigned int len = GetXHTMLEntityLength(markupStringBuffer, markupStringEndBuffer);
// Parse markupStringTxt if it contains XHTML Entity between '&' and ';'
- if( len > 0 )
+ if(len > 0)
{
char* entityCode = NULL;
- bool result = false;
- count = 0;
+ bool result = false;
+ count = 0;
// Checking if XHTML Numeric Entity
- if( HASH == *( markupBuffer + 1u ) )
+ if(HASH == *(markupBuffer + 1u))
{
entityCode = &utf8[0];
// markupBuffer is currently pointing to '&'. By adding 2u to markupBuffer it will point to numeric string by skipping "&#'
- result = XHTMLNumericEntityToUtf8( ( markupBuffer + 2u ), entityCode );
+ result = XHTMLNumericEntityToUtf8((markupBuffer + 2u), entityCode);
}
- else // Checking if XHTML Named Entity
+ else // Checking if XHTML Named Entity
{
- entityCode = const_cast<char*> ( NamedEntityToUtf8( markupBuffer, len ) );
- result = ( entityCode != NULL );
+ entityCode = const_cast<char*>(NamedEntityToUtf8(markupBuffer, len));
+ result = (entityCode != NULL);
}
- if ( result )
+ if(result)
{
markupBuffer = entityCode; //utf8 text assigned to markupBuffer
- character = markupBuffer[0];
+ character = markupBuffer[0];
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Not valid XHTML entity : (%.*s) \n", len, markupBuffer );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Not valid XHTML entity : (%.*s) \n", len, markupBuffer);
markupBuffer = NULL;
}
}
- else // in case string conatins Start of XHTML Entity('&') but not its end character(';')
+ else // in case string conatins Start of XHTML Entity('&') but not its end character(';')
{
- if( character == AMPERSAND )
+ if(character == AMPERSAND)
{
markupBuffer = NULL;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Not Well formed XHTML content \n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Not Well formed XHTML content \n");
}
}
}
- if( markupBuffer != NULL )
+ if(markupBuffer != NULL)
{
- const unsigned char numberOfBytes = GetUtf8Length( character );
- markupProcessData.markupProcessedText.push_back( character );
+ const unsigned char numberOfBytes = GetUtf8Length(character);
+ markupProcessData.markupProcessedText.push_back(character);
- for( unsigned char i = 1u; i < numberOfBytes; ++i )
+ for(unsigned char i = 1u; i < numberOfBytes; ++i)
{
++markupBuffer;
- markupProcessData.markupProcessedText.push_back( *markupBuffer );
+ markupProcessData.markupProcessedText.push_back(*markupBuffer);
}
++characterIndex;
} // namespace
-void ProcessMarkupString( const std::string& markupString, MarkupProcessData& markupProcessData )
+void ProcessMarkupString(const std::string& markupString, MarkupProcessData& markupProcessData)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "markupString: %s\n", markupString.c_str() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "markupString: %s\n", markupString.c_str());
// Reserve space for the plain text.
const Length markupStringSize = markupString.size();
- markupProcessData.markupProcessedText.reserve( markupStringSize );
+ markupProcessData.markupProcessedText.reserve(markupStringSize);
// Stores a struct with the index to the first character of the run, the type of run and its parameters.
StyleStack styleStack;
// Points the next free position in the vector of runs.
StyleStack::RunIndex colorRunIndex = 0u;
- StyleStack::RunIndex fontRunIndex = 0u;
+ StyleStack::RunIndex fontRunIndex = 0u;
// check tag reference
int colorTagReference = 0u;
- int fontTagReference = 0u;
- int iTagReference = 0u;
- int bTagReference = 0u;
+ int fontTagReference = 0u;
+ int iTagReference = 0u;
+ int bTagReference = 0u;
// Give an initial default value to the model's vectors.
- markupProcessData.colorRuns.Reserve( DEFAULT_VECTOR_SIZE );
- markupProcessData.fontRuns.Reserve( DEFAULT_VECTOR_SIZE );
+ markupProcessData.colorRuns.Reserve(DEFAULT_VECTOR_SIZE);
+ markupProcessData.fontRuns.Reserve(DEFAULT_VECTOR_SIZE);
// Get the mark-up string buffer.
- const char* markupStringBuffer = markupString.c_str();
+ const char* markupStringBuffer = markupString.c_str();
const char* const markupStringEndBuffer = markupStringBuffer + markupStringSize;
- Tag tag;
+ Tag tag;
CharacterIndex characterIndex = 0u;
- for( ; markupStringBuffer < markupStringEndBuffer; )
+ for(; markupStringBuffer < markupStringEndBuffer;)
{
tag.attributes.Clear();
- if( IsTag( markupStringBuffer,
- markupStringEndBuffer,
- tag ) )
+ if(IsTag(markupStringBuffer,
+ markupStringEndBuffer,
+ tag))
{
- if( TokenComparison( XHTML_COLOR_TAG, tag.buffer, tag.length ) )
+ if(TokenComparison(XHTML_COLOR_TAG, tag.buffer, tag.length))
{
ProcessTagForRun<ColorRun>(
- markupProcessData.colorRuns, styleStack, tag, characterIndex, colorRunIndex, colorTagReference,
- [] (const Tag& tag, ColorRun& run) { ProcessColorTag( tag, run ); });
+ markupProcessData.colorRuns, styleStack, tag, characterIndex, colorRunIndex, colorTagReference, [](const Tag& tag, ColorRun& run) { ProcessColorTag(tag, run); });
} // <color></color>
- else if( TokenComparison( XHTML_I_TAG, tag.buffer, tag.length ) )
+ else if(TokenComparison(XHTML_I_TAG, tag.buffer, tag.length))
{
ProcessTagForRun<FontDescriptionRun>(
- markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, iTagReference,
- [] (const Tag&, FontDescriptionRun& fontRun)
- {
- fontRun.slant = TextAbstraction::FontSlant::ITALIC;
- fontRun.slantDefined = true;
- });
+ markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, iTagReference, [](const Tag&, FontDescriptionRun& fontRun) {
+ fontRun.slant = TextAbstraction::FontSlant::ITALIC;
+ fontRun.slantDefined = true;
+ });
} // <i></i>
- else if( TokenComparison( XHTML_U_TAG, tag.buffer, tag.length ) )
+ else if(TokenComparison(XHTML_U_TAG, tag.buffer, tag.length))
{
// TODO: If !tag.isEndTag, then create a new underline run.
// else Pop the top of the stack and set the number of characters of the run.
} // <u></u>
- else if( TokenComparison( XHTML_B_TAG, tag.buffer, tag.length ) )
+ else if(TokenComparison(XHTML_B_TAG, tag.buffer, tag.length))
{
ProcessTagForRun<FontDescriptionRun>(
- markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, bTagReference,
- [] (const Tag&, FontDescriptionRun& fontRun)
- {
- fontRun.weight = TextAbstraction::FontWeight::BOLD;
- fontRun.weightDefined = true;
- });
+ markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, bTagReference, [](const Tag&, FontDescriptionRun& fontRun) {
+ fontRun.weight = TextAbstraction::FontWeight::BOLD;
+ fontRun.weightDefined = true;
+ });
} // <b></b>
- else if( TokenComparison( XHTML_FONT_TAG, tag.buffer, tag.length ) )
+ else if(TokenComparison(XHTML_FONT_TAG, tag.buffer, tag.length))
{
ProcessTagForRun<FontDescriptionRun>(
- markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, fontTagReference,
- [] (const Tag& tag, FontDescriptionRun& fontRun) { ProcessFontTag( tag, fontRun ); });
+ markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, fontTagReference, [](const Tag& tag, FontDescriptionRun& fontRun) { ProcessFontTag(tag, fontRun); });
} // <font></font>
- else if( TokenComparison( XHTML_SHADOW_TAG, tag.buffer, tag.length ) )
+ else if(TokenComparison(XHTML_SHADOW_TAG, tag.buffer, tag.length))
{
// TODO: If !tag.isEndTag, then create a new shadow run.
// else Pop the top of the stack and set the number of characters of the run.
} // <shadow></shadow>
- else if( TokenComparison( XHTML_GLOW_TAG, tag.buffer, tag.length ) )
+ else if(TokenComparison(XHTML_GLOW_TAG, tag.buffer, tag.length))
{
// TODO: If !tag.isEndTag, then create a new glow run.
// else Pop the top of the stack and set the number of characters of the run.
} // <glow></glow>
- else if( TokenComparison( XHTML_OUTLINE_TAG, tag.buffer, tag.length ) )
+ else if(TokenComparison(XHTML_OUTLINE_TAG, tag.buffer, tag.length))
{
// TODO: If !tag.isEndTag, then create a new outline run.
// else Pop the top of the stack and set the number of characters of the run.
} // <outline></outline>
- else if (TokenComparison(XHTML_ITEM_TAG, tag.buffer, tag.length))
+ else if(TokenComparison(XHTML_ITEM_TAG, tag.buffer, tag.length))
{
ProcessItemTag(markupProcessData, tag, characterIndex);
}
- } // end if( IsTag() )
- else if( markupStringBuffer < markupStringEndBuffer )
+ } // end if( IsTag() )
+ else if(markupStringBuffer < markupStringEndBuffer)
{
ProcessMarkupStringBuffer(markupProcessData, markupStringBuffer, markupStringEndBuffer, characterIndex);
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-void MergeFontDescriptions( const Vector<FontDescriptionRun>& fontDescriptions,
- const TextAbstraction::FontDescription& defaultFontDescription,
- TextAbstraction::PointSize26Dot6 defaultPointSize,
- CharacterIndex characterIndex,
- TextAbstraction::FontDescription& fontDescription,
- TextAbstraction::PointSize26Dot6& fontPointSize,
- bool& isDefaultFont )
+void MergeFontDescriptions(const Vector<FontDescriptionRun>& fontDescriptions,
+ const TextAbstraction::FontDescription& defaultFontDescription,
+ TextAbstraction::PointSize26Dot6 defaultPointSize,
+ CharacterIndex characterIndex,
+ TextAbstraction::FontDescription& fontDescription,
+ TextAbstraction::PointSize26Dot6& fontPointSize,
+ bool& isDefaultFont)
{
// Initialize with the default font's point size.
fontPointSize = defaultPointSize;
Length familyIndex = 0u;
Length weightIndex = 0u;
- Length widthIndex = 0u;
- Length slantIndex = 0u;
- Length sizeIndex = 0u;
+ Length widthIndex = 0u;
+ Length slantIndex = 0u;
+ Length sizeIndex = 0u;
bool familyOverriden = false;
bool weightOverriden = false;
- bool widthOverriden = false;
- bool slantOverriden = false;
- bool sizeOverriden = false;
+ bool widthOverriden = false;
+ bool slantOverriden = false;
+ bool sizeOverriden = false;
// Traverse all the font descriptions.
const FontDescriptionRun* const fontDescriptionsBuffer = fontDescriptions.Begin();
- for( Vector<FontDescriptionRun>::ConstIterator it = fontDescriptionsBuffer,
- endIt = fontDescriptions.End();
- it != endIt;
- ++it, ++runIndex )
+ for(Vector<FontDescriptionRun>::ConstIterator it = fontDescriptionsBuffer,
+ endIt = fontDescriptions.End();
+ it != endIt;
+ ++it, ++runIndex)
{
// Check whether the character's font is modified by the current font description.
const FontDescriptionRun& fontRun = *it;
- if( ( characterIndex >= fontRun.characterRun.characterIndex ) &&
- ( characterIndex < fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters ) )
+ if((characterIndex >= fontRun.characterRun.characterIndex) &&
+ (characterIndex < fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters))
{
- if( fontRun.familyDefined )
+ if(fontRun.familyDefined)
{
- isDefaultFont = false;
+ isDefaultFont = false;
familyOverriden = true;
- familyIndex = runIndex;
+ familyIndex = runIndex;
}
- if( fontRun.weightDefined )
+ if(fontRun.weightDefined)
{
- isDefaultFont = false;
+ isDefaultFont = false;
weightOverriden = true;
- weightIndex = runIndex;
+ weightIndex = runIndex;
}
- if( fontRun.widthDefined )
+ if(fontRun.widthDefined)
{
- isDefaultFont = false;
+ isDefaultFont = false;
widthOverriden = true;
- widthIndex = runIndex;
+ widthIndex = runIndex;
}
- if( fontRun.slantDefined )
+ if(fontRun.slantDefined)
{
- isDefaultFont = false;
+ isDefaultFont = false;
slantOverriden = true;
- slantIndex = runIndex;
+ slantIndex = runIndex;
}
- if( fontRun.sizeDefined )
+ if(fontRun.sizeDefined)
{
isDefaultFont = false;
sizeOverriden = true;
- sizeIndex = runIndex;
+ sizeIndex = runIndex;
}
}
}
// Get the font's description if is not the default font.
- if( !isDefaultFont )
+ if(!isDefaultFont)
{
- if( familyOverriden )
+ if(familyOverriden)
{
- const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + familyIndex );
- fontDescription.family = std::string( fontRun.familyName, fontRun.familyLength );
+ const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + familyIndex);
+ fontDescription.family = std::string(fontRun.familyName, fontRun.familyLength);
}
- if( weightOverriden )
+ if(weightOverriden)
{
- const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + weightIndex );
- fontDescription.weight = fontRun.weight;
+ const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + weightIndex);
+ fontDescription.weight = fontRun.weight;
}
- if( widthOverriden )
+ if(widthOverriden)
{
- const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + widthIndex );
- fontDescription.width = fontRun.width;
+ const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + widthIndex);
+ fontDescription.width = fontRun.width;
}
- if( slantOverriden )
+ if(slantOverriden)
{
- const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + slantIndex );
- fontDescription.slant = fontRun.slant;
+ const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + slantIndex);
+ fontDescription.slant = fontRun.slant;
}
- if( sizeOverriden )
+ if(sizeOverriden)
{
- const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + sizeIndex );
- fontPointSize = fontRun.size;
+ const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + sizeIndex);
+ fontPointSize = fontRun.size;
}
}
}
-Script GetScript( Length index,
- Vector<ScriptRun>::ConstIterator& scriptRunIt,
- const Vector<ScriptRun>::ConstIterator& scriptRunEndIt )
+Script GetScript(Length index,
+ Vector<ScriptRun>::ConstIterator& scriptRunIt,
+ const Vector<ScriptRun>::ConstIterator& scriptRunEndIt)
{
Script script = TextAbstraction::UNKNOWN;
- while( scriptRunIt != scriptRunEndIt )
+ while(scriptRunIt != scriptRunEndIt)
{
const ScriptRun& scriptRun = *scriptRunIt;
- if( index >= scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters )
+ if(index >= scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters)
{
++scriptRunIt;
}
- else if( index >= scriptRun.characterRun.characterIndex )
+ else if(index >= scriptRun.characterRun.characterIndex)
{
script = scriptRun.script;
- if( index + 1u == scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters )
+ if(index + 1u == scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters)
{
// All the characters of the current run have been traversed. Get the next one for the next iteration.
++scriptRunIt;
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/multi-language-support-impl.h>
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
#include <dali/devel-api/common/singleton-service.h>
#include <dali/devel-api/text-abstraction/font-client.h>
+#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/multi-language-helper-functions.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace
{
#if defined(DEBUG_ENABLED)
#endif
const Dali::Toolkit::Text::Character UTF32_A = 0x0041;
-}
+} // namespace
namespace Text
{
-
namespace Internal
{
-
-bool ValidateFontsPerScript::IsValidFont( FontId fontId ) const
+bool ValidateFontsPerScript::IsValidFont(FontId fontId) const
{
- for( Vector<FontId>::ConstIterator it = mValidFonts.Begin(),
- endIt = mValidFonts.End();
- it != endIt;
- ++it )
+ for(Vector<FontId>::ConstIterator it = mValidFonts.Begin(),
+ endIt = mValidFonts.End();
+ it != endIt;
+ ++it)
{
- if( fontId == *it )
+ if(fontId == *it)
{
return true;
}
return false;
}
-FontId DefaultFonts::FindFont( TextAbstraction::FontClient& fontClient,
- const TextAbstraction::FontDescription& description,
- PointSize26Dot6 size ) const
+FontId DefaultFonts::FindFont(TextAbstraction::FontClient& fontClient,
+ const TextAbstraction::FontDescription& description,
+ PointSize26Dot6 size) const
{
- for( std::vector<CacheItem>::const_iterator it = mFonts.begin(),
- endIt = mFonts.end();
- it != endIt;
- ++it )
+ for(std::vector<CacheItem>::const_iterator it = mFonts.begin(),
+ endIt = mFonts.end();
+ it != endIt;
+ ++it)
{
const CacheItem& item = *it;
- if( ( ( TextAbstraction::FontWeight::NONE == description.weight ) || ( description.weight == item.description.weight ) ) &&
- ( ( TextAbstraction::FontWidth::NONE == description.width ) || ( description.width == item.description.width ) ) &&
- ( ( TextAbstraction::FontSlant::NONE == description.slant ) || ( description.slant == item.description.slant ) ) &&
- ( size == fontClient.GetPointSize( item.fontId ) ) &&
- ( description.family.empty() || ( description.family == item.description.family ) ) )
+ if(((TextAbstraction::FontWeight::NONE == description.weight) || (description.weight == item.description.weight)) &&
+ ((TextAbstraction::FontWidth::NONE == description.width) || (description.width == item.description.width)) &&
+ ((TextAbstraction::FontSlant::NONE == description.slant) || (description.slant == item.description.slant)) &&
+ (size == fontClient.GetPointSize(item.fontId)) &&
+ (description.family.empty() || (description.family == item.description.family)))
{
return item.fontId;
}
return 0u;
}
-void DefaultFonts::Cache( const TextAbstraction::FontDescription& description, FontId fontId )
+void DefaultFonts::Cache(const TextAbstraction::FontDescription& description, FontId fontId)
{
CacheItem item;
item.description = description;
- item.fontId = fontId;
- mFonts.push_back( item );
+ item.fontId = fontId;
+ mFonts.push_back(item);
}
MultilanguageSupport::MultilanguageSupport()
{
// Initializes the default font cache to zero (invalid font).
// Reserves space to cache the default fonts and access them with the script as an index.
- mDefaultFontPerScriptCache.Resize( TextAbstraction::UNKNOWN + 1, NULL );
+ mDefaultFontPerScriptCache.Resize(TextAbstraction::UNKNOWN + 1, NULL);
// Initializes the valid fonts cache to NULL (no valid fonts).
// Reserves space to cache the valid fonts and access them with the script as an index.
- mValidFontsPerScriptCache.Resize( TextAbstraction::UNKNOWN + 1, NULL );
+ mValidFontsPerScriptCache.Resize(TextAbstraction::UNKNOWN + 1, NULL);
}
MultilanguageSupport::~MultilanguageSupport()
{
// Destroy the default font per script cache.
- for( Vector<DefaultFonts*>::Iterator it = mDefaultFontPerScriptCache.Begin(),
- endIt = mDefaultFontPerScriptCache.End();
- it != endIt;
- ++it )
+ for(Vector<DefaultFonts*>::Iterator it = mDefaultFontPerScriptCache.Begin(),
+ endIt = mDefaultFontPerScriptCache.End();
+ it != endIt;
+ ++it)
{
delete *it;
}
// Destroy the valid fonts per script cache.
- for( Vector<ValidateFontsPerScript*>::Iterator it = mValidFontsPerScriptCache.Begin(),
- endIt = mValidFontsPerScriptCache.End();
- it != endIt;
- ++it )
+ for(Vector<ValidateFontsPerScript*>::Iterator it = mValidFontsPerScriptCache.Begin(),
+ endIt = mValidFontsPerScriptCache.End();
+ it != endIt;
+ ++it)
{
delete *it;
}
{
Text::MultilanguageSupport multilanguageSupportHandle;
- SingletonService service( SingletonService::Get() );
- if( service )
+ SingletonService service(SingletonService::Get());
+ if(service)
{
// Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Text::MultilanguageSupport ) );
- if( handle )
+ Dali::BaseHandle handle = service.GetSingleton(typeid(Text::MultilanguageSupport));
+ if(handle)
{
// If so, downcast the handle
- MultilanguageSupport* impl = dynamic_cast< Internal::MultilanguageSupport* >( handle.GetObjectPtr() );
- multilanguageSupportHandle = Text::MultilanguageSupport( impl );
+ MultilanguageSupport* impl = dynamic_cast<Internal::MultilanguageSupport*>(handle.GetObjectPtr());
+ multilanguageSupportHandle = Text::MultilanguageSupport(impl);
}
else // create and register the object
{
- multilanguageSupportHandle = Text::MultilanguageSupport( new MultilanguageSupport );
- service.Register( typeid( multilanguageSupportHandle ), multilanguageSupportHandle );
+ multilanguageSupportHandle = Text::MultilanguageSupport(new MultilanguageSupport);
+ service.Register(typeid(multilanguageSupportHandle), multilanguageSupportHandle);
}
}
return multilanguageSupportHandle;
}
-void MultilanguageSupport::SetScripts( const Vector<Character>& text,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<ScriptRun>& scripts )
+void MultilanguageSupport::SetScripts(const Vector<Character>& text,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<ScriptRun>& scripts)
{
- if( 0u == numberOfCharacters )
+ if(0u == numberOfCharacters)
{
// Nothing to do if there are no characters.
return;
// Find the first index where to insert the script.
ScriptRunIndex scriptIndex = 0u;
- if( 0u != startIndex )
+ if(0u != startIndex)
{
- for( Vector<ScriptRun>::ConstIterator it = scripts.Begin(),
- endIt = scripts.End();
- it != endIt;
- ++it, ++scriptIndex )
+ for(Vector<ScriptRun>::ConstIterator it = scripts.Begin(),
+ endIt = scripts.End();
+ it != endIt;
+ ++it, ++scriptIndex)
{
const ScriptRun& run = *it;
- if( startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters )
+ if(startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters)
{
// Run found.
break;
// Stores the current script run.
ScriptRun currentScriptRun;
- currentScriptRun.characterRun.characterIndex = startIndex;
+ currentScriptRun.characterRun.characterIndex = startIndex;
currentScriptRun.characterRun.numberOfCharacters = 0u;
- currentScriptRun.script = TextAbstraction::UNKNOWN;
+ currentScriptRun.script = TextAbstraction::UNKNOWN;
// Reserve some space to reduce the number of reallocations.
- scripts.Reserve( text.Count() << 2u );
+ scripts.Reserve(text.Count() << 2u);
// Whether the first valid script needs to be set.
bool isFirstScriptToBeSet = true;
// Traverse all characters and set the scripts.
const Length lastCharacter = startIndex + numberOfCharacters;
- for( Length index = startIndex; index < lastCharacter; ++index )
+ for(Length index = startIndex; index < lastCharacter; ++index)
{
- Character character = *( textBuffer + index );
+ Character character = *(textBuffer + index);
// Get the script of the character.
- Script script = TextAbstraction::GetCharacterScript( character );
+ Script script = TextAbstraction::GetCharacterScript(character);
// Some characters (like white spaces) are valid for many scripts. The rules to set a script
// for them are:
// Skip those characters valid for many scripts like white spaces or '\n'.
bool endOfText = index == lastCharacter;
- while( !endOfText &&
- ( TextAbstraction::COMMON == script ) )
+ while(!endOfText &&
+ (TextAbstraction::COMMON == script))
{
// Check if whether is right to left markup and Keeps true if the previous value was true.
- currentScriptRun.isRightToLeft = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftMark( character );
+ currentScriptRun.isRightToLeft = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftMark(character);
- if( TextAbstraction::EMOJI == currentScriptRun.script )
+ if(TextAbstraction::EMOJI == currentScriptRun.script)
{
// Emojis doesn't mix well with characters common to all scripts. Insert the emoji run.
- scripts.Insert( scripts.Begin() + scriptIndex, currentScriptRun );
+ scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun);
++scriptIndex;
// Initialize the new one.
- currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters;
+ currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters;
currentScriptRun.characterRun.numberOfCharacters = 0u;
- currentScriptRun.script = TextAbstraction::UNKNOWN;
- numberOfAllScriptCharacters = 0u;
+ currentScriptRun.script = TextAbstraction::UNKNOWN;
+ numberOfAllScriptCharacters = 0u;
}
// Count all these characters to be added into a script.
++numberOfAllScriptCharacters;
- if( TextAbstraction::IsNewParagraph( character ) )
+ if(TextAbstraction::IsNewParagraph(character))
{
// The character is a new paragraph.
// To know when there is a new paragraph is needed because if there is a white space
currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
// Store the script run.
- scripts.Insert( scripts.Begin() + scriptIndex, currentScriptRun );
+ scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun);
++scriptIndex;
// Initialize the new one.
- currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters;
+ currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters;
currentScriptRun.characterRun.numberOfCharacters = 0u;
- currentScriptRun.script = TextAbstraction::UNKNOWN;
- numberOfAllScriptCharacters = 0u;
+ currentScriptRun.script = TextAbstraction::UNKNOWN;
+ numberOfAllScriptCharacters = 0u;
// Initialize whether is right to left direction
currentScriptRun.isRightToLeft = false;
}
// Get the next character.
++index;
endOfText = index == lastCharacter;
- if( !endOfText )
+ if(!endOfText)
{
- character = *( textBuffer + index );
- script = TextAbstraction::GetCharacterScript( character );
+ character = *(textBuffer + index);
+ script = TextAbstraction::GetCharacterScript(character);
}
} // end while( !endOfText && ( TextAbstraction::COMMON == script ) )
- if( endOfText )
+ if(endOfText)
{
// Last characters of the text are 'white spaces'.
// There is nothing else to do. Just add the remaining characters to the last script after this bucle.
}
// Check if it is the first character of a paragraph.
- if( isFirstScriptToBeSet &&
- ( TextAbstraction::UNKNOWN != script ) &&
- ( TextAbstraction::COMMON != script ) &&
- ( TextAbstraction::EMOJI != script ) )
+ if(isFirstScriptToBeSet &&
+ (TextAbstraction::UNKNOWN != script) &&
+ (TextAbstraction::COMMON != script) &&
+ (TextAbstraction::EMOJI != script))
{
// Sets the direction of the first valid script.
- isParagraphRTL = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftScript( script );
+ isParagraphRTL = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftScript(script);
isFirstScriptToBeSet = false;
}
- if( ( script != currentScriptRun.script ) &&
- ( TextAbstraction::COMMON != script ) )
+ if((script != currentScriptRun.script) &&
+ (TextAbstraction::COMMON != script))
{
// Current run needs to be stored and a new one initialized.
- if( ( isParagraphRTL == TextAbstraction::IsRightToLeftScript( currentScriptRun.script ) ) &&
- ( TextAbstraction::UNKNOWN != currentScriptRun.script ) )
+ if((isParagraphRTL == TextAbstraction::IsRightToLeftScript(currentScriptRun.script)) &&
+ (TextAbstraction::UNKNOWN != currentScriptRun.script))
{
// Previous script has the same direction than the first script of the paragraph.
// All the previously skipped characters need to be added to the previous script before it's stored.
currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
numberOfAllScriptCharacters = 0u;
}
- else if( ( TextAbstraction::IsRightToLeftScript( currentScriptRun.script ) == TextAbstraction::IsRightToLeftScript( script ) ) &&
- ( TextAbstraction::UNKNOWN != currentScriptRun.script ) )
+ else if((TextAbstraction::IsRightToLeftScript(currentScriptRun.script) == TextAbstraction::IsRightToLeftScript(script)) &&
+ (TextAbstraction::UNKNOWN != currentScriptRun.script))
{
// Current script and previous one have the same direction.
// All the previously skipped characters need to be added to the previous script before it's stored.
currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
numberOfAllScriptCharacters = 0u;
}
- else if( ( TextAbstraction::UNKNOWN == currentScriptRun.script ) &&
- ( TextAbstraction::EMOJI == script ) )
+ else if((TextAbstraction::UNKNOWN == currentScriptRun.script) &&
+ (TextAbstraction::EMOJI == script))
{
currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
numberOfAllScriptCharacters = 0u;
}
- if( 0u != currentScriptRun.characterRun.numberOfCharacters )
+ if(0u != currentScriptRun.characterRun.numberOfCharacters)
{
// Store the script run.
- scripts.Insert( scripts.Begin() + scriptIndex, currentScriptRun );
+ scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun);
++scriptIndex;
}
// Initialize the new one.
- currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters;
+ currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters;
currentScriptRun.characterRun.numberOfCharacters = numberOfAllScriptCharacters + 1u; // Adds the white spaces which are at the begining of the script.
- currentScriptRun.script = script;
- numberOfAllScriptCharacters = 0u;
+ currentScriptRun.script = script;
+ numberOfAllScriptCharacters = 0u;
// Check if whether is right to left script.
- currentScriptRun.isRightToLeft = TextAbstraction::IsRightToLeftScript( currentScriptRun.script );
+ currentScriptRun.isRightToLeft = TextAbstraction::IsRightToLeftScript(currentScriptRun.script);
}
else
{
- if( TextAbstraction::UNKNOWN != currentScriptRun.script )
+ if(TextAbstraction::UNKNOWN != currentScriptRun.script)
{
// Adds white spaces between characters.
currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
// Add remaining characters into the last script.
currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters;
- if( 0u != currentScriptRun.characterRun.numberOfCharacters )
+ if(0u != currentScriptRun.characterRun.numberOfCharacters)
{
// Store the last run.
- scripts.Insert( scripts.Begin() + scriptIndex, currentScriptRun );
+ scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun);
++scriptIndex;
}
- if( scriptIndex < scripts.Count() )
+ if(scriptIndex < scripts.Count())
{
// Update the indices of the next script runs.
- const ScriptRun& run = *( scripts.Begin() + scriptIndex - 1u );
- CharacterIndex nextCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters;
+ const ScriptRun& run = *(scripts.Begin() + scriptIndex - 1u);
+ CharacterIndex nextCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters;
- for( Vector<ScriptRun>::Iterator it = scripts.Begin() + scriptIndex,
- endIt = scripts.End();
- it != endIt;
- ++it )
+ for(Vector<ScriptRun>::Iterator it = scripts.Begin() + scriptIndex,
+ endIt = scripts.End();
+ it != endIt;
+ ++it)
{
- ScriptRun& run = *it;
+ ScriptRun& run = *it;
run.characterRun.characterIndex = nextCharacterIndex;
nextCharacterIndex += run.characterRun.numberOfCharacters;
}
}
}
-void MultilanguageSupport::ValidateFonts( const Vector<Character>& text,
- const Vector<ScriptRun>& scripts,
- const Vector<FontDescriptionRun>& fontDescriptions,
- const TextAbstraction::FontDescription& defaultFontDescription,
- TextAbstraction::PointSize26Dot6 defaultFontPointSize,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<FontRun>& fonts )
+void MultilanguageSupport::ValidateFonts(const Vector<Character>& text,
+ const Vector<ScriptRun>& scripts,
+ const Vector<FontDescriptionRun>& fontDescriptions,
+ const TextAbstraction::FontDescription& defaultFontDescription,
+ TextAbstraction::PointSize26Dot6 defaultFontPointSize,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<FontRun>& fonts)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "-->MultilanguageSupport::ValidateFonts\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "-->MultilanguageSupport::ValidateFonts\n");
- if( 0u == numberOfCharacters )
+ if(0u == numberOfCharacters)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n");
// Nothing to do if there are no characters.
return;
}
// Find the first index where to insert the font run.
FontRunIndex fontIndex = 0u;
- if( 0u != startIndex )
+ if(0u != startIndex)
{
- for( Vector<FontRun>::ConstIterator it = fonts.Begin(),
- endIt = fonts.End();
- it != endIt;
- ++it, ++fontIndex )
+ for(Vector<FontRun>::ConstIterator it = fonts.Begin(),
+ endIt = fonts.End();
+ it != endIt;
+ ++it, ++fontIndex)
{
const FontRun& run = *it;
- if( startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters )
+ if(startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters)
{
// Run found.
break;
// Traverse the characters and validate/set the fonts.
// Get the caches.
- DefaultFonts** defaultFontPerScriptCacheBuffer = mDefaultFontPerScriptCache.Begin();
- ValidateFontsPerScript** validFontsPerScriptCacheBuffer = mValidFontsPerScriptCache.Begin();
+ DefaultFonts** defaultFontPerScriptCacheBuffer = mDefaultFontPerScriptCache.Begin();
+ ValidateFontsPerScript** validFontsPerScriptCacheBuffer = mValidFontsPerScriptCache.Begin();
// Stores the validated font runs.
- fonts.Reserve( fontDescriptions.Count() );
+ fonts.Reserve(fontDescriptions.Count());
// Initializes a validated font run.
FontRun currentFontRun;
- currentFontRun.characterRun.characterIndex = startIndex;
+ currentFontRun.characterRun.characterIndex = startIndex;
currentFontRun.characterRun.numberOfCharacters = 0u;
- currentFontRun.fontId = 0u;
- currentFontRun.isBoldRequired = false;
- currentFontRun.isItalicRequired = false;
+ currentFontRun.fontId = 0u;
+ currentFontRun.isBoldRequired = false;
+ currentFontRun.isItalicRequired = false;
// Get the font client.
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
const Character* const textBuffer = text.Begin();
// Iterators of the script runs.
- Vector<ScriptRun>::ConstIterator scriptRunIt = scripts.Begin();
- Vector<ScriptRun>::ConstIterator scriptRunEndIt = scripts.End();
- bool isNewParagraphCharacter = false;
+ Vector<ScriptRun>::ConstIterator scriptRunIt = scripts.Begin();
+ Vector<ScriptRun>::ConstIterator scriptRunEndIt = scripts.End();
+ bool isNewParagraphCharacter = false;
bool isPreviousEmojiScript = false;
CharacterIndex lastCharacter = startIndex + numberOfCharacters;
- for( Length index = startIndex; index < lastCharacter; ++index )
+ for(Length index = startIndex; index < lastCharacter; ++index)
{
// Get the current character.
- const Character character = *( textBuffer + index );
- bool isItalicRequired = false;
- bool isBoldRequired = false;
+ const Character character = *(textBuffer + index);
+ bool isItalicRequired = false;
+ bool isBoldRequired = false;
// new description for current character
TextAbstraction::FontDescription currentFontDescription;
TextAbstraction::PointSize26Dot6 currentFontPointSize = defaultFontPointSize;
- bool isDefaultFont = true;
- MergeFontDescriptions( fontDescriptions,
- defaultFontDescription,
- defaultFontPointSize,
- index,
- currentFontDescription,
- currentFontPointSize,
- isDefaultFont );
+ bool isDefaultFont = true;
+ MergeFontDescriptions(fontDescriptions,
+ defaultFontDescription,
+ defaultFontPointSize,
+ index,
+ currentFontDescription,
+ currentFontPointSize,
+ isDefaultFont);
// Get the font for the current character.
- FontId fontId = fontClient.GetFontId( currentFontDescription, currentFontPointSize );
+ FontId fontId = fontClient.GetFontId(currentFontDescription, currentFontPointSize);
// Get the script for the current character.
- Script script = GetScript( index,
- scriptRunIt,
- scriptRunEndIt );
+ Script script = GetScript(index,
+ scriptRunIt,
+ scriptRunEndIt);
#ifdef DEBUG_ENABLED
{
Dali::TextAbstraction::FontDescription description;
- fontClient.GetDescription( fontId, description );
-
- DALI_LOG_INFO( gLogFilter,
- Debug::Verbose,
- " Initial font set\n Character : %x, Script : %s, Font : %s \n",
- character,
- Dali::TextAbstraction::ScriptName[script],
- description.path.c_str() );
+ fontClient.GetDescription(fontId, description);
+
+ DALI_LOG_INFO(gLogFilter,
+ Debug::Verbose,
+ " Initial font set\n Character : %x, Script : %s, Font : %s \n",
+ character,
+ Dali::TextAbstraction::ScriptName[script],
+ description.path.c_str());
}
#endif
// Check first in the cache of default fonts per script and size.
- FontId cachedDefaultFontId = 0u;
- DefaultFonts* defaultFonts = *( defaultFontPerScriptCacheBuffer + script );
- if( NULL != defaultFonts )
+ FontId cachedDefaultFontId = 0u;
+ DefaultFonts* defaultFonts = *(defaultFontPerScriptCacheBuffer + script);
+ if(NULL != defaultFonts)
{
// This cache stores fall-back fonts.
- cachedDefaultFontId = defaultFonts->FindFont( fontClient,
- currentFontDescription,
- currentFontPointSize );
+ cachedDefaultFontId = defaultFonts->FindFont(fontClient,
+ currentFontDescription,
+ currentFontPointSize);
}
// Whether the cached default font is valid.
const bool isValidCachedDefaultFont = 0u != cachedDefaultFontId;
// The font is valid if it matches with the default one for the current script and size and it's different than zero.
- isValidFont = isValidCachedDefaultFont && ( fontId == cachedDefaultFontId );
+ isValidFont = isValidCachedDefaultFont && (fontId == cachedDefaultFontId);
- if( isValidFont )
+ if(isValidFont)
{
// Check if the font supports the character.
- isValidFont = fontClient.IsCharacterSupportedByFont( fontId, character );
+ isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character);
}
bool isCommonScript = false;
- bool isEmojiScript = TextAbstraction::EMOJI == script;
+ bool isEmojiScript = TextAbstraction::EMOJI == script;
- if( isEmojiScript && !isPreviousEmojiScript )
+ if(isEmojiScript && !isPreviousEmojiScript)
{
- if( 0u != currentFontRun.characterRun.numberOfCharacters )
+ if(0u != currentFontRun.characterRun.numberOfCharacters)
{
// Store the font run.
- fonts.Insert( fonts.Begin() + fontIndex, currentFontRun );
+ fonts.Insert(fonts.Begin() + fontIndex, currentFontRun);
++fontIndex;
}
// Initialize the new one.
- currentFontRun.characterRun.characterIndex = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters;
+ currentFontRun.characterRun.characterIndex = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters;
currentFontRun.characterRun.numberOfCharacters = 0u;
- currentFontRun.fontId = fontId;
- currentFontRun.isItalicRequired = false;
- currentFontRun.isBoldRequired = false;
+ currentFontRun.fontId = fontId;
+ currentFontRun.isItalicRequired = false;
+ currentFontRun.isBoldRequired = false;
}
// If the given font is not valid, it means either:
// - the platform default font is different than the default font for the current script.
// Need to check if the given font supports the current character.
- if( !isValidFont ) // (1)
+ if(!isValidFont) // (1)
{
// Whether the current character is common for all scripts (i.e. white spaces, ...)
//
// Many fonts support 'white spaces' so probably the font set by the user or the platform's default
// supports the 'white space'. However, that font may not support the DEVANAGARI script.
- isCommonScript = TextAbstraction::IsCommonScript( character );
+ isCommonScript = TextAbstraction::IsCommonScript(character);
// Check in the valid fonts cache.
- ValidateFontsPerScript* validateFontsPerScript = *( validFontsPerScriptCacheBuffer + script );
+ ValidateFontsPerScript* validateFontsPerScript = *(validFontsPerScriptCacheBuffer + script);
- if( NULL != validateFontsPerScript )
+ if(NULL != validateFontsPerScript)
{
// This cache stores valid fonts set by the user.
- isValidFont = validateFontsPerScript->IsValidFont( fontId );
+ isValidFont = validateFontsPerScript->IsValidFont(fontId);
// It may happen that a validated font for a script doesn't have all the glyphs for that script.
// i.e a font validated for the CJK script may contain glyphs for the chinese language but not for the Japanese.
- if( isValidFont )
+ if(isValidFont)
{
// Checks if the current character is supported by the font is needed.
- isValidFont = fontClient.IsCharacterSupportedByFont( fontId, character );
+ isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character);
}
}
- if( !isValidFont ) // (2)
+ if(!isValidFont) // (2)
{
// The selected font is not stored in any cache.
// Checks if the current character is supported by the selected font.
- isValidFont = fontClient.IsCharacterSupportedByFont( fontId, character );
+ isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character);
// If there is a valid font, cache it.
- if( isValidFont && !isCommonScript )
+ if(isValidFont && !isCommonScript)
{
- if( NULL == validateFontsPerScript )
+ if(NULL == validateFontsPerScript)
{
validateFontsPerScript = new ValidateFontsPerScript();
- *( validFontsPerScriptCacheBuffer + script ) = validateFontsPerScript;
+ *(validFontsPerScriptCacheBuffer + script) = validateFontsPerScript;
}
- validateFontsPerScript->mValidFonts.PushBack( fontId );
+ validateFontsPerScript->mValidFonts.PushBack(fontId);
}
- if( !isValidFont && ( fontId != cachedDefaultFontId ) && ( !TextAbstraction::IsNewParagraph( character ) )) // (3)
+ if(!isValidFont && (fontId != cachedDefaultFontId) && (!TextAbstraction::IsNewParagraph(character))) // (3)
{
// The selected font by the user or the platform's default font has failed to validate the character.
// Checks if the previously discarted cached default font supports the character.
bool isValidCachedFont = false;
- if( isValidCachedDefaultFont )
+ if(isValidCachedDefaultFont)
{
- isValidCachedFont = fontClient.IsCharacterSupportedByFont( cachedDefaultFontId, character );
+ isValidCachedFont = fontClient.IsCharacterSupportedByFont(cachedDefaultFontId, character);
}
- if( isValidCachedFont )
+ if(isValidCachedFont)
{
// Use the cached default font for the script if there is one.
fontId = cachedDefaultFontId;
DefaultFonts* defaultFontsPerScript = NULL;
// Find a fallback-font.
- fontId = fontClient.FindFallbackFont( character,
- currentFontDescription,
- currentFontPointSize,
- false );
+ fontId = fontClient.FindFallbackFont(character,
+ currentFontDescription,
+ currentFontPointSize,
+ false);
- if( 0u == fontId )
+ if(0u == fontId)
{
- fontId = fontClient.FindDefaultFont( UTF32_A, currentFontPointSize );
+ fontId = fontClient.FindDefaultFont(UTF32_A, currentFontPointSize);
}
- if ( !isCommonScript && (script != TextAbstraction::UNKNOWN) )
+ if(!isCommonScript && (script != TextAbstraction::UNKNOWN))
{
// Cache the font if it is not an unknown script
- if( NULL == defaultFontsPerScript )
+ if(NULL == defaultFontsPerScript)
{
- defaultFontsPerScript = *( defaultFontPerScriptCacheBuffer + script );
+ defaultFontsPerScript = *(defaultFontPerScriptCacheBuffer + script);
- if( NULL == defaultFontsPerScript )
+ if(NULL == defaultFontsPerScript)
{
- defaultFontsPerScript = new DefaultFonts();
- *( defaultFontPerScriptCacheBuffer + script ) = defaultFontsPerScript;
+ defaultFontsPerScript = new DefaultFonts();
+ *(defaultFontPerScriptCacheBuffer + script) = defaultFontsPerScript;
}
}
- defaultFontsPerScript->Cache( currentFontDescription, fontId );
+ defaultFontsPerScript->Cache(currentFontDescription, fontId);
}
}
} // !isValidFont (3)
- } // !isValidFont (2)
- } // !isValidFont (1)
+ } // !isValidFont (2)
+ } // !isValidFont (1)
#ifdef DEBUG_ENABLED
{
Dali::TextAbstraction::FontDescription description;
- fontClient.GetDescription( fontId, description );
- DALI_LOG_INFO( gLogFilter,
- Debug::Verbose,
- " Validated font set\n Character : %x, Script : %s, Font : %s \n",
- character,
- Dali::TextAbstraction::ScriptName[script],
- description.path.c_str() );
+ fontClient.GetDescription(fontId, description);
+ DALI_LOG_INFO(gLogFilter,
+ Debug::Verbose,
+ " Validated font set\n Character : %x, Script : %s, Font : %s \n",
+ character,
+ Dali::TextAbstraction::ScriptName[script],
+ description.path.c_str());
}
#endif
// Whether bols style is required.
- isBoldRequired = ( currentFontDescription.weight >= TextAbstraction::FontWeight::BOLD );
+ isBoldRequired = (currentFontDescription.weight >= TextAbstraction::FontWeight::BOLD);
// Whether italic style is required.
- isItalicRequired = ( currentFontDescription.slant >= TextAbstraction::FontSlant::ITALIC );
+ isItalicRequired = (currentFontDescription.slant >= TextAbstraction::FontSlant::ITALIC);
// The font is now validated.
- if( ( fontId != currentFontRun.fontId ) ||
- isNewParagraphCharacter ||
- // If font id is same as previous but style is diffrent, initialize new one
- ( ( fontId == currentFontRun.fontId ) && ( ( isBoldRequired != currentFontRun.isBoldRequired ) || ( isItalicRequired != currentFontRun.isItalicRequired ) ) ) )
+ if((fontId != currentFontRun.fontId) ||
+ isNewParagraphCharacter ||
+ // If font id is same as previous but style is diffrent, initialize new one
+ ((fontId == currentFontRun.fontId) && ((isBoldRequired != currentFontRun.isBoldRequired) || (isItalicRequired != currentFontRun.isItalicRequired))))
{
// Current run needs to be stored and a new one initialized.
- if( 0u != currentFontRun.characterRun.numberOfCharacters )
+ if(0u != currentFontRun.characterRun.numberOfCharacters)
{
// Store the font run.
- fonts.Insert( fonts.Begin() + fontIndex, currentFontRun );
+ fonts.Insert(fonts.Begin() + fontIndex, currentFontRun);
++fontIndex;
}
// Initialize the new one.
- currentFontRun.characterRun.characterIndex = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters;
+ currentFontRun.characterRun.characterIndex = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters;
currentFontRun.characterRun.numberOfCharacters = 0u;
- currentFontRun.fontId = fontId;
- currentFontRun.isBoldRequired = isBoldRequired;
- currentFontRun.isItalicRequired = isItalicRequired;
+ currentFontRun.fontId = fontId;
+ currentFontRun.isBoldRequired = isBoldRequired;
+ currentFontRun.isItalicRequired = isItalicRequired;
}
// Add one more character to the run.
++currentFontRun.characterRun.numberOfCharacters;
// Whether the current character is a new paragraph character.
- isNewParagraphCharacter = TextAbstraction::IsNewParagraph( character );
- isPreviousEmojiScript = isEmojiScript;
+ isNewParagraphCharacter = TextAbstraction::IsNewParagraph(character);
+ isPreviousEmojiScript = isEmojiScript;
} // end traverse characters.
- if( 0u != currentFontRun.characterRun.numberOfCharacters )
+ if(0u != currentFontRun.characterRun.numberOfCharacters)
{
// Store the last run.
- fonts.Insert( fonts.Begin() + fontIndex, currentFontRun );
+ fonts.Insert(fonts.Begin() + fontIndex, currentFontRun);
++fontIndex;
}
- if( fontIndex < fonts.Count() )
+ if(fontIndex < fonts.Count())
{
// Update the indices of the next font runs.
- const FontRun& run = *( fonts.Begin() + fontIndex - 1u );
+ const FontRun& run = *(fonts.Begin() + fontIndex - 1u);
CharacterIndex nextCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters;
- for( Vector<FontRun>::Iterator it = fonts.Begin() + fontIndex,
- endIt = fonts.End();
- it != endIt;
- ++it )
+ for(Vector<FontRun>::Iterator it = fonts.Begin() + fontIndex,
+ endIt = fonts.End();
+ it != endIt;
+ ++it)
{
FontRun& run = *it;
}
}
- DALI_LOG_INFO( gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n");
}
} // namespace Internal
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
MultilanguageSupport::MultilanguageSupport()
{
}
{
}
-MultilanguageSupport::MultilanguageSupport( Internal::MultilanguageSupport* implementation )
-: BaseHandle( implementation )
+MultilanguageSupport::MultilanguageSupport(Internal::MultilanguageSupport* implementation)
+: BaseHandle(implementation)
{
}
return Internal::MultilanguageSupport::Get();
}
-void MultilanguageSupport::SetScripts( const Vector<Character>& text,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<ScriptRun>& scripts )
+void MultilanguageSupport::SetScripts(const Vector<Character>& text,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<ScriptRun>& scripts)
{
- GetImplementation( *this ).SetScripts( text,
- startIndex,
- numberOfCharacters,
- scripts );
+ GetImplementation(*this).SetScripts(text,
+ startIndex,
+ numberOfCharacters,
+ scripts);
}
-void MultilanguageSupport::ValidateFonts( const Vector<Character>& text,
- const Vector<ScriptRun>& scripts,
- const Vector<FontDescriptionRun>& fontDescriptions,
- const TextAbstraction::FontDescription& defaultFontDescription,
- TextAbstraction::PointSize26Dot6 defaultFontPointSize,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<FontRun>& fonts )
+void MultilanguageSupport::ValidateFonts(const Vector<Character>& text,
+ const Vector<ScriptRun>& scripts,
+ const Vector<FontDescriptionRun>& fontDescriptions,
+ const TextAbstraction::FontDescription& defaultFontDescription,
+ TextAbstraction::PointSize26Dot6 defaultFontPointSize,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<FontRun>& fonts)
{
- GetImplementation( *this ).ValidateFonts( text,
- scripts,
- fontDescriptions,
- defaultFontDescription,
- defaultFontPointSize,
- startIndex,
- numberOfCharacters,
- fonts );
+ GetImplementation(*this).ValidateFonts(text,
+ scripts,
+ fontDescriptions,
+ defaultFontDescription,
+ defaultFontPointSize,
+ startIndex,
+ numberOfCharacters,
+ fonts);
}
} // namespace Text
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-void CreatePropertyMap( const TreeNode* const node, Property::Map& map )
+void CreatePropertyMap(const TreeNode* const node, Property::Map& map)
{
- switch( node->GetType() )
+ switch(node->GetType())
{
case TreeNode::IS_NULL:
case TreeNode::OBJECT:
}
case TreeNode::STRING:
{
- map.Insert( node->GetName(), Property::Value( node->GetString() ) );
+ map.Insert(node->GetName(), Property::Value(node->GetString()));
break;
}
case TreeNode::INTEGER:
}
}
- for( TreeNode::ConstIterator it = node->CBegin(), endIt = node->CEnd(); it != endIt; ++it )
+ for(TreeNode::ConstIterator it = node->CBegin(), endIt = node->CEnd(); it != endIt; ++it)
{
const TreeNode::KeyNodePair& pair = *it;
- CreatePropertyMap( &pair.second, map );
+ CreatePropertyMap(&pair.second, map);
}
}
-void ParsePropertyString( const std::string& property, Property::Map& map )
+void ParsePropertyString(const std::string& property, Property::Map& map)
{
Toolkit::JsonParser parser = Toolkit::JsonParser::New();
- if( parser.Parse( property ) )
+ if(parser.Parse(property))
{
const TreeNode* const node = parser.GetRoot();
- if( node )
+ if(node)
{
- CreatePropertyMap( node, map );
+ CreatePropertyMap(node, map);
}
}
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace
{
-
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
#endif
} // unnamed namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
AtlasGlyphManager::AtlasGlyphManager()
{
mAtlasManager = Dali::Toolkit::AtlasManager::New();
- mSampler = Sampler::New();
- mSampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
+ mSampler = Sampler::New();
+ mSampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR);
}
-void AtlasGlyphManager::Add( const Text::GlyphInfo& glyph,
- const Toolkit::AtlasGlyphManager::GlyphStyle& style,
- const PixelData& bitmap,
- Dali::Toolkit::AtlasManager::AtlasSlot& slot )
+void AtlasGlyphManager::Add(const Text::GlyphInfo& glyph,
+ const Toolkit::AtlasGlyphManager::GlyphStyle& style,
+ const PixelData& bitmap,
+ Dali::Toolkit::AtlasManager::AtlasSlot& slot)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Added glyph, font: %d index: %d\n", glyph.fontId, glyph.index );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Added glyph, font: %d index: %d\n", glyph.fontId, glyph.index);
// If glyph added to an existing or new atlas then a new glyph record is required.
// Check if an existing atlas will fit the image, create a new one if required.
- if ( mAtlasManager.Add( bitmap, slot ) )
+ if(mAtlasManager.Add(bitmap, slot))
{
// A new atlas was created so set the texture set details for the atlas
- Dali::Texture atlas = mAtlasManager.GetAtlasContainer( slot.mAtlasId );
- TextureSet textureSet = TextureSet::New();
- textureSet.SetTexture( 0u, atlas );
- textureSet.SetSampler( 0u, mSampler);
- mAtlasManager.SetTextures( slot.mAtlasId, textureSet );
+ Dali::Texture atlas = mAtlasManager.GetAtlasContainer(slot.mAtlasId);
+ TextureSet textureSet = TextureSet::New();
+ textureSet.SetTexture(0u, atlas);
+ textureSet.SetSampler(0u, mSampler);
+ mAtlasManager.SetTextures(slot.mAtlasId, textureSet);
}
GlyphRecordEntry record;
- record.mIndex = glyph.index;
- record.mImageId = slot.mImageId;
- record.mCount = 1;
+ record.mIndex = glyph.index;
+ record.mImageId = slot.mImageId;
+ record.mCount = 1;
record.mOutlineWidth = style.outline;
- record.isItalic = style.isItalic;
- record.isBold = style.isBold;
+ record.isItalic = style.isItalic;
+ record.isBold = style.isBold;
// Have glyph records been created for this fontId ?
bool foundGlyph = false;
- for ( std::vector< FontGlyphRecord >::iterator fontGlyphRecordIt = mFontGlyphRecords.begin();
- fontGlyphRecordIt != mFontGlyphRecords.end(); ++fontGlyphRecordIt )
+ for(std::vector<FontGlyphRecord>::iterator fontGlyphRecordIt = mFontGlyphRecords.begin();
+ fontGlyphRecordIt != mFontGlyphRecords.end();
+ ++fontGlyphRecordIt)
{
- if ( fontGlyphRecordIt->mFontId == glyph.fontId )
+ if(fontGlyphRecordIt->mFontId == glyph.fontId)
{
- fontGlyphRecordIt->mGlyphRecords.PushBack( record );
+ fontGlyphRecordIt->mGlyphRecords.PushBack(record);
foundGlyph = true;
break;
}
}
- if ( !foundGlyph )
+ if(!foundGlyph)
{
// We need to add a new font entry
FontGlyphRecord fontGlyphRecord;
fontGlyphRecord.mFontId = glyph.fontId;
- fontGlyphRecord.mGlyphRecords.PushBack( record );
- mFontGlyphRecords.push_back( fontGlyphRecord );
+ fontGlyphRecord.mGlyphRecords.PushBack(record);
+ mFontGlyphRecords.push_back(fontGlyphRecord);
}
}
-void AtlasGlyphManager::GenerateMeshData( uint32_t imageId,
- const Vector2& position,
- Toolkit::AtlasManager::Mesh2D& mesh )
+void AtlasGlyphManager::GenerateMeshData(uint32_t imageId,
+ const Vector2& position,
+ Toolkit::AtlasManager::Mesh2D& mesh)
{
// Generate mesh data and tell Atlas Manager not to handle reference counting ( we'll do it )
- mAtlasManager.GenerateMeshData( imageId, position, mesh, false );
+ mAtlasManager.GenerateMeshData(imageId, position, mesh, false);
}
-bool AtlasGlyphManager::IsCached( Text::FontId fontId,
- Text::GlyphIndex index,
- const Toolkit::AtlasGlyphManager::GlyphStyle& style,
- Dali::Toolkit::AtlasManager::AtlasSlot& slot )
+bool AtlasGlyphManager::IsCached(Text::FontId fontId,
+ Text::GlyphIndex index,
+ const Toolkit::AtlasGlyphManager::GlyphStyle& style,
+ Dali::Toolkit::AtlasManager::AtlasSlot& slot)
{
- for ( std::vector< FontGlyphRecord >::iterator fontGlyphRecordIt = mFontGlyphRecords.begin();
- fontGlyphRecordIt != mFontGlyphRecords.end();
- ++fontGlyphRecordIt )
+ for(std::vector<FontGlyphRecord>::iterator fontGlyphRecordIt = mFontGlyphRecords.begin();
+ fontGlyphRecordIt != mFontGlyphRecords.end();
+ ++fontGlyphRecordIt)
{
- if ( fontGlyphRecordIt->mFontId == fontId )
+ if(fontGlyphRecordIt->mFontId == fontId)
{
- for ( Vector< GlyphRecordEntry >::Iterator glyphRecordIt = fontGlyphRecordIt->mGlyphRecords.Begin();
- glyphRecordIt != fontGlyphRecordIt->mGlyphRecords.End();
- ++glyphRecordIt )
+ for(Vector<GlyphRecordEntry>::Iterator glyphRecordIt = fontGlyphRecordIt->mGlyphRecords.Begin();
+ glyphRecordIt != fontGlyphRecordIt->mGlyphRecords.End();
+ ++glyphRecordIt)
{
- if ( ( glyphRecordIt->mIndex == index ) &&
- ( glyphRecordIt->mOutlineWidth == style.outline ) &&
- ( glyphRecordIt->isItalic == style.isItalic ) &&
- ( glyphRecordIt->isBold == style.isBold ) )
+ if((glyphRecordIt->mIndex == index) &&
+ (glyphRecordIt->mOutlineWidth == style.outline) &&
+ (glyphRecordIt->isItalic == style.isItalic) &&
+ (glyphRecordIt->isBold == style.isBold))
{
slot.mImageId = glyphRecordIt->mImageId;
- slot.mAtlasId = mAtlasManager.GetAtlas( slot.mImageId );
+ slot.mAtlasId = mAtlasManager.GetAtlas(slot.mImageId);
return true;
}
}
return false;
}
-Vector2 AtlasGlyphManager::GetAtlasSize( uint32_t atlasId )
+Vector2 AtlasGlyphManager::GetAtlasSize(uint32_t atlasId)
{
- Toolkit::AtlasManager::AtlasSize size = mAtlasManager.GetAtlasSize( atlasId );
- return Vector2( static_cast< float >( size.mWidth ), static_cast< float >( size.mHeight ) );
+ Toolkit::AtlasManager::AtlasSize size = mAtlasManager.GetAtlasSize(atlasId);
+ return Vector2(static_cast<float>(size.mWidth), static_cast<float>(size.mHeight));
}
-void AtlasGlyphManager::SetNewAtlasSize( uint32_t width, uint32_t height, uint32_t blockWidth, uint32_t blockHeight )
+void AtlasGlyphManager::SetNewAtlasSize(uint32_t width, uint32_t height, uint32_t blockWidth, uint32_t blockHeight)
{
Toolkit::AtlasManager::AtlasSize size;
- size.mWidth = width;
- size.mHeight = height;
- size.mBlockWidth = blockWidth;
+ size.mWidth = width;
+ size.mHeight = height;
+ size.mBlockWidth = blockWidth;
size.mBlockHeight = blockHeight;
- mAtlasManager.SetNewAtlasSize( size );
+ mAtlasManager.SetNewAtlasSize(size);
}
-Pixel::Format AtlasGlyphManager::GetPixelFormat( uint32_t atlasId )
+Pixel::Format AtlasGlyphManager::GetPixelFormat(uint32_t atlasId)
{
- return mAtlasManager.GetPixelFormat( atlasId );
+ return mAtlasManager.GetPixelFormat(atlasId);
}
const Toolkit::AtlasGlyphManager::Metrics& AtlasGlyphManager::GetMetrics()
std::ostringstream verboseMetrics;
mMetrics.mGlyphCount = 0u;
- for ( std::vector< FontGlyphRecord >::iterator fontGlyphRecordIt = mFontGlyphRecords.begin();
- fontGlyphRecordIt != mFontGlyphRecords.end();
- ++fontGlyphRecordIt )
+ for(std::vector<FontGlyphRecord>::iterator fontGlyphRecordIt = mFontGlyphRecords.begin();
+ fontGlyphRecordIt != mFontGlyphRecords.end();
+ ++fontGlyphRecordIt)
{
mMetrics.mGlyphCount += fontGlyphRecordIt->mGlyphRecords.Size();
verboseMetrics << "[FontId " << fontGlyphRecordIt->mFontId << " Glyph ";
- for ( Vector< GlyphRecordEntry >::Iterator glyphRecordEntryIt = fontGlyphRecordIt->mGlyphRecords.Begin();
- glyphRecordEntryIt != fontGlyphRecordIt->mGlyphRecords.End();
- ++glyphRecordEntryIt )
+ for(Vector<GlyphRecordEntry>::Iterator glyphRecordEntryIt = fontGlyphRecordIt->mGlyphRecords.Begin();
+ glyphRecordEntryIt != fontGlyphRecordIt->mGlyphRecords.End();
+ ++glyphRecordEntryIt)
{
verboseMetrics << glyphRecordEntryIt->mIndex << "(" << glyphRecordEntryIt->mCount << ") ";
}
}
mMetrics.mVerboseGlyphCounts = verboseMetrics.str();
- mAtlasManager.GetMetrics( mMetrics.mAtlasMetrics );
+ mAtlasManager.GetMetrics(mMetrics.mAtlasMetrics);
return mMetrics;
}
-void AtlasGlyphManager::AdjustReferenceCount( Text::FontId fontId, Text::GlyphIndex index, const Toolkit::AtlasGlyphManager::GlyphStyle& style, int32_t delta )
+void AtlasGlyphManager::AdjustReferenceCount(Text::FontId fontId, Text::GlyphIndex index, const Toolkit::AtlasGlyphManager::GlyphStyle& style, int32_t delta)
{
- if( 0 != delta )
+ if(0 != delta)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "AdjustReferenceCount %d, font: %d index: %d\n", delta, fontId, index );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "AdjustReferenceCount %d, font: %d index: %d\n", delta, fontId, index);
- for ( std::vector< FontGlyphRecord >::iterator fontGlyphRecordIt = mFontGlyphRecords.begin();
- fontGlyphRecordIt != mFontGlyphRecords.end();
- ++fontGlyphRecordIt )
+ for(std::vector<FontGlyphRecord>::iterator fontGlyphRecordIt = mFontGlyphRecords.begin();
+ fontGlyphRecordIt != mFontGlyphRecords.end();
+ ++fontGlyphRecordIt)
{
- if ( fontGlyphRecordIt->mFontId == fontId )
+ if(fontGlyphRecordIt->mFontId == fontId)
{
- for ( Vector< GlyphRecordEntry >::Iterator glyphRecordIt = fontGlyphRecordIt->mGlyphRecords.Begin();
- glyphRecordIt != fontGlyphRecordIt->mGlyphRecords.End();
- ++glyphRecordIt )
+ for(Vector<GlyphRecordEntry>::Iterator glyphRecordIt = fontGlyphRecordIt->mGlyphRecords.Begin();
+ glyphRecordIt != fontGlyphRecordIt->mGlyphRecords.End();
+ ++glyphRecordIt)
{
- if ( ( glyphRecordIt->mIndex == index ) &&
- ( glyphRecordIt->mOutlineWidth == style.outline ) &&
- ( glyphRecordIt->isItalic == style.isItalic ) &&
- ( glyphRecordIt->isBold == style.isBold ) )
+ if((glyphRecordIt->mIndex == index) &&
+ (glyphRecordIt->mOutlineWidth == style.outline) &&
+ (glyphRecordIt->isItalic == style.isItalic) &&
+ (glyphRecordIt->isBold == style.isBold))
{
glyphRecordIt->mCount += delta;
- DALI_ASSERT_DEBUG( glyphRecordIt->mCount >= 0 && "Glyph ref-count should not be negative" );
+ DALI_ASSERT_DEBUG(glyphRecordIt->mCount >= 0 && "Glyph ref-count should not be negative");
- if ( !glyphRecordIt->mCount )
+ if(!glyphRecordIt->mCount)
{
- mAtlasManager.Remove( glyphRecordIt->mImageId );
- fontGlyphRecordIt->mGlyphRecords.Remove( glyphRecordIt );
+ mAtlasManager.Remove(glyphRecordIt->mImageId);
+ fontGlyphRecordIt->mGlyphRecords.Remove(glyphRecordIt);
}
return;
}
}
// Should not arrive here
- DALI_ASSERT_DEBUG( false && "Failed to adjust ref-count" );
+ DALI_ASSERT_DEBUG(false && "Failed to adjust ref-count");
}
}
-TextureSet AtlasGlyphManager::GetTextures( uint32_t atlasId ) const
+TextureSet AtlasGlyphManager::GetTextures(uint32_t atlasId) const
{
- return mAtlasManager.GetTextures( atlasId );
+ return mAtlasManager.GetTextures(atlasId);
}
AtlasGlyphManager::~AtlasGlyphManager()
- /*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
AtlasGlyphManager::AtlasGlyphManager()
{
}
AtlasGlyphManager manager;
// Check whether the AtlasGlyphManager is already created
- SingletonService singletonService( SingletonService::Get() );
- if ( singletonService )
+ SingletonService singletonService(SingletonService::Get());
+ if(singletonService)
{
Dali::BaseHandle handle = singletonService.GetSingleton(typeid(AtlasGlyphManager));
if(handle)
return manager;
}
-AtlasGlyphManager::AtlasGlyphManager(Internal::AtlasGlyphManager *impl)
- : BaseHandle(impl)
+AtlasGlyphManager::AtlasGlyphManager(Internal::AtlasGlyphManager* impl)
+: BaseHandle(impl)
{
}
-void AtlasGlyphManager::Add( const Text::GlyphInfo& glyph,
- const GlyphStyle& style,
- const PixelData& bitmap,
- AtlasManager::AtlasSlot& slot )
+void AtlasGlyphManager::Add(const Text::GlyphInfo& glyph,
+ const GlyphStyle& style,
+ const PixelData& bitmap,
+ AtlasManager::AtlasSlot& slot)
{
- GetImplementation(*this).Add( glyph, style, bitmap, slot );
+ GetImplementation(*this).Add(glyph, style, bitmap, slot);
}
-void AtlasGlyphManager::GenerateMeshData( uint32_t imageId,
- const Vector2& position,
- Toolkit::AtlasManager::Mesh2D& mesh )
+void AtlasGlyphManager::GenerateMeshData(uint32_t imageId,
+ const Vector2& position,
+ Toolkit::AtlasManager::Mesh2D& mesh)
{
- GetImplementation(*this).GenerateMeshData( imageId,
- position,
- mesh );
+ GetImplementation(*this).GenerateMeshData(imageId,
+ position,
+ mesh);
}
-bool AtlasGlyphManager::IsCached( Text::FontId fontId,
- Text::GlyphIndex index,
- const GlyphStyle& style,
- AtlasManager::AtlasSlot& slot )
+bool AtlasGlyphManager::IsCached(Text::FontId fontId,
+ Text::GlyphIndex index,
+ const GlyphStyle& style,
+ AtlasManager::AtlasSlot& slot)
{
- return GetImplementation(*this).IsCached( fontId, index, style, slot );
+ return GetImplementation(*this).IsCached(fontId, index, style, slot);
}
-void AtlasGlyphManager::SetNewAtlasSize( uint32_t width, uint32_t height, uint32_t blockWidth, uint32_t blockHeight )
+void AtlasGlyphManager::SetNewAtlasSize(uint32_t width, uint32_t height, uint32_t blockWidth, uint32_t blockHeight)
{
- GetImplementation(*this).SetNewAtlasSize( width, height, blockWidth, blockHeight );
+ GetImplementation(*this).SetNewAtlasSize(width, height, blockWidth, blockHeight);
}
-Vector2 AtlasGlyphManager::GetAtlasSize( uint32_t atlasId )
+Vector2 AtlasGlyphManager::GetAtlasSize(uint32_t atlasId)
{
- return GetImplementation(*this).GetAtlasSize( atlasId );
+ return GetImplementation(*this).GetAtlasSize(atlasId);
}
-Pixel::Format AtlasGlyphManager::GetPixelFormat( uint32_t atlasId )
+Pixel::Format AtlasGlyphManager::GetPixelFormat(uint32_t atlasId)
{
- return GetImplementation(*this).GetPixelFormat( atlasId );
+ return GetImplementation(*this).GetPixelFormat(atlasId);
}
-TextureSet AtlasGlyphManager::GetTextures( uint32_t atlasId ) const
+TextureSet AtlasGlyphManager::GetTextures(uint32_t atlasId) const
{
- return GetImplementation(*this).GetTextures( atlasId );
+ return GetImplementation(*this).GetTextures(atlasId);
}
const Toolkit::AtlasGlyphManager::Metrics& AtlasGlyphManager::GetMetrics()
return GetImplementation(*this).GetMetrics();
}
-void AtlasGlyphManager::AdjustReferenceCount( Text::FontId fontId, Text::GlyphIndex index, const GlyphStyle& style, int32_t delta )
+void AtlasGlyphManager::AdjustReferenceCount(Text::FontId fontId, Text::GlyphIndex index, const GlyphStyle& style, int32_t delta)
{
- GetImplementation(*this).AdjustReferenceCount( fontId, index, style, delta );
+ GetImplementation(*this).AdjustReferenceCount(fontId, index, style, delta);
}
} // namespace Toolkit
#include <dali-toolkit/internal/text/rendering/atlas/atlas-manager-impl.h>
// EXTERNAL INCLUDES
-#include <string.h>
#include <dali/integration-api/debug.h>
+#include <string.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
- const uint32_t DEFAULT_ATLAS_WIDTH( 512u );
- const uint32_t DEFAULT_ATLAS_HEIGHT( 512u );
- const uint32_t DEFAULT_BLOCK_WIDTH( 16u );
- const uint32_t DEFAULT_BLOCK_HEIGHT( 16u );
- const uint32_t SINGLE_PIXEL_PADDING( 1u );
- const uint32_t DOUBLE_PIXEL_PADDING( SINGLE_PIXEL_PADDING << 1 );
- Toolkit::AtlasManager::AtlasSize EMPTY_SIZE;
-
- bool IsBlockSizeSufficient( uint32_t width, uint32_t height, uint32_t requiredBlockWidth, uint32_t requiredBlockHeight )
- {
- return ( width + DOUBLE_PIXEL_PADDING <= requiredBlockWidth ) && ( height + DOUBLE_PIXEL_PADDING <= requiredBlockHeight );
- }
+const uint32_t DEFAULT_ATLAS_WIDTH(512u);
+const uint32_t DEFAULT_ATLAS_HEIGHT(512u);
+const uint32_t DEFAULT_BLOCK_WIDTH(16u);
+const uint32_t DEFAULT_BLOCK_HEIGHT(16u);
+const uint32_t SINGLE_PIXEL_PADDING(1u);
+const uint32_t DOUBLE_PIXEL_PADDING(SINGLE_PIXEL_PADDING << 1);
+Toolkit::AtlasManager::AtlasSize EMPTY_SIZE;
+
+bool IsBlockSizeSufficient(uint32_t width, uint32_t height, uint32_t requiredBlockWidth, uint32_t requiredBlockHeight)
+{
+ return (width + DOUBLE_PIXEL_PADDING <= requiredBlockWidth) && (height + DOUBLE_PIXEL_PADDING <= requiredBlockHeight);
}
+} // namespace
AtlasManager::AtlasManager()
-: mAddFailPolicy( Toolkit::AtlasManager::FAIL_ON_ADD_CREATES )
+: mAddFailPolicy(Toolkit::AtlasManager::FAIL_ON_ADD_CREATES)
{
- mNewAtlasSize.mWidth = DEFAULT_ATLAS_WIDTH;
- mNewAtlasSize.mHeight = DEFAULT_ATLAS_HEIGHT;
- mNewAtlasSize.mBlockWidth = DEFAULT_BLOCK_WIDTH;
+ mNewAtlasSize.mWidth = DEFAULT_ATLAS_WIDTH;
+ mNewAtlasSize.mHeight = DEFAULT_ATLAS_HEIGHT;
+ mNewAtlasSize.mBlockWidth = DEFAULT_BLOCK_WIDTH;
mNewAtlasSize.mBlockHeight = DEFAULT_BLOCK_HEIGHT;
}
{
}
-Toolkit::AtlasManager::AtlasId AtlasManager::CreateAtlas( const Toolkit::AtlasManager::AtlasSize& size, Pixel::Format pixelformat )
+Toolkit::AtlasManager::AtlasId AtlasManager::CreateAtlas(const Toolkit::AtlasManager::AtlasSize& size, Pixel::Format pixelformat)
{
- SizeType width = size.mWidth;
- SizeType height = size.mHeight;
- SizeType blockWidth = size.mBlockWidth;
+ SizeType width = size.mWidth;
+ SizeType height = size.mHeight;
+ SizeType blockWidth = size.mBlockWidth;
SizeType blockHeight = size.mBlockHeight;
// Check to see if the atlas is large enough to hold a single block even ?
- if ( blockWidth + DOUBLE_PIXEL_PADDING + 1u > width || blockHeight + DOUBLE_PIXEL_PADDING + 1u > height )
+ if(blockWidth + DOUBLE_PIXEL_PADDING + 1u > width || blockHeight + DOUBLE_PIXEL_PADDING + 1u > height)
{
DALI_LOG_ERROR("Atlas %i x %i too small. Dimensions need to be at least %ix%i\n",
- width, height, blockWidth + DOUBLE_PIXEL_PADDING + 1u, blockHeight + DOUBLE_PIXEL_PADDING + 1u );
+ width,
+ height,
+ blockWidth + DOUBLE_PIXEL_PADDING + 1u,
+ blockHeight + DOUBLE_PIXEL_PADDING + 1u);
return 0;
}
- Dali::Texture atlas = Dali::Texture::New( TextureType::TEXTURE_2D, pixelformat, width, height );
+ Dali::Texture atlas = Dali::Texture::New(TextureType::TEXTURE_2D, pixelformat, width, height);
// Clear the background
- unsigned int bufferSize( width * height * Dali::Pixel::GetBytesPerPixel( pixelformat ) );
+ unsigned int bufferSize(width * height * Dali::Pixel::GetBytesPerPixel(pixelformat));
unsigned char* background = new unsigned char[bufferSize];
- memset( background, 0, bufferSize );
- PixelData backgroundPixels = PixelData::New( background, bufferSize, width, height, pixelformat, PixelData::DELETE_ARRAY );
- atlas.Upload( backgroundPixels, 0u, 0u, 0u, 0u, width, height );
+ memset(background, 0, bufferSize);
+ PixelData backgroundPixels = PixelData::New(background, bufferSize, width, height, pixelformat, PixelData::DELETE_ARRAY);
+ atlas.Upload(backgroundPixels, 0u, 0u, 0u, 0u, width, height);
AtlasDescriptor atlasDescriptor;
- atlasDescriptor.mAtlas = atlas;
- atlasDescriptor.mSize = size;
- atlasDescriptor.mPixelFormat = pixelformat;
- atlasDescriptor.mTotalBlocks = ( ( width - 1u ) / blockWidth ) * ( ( height - 1u ) / blockHeight );
+ atlasDescriptor.mAtlas = atlas;
+ atlasDescriptor.mSize = size;
+ atlasDescriptor.mPixelFormat = pixelformat;
+ atlasDescriptor.mTotalBlocks = ((width - 1u) / blockWidth) * ((height - 1u) / blockHeight);
atlasDescriptor.mAvailableBlocks = atlasDescriptor.mTotalBlocks;
- bufferSize = blockWidth * SINGLE_PIXEL_PADDING * Dali::Pixel::GetBytesPerPixel(pixelformat);
+ bufferSize = blockWidth * SINGLE_PIXEL_PADDING * Dali::Pixel::GetBytesPerPixel(pixelformat);
unsigned char* bufferHorizontalStrip = new unsigned char[bufferSize];
- memset( bufferHorizontalStrip, 0, bufferSize );
- atlasDescriptor.mHorizontalStrip = PixelData::New( bufferHorizontalStrip, bufferSize, blockWidth, SINGLE_PIXEL_PADDING, pixelformat, PixelData::DELETE_ARRAY );
+ memset(bufferHorizontalStrip, 0, bufferSize);
+ atlasDescriptor.mHorizontalStrip = PixelData::New(bufferHorizontalStrip, bufferSize, blockWidth, SINGLE_PIXEL_PADDING, pixelformat, PixelData::DELETE_ARRAY);
- bufferSize = SINGLE_PIXEL_PADDING * (blockHeight - DOUBLE_PIXEL_PADDING) * Dali::Pixel::GetBytesPerPixel(pixelformat);
+ bufferSize = SINGLE_PIXEL_PADDING * (blockHeight - DOUBLE_PIXEL_PADDING) * Dali::Pixel::GetBytesPerPixel(pixelformat);
unsigned char* bufferVerticalStrip = new unsigned char[bufferSize];
- memset( bufferVerticalStrip, 0, bufferSize );
- atlasDescriptor.mVerticalStrip = PixelData::New( bufferVerticalStrip, bufferSize, SINGLE_PIXEL_PADDING, blockHeight - DOUBLE_PIXEL_PADDING, pixelformat, PixelData::DELETE_ARRAY );
+ memset(bufferVerticalStrip, 0, bufferSize);
+ atlasDescriptor.mVerticalStrip = PixelData::New(bufferVerticalStrip, bufferSize, SINGLE_PIXEL_PADDING, blockHeight - DOUBLE_PIXEL_PADDING, pixelformat, PixelData::DELETE_ARRAY);
- bufferSize = Dali::Pixel::GetBytesPerPixel(pixelformat);
+ bufferSize = Dali::Pixel::GetBytesPerPixel(pixelformat);
unsigned char* buffer = new unsigned char[bufferSize];
- memset( buffer, 0xFF, bufferSize );
- PixelData filledPixelImage = PixelData::New( buffer, bufferSize, 1u, 1u, pixelformat, PixelData::DELETE_ARRAY );
- atlas.Upload( filledPixelImage, 0u, 0u, 0u, 0u, 1u, 1u );
- mAtlasList.push_back( atlasDescriptor );
+ memset(buffer, 0xFF, bufferSize);
+ PixelData filledPixelImage = PixelData::New(buffer, bufferSize, 1u, 1u, pixelformat, PixelData::DELETE_ARRAY);
+ atlas.Upload(filledPixelImage, 0u, 0u, 0u, 0u, 1u, 1u);
+ mAtlasList.push_back(atlasDescriptor);
return mAtlasList.size();
}
-void AtlasManager::SetAddPolicy( Toolkit::AtlasManager::AddFailPolicy policy )
+void AtlasManager::SetAddPolicy(Toolkit::AtlasManager::AddFailPolicy policy)
{
mAddFailPolicy = policy;
}
-bool AtlasManager::Add( const PixelData& image,
- Toolkit::AtlasManager::AtlasSlot& slot,
- Toolkit::AtlasManager::AtlasId atlas )
+bool AtlasManager::Add(const PixelData& image,
+ Toolkit::AtlasManager::AtlasSlot& slot,
+ Toolkit::AtlasManager::AtlasId atlas)
{
- bool created = false;
+ bool created = false;
Pixel::Format pixelFormat = image.GetPixelFormat();
- SizeType width = image.GetWidth();
- SizeType height = image.GetHeight();
- SizeType foundAtlas = 0;
- SizeType index = 0;
- slot.mImageId = 0;
+ SizeType width = image.GetWidth();
+ SizeType height = image.GetHeight();
+ SizeType foundAtlas = 0;
+ SizeType index = 0;
+ slot.mImageId = 0;
AtlasSlotDescriptor desc;
// If there is a preferred atlas then check for room in that first
- if ( atlas-- )
+ if(atlas--)
{
- foundAtlas = CheckAtlas( atlas, width, height, pixelFormat );
+ foundAtlas = CheckAtlas(atlas, width, height, pixelFormat);
}
// Search current atlases to see if there is a good match
- while( ( 0u == foundAtlas ) && ( index < mAtlasList.size() ) )
+ while((0u == foundAtlas) && (index < mAtlasList.size()))
{
- foundAtlas = CheckAtlas( index, width, height, pixelFormat );
+ foundAtlas = CheckAtlas(index, width, height, pixelFormat);
++index;
}
// If we can't find a suitable atlas then check the policy to determine action
- if ( 0u == foundAtlas )
+ if(0u == foundAtlas)
{
- if ( Toolkit::AtlasManager::FAIL_ON_ADD_CREATES == mAddFailPolicy )
+ if(Toolkit::AtlasManager::FAIL_ON_ADD_CREATES == mAddFailPolicy)
{
- if ( IsBlockSizeSufficient( width, height, mNewAtlasSize.mBlockWidth, mNewAtlasSize.mBlockHeight ) ) // Checks if image fits within the atlas blocks
+ if(IsBlockSizeSufficient(width, height, mNewAtlasSize.mBlockWidth, mNewAtlasSize.mBlockHeight)) // Checks if image fits within the atlas blocks
{
- foundAtlas = CreateAtlas( mNewAtlasSize, pixelFormat ); // Creating atlas with mNewAtlasSize, may not be the needed size!
- if ( 0u == foundAtlas )
+ foundAtlas = CreateAtlas(mNewAtlasSize, pixelFormat); // Creating atlas with mNewAtlasSize, may not be the needed size!
+ if(0u == foundAtlas)
{
DALI_LOG_ERROR("Failed to create an atlas of %i x %i blocksize: %i x %i.\n",
mNewAtlasSize.mWidth,
mNewAtlasSize.mHeight,
mNewAtlasSize.mBlockWidth,
- mNewAtlasSize.mBlockHeight );
+ mNewAtlasSize.mBlockHeight);
return false;
}
else
}
}
- if ( ( 0u == foundAtlas ) || Toolkit::AtlasManager::FAIL_ON_ADD_FAILS == mAddFailPolicy )
+ if((0u == foundAtlas) || Toolkit::AtlasManager::FAIL_ON_ADD_FAILS == mAddFailPolicy)
{
// Haven't found an atlas for this image ( may have failed to add image to atlas )
DALI_LOG_ERROR("Failed to create an atlas under current policy.\n");
// Work out which the block we're going to use
// Is there currently a next free block available ?
- if ( mAtlasList[ foundAtlas ].mAvailableBlocks )
+ if(mAtlasList[foundAtlas].mAvailableBlocks)
{
// Yes, so select our next block
- desc.mBlock = mAtlasList[ foundAtlas ].mTotalBlocks - mAtlasList[ foundAtlas ].mAvailableBlocks--;
+ desc.mBlock = mAtlasList[foundAtlas].mTotalBlocks - mAtlasList[foundAtlas].mAvailableBlocks--;
}
else
{
// Our next block must be from the free list, fetch from the start of the list
- desc.mBlock = mAtlasList[ foundAtlas ].mFreeBlocksList[ 0 ];
- mAtlasList[ foundAtlas ].mFreeBlocksList.Remove( mAtlasList[ foundAtlas ].mFreeBlocksList.Begin() );
+ desc.mBlock = mAtlasList[foundAtlas].mFreeBlocksList[0];
+ mAtlasList[foundAtlas].mFreeBlocksList.Remove(mAtlasList[foundAtlas].mFreeBlocksList.Begin());
}
- desc.mImageWidth = width;
+ desc.mImageWidth = width;
desc.mImageHeight = height;
- desc.mAtlasId = foundAtlas + 1u; // Ids start from 1 not the 0 index
- desc.mCount = 1u;
+ desc.mAtlasId = foundAtlas + 1u; // Ids start from 1 not the 0 index
+ desc.mCount = 1u;
// See if there's a previously freed image ID that we can assign to this new image
uint32_t imageId = 0u;
- for ( uint32_t i = 0u; i < mImageList.Size(); ++i )
+ for(uint32_t i = 0u; i < mImageList.Size(); ++i)
{
- if ( !mImageList[ i ].mCount )
+ if(!mImageList[i].mCount)
{
imageId = i + 1u;
break;
}
}
- if ( !imageId )
+ if(!imageId)
{
- mImageList.PushBack( desc );
+ mImageList.PushBack(desc);
slot.mImageId = mImageList.Size();
}
else
{
- mImageList[ imageId - 1u ] = desc;
- slot.mImageId = imageId;
+ mImageList[imageId - 1u] = desc;
+ slot.mImageId = imageId;
}
slot.mAtlasId = foundAtlas + 1u; // Ids start from 1 not the 0 index
// Upload the buffer image into the atlas
- UploadImage( image, desc );
+ UploadImage(image, desc);
return created;
}
-AtlasManager::SizeType AtlasManager::CheckAtlas( SizeType atlas,
- SizeType width,
- SizeType height,
- Pixel::Format pixelFormat )
+AtlasManager::SizeType AtlasManager::CheckAtlas(SizeType atlas,
+ SizeType width,
+ SizeType height,
+ Pixel::Format pixelFormat)
{
AtlasManager::SizeType result = 0u;
- if ( pixelFormat == mAtlasList[ atlas ].mPixelFormat )
+ if(pixelFormat == mAtlasList[atlas].mPixelFormat)
{
// Check to see if the image will fit in these blocks
- const SizeType availableBlocks = mAtlasList[ atlas ].mAvailableBlocks + mAtlasList[ atlas ].mFreeBlocksList.Size();
+ const SizeType availableBlocks = mAtlasList[atlas].mAvailableBlocks + mAtlasList[atlas].mFreeBlocksList.Size();
- if ( availableBlocks && IsBlockSizeSufficient( width, height,mAtlasList[ atlas ].mSize.mBlockWidth, mAtlasList[ atlas ].mSize.mBlockHeight ) )
+ if(availableBlocks && IsBlockSizeSufficient(width, height, mAtlasList[atlas].mSize.mBlockWidth, mAtlasList[atlas].mSize.mBlockHeight))
{
result = atlas + 1u; // Atlas ids start from 1 not 0
}
return result;
}
-void AtlasManager::UploadImage( const PixelData& image,
- const AtlasSlotDescriptor& desc )
+void AtlasManager::UploadImage(const PixelData& image,
+ const AtlasSlotDescriptor& desc)
{
// Get the atlas to upload the image to
SizeType atlas = desc.mAtlasId - 1u;
// Check to see that the pixel formats are compatible
- if ( image.GetPixelFormat() != mAtlasList[ atlas ].mPixelFormat )
+ if(image.GetPixelFormat() != mAtlasList[atlas].mPixelFormat)
{
DALI_LOG_ERROR("Cannot upload an image with a different PixelFormat to the Atlas.\n");
return;
}
- SizeType atlasBlockWidth = mAtlasList[ atlas ].mSize.mBlockWidth;
- SizeType atlasBlockHeight = mAtlasList[ atlas ].mSize.mBlockHeight;
- SizeType atlasWidthInBlocks = ( mAtlasList[ atlas ].mSize.mWidth - 1u ) / mAtlasList[ atlas ].mSize.mBlockWidth;
+ SizeType atlasBlockWidth = mAtlasList[atlas].mSize.mBlockWidth;
+ SizeType atlasBlockHeight = mAtlasList[atlas].mSize.mBlockHeight;
+ SizeType atlasWidthInBlocks = (mAtlasList[atlas].mSize.mWidth - 1u) / mAtlasList[atlas].mSize.mBlockWidth;
- SizeType blockX = desc.mBlock % atlasWidthInBlocks;
- SizeType blockY = desc.mBlock / atlasWidthInBlocks;
- SizeType blockOffsetX = ( blockX * atlasBlockWidth ) + 1u;
- SizeType blockOffsetY = ( blockY * atlasBlockHeight) + 1u;
+ SizeType blockX = desc.mBlock % atlasWidthInBlocks;
+ SizeType blockY = desc.mBlock / atlasWidthInBlocks;
+ SizeType blockOffsetX = (blockX * atlasBlockWidth) + 1u;
+ SizeType blockOffsetY = (blockY * atlasBlockHeight) + 1u;
- SizeType width = image.GetWidth();
+ SizeType width = image.GetWidth();
SizeType height = image.GetHeight();
// Blit image 1 pixel to the right and down into the block to compensate for texture filtering
- if ( !mAtlasList[ atlas ].mAtlas.Upload( image, 0u, 0u,
- blockOffsetX + SINGLE_PIXEL_PADDING,
- blockOffsetY + SINGLE_PIXEL_PADDING,
- width, height) )
+ if(!mAtlasList[atlas].mAtlas.Upload(image, 0u, 0u, blockOffsetX + SINGLE_PIXEL_PADDING, blockOffsetY + SINGLE_PIXEL_PADDING, width, height))
{
DALI_LOG_ERROR("Uploading image to Atlas Failed!.\n");
}
// Blit top strip
- if ( !mAtlasList[ atlas ].mAtlas.Upload( mAtlasList[ atlas ].mHorizontalStrip, 0u, 0u,
- blockOffsetX,
- blockOffsetY,
- mAtlasList[ atlas ].mHorizontalStrip.GetWidth(),
- mAtlasList[ atlas ].mHorizontalStrip.GetHeight()) )
+ if(!mAtlasList[atlas].mAtlas.Upload(mAtlasList[atlas].mHorizontalStrip, 0u, 0u, blockOffsetX, blockOffsetY, mAtlasList[atlas].mHorizontalStrip.GetWidth(), mAtlasList[atlas].mHorizontalStrip.GetHeight()))
{
DALI_LOG_ERROR("Uploading top strip to Atlas Failed!\n");
}
// Blit left strip
- if ( !mAtlasList[ atlas ].mAtlas.Upload( mAtlasList[ atlas ].mVerticalStrip, 0u, 0u,
- blockOffsetX,
- blockOffsetY + SINGLE_PIXEL_PADDING,
- mAtlasList[ atlas ].mVerticalStrip.GetWidth(),
- mAtlasList[ atlas ].mVerticalStrip.GetHeight() ) )
+ if(!mAtlasList[atlas].mAtlas.Upload(mAtlasList[atlas].mVerticalStrip, 0u, 0u, blockOffsetX, blockOffsetY + SINGLE_PIXEL_PADDING, mAtlasList[atlas].mVerticalStrip.GetWidth(), mAtlasList[atlas].mVerticalStrip.GetHeight()))
{
DALI_LOG_ERROR("Uploading left strip to Atlas Failed!\n");
}
// Blit bottom strip
- if ( blockOffsetY + height + DOUBLE_PIXEL_PADDING <= mAtlasList[ atlas ].mSize.mHeight )
+ if(blockOffsetY + height + DOUBLE_PIXEL_PADDING <= mAtlasList[atlas].mSize.mHeight)
{
- if ( !mAtlasList[ atlas ].mAtlas.Upload( mAtlasList[ atlas ].mHorizontalStrip, 0u, 0u,
- blockOffsetX,
- blockOffsetY + height + SINGLE_PIXEL_PADDING,
- mAtlasList[ atlas ].mHorizontalStrip.GetWidth(),
- mAtlasList[ atlas ].mHorizontalStrip.GetHeight() ) )
+ if(!mAtlasList[atlas].mAtlas.Upload(mAtlasList[atlas].mHorizontalStrip, 0u, 0u, blockOffsetX, blockOffsetY + height + SINGLE_PIXEL_PADDING, mAtlasList[atlas].mHorizontalStrip.GetWidth(), mAtlasList[atlas].mHorizontalStrip.GetHeight()))
{
DALI_LOG_ERROR("Uploading bottom strip to Atlas Failed!.\n");
}
}
// Blit right strip
- if ( blockOffsetX + width + DOUBLE_PIXEL_PADDING <= mAtlasList[ atlas ].mSize.mWidth )
+ if(blockOffsetX + width + DOUBLE_PIXEL_PADDING <= mAtlasList[atlas].mSize.mWidth)
{
- if ( !mAtlasList[ atlas ].mAtlas.Upload( mAtlasList[ atlas ].mVerticalStrip, 0u, 0u,
- blockOffsetX + width + SINGLE_PIXEL_PADDING,
- blockOffsetY + SINGLE_PIXEL_PADDING,
- mAtlasList[ atlas ].mVerticalStrip.GetWidth(),
- mAtlasList[ atlas ].mVerticalStrip.GetHeight() ) )
+ if(!mAtlasList[atlas].mAtlas.Upload(mAtlasList[atlas].mVerticalStrip, 0u, 0u, blockOffsetX + width + SINGLE_PIXEL_PADDING, blockOffsetY + SINGLE_PIXEL_PADDING, mAtlasList[atlas].mVerticalStrip.GetWidth(), mAtlasList[atlas].mVerticalStrip.GetHeight()))
{
DALI_LOG_ERROR("Uploading right strip to Atlas Failed!.\n");
}
}
}
-void AtlasManager::GenerateMeshData( ImageId id,
- const Vector2& position,
- Toolkit::AtlasManager::Mesh2D& meshData,
- bool addReference )
+void AtlasManager::GenerateMeshData(ImageId id,
+ const Vector2& position,
+ Toolkit::AtlasManager::Mesh2D& meshData,
+ bool addReference)
{
- if ( id )
+ if(id)
{
// Read the atlas Id to use for this image
SizeType imageId = id - 1u;
- SizeType atlas = mImageList[ imageId ].mAtlasId - 1u;
- SizeType width = mImageList[ imageId ].mImageWidth;
- SizeType height = mImageList[ imageId ].mImageHeight;
+ SizeType atlas = mImageList[imageId].mAtlasId - 1u;
+ SizeType width = mImageList[imageId].mImageWidth;
+ SizeType height = mImageList[imageId].mImageHeight;
- AtlasMeshFactory::CreateQuad( width,
- height,
- mImageList[ imageId ].mBlock,
- mAtlasList[ atlas ].mSize,
- position,
- meshData );
+ AtlasMeshFactory::CreateQuad(width,
+ height,
+ mImageList[imageId].mBlock,
+ mAtlasList[atlas].mSize,
+ position,
+ meshData);
// Mesh created so increase the reference count, if we're asked to
- if ( addReference )
+ if(addReference)
{
- mImageList[ imageId ].mCount++;
+ mImageList[imageId].mCount++;
}
}
else
}
}
-Dali::Texture AtlasManager::GetAtlasContainer( AtlasId atlas ) const
+Dali::Texture AtlasManager::GetAtlasContainer(AtlasId atlas) const
{
- DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() );
+ DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size());
Dali::Texture atlasContainer;
- if ( atlas && atlas-- <= mAtlasList.size() )
+ if(atlas && atlas-- <= mAtlasList.size())
{
- atlasContainer = mAtlasList[ atlas ].mAtlas;
+ atlasContainer = mAtlasList[atlas].mAtlas;
}
return atlasContainer;
}
-bool AtlasManager::Remove( ImageId id )
+bool AtlasManager::Remove(ImageId id)
{
// Decrements the reference count of this image, and removes the blocks if zero.
SizeType imageId = id - 1u;
- bool removed = false;
+ bool removed = false;
- if ( id > mImageList.Size() )
- {
- DALI_LOG_ERROR("Atlas was asked to free an invalid imageID: %i\n", id );
+ if(id > mImageList.Size())
+ {
+ DALI_LOG_ERROR("Atlas was asked to free an invalid imageID: %i\n", id);
return false;
}
// If we attempt to free an image that is already freed then do nothing, other than log
- if ( !mImageList[ imageId ].mCount )
+ if(!mImageList[imageId].mCount)
{
- DALI_LOG_ERROR("Atlas was asked to free an imageID: %i, that has already been freed!\n", id );
+ DALI_LOG_ERROR("Atlas was asked to free an imageID: %i, that has already been freed!\n", id);
return false;
}
- if ( 2u > --mImageList[ imageId ].mCount )
+ if(2u > --mImageList[imageId].mCount)
{
// 'Remove the blocks' from this image and add to the atlas' freelist
- removed = true;
- mImageList[ imageId ].mCount = 0;
- SizeType atlas = mImageList[ imageId ].mAtlasId - 1u;
- mAtlasList[ atlas ].mFreeBlocksList.PushBack( mImageList[ imageId ].mBlock );
+ removed = true;
+ mImageList[imageId].mCount = 0;
+ SizeType atlas = mImageList[imageId].mAtlasId - 1u;
+ mAtlasList[atlas].mFreeBlocksList.PushBack(mImageList[imageId].mBlock);
}
return removed;
}
-AtlasManager::AtlasId AtlasManager::GetAtlas( ImageId id ) const
+AtlasManager::AtlasId AtlasManager::GetAtlas(ImageId id) const
{
- DALI_ASSERT_DEBUG( id && id <= mImageList.Size() );
+ DALI_ASSERT_DEBUG(id && id <= mImageList.Size());
AtlasManager::AtlasId atlasId = 0u;
- if ( id && id-- <= mImageList.Size() )
+ if(id && id-- <= mImageList.Size())
{
- atlasId = mImageList[ id ].mAtlasId;
+ atlasId = mImageList[id].mAtlasId;
}
return atlasId;
}
-void AtlasManager::SetNewAtlasSize( const Toolkit::AtlasManager::AtlasSize& size )
+void AtlasManager::SetNewAtlasSize(const Toolkit::AtlasManager::AtlasSize& size)
{
mNewAtlasSize = size;
mNewAtlasSize.mBlockHeight += DOUBLE_PIXEL_PADDING;
}
-const Toolkit::AtlasManager::AtlasSize& AtlasManager::GetAtlasSize( AtlasId atlas )
+const Toolkit::AtlasManager::AtlasSize& AtlasManager::GetAtlasSize(AtlasId atlas)
{
- DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() );
- if ( atlas && atlas-- <= mAtlasList.size() )
+ DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size());
+ if(atlas && atlas-- <= mAtlasList.size())
{
- return mAtlasList[ atlas ].mSize;
+ return mAtlasList[atlas].mSize;
}
return EMPTY_SIZE;
}
-AtlasManager::SizeType AtlasManager::GetFreeBlocks( AtlasId atlas ) const
+AtlasManager::SizeType AtlasManager::GetFreeBlocks(AtlasId atlas) const
{
- DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() );
+ DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size());
AtlasManager::SizeType freeBlocks = 0u;
- if ( atlas && atlas-- <= mAtlasList.size() )
+ if(atlas && atlas-- <= mAtlasList.size())
{
- freeBlocks = mAtlasList[ atlas ].mAvailableBlocks + mAtlasList[ atlas ].mFreeBlocksList.Size();
+ freeBlocks = mAtlasList[atlas].mAvailableBlocks + mAtlasList[atlas].mFreeBlocksList.Size();
}
return freeBlocks;
}
return mAtlasList.size();
}
-Pixel::Format AtlasManager::GetPixelFormat( AtlasId atlas ) const
+Pixel::Format AtlasManager::GetPixelFormat(AtlasId atlas) const
{
- DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() );
+ DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size());
Pixel::Format pixelFormat = Pixel::RGBA8888;
- if ( atlas && atlas-- <= mAtlasList.size() )
+ if(atlas && atlas-- <= mAtlasList.size())
{
- pixelFormat = mAtlasList[ atlas ].mPixelFormat;
+ pixelFormat = mAtlasList[atlas].mPixelFormat;
}
return pixelFormat;
}
-void AtlasManager::GetMetrics( Toolkit::AtlasManager::Metrics& metrics )
+void AtlasManager::GetMetrics(Toolkit::AtlasManager::Metrics& metrics)
{
Toolkit::AtlasManager::AtlasMetricsEntry entry;
- uint32_t textureMemoryUsed = 0;
- uint32_t atlasCount = mAtlasList.size();
- metrics.mAtlasCount = atlasCount;
+ uint32_t textureMemoryUsed = 0;
+ uint32_t atlasCount = mAtlasList.size();
+ metrics.mAtlasCount = atlasCount;
metrics.mAtlasMetrics.Resize(0);
- for ( uint32_t i = 0; i < atlasCount; ++i )
+ for(uint32_t i = 0; i < atlasCount; ++i)
{
- entry.mSize = mAtlasList[ i ].mSize;
- entry.mTotalBlocks = mAtlasList[ i ].mTotalBlocks;
- entry.mBlocksUsed = entry.mTotalBlocks - mAtlasList[ i ].mAvailableBlocks + mAtlasList[ i ].mFreeBlocksList.Size();
- entry.mPixelFormat = GetPixelFormat( i + 1 );
+ entry.mSize = mAtlasList[i].mSize;
+ entry.mTotalBlocks = mAtlasList[i].mTotalBlocks;
+ entry.mBlocksUsed = entry.mTotalBlocks - mAtlasList[i].mAvailableBlocks + mAtlasList[i].mFreeBlocksList.Size();
+ entry.mPixelFormat = GetPixelFormat(i + 1);
- metrics.mAtlasMetrics.PushBack( entry );
+ metrics.mAtlasMetrics.PushBack(entry);
uint32_t size = entry.mSize.mWidth * entry.mSize.mHeight;
- if ( entry.mPixelFormat == Pixel::BGRA8888 )
+ if(entry.mPixelFormat == Pixel::BGRA8888)
{
size <<= 2;
}
textureMemoryUsed += size;
-
}
metrics.mTextureMemoryUsed = textureMemoryUsed;
}
-TextureSet AtlasManager::GetTextures( AtlasId atlas ) const
+TextureSet AtlasManager::GetTextures(AtlasId atlas) const
{
- DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() );
+ DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size());
TextureSet textureSet;
- if ( atlas && atlas-- <= mAtlasList.size() )
+ if(atlas && atlas-- <= mAtlasList.size())
{
- textureSet = mAtlasList[ atlas ].mTextureSet;
+ textureSet = mAtlasList[atlas].mTextureSet;
}
return textureSet;
}
-void AtlasManager::SetTextures( AtlasId atlas, TextureSet& textureSet )
+void AtlasManager::SetTextures(AtlasId atlas, TextureSet& textureSet)
{
- DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() );
- if ( atlas && atlas-- <= mAtlasList.size() )
+ DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size());
+ if(atlas && atlas-- <= mAtlasList.size())
{
- mAtlasList[ atlas ].mTextureSet = textureSet;
+ mAtlasList[atlas].mTextureSet = textureSet;
}
}
} // namespace Toolkit
} // namespace Dali
-
-
namespace Dali
{
-
namespace Toolkit
{
-
AtlasManager::AtlasManager()
{
}
return AtlasManager(internal.Get());
}
-AtlasManager::AtlasManager(Internal::AtlasManager *impl)
- : BaseHandle(impl)
+AtlasManager::AtlasManager(Internal::AtlasManager* impl)
+: BaseHandle(impl)
{
}
-AtlasManager::AtlasId AtlasManager::CreateAtlas( const AtlasManager::AtlasSize& size, Pixel::Format pixelformat )
+AtlasManager::AtlasId AtlasManager::CreateAtlas(const AtlasManager::AtlasSize& size, Pixel::Format pixelformat)
{
- return GetImplementation(*this).CreateAtlas( size, pixelformat );
+ return GetImplementation(*this).CreateAtlas(size, pixelformat);
}
-void AtlasManager::SetAddPolicy( AddFailPolicy policy )
+void AtlasManager::SetAddPolicy(AddFailPolicy policy)
{
- GetImplementation(*this).SetAddPolicy( policy );
+ GetImplementation(*this).SetAddPolicy(policy);
}
-bool AtlasManager::Add( const PixelData& image,
- AtlasManager::AtlasSlot& slot,
- AtlasManager::AtlasId atlas )
+bool AtlasManager::Add(const PixelData& image,
+ AtlasManager::AtlasSlot& slot,
+ AtlasManager::AtlasId atlas)
{
- return GetImplementation(*this).Add( image, slot, atlas );
+ return GetImplementation(*this).Add(image, slot, atlas);
}
-bool AtlasManager::Remove( ImageId id )
+bool AtlasManager::Remove(ImageId id)
{
- return GetImplementation(*this).Remove( id );
+ return GetImplementation(*this).Remove(id);
}
-void AtlasManager::GenerateMeshData( ImageId id,
- const Vector2& position,
- Mesh2D& mesh,
- bool addReference )
+void AtlasManager::GenerateMeshData(ImageId id,
+ const Vector2& position,
+ Mesh2D& mesh,
+ bool addReference)
{
- GetImplementation(*this).GenerateMeshData( id,
- position,
- mesh,
- addReference );
+ GetImplementation(*this).GenerateMeshData(id,
+ position,
+ mesh,
+ addReference);
}
-Dali::Texture AtlasManager::GetAtlasContainer( AtlasId atlas ) const
+Dali::Texture AtlasManager::GetAtlasContainer(AtlasId atlas) const
{
- return GetImplementation(*this).GetAtlasContainer( atlas );
+ return GetImplementation(*this).GetAtlasContainer(atlas);
}
-AtlasManager::AtlasId AtlasManager::GetAtlas( ImageId id )
+AtlasManager::AtlasId AtlasManager::GetAtlas(ImageId id)
{
- return GetImplementation(*this).GetAtlas( id );
+ return GetImplementation(*this).GetAtlas(id);
}
-const AtlasManager::AtlasSize& AtlasManager::GetAtlasSize( AtlasId atlas )
+const AtlasManager::AtlasSize& AtlasManager::GetAtlasSize(AtlasId atlas)
{
- return GetImplementation(*this).GetAtlasSize( atlas );
+ return GetImplementation(*this).GetAtlasSize(atlas);
}
-AtlasManager::SizeType AtlasManager::GetFreeBlocks( AtlasId atlas )
+AtlasManager::SizeType AtlasManager::GetFreeBlocks(AtlasId atlas)
{
- return GetImplementation(*this).GetFreeBlocks( atlas );
+ return GetImplementation(*this).GetFreeBlocks(atlas);
}
-void AtlasManager::SetNewAtlasSize( const AtlasSize& size )
+void AtlasManager::SetNewAtlasSize(const AtlasSize& size)
{
- GetImplementation(*this).SetNewAtlasSize( size );
+ GetImplementation(*this).SetNewAtlasSize(size);
}
AtlasManager::SizeType AtlasManager::GetAtlasCount() const
return GetImplementation(*this).GetAtlasCount();
}
-Pixel::Format AtlasManager::GetPixelFormat( AtlasId atlas ) const
+Pixel::Format AtlasManager::GetPixelFormat(AtlasId atlas) const
{
- return GetImplementation(*this).GetPixelFormat( atlas );
+ return GetImplementation(*this).GetPixelFormat(atlas);
}
-void AtlasManager::GetMetrics( Metrics& metrics )
+void AtlasManager::GetMetrics(Metrics& metrics)
{
- GetImplementation(*this).GetMetrics( metrics );
+ GetImplementation(*this).GetMetrics(metrics);
}
-TextureSet AtlasManager::GetTextures( AtlasId atlas ) const
+TextureSet AtlasManager::GetTextures(AtlasId atlas) const
{
- return GetImplementation(*this).GetTextures( atlas );
+ return GetImplementation(*this).GetTextures(atlas);
}
-void AtlasManager::SetTextures( AtlasId atlas, TextureSet& textureSet )
+void AtlasManager::SetTextures(AtlasId atlas, TextureSet& textureSet)
{
- GetImplementation(*this).SetTextures( atlas, textureSet );
+ GetImplementation(*this).SetTextures(atlas, textureSet);
}
} // namespace Toolkit
- /*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace AtlasMeshFactory
{
-
-void CreateQuad( SizeType imageWidth,
- SizeType imageHeight,
- SizeType block,
- const Toolkit::AtlasManager::AtlasSize& atlasSize,
- const Vector2& position,
- Toolkit::AtlasManager::Mesh2D& mesh )
+void CreateQuad(SizeType imageWidth,
+ SizeType imageHeight,
+ SizeType block,
+ const Toolkit::AtlasManager::AtlasSize& atlasSize,
+ const Vector2& position,
+ Toolkit::AtlasManager::Mesh2D& mesh)
{
Toolkit::AtlasManager::Vertex2D vertex;
- SizeType blockWidth = atlasSize.mBlockWidth;
+ SizeType blockWidth = atlasSize.mBlockWidth;
SizeType blockHeight = atlasSize.mBlockHeight;
- float vertexBlockWidth = static_cast< float >( blockWidth );
- float vertexBlockHeight = static_cast< float >( blockHeight );
+ float vertexBlockWidth = static_cast<float>(blockWidth);
+ float vertexBlockHeight = static_cast<float>(blockHeight);
- SizeType atlasWidth = atlasSize.mWidth;
+ SizeType atlasWidth = atlasSize.mWidth;
SizeType atlasHeight = atlasSize.mHeight;
- SizeType atlasWidthInBlocks = ( atlasWidth - 1u ) / blockWidth;
+ SizeType atlasWidthInBlocks = (atlasWidth - 1u) / blockWidth;
// Get the normalized size of a texel in both directions
- float texelX = 1.0f / static_cast< float >( atlasWidth );
- float texelY = 1.0f / static_cast< float >( atlasHeight );
+ float texelX = 1.0f / static_cast<float>(atlasWidth);
+ float texelY = 1.0f / static_cast<float>(atlasHeight);
- float oneAndAHalfTexelX = texelX + ( texelX * 0.5f );
- float oneAndAHalfTexelY = texelY + ( texelY * 0.5f );
+ float oneAndAHalfTexelX = texelX + (texelX * 0.5f);
+ float oneAndAHalfTexelY = texelY + (texelY * 0.5f);
- float texelBlockWidth = texelX * vertexBlockWidth;
+ float texelBlockWidth = texelX * vertexBlockWidth;
float texelBlockHeight = texelY * vertexBlockHeight;
uint32_t pixelsX = imageWidth % blockWidth;
uint32_t pixelsY = imageHeight % blockHeight;
- if ( !pixelsX )
+ if(!pixelsX)
{
pixelsX = blockWidth;
}
- if ( !pixelsY )
+ if(!pixelsY)
{
pixelsY = blockHeight;
}
- float vertexWidth = static_cast< float >( pixelsX );
- float vertexHeight = static_cast< float >( pixelsY );
- float texelWidth = texelX * vertexWidth;
- float texelHeight = texelY * vertexHeight;
+ float vertexWidth = static_cast<float>(pixelsX);
+ float vertexHeight = static_cast<float>(pixelsY);
+ float texelWidth = texelX * vertexWidth;
+ float texelHeight = texelY * vertexHeight;
// We're going to 'blit' half a pixel more on each edge
vertexWidth++;
vertexHeight++;
// Move back half a pixel
- Vector2 topLeft = Vector2( position.x - 0.5f, position.y - 0.5f );
+ Vector2 topLeft = Vector2(position.x - 0.5f, position.y - 0.5f);
- float fBlockX = texelBlockWidth * static_cast< float >( block % atlasWidthInBlocks );
+ float fBlockX = texelBlockWidth * static_cast<float>(block % atlasWidthInBlocks);
// In the next expression, we have purposely made ( block / atlasWidthInBlocks ) yield an integer value and then convert to float as
// we do not want the remainder in that expression to affect the value of fBlockY
- float fBlockY = texelBlockHeight * static_cast< float >( block / atlasWidthInBlocks );
+ float fBlockY = texelBlockHeight * static_cast<float>(block / atlasWidthInBlocks);
// Add on texture filtering compensation ( half a texel plus compensation for filled pixel in top left corner )
fBlockX += oneAndAHalfTexelX;
fBlockY += oneAndAHalfTexelY;
- float texelWidthOffset = texelWidth + texelX;
+ float texelWidthOffset = texelWidth + texelX;
float texelHeightOffset = texelHeight + texelY;
// Top left
- vertex.mPosition.x = topLeft.x;
- vertex.mPosition.y = topLeft.y;
+ vertex.mPosition.x = topLeft.x;
+ vertex.mPosition.y = topLeft.y;
vertex.mTexCoords.x = fBlockX;
vertex.mTexCoords.y = fBlockY;
- mesh.mVertices.Reserve( 4u );
- mesh.mVertices.PushBack( vertex );
+ mesh.mVertices.Reserve(4u);
+ mesh.mVertices.PushBack(vertex);
// Top Right
- vertex.mPosition.x = topLeft.x + vertexWidth;
- vertex.mPosition.y = topLeft.y;
+ vertex.mPosition.x = topLeft.x + vertexWidth;
+ vertex.mPosition.y = topLeft.y;
vertex.mTexCoords.x = fBlockX + texelWidthOffset;
vertex.mTexCoords.y = fBlockY;
- mesh.mVertices.PushBack( vertex );
+ mesh.mVertices.PushBack(vertex);
// Bottom Left
- vertex.mPosition.x = topLeft.x;
- vertex.mPosition.y = topLeft.y + vertexHeight;
+ vertex.mPosition.x = topLeft.x;
+ vertex.mPosition.y = topLeft.y + vertexHeight;
vertex.mTexCoords.x = fBlockX;
vertex.mTexCoords.y = fBlockY + texelHeightOffset;
- mesh.mVertices.PushBack( vertex );
+ mesh.mVertices.PushBack(vertex);
// Bottom Right
- vertex.mPosition.x = topLeft.x + vertexWidth;
- vertex.mPosition.y = topLeft.y + vertexHeight;
+ vertex.mPosition.x = topLeft.x + vertexWidth;
+ vertex.mPosition.y = topLeft.y + vertexHeight;
vertex.mTexCoords.x = fBlockX + texelWidthOffset;
vertex.mTexCoords.y = fBlockY + texelHeightOffset;
- mesh.mVertices.PushBack( vertex );
+ mesh.mVertices.PushBack(vertex);
// Six indices in counter clockwise winding
- mesh.mIndices.Reserve( 6u );
- mesh.mIndices.PushBack( 1u );
- mesh.mIndices.PushBack( 0u );
- mesh.mIndices.PushBack( 2u );
- mesh.mIndices.PushBack( 2u );
- mesh.mIndices.PushBack( 3u );
- mesh.mIndices.PushBack( 1u );
+ mesh.mIndices.Reserve(6u);
+ mesh.mIndices.PushBack(1u);
+ mesh.mIndices.PushBack(0u);
+ mesh.mIndices.PushBack(2u);
+ mesh.mIndices.PushBack(2u);
+ mesh.mIndices.PushBack(3u);
+ mesh.mIndices.PushBack(1u);
}
-void AppendMesh( Toolkit::AtlasManager::Mesh2D& first,
- const Toolkit::AtlasManager::Mesh2D& second )
+void AppendMesh(Toolkit::AtlasManager::Mesh2D& first,
+ const Toolkit::AtlasManager::Mesh2D& second)
{
const uint32_t verticesCount = first.mVertices.Size();
- first.mVertices.Insert( first.mVertices.End(),
- second.mVertices.Begin(),
- second.mVertices.End() );
+ first.mVertices.Insert(first.mVertices.End(),
+ second.mVertices.Begin(),
+ second.mVertices.End());
const uint32_t indicesCount = first.mIndices.Size();
- first.mIndices.Insert( first.mIndices.End(),
- second.mIndices.Begin(),
- second.mIndices.End() );
-
- for( Vector<unsigned short>::Iterator it = first.mIndices.Begin() + indicesCount,
- endIt = first.mIndices.End();
- it != endIt;
- ++it )
+ first.mIndices.Insert(first.mIndices.End(),
+ second.mIndices.Begin(),
+ second.mIndices.End());
+
+ for(Vector<unsigned short>::Iterator it = first.mIndices.Begin() + indicesCount,
+ endIt = first.mIndices.End();
+ it != endIt;
+ ++it)
{
*it += verticesCount;
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/rendering/geometry.h>
-#include <dali/public-api/rendering/renderer.h>
#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/animation/constraints.h>
+#include <dali/public-api/rendering/geometry.h>
+#include <dali/public-api/rendering/renderer.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
#include <dali-toolkit/internal/text/glyph-run.h>
#include <dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.h>
#include <dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.h>
#include <dali-toolkit/internal/text/text-view.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
using namespace Dali;
using namespace Dali::Toolkit;
namespace
{
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_RENDERING");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_RENDERING");
#endif
-const float ZERO( 0.0f );
-const float HALF( 0.5f );
-const float ONE( 1.0f );
-const uint32_t DEFAULT_ATLAS_WIDTH = 512u;
+const float ZERO(0.0f);
+const float HALF(0.5f);
+const float ONE(1.0f);
+const uint32_t DEFAULT_ATLAS_WIDTH = 512u;
const uint32_t DEFAULT_ATLAS_HEIGHT = 512u;
-const uint16_t NO_OUTLINE = 0u;
-}
+const uint16_t NO_OUTLINE = 0u;
+} // namespace
struct AtlasRenderer::Impl
{
struct MeshRecord
{
MeshRecord()
- : mAtlasId( 0u )
+ : mAtlasId(0u)
{
}
- uint32_t mAtlasId;
+ uint32_t mAtlasId;
AtlasManager::Mesh2D mMesh;
};
struct Extent
{
Extent()
- : mBaseLine( 0.0f ),
- mLeft( 0.0f ),
- mRight( 0.0f ),
- mUnderlinePosition( 0.0f ),
- mUnderlineThickness( 0.0f ),
- mMeshRecordIndex( 0u )
+ : mBaseLine(0.0f),
+ mLeft(0.0f),
+ mRight(0.0f),
+ mUnderlinePosition(0.0f),
+ mUnderlineThickness(0.0f),
+ mMeshRecordIndex(0u)
{
}
- float mBaseLine;
- float mLeft;
- float mRight;
- float mUnderlinePosition;
- float mUnderlineThickness;
+ float mBaseLine;
+ float mLeft;
+ float mRight;
+ float mUnderlinePosition;
+ float mUnderlineThickness;
uint32_t mMeshRecordIndex;
};
struct MaxBlockSize
{
MaxBlockSize()
- : mFontId( 0 ),
- mNeededBlockWidth( 0 ),
- mNeededBlockHeight( 0 )
+ : mFontId(0),
+ mNeededBlockWidth(0),
+ mNeededBlockHeight(0)
{
}
- FontId mFontId;
+ FontId mFontId;
uint32_t mNeededBlockWidth;
uint32_t mNeededBlockHeight;
};
struct CheckEntry
{
CheckEntry()
- : mFontId( 0 ),
- mIndex( 0 )
+ : mFontId(0),
+ mIndex(0)
{
}
- FontId mFontId;
+ FontId mFontId;
Text::GlyphIndex mIndex;
};
struct TextCacheEntry
{
TextCacheEntry()
- : mFontId{ 0u },
- mIndex{ 0u },
- mImageId{ 0u },
- mOutlineWidth{ 0u },
- isItalic{ false },
- isBold{ false }
+ : mFontId{0u},
+ mIndex{0u},
+ mImageId{0u},
+ mOutlineWidth{0u},
+ isItalic{false},
+ isBold{false}
{
}
- FontId mFontId;
+ FontId mFontId;
Text::GlyphIndex mIndex;
- uint32_t mImageId;
- uint16_t mOutlineWidth;
- bool isItalic:1;
- bool isBold:1;
+ uint32_t mImageId;
+ uint16_t mOutlineWidth;
+ bool isItalic : 1;
+ bool isBold : 1;
};
Impl()
- : mDepth( 0 )
+ : mDepth(0)
{
mGlyphManager = AtlasGlyphManager::Get();
- mFontClient = TextAbstraction::FontClient::Get();
+ mFontClient = TextAbstraction::FontClient::Get();
- mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
- mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2;
- mQuadVertexFormat[ "aColor" ] = Property::VECTOR4;
+ mQuadVertexFormat["aPosition"] = Property::VECTOR2;
+ mQuadVertexFormat["aTexCoord"] = Property::VECTOR2;
+ mQuadVertexFormat["aColor"] = Property::VECTOR4;
}
- bool IsGlyphUnderlined( GlyphIndex index,
- const Vector<GlyphRun>& underlineRuns )
+ bool IsGlyphUnderlined(GlyphIndex index,
+ const Vector<GlyphRun>& underlineRuns)
{
- for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
- endIt = underlineRuns.End();
- it != endIt;
- ++it )
+ for(Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
+ endIt = underlineRuns.End();
+ it != endIt;
+ ++it)
{
const GlyphRun& run = *it;
- if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
+ if((run.glyphIndex <= index) && (index < run.glyphIndex + run.numberOfGlyphs))
{
return true;
}
return false;
}
- void CacheGlyph( const GlyphInfo& glyph, FontId lastFontId, const AtlasGlyphManager::GlyphStyle& style, AtlasManager::AtlasSlot& slot )
+ void CacheGlyph(const GlyphInfo& glyph, FontId lastFontId, const AtlasGlyphManager::GlyphStyle& style, AtlasManager::AtlasSlot& slot)
{
- const bool glyphNotCached = !mGlyphManager.IsCached( glyph.fontId, glyph.index, style, slot ); // Check FontGlyphRecord vector for entry with glyph index and fontId
+ const bool glyphNotCached = !mGlyphManager.IsCached(glyph.fontId, glyph.index, style, slot); // Check FontGlyphRecord vector for entry with glyph index and fontId
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "AddGlyphs fontID[%u] glyphIndex[%u] [%s]\n", glyph.fontId, glyph.index, (glyphNotCached)?"not cached":"cached" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "AddGlyphs fontID[%u] glyphIndex[%u] [%s]\n", glyph.fontId, glyph.index, (glyphNotCached) ? "not cached" : "cached");
- if( glyphNotCached )
+ if(glyphNotCached)
{
MaxBlockSize& blockSize = mBlockSizes[0u];
- if ( lastFontId != glyph.fontId )
+ if(lastFontId != glyph.fontId)
{
uint32_t index = 0u;
// Looks through all stored block sizes until finds the one which mataches required glyph font it. Ensures new atlas block size will match existing for same font id.
// CalculateBlocksSize() above ensures a block size entry exists.
- for( std::vector<MaxBlockSize>::const_iterator it = mBlockSizes.begin(),
- endIt = mBlockSizes.end();
- it != endIt;
- ++it, ++index )
+ for(std::vector<MaxBlockSize>::const_iterator it = mBlockSizes.begin(),
+ endIt = mBlockSizes.end();
+ it != endIt;
+ ++it, ++index)
{
const MaxBlockSize& blockSizeEntry = *it;
- if( blockSizeEntry.mFontId == glyph.fontId )
+ if(blockSizeEntry.mFontId == glyph.fontId)
{
blockSize = mBlockSizes[index];
}
const bool isOutline = 0u != style.outline;
// Whether the current glyph is a color one.
- const bool isColorGlyph = mFontClient.IsColorGlyph( glyph.fontId, glyph.index );
+ const bool isColorGlyph = mFontClient.IsColorGlyph(glyph.fontId, glyph.index);
- if( !isOutline || ( isOutline && !isColorGlyph) )
+ if(!isOutline || (isOutline && !isColorGlyph))
{
// Retrieve the emoji's bitmap.
TextAbstraction::FontClient::GlyphBufferData glyphBufferData;
- glyphBufferData.width = isColorGlyph ? glyph.width : 0; // Desired width and height.
+ glyphBufferData.width = isColorGlyph ? glyph.width : 0; // Desired width and height.
glyphBufferData.height = isColorGlyph ? glyph.height : 0;
- mFontClient.CreateBitmap( glyph.fontId,
- glyph.index,
- glyph.isItalicRequired,
- glyph.isBoldRequired,
- glyphBufferData,
- style.outline );
+ mFontClient.CreateBitmap(glyph.fontId,
+ glyph.index,
+ glyph.isItalicRequired,
+ glyph.isBoldRequired,
+ glyphBufferData,
+ style.outline);
// Create the pixel data.
- bitmap = PixelData::New( glyphBufferData.buffer,
- glyphBufferData.width * glyphBufferData.height * GetBytesPerPixel( glyphBufferData.format ),
- glyphBufferData.width,
- glyphBufferData.height,
- glyphBufferData.format,
- PixelData::DELETE_ARRAY );
-
- if( bitmap )
+ bitmap = PixelData::New(glyphBufferData.buffer,
+ glyphBufferData.width * glyphBufferData.height * GetBytesPerPixel(glyphBufferData.format),
+ glyphBufferData.width,
+ glyphBufferData.height,
+ glyphBufferData.format,
+ PixelData::DELETE_ARRAY);
+
+ if(bitmap)
{
// Ensure that the next image will fit into the current block size
- if( bitmap.GetWidth() > blockSize.mNeededBlockWidth )
+ if(bitmap.GetWidth() > blockSize.mNeededBlockWidth)
{
blockSize.mNeededBlockWidth = bitmap.GetWidth();
}
- if( bitmap.GetHeight() > blockSize.mNeededBlockHeight )
+ if(bitmap.GetHeight() > blockSize.mNeededBlockHeight)
{
blockSize.mNeededBlockHeight = bitmap.GetHeight();
}
// If CheckAtlas in AtlasManager::Add can't fit the bitmap in the current atlas it will create a new atlas
// Setting the block size and size of new atlas does not mean a new one will be created. An existing atlas may still surffice.
- mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
- DEFAULT_ATLAS_HEIGHT,
- blockSize.mNeededBlockWidth,
- blockSize.mNeededBlockHeight );
+ mGlyphManager.SetNewAtlasSize(DEFAULT_ATLAS_WIDTH,
+ DEFAULT_ATLAS_HEIGHT,
+ blockSize.mNeededBlockWidth,
+ blockSize.mNeededBlockHeight);
// Locate a new slot for our glyph
- mGlyphManager.Add( glyph, style, bitmap, slot ); // slot will be 0 is glyph not added
+ mGlyphManager.Add(glyph, style, bitmap, slot); // slot will be 0 is glyph not added
}
}
}
else
{
// We have 2+ copies of the same glyph
- mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, style, 1 ); //increment
+ mGlyphManager.AdjustReferenceCount(glyph.fontId, glyph.index, style, 1); //increment
}
}
- void GenerateMesh( const GlyphInfo& glyph,
- const Vector2& position,
- const Vector4& color,
- uint16_t outline,
- AtlasManager::AtlasSlot& slot,
- bool underlineGlyph,
- float currentUnderlinePosition,
- float currentUnderlineThickness,
- std::vector<MeshRecord>& meshContainer,
- Vector<TextCacheEntry>& newTextCache,
- Vector<Extent>& extents )
+ void GenerateMesh(const GlyphInfo& glyph,
+ const Vector2& position,
+ const Vector4& color,
+ uint16_t outline,
+ AtlasManager::AtlasSlot& slot,
+ bool underlineGlyph,
+ float currentUnderlinePosition,
+ float currentUnderlineThickness,
+ std::vector<MeshRecord>& meshContainer,
+ Vector<TextCacheEntry>& newTextCache,
+ Vector<Extent>& extents)
{
// Generate mesh data for this quad, plugging in our supplied position
AtlasManager::Mesh2D newMesh;
- mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh );
+ mGlyphManager.GenerateMeshData(slot.mImageId, position, newMesh);
TextCacheEntry textCacheEntry;
- textCacheEntry.mFontId = glyph.fontId;
- textCacheEntry.mImageId = slot.mImageId;
- textCacheEntry.mIndex = glyph.index;
+ textCacheEntry.mFontId = glyph.fontId;
+ textCacheEntry.mImageId = slot.mImageId;
+ textCacheEntry.mIndex = glyph.index;
textCacheEntry.mOutlineWidth = outline;
- textCacheEntry.isItalic = glyph.isItalicRequired;
- textCacheEntry.isBold = glyph.isBoldRequired;
+ textCacheEntry.isItalic = glyph.isItalicRequired;
+ textCacheEntry.isBold = glyph.isBoldRequired;
- newTextCache.PushBack( textCacheEntry );
+ newTextCache.PushBack(textCacheEntry);
AtlasManager::Vertex2D* verticesBuffer = newMesh.mVertices.Begin();
- for( unsigned int index = 0u, size = newMesh.mVertices.Count();
- index < size;
- ++index )
+ for(unsigned int index = 0u, size = newMesh.mVertices.Count();
+ index < size;
+ ++index)
{
- AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
+ AtlasManager::Vertex2D& vertex = *(verticesBuffer + index);
// Set the color of the vertex.
vertex.mColor = color;
}
// Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
- StitchTextMesh( meshContainer,
- newMesh,
- extents,
- position.y + glyph.yBearing,
- underlineGlyph,
- currentUnderlinePosition,
- currentUnderlineThickness,
- slot );
+ StitchTextMesh(meshContainer,
+ newMesh,
+ extents,
+ position.y + glyph.yBearing,
+ underlineGlyph,
+ currentUnderlinePosition,
+ currentUnderlineThickness,
+ slot);
}
- void CreateActors( const std::vector<MeshRecord>& meshContainer,
- const Size& textSize,
- const Vector4& color,
- const Vector4& shadowColor,
- const Vector2& shadowOffset,
- Actor textControl,
- Property::Index animatablePropertyIndex,
- bool drawShadow )
+ void CreateActors(const std::vector<MeshRecord>& meshContainer,
+ const Size& textSize,
+ const Vector4& color,
+ const Vector4& shadowColor,
+ const Vector2& shadowOffset,
+ Actor textControl,
+ Property::Index animatablePropertyIndex,
+ bool drawShadow)
{
- if( !mActor )
+ if(!mActor)
{
// Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues.
mActor = Actor::New();
- mActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- mActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- mActor.SetProperty( Actor::Property::SIZE, textSize );
- mActor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR );
+ mActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ mActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ mActor.SetProperty(Actor::Property::SIZE, textSize);
+ mActor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR);
}
- for( std::vector< MeshRecord >::const_iterator it = meshContainer.begin(),
- endIt = meshContainer.end();
- it != endIt; ++it )
+ for(std::vector<MeshRecord>::const_iterator it = meshContainer.begin(),
+ endIt = meshContainer.end();
+ it != endIt;
+ ++it)
{
const MeshRecord& meshRecord = *it;
- Actor actor = CreateMeshActor( textControl, animatablePropertyIndex, color, meshRecord, textSize, STYLE_NORMAL );
+ Actor actor = CreateMeshActor(textControl, animatablePropertyIndex, color, meshRecord, textSize, STYLE_NORMAL);
// Whether the actor has renderers.
const bool hasRenderer = actor.GetRendererCount() > 0u;
// Create an effect if necessary
- if( hasRenderer &&
- drawShadow )
+ if(hasRenderer &&
+ drawShadow)
{
// Change the color of the vertices.
- for( Vector<AtlasManager::Vertex2D>::Iterator vIt = meshRecord.mMesh.mVertices.Begin(),
- vEndIt = meshRecord.mMesh.mVertices.End();
- vIt != vEndIt;
- ++vIt )
+ for(Vector<AtlasManager::Vertex2D>::Iterator vIt = meshRecord.mMesh.mVertices.Begin(),
+ vEndIt = meshRecord.mMesh.mVertices.End();
+ vIt != vEndIt;
+ ++vIt)
{
AtlasManager::Vertex2D& vertex = *vIt;
vertex.mColor = shadowColor;
}
- Actor shadowActor = CreateMeshActor(textControl, animatablePropertyIndex, color, meshRecord, textSize, STYLE_DROP_SHADOW );
+ Actor shadowActor = CreateMeshActor(textControl, animatablePropertyIndex, color, meshRecord, textSize, STYLE_DROP_SHADOW);
#if defined(DEBUG_ENABLED)
- shadowActor.SetProperty( Dali::Actor::Property::NAME, "Text Shadow renderable actor" );
+ shadowActor.SetProperty(Dali::Actor::Property::NAME, "Text Shadow renderable actor");
#endif
// Offset shadow in x and y
- shadowActor.RegisterProperty("uOffset", shadowOffset );
- Dali::Renderer renderer( shadowActor.GetRendererAt( 0 ) );
- int depthIndex = renderer.GetProperty<int>(Dali::Renderer::Property::DEPTH_INDEX);
- renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1 );
- mActor.Add( shadowActor );
+ shadowActor.RegisterProperty("uOffset", shadowOffset);
+ Dali::Renderer renderer(shadowActor.GetRendererAt(0));
+ int depthIndex = renderer.GetProperty<int>(Dali::Renderer::Property::DEPTH_INDEX);
+ renderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1);
+ mActor.Add(shadowActor);
}
- if( hasRenderer )
+ if(hasRenderer)
{
- mActor.Add( actor );
+ mActor.Add(actor);
}
}
}
- void AddGlyphs( Text::ViewInterface& view,
- Actor textControl,
- Property::Index animatablePropertyIndex,
- const Vector<Vector2>& positions,
- const Vector<GlyphInfo>& glyphs,
- const Vector4& defaultColor,
- const Vector4* const colorsBuffer,
- const ColorIndex* const colorIndicesBuffer,
- int depth,
- float minLineOffset )
+ void AddGlyphs(Text::ViewInterface& view,
+ Actor textControl,
+ Property::Index animatablePropertyIndex,
+ const Vector<Vector2>& positions,
+ const Vector<GlyphInfo>& glyphs,
+ const Vector4& defaultColor,
+ const Vector4* const colorsBuffer,
+ const ColorIndex* const colorIndicesBuffer,
+ int depth,
+ float minLineOffset)
{
AtlasManager::AtlasSlot slot;
slot.mImageId = 0u;
slotOutline.mImageId = 0u;
slotOutline.mAtlasId = 0u;
- std::vector< MeshRecord > meshContainer;
- std::vector< MeshRecord > meshContainerOutline;
- Vector< Extent > extents;
+ std::vector<MeshRecord> meshContainer;
+ std::vector<MeshRecord> meshContainerOutline;
+ Vector<Extent> extents;
mDepth = depth;
- const Vector2& textSize( view.GetLayoutSize() );
- const Vector2 halfTextSize( textSize * 0.5f );
- const Vector2& shadowOffset( view.GetShadowOffset() );
- const Vector4& shadowColor( view.GetShadowColor() );
- const bool underlineEnabled = view.IsUnderlineEnabled();
- const Vector4& underlineColor( view.GetUnderlineColor() );
- const float underlineHeight = view.GetUnderlineHeight();
- const uint16_t outlineWidth = view.GetOutlineWidth();
- const Vector4& outlineColor( view.GetOutlineColor() );
- const bool isOutline = 0u != outlineWidth;
+ const Vector2& textSize(view.GetLayoutSize());
+ const Vector2 halfTextSize(textSize * 0.5f);
+ const Vector2& shadowOffset(view.GetShadowOffset());
+ const Vector4& shadowColor(view.GetShadowColor());
+ const bool underlineEnabled = view.IsUnderlineEnabled();
+ const Vector4& underlineColor(view.GetUnderlineColor());
+ const float underlineHeight = view.GetUnderlineHeight();
+ const uint16_t outlineWidth = view.GetOutlineWidth();
+ const Vector4& outlineColor(view.GetOutlineColor());
+ const bool isOutline = 0u != outlineWidth;
- const bool useDefaultColor = ( NULL == colorsBuffer );
+ const bool useDefaultColor = (NULL == colorsBuffer);
// Get the underline runs.
- const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns();
+ const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns();
Vector<GlyphRun> underlineRuns;
- underlineRuns.Resize( numberOfUnderlineRuns );
- view.GetUnderlineRuns( underlineRuns.Begin(),
- 0u,
- numberOfUnderlineRuns );
+ underlineRuns.Resize(numberOfUnderlineRuns);
+ view.GetUnderlineRuns(underlineRuns.Begin(),
+ 0u,
+ numberOfUnderlineRuns);
bool thereAreUnderlinedGlyphs = false;
- float currentUnderlinePosition = ZERO;
- float currentUnderlineThickness = underlineHeight;
- FontId lastFontId = 0;
- FontId lastUnderlinedFontId = 0;
- Style style = STYLE_NORMAL;
+ float currentUnderlinePosition = ZERO;
+ float currentUnderlineThickness = underlineHeight;
+ FontId lastFontId = 0;
+ FontId lastUnderlinedFontId = 0;
+ Style style = STYLE_NORMAL;
- if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
+ if(fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1)
{
style = STYLE_DROP_SHADOW;
}
- CalculateBlocksSize( glyphs );
+ CalculateBlocksSize(glyphs);
// Avoid emptying mTextCache (& removing references) until after incremented references for the new text
- Vector< TextCacheEntry > newTextCache;
- const GlyphInfo* const glyphsBuffer = glyphs.Begin();
- const Vector2* const positionsBuffer = positions.Begin();
- const Vector2 lineOffsetPosition( minLineOffset, 0.f );
+ Vector<TextCacheEntry> newTextCache;
+ const GlyphInfo* const glyphsBuffer = glyphs.Begin();
+ const Vector2* const positionsBuffer = positions.Begin();
+ const Vector2 lineOffsetPosition(minLineOffset, 0.f);
- for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
+ for(uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i)
{
- const GlyphInfo& glyph = *( glyphsBuffer + i );
- const bool isGlyphUnderlined = underlineEnabled || IsGlyphUnderlined( i, underlineRuns );
- thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || isGlyphUnderlined;
+ const GlyphInfo& glyph = *(glyphsBuffer + i);
+ const bool isGlyphUnderlined = underlineEnabled || IsGlyphUnderlined(i, underlineRuns);
+ thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || isGlyphUnderlined;
// No operation for white space
- if( glyph.width && glyph.height )
+ if(glyph.width && glyph.height)
{
// Are we still using the same fontId as previous
- if( isGlyphUnderlined && ( glyph.fontId != lastUnderlinedFontId ) )
+ if(isGlyphUnderlined && (glyph.fontId != lastUnderlinedFontId))
{
// We need to fetch fresh font underline metrics
FontMetrics fontMetrics;
- mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
- currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
- const float descender = ceil( fabsf( fontMetrics.descender ) );
+ mFontClient.GetFontMetrics(glyph.fontId, fontMetrics);
+ currentUnderlinePosition = ceil(fabsf(fontMetrics.underlinePosition));
+ const float descender = ceil(fabsf(fontMetrics.descender));
- if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
+ if(fabsf(underlineHeight) < Math::MACHINE_EPSILON_1000)
{
currentUnderlineThickness = fontMetrics.underlineThickness;
// Ensure underline will be at least a pixel high
- if ( currentUnderlineThickness < ONE )
+ if(currentUnderlineThickness < ONE)
{
currentUnderlineThickness = ONE;
}
else
{
- currentUnderlineThickness = ceil( currentUnderlineThickness );
+ currentUnderlineThickness = ceil(currentUnderlineThickness);
}
}
// Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
- if( currentUnderlinePosition > descender )
+ if(currentUnderlinePosition > descender)
{
currentUnderlinePosition = descender;
}
- if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
+ if(fabsf(currentUnderlinePosition) < Math::MACHINE_EPSILON_1000)
{
// Move offset down by one ( EFL behavior )
currentUnderlinePosition = ONE;
AtlasGlyphManager::GlyphStyle style;
style.isItalic = glyph.isItalicRequired;
- style.isBold = glyph.isBoldRequired;
+ style.isBold = glyph.isBoldRequired;
// Retrieves and caches the glyph's bitmap.
- CacheGlyph( glyph, lastFontId, style, slot );
+ CacheGlyph(glyph, lastFontId, style, slot);
// Retrieves and caches the outline glyph's bitmap.
- if( isOutline )
+ if(isOutline)
{
style.outline = outlineWidth;
- CacheGlyph( glyph, lastFontId, style, slotOutline );
+ CacheGlyph(glyph, lastFontId, style, slotOutline);
}
// Move the origin (0,0) of the mesh to the center of the actor
- const Vector2& temp = *( positionsBuffer + i );
- const Vector2 position = Vector2( roundf( temp.x ), temp.y ) - halfTextSize - lineOffsetPosition; // roundf() avoids pixel alignment issues.
+ const Vector2& temp = *(positionsBuffer + i);
+ const Vector2 position = Vector2(roundf(temp.x), temp.y) - halfTextSize - lineOffsetPosition; // roundf() avoids pixel alignment issues.
- if ( 0u != slot.mImageId ) // invalid slot id, glyph has failed to be added to atlas
+ if(0u != slot.mImageId) // invalid slot id, glyph has failed to be added to atlas
{
Vector2 positionPlusOutlineOffset = position;
- if( isOutline )
+ if(isOutline)
{
// Add an offset to the text.
- const float outlineWidthOffset = static_cast<float>( outlineWidth );
- positionPlusOutlineOffset += Vector2( outlineWidthOffset, outlineWidthOffset );
+ const float outlineWidthOffset = static_cast<float>(outlineWidth);
+ positionPlusOutlineOffset += Vector2(outlineWidthOffset, outlineWidthOffset);
}
// Get the color of the character.
- const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndicesBuffer + i );
- const Vector4& color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + colorIndex - 1u );
-
- GenerateMesh( glyph,
- positionPlusOutlineOffset,
- color,
- NO_OUTLINE,
- slot,
- isGlyphUnderlined,
- currentUnderlinePosition,
- currentUnderlineThickness,
- meshContainer,
- newTextCache,
- extents);
+ const ColorIndex colorIndex = useDefaultColor ? 0u : *(colorIndicesBuffer + i);
+ const Vector4& color = (useDefaultColor || (0u == colorIndex)) ? defaultColor : *(colorsBuffer + colorIndex - 1u);
+
+ GenerateMesh(glyph,
+ positionPlusOutlineOffset,
+ color,
+ NO_OUTLINE,
+ slot,
+ isGlyphUnderlined,
+ currentUnderlinePosition,
+ currentUnderlineThickness,
+ meshContainer,
+ newTextCache,
+ extents);
lastFontId = glyph.fontId; // Prevents searching for existing blocksizes when string of the same fontId.
}
- if( isOutline && ( 0u != slotOutline.mImageId ) ) // invalid slot id, glyph has failed to be added to atlas
+ if(isOutline && (0u != slotOutline.mImageId)) // invalid slot id, glyph has failed to be added to atlas
{
- GenerateMesh( glyph,
- position,
- outlineColor,
- outlineWidth,
- slotOutline,
- false,
- currentUnderlinePosition,
- currentUnderlineThickness,
- meshContainerOutline,
- newTextCache,
- extents);
+ GenerateMesh(glyph,
+ position,
+ outlineColor,
+ outlineWidth,
+ slotOutline,
+ false,
+ currentUnderlinePosition,
+ currentUnderlineThickness,
+ meshContainerOutline,
+ newTextCache,
+ extents);
}
}
} // glyphs
// Now remove references for the old text
RemoveText();
- mTextCache.Swap( newTextCache );
+ mTextCache.Swap(newTextCache);
- if( thereAreUnderlinedGlyphs )
+ if(thereAreUnderlinedGlyphs)
{
// Check to see if any of the text needs an underline
- GenerateUnderlines( meshContainer, extents, underlineColor );
+ GenerateUnderlines(meshContainer, extents, underlineColor);
}
// For each MeshData object, create a mesh actor and add to the renderable actor
bool isShadowDrawn = false;
- if( !meshContainerOutline.empty() )
+ if(!meshContainerOutline.empty())
{
const bool drawShadow = STYLE_DROP_SHADOW == style;
- CreateActors( meshContainerOutline,
- textSize,
- outlineColor,
- shadowColor,
- shadowOffset,
- textControl,
- animatablePropertyIndex,
- drawShadow );
+ CreateActors(meshContainerOutline,
+ textSize,
+ outlineColor,
+ shadowColor,
+ shadowOffset,
+ textControl,
+ animatablePropertyIndex,
+ drawShadow);
isShadowDrawn = drawShadow;
}
// For each MeshData object, create a mesh actor and add to the renderable actor
- if( !meshContainer.empty() )
+ if(!meshContainer.empty())
{
- const bool drawShadow = !isShadowDrawn && ( STYLE_DROP_SHADOW == style );
- CreateActors( meshContainer,
- textSize,
- defaultColor,
- shadowColor,
- shadowOffset,
- textControl,
- animatablePropertyIndex,
- drawShadow );
+ const bool drawShadow = !isShadowDrawn && (STYLE_DROP_SHADOW == style);
+ CreateActors(meshContainer,
+ textSize,
+ defaultColor,
+ shadowColor,
+ shadowOffset,
+ textControl,
+ animatablePropertyIndex,
+ drawShadow);
}
#if defined(DEBUG_ENABLED)
Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
- DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
- metrics.mGlyphCount,
- metrics.mAtlasMetrics.mAtlasCount,
- metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n", metrics.mGlyphCount, metrics.mAtlasMetrics.mAtlasCount, metrics.mAtlasMetrics.mTextureMemoryUsed / 1024);
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str());
- for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
+ for(uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
- i + 1, i > 8 ? "" : " ",
- metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA",
- metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
- metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
- metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
- metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
- metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
- metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, " Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n", i + 1, i > 8 ? "" : " ", metrics.mAtlasMetrics.mAtlasMetrics[i].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA", metrics.mAtlasMetrics.mAtlasMetrics[i].mSize.mWidth, metrics.mAtlasMetrics.mAtlasMetrics[i].mSize.mHeight, metrics.mAtlasMetrics.mAtlasMetrics[i].mSize.mBlockWidth, metrics.mAtlasMetrics.mAtlasMetrics[i].mSize.mBlockHeight, metrics.mAtlasMetrics.mAtlasMetrics[i].mBlocksUsed, metrics.mAtlasMetrics.mAtlasMetrics[i].mTotalBlocks);
}
#endif
}
void RemoveText()
{
- for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
+ for(Vector<TextCacheEntry>::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter)
{
AtlasGlyphManager::GlyphStyle style;
- style.outline = oldTextIter->mOutlineWidth;
+ style.outline = oldTextIter->mOutlineWidth;
style.isItalic = oldTextIter->isItalic;
- style.isBold = oldTextIter->isBold;
- mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, style, -1/*decrement*/ );
+ style.isBold = oldTextIter->isBold;
+ mGlyphManager.AdjustReferenceCount(oldTextIter->mFontId, oldTextIter->mIndex, style, -1 /*decrement*/);
}
- mTextCache.Resize( 0 );
+ mTextCache.Resize(0);
}
- Actor CreateMeshActor( Actor textControl, Property::Index animatablePropertyIndex, const Vector4& defaultColor, const MeshRecord& meshRecord,
- const Vector2& actorSize, Style style )
+ Actor CreateMeshActor(Actor textControl, Property::Index animatablePropertyIndex, const Vector4& defaultColor, const MeshRecord& meshRecord, const Vector2& actorSize, Style style)
{
- VertexBuffer quadVertices = VertexBuffer::New( mQuadVertexFormat );
- quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ), meshRecord.mMesh.mVertices.Size() );
+ VertexBuffer quadVertices = VertexBuffer::New(mQuadVertexFormat);
+ quadVertices.SetData(const_cast<AtlasManager::Vertex2D*>(&meshRecord.mMesh.mVertices[0]), meshRecord.mMesh.mVertices.Size());
Geometry quadGeometry = Geometry::New();
- quadGeometry.AddVertexBuffer( quadVertices );
- quadGeometry.SetIndexBuffer( &meshRecord.mMesh.mIndices[0], meshRecord.mMesh.mIndices.Size() );
+ quadGeometry.AddVertexBuffer(quadVertices);
+ quadGeometry.SetIndexBuffer(&meshRecord.mMesh.mIndices[0], meshRecord.mMesh.mIndices.Size());
- TextureSet textureSet( mGlyphManager.GetTextures( meshRecord.mAtlasId ) );
+ TextureSet textureSet(mGlyphManager.GetTextures(meshRecord.mAtlasId));
// Choose the shader to use.
- const bool isColorShader = ( STYLE_DROP_SHADOW != style ) && ( Pixel::BGRA8888 == mGlyphManager.GetPixelFormat( meshRecord.mAtlasId ) );
- Shader shader;
- if( isColorShader )
+ const bool isColorShader = (STYLE_DROP_SHADOW != style) && (Pixel::BGRA8888 == mGlyphManager.GetPixelFormat(meshRecord.mAtlasId));
+ Shader shader;
+ if(isColorShader)
{
// The glyph is an emoji and is not a shadow.
- if( !mShaderRgba )
+ if(!mShaderRgba)
{
- mShaderRgba = Shader::New( SHADER_TEXT_ATLAS_SHADER_VERT, SHADER_TEXT_ATLAS_RGBA_SHADER_FRAG );
+ mShaderRgba = Shader::New(SHADER_TEXT_ATLAS_SHADER_VERT, SHADER_TEXT_ATLAS_RGBA_SHADER_FRAG);
}
shader = mShaderRgba;
}
else
{
// The glyph is text or a shadow.
- if( !mShaderL8 )
+ if(!mShaderL8)
{
- mShaderL8 = Shader::New( SHADER_TEXT_ATLAS_SHADER_VERT, SHADER_TEXT_ATLAS_L8_SHADER_FRAG );
+ mShaderL8 = Shader::New(SHADER_TEXT_ATLAS_SHADER_VERT, SHADER_TEXT_ATLAS_L8_SHADER_FRAG);
}
shader = mShaderL8;
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "defaultColor[%f, %f, %f, %f ]\n", defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "defaultColor[%f, %f, %f, %f ]\n", defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a);
- Dali::Property::Index shaderTextColorIndex = shader.RegisterProperty( "textColorAnimatable", defaultColor );
+ Dali::Property::Index shaderTextColorIndex = shader.RegisterProperty("textColorAnimatable", defaultColor);
- if ( animatablePropertyIndex != Property::INVALID_INDEX )
+ if(animatablePropertyIndex != Property::INVALID_INDEX)
{
// create constraint for the animatable text's color Property with textColorAnimatable in the shader.
- if( shaderTextColorIndex )
+ if(shaderTextColorIndex)
{
- Constraint constraint = Constraint::New<Vector4>( shader, shaderTextColorIndex, EqualToConstraint() );
- constraint.AddSource( Source( textControl, animatablePropertyIndex ) );
+ Constraint constraint = Constraint::New<Vector4>(shader, shaderTextColorIndex, EqualToConstraint());
+ constraint.AddSource(Source(textControl, animatablePropertyIndex));
constraint.Apply();
}
}
else
{
// If not animating the text colour then set to 1's so shader uses the current vertex color
- shader.RegisterProperty( "textColorAnimatable", Vector4(1.0, 1.0, 1.0, 1.0 ) );
+ shader.RegisterProperty("textColorAnimatable", Vector4(1.0, 1.0, 1.0, 1.0));
}
- Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, shader );
- renderer.SetTextures( textureSet );
- renderer.SetProperty( Dali::Renderer::Property::BLEND_MODE, BlendMode::ON );
- renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth );
+ Dali::Renderer renderer = Dali::Renderer::New(quadGeometry, shader);
+ renderer.SetTextures(textureSet);
+ renderer.SetProperty(Dali::Renderer::Property::BLEND_MODE, BlendMode::ON);
+ renderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth);
Actor actor = Actor::New();
#if defined(DEBUG_ENABLED)
- actor.SetProperty( Dali::Actor::Property::NAME, "Text renderable actor" );
+ actor.SetProperty(Dali::Actor::Property::NAME, "Text renderable actor");
#endif
- actor.AddRenderer( renderer );
+ actor.AddRenderer(renderer);
// Keep all of the origins aligned
- actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- actor.SetProperty( Actor::Property::SIZE, actorSize );
- actor.RegisterProperty("uOffset", Vector2::ZERO );
- actor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR );
+ actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ actor.SetProperty(Actor::Property::SIZE, actorSize);
+ actor.RegisterProperty("uOffset", Vector2::ZERO);
+ actor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR);
return actor;
}
- void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
- AtlasManager::Mesh2D& newMesh,
- Vector< Extent >& extents,
- float baseLine,
- bool underlineGlyph,
- float underlinePosition,
- float underlineThickness,
- AtlasManager::AtlasSlot& slot )
+ void StitchTextMesh(std::vector<MeshRecord>& meshContainer,
+ AtlasManager::Mesh2D& newMesh,
+ Vector<Extent>& extents,
+ float baseLine,
+ bool underlineGlyph,
+ float underlinePosition,
+ float underlineThickness,
+ AtlasManager::AtlasSlot& slot)
{
- if ( slot.mImageId )
+ if(slot.mImageId)
{
- float left = newMesh.mVertices[ 0 ].mPosition.x;
- float right = newMesh.mVertices[ 1 ].mPosition.x;
+ float left = newMesh.mVertices[0].mPosition.x;
+ float right = newMesh.mVertices[1].mPosition.x;
// Check to see if there's a mesh data object that references the same atlas ?
uint32_t index = 0;
- for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
- mEndIt = meshContainer.end();
- mIt != mEndIt;
- ++mIt, ++index )
+ for(std::vector<MeshRecord>::iterator mIt = meshContainer.begin(),
+ mEndIt = meshContainer.end();
+ mIt != mEndIt;
+ ++mIt, ++index)
{
- if( slot.mAtlasId == mIt->mAtlasId )
+ if(slot.mAtlasId == mIt->mAtlasId)
{
// Append the mesh to the existing mesh and adjust any extents
- Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
+ Toolkit::Internal::AtlasMeshFactory::AppendMesh(mIt->mMesh, newMesh);
- if( underlineGlyph )
+ if(underlineGlyph)
{
- AdjustExtents( extents,
- meshContainer,
- index,
- left,
- right,
- baseLine,
- underlinePosition,
- underlineThickness );
+ AdjustExtents(extents,
+ meshContainer,
+ index,
+ left,
+ right,
+ baseLine,
+ underlinePosition,
+ underlineThickness);
}
return;
// No mesh data object currently exists that references this atlas, so create a new one
MeshRecord meshRecord;
meshRecord.mAtlasId = slot.mAtlasId;
- meshRecord.mMesh = newMesh;
- meshContainer.push_back( meshRecord );
+ meshRecord.mMesh = newMesh;
+ meshContainer.push_back(meshRecord);
- if( underlineGlyph )
+ if(underlineGlyph)
{
// Adjust extents for this new meshrecord
- AdjustExtents( extents,
- meshContainer,
- meshContainer.size() - 1u,
- left,
- right,
- baseLine,
- underlinePosition,
- underlineThickness );
+ AdjustExtents(extents,
+ meshContainer,
+ meshContainer.size() - 1u,
+ left,
+ right,
+ baseLine,
+ underlinePosition,
+ underlineThickness);
}
}
}
- void AdjustExtents( Vector< Extent >& extents,
- std::vector< MeshRecord>& meshRecords,
- uint32_t index,
- float left,
- float right,
- float baseLine,
- float underlinePosition,
- float underlineThickness )
+ void AdjustExtents(Vector<Extent>& extents,
+ std::vector<MeshRecord>& meshRecords,
+ uint32_t index,
+ float left,
+ float right,
+ float baseLine,
+ float underlinePosition,
+ float underlineThickness)
{
bool foundExtent = false;
- for ( Vector< Extent >::Iterator eIt = extents.Begin(),
- eEndIt = extents.End();
- eIt != eEndIt;
- ++eIt )
+ for(Vector<Extent>::Iterator eIt = extents.Begin(),
+ eEndIt = extents.End();
+ eIt != eEndIt;
+ ++eIt)
{
- if ( Equals( baseLine, eIt->mBaseLine ) )
+ if(Equals(baseLine, eIt->mBaseLine))
{
foundExtent = true;
- if ( left < eIt->mLeft )
+ if(left < eIt->mLeft)
{
eIt->mLeft = left;
}
- if ( right > eIt->mRight )
+ if(right > eIt->mRight)
{
eIt->mRight = right;
}
- if ( underlinePosition > eIt->mUnderlinePosition )
+ if(underlinePosition > eIt->mUnderlinePosition)
{
eIt->mUnderlinePosition = underlinePosition;
}
- if ( underlineThickness > eIt->mUnderlineThickness )
+ if(underlineThickness > eIt->mUnderlineThickness)
{
eIt->mUnderlineThickness = underlineThickness;
}
}
}
- if ( !foundExtent )
+ if(!foundExtent)
{
Extent extent;
- extent.mLeft = left;
- extent.mRight = right;
- extent.mBaseLine = baseLine;
- extent.mUnderlinePosition = underlinePosition;
+ extent.mLeft = left;
+ extent.mRight = right;
+ extent.mBaseLine = baseLine;
+ extent.mUnderlinePosition = underlinePosition;
extent.mUnderlineThickness = underlineThickness;
- extent.mMeshRecordIndex = index;
- extents.PushBack( extent );
+ extent.mMeshRecordIndex = index;
+ extents.PushBack(extent);
}
}
- void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
+ void CalculateBlocksSize(const Vector<GlyphInfo>& glyphs)
{
- for( Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
- glyphEndIt = glyphs.End();
- glyphIt != glyphEndIt;
- ++glyphIt )
+ for(Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
+ glyphEndIt = glyphs.End();
+ glyphIt != glyphEndIt;
+ ++glyphIt)
{
- const FontId fontId = (*glyphIt).fontId;
- bool foundFont = false;
+ const FontId fontId = (*glyphIt).fontId;
+ bool foundFont = false;
- for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(),
- blockEndIt = mBlockSizes.end();
- blockIt != blockEndIt;
- ++blockIt )
+ for(std::vector<MaxBlockSize>::const_iterator blockIt = mBlockSizes.begin(),
+ blockEndIt = mBlockSizes.end();
+ blockIt != blockEndIt;
+ ++blockIt)
{
- if( (*blockIt).mFontId == fontId ) // Different size fonts will have a different fontId
+ if((*blockIt).mFontId == fontId) // Different size fonts will have a different fontId
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::CalculateBlocksSize match found fontID(%u) glyphIndex(%u)\n", fontId, (*glyphIt).index );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::AtlasRenderer::CalculateBlocksSize match found fontID(%u) glyphIndex(%u)\n", fontId, (*glyphIt).index);
foundFont = true;
break;
}
}
- if ( !foundFont )
+ if(!foundFont)
{
FontMetrics fontMetrics;
- mFontClient.GetFontMetrics( fontId, fontMetrics );
+ mFontClient.GetFontMetrics(fontId, fontMetrics);
MaxBlockSize maxBlockSize;
- maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
+ maxBlockSize.mNeededBlockWidth = static_cast<uint32_t>(fontMetrics.height);
maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth;
- maxBlockSize.mFontId = fontId;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::CalculateBlocksSize New font with no matched blocksize, setting blocksize[%u]\n", maxBlockSize.mNeededBlockWidth );
- mBlockSizes.push_back( maxBlockSize );
+ maxBlockSize.mFontId = fontId;
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::AtlasRenderer::CalculateBlocksSize New font with no matched blocksize, setting blocksize[%u]\n", maxBlockSize.mNeededBlockWidth);
+ mBlockSizes.push_back(maxBlockSize);
}
}
}
- void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
- Vector< Extent >& extents,
- const Vector4& underlineColor )
+ void GenerateUnderlines(std::vector<MeshRecord>& meshRecords,
+ Vector<Extent>& extents,
+ const Vector4& underlineColor)
{
AtlasManager::Mesh2D newMesh;
- unsigned short faceIndex = 0;
- for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
- eEndIt = extents.End();
- eIt != eEndIt;
- ++eIt )
+ unsigned short faceIndex = 0;
+ for(Vector<Extent>::ConstIterator eIt = extents.Begin(),
+ eEndIt = extents.End();
+ eIt != eEndIt;
+ ++eIt)
{
AtlasManager::Vertex2D vert;
- uint32_t index = eIt->mMeshRecordIndex;
- Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
+ uint32_t index = eIt->mMeshRecordIndex;
+ Vector2 uv = mGlyphManager.GetAtlasSize(meshRecords[index].mAtlasId);
// Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
- float u = HALF / uv.x;
- float v = HALF / uv.y;
+ float u = HALF / uv.x;
+ float v = HALF / uv.y;
float thickness = eIt->mUnderlineThickness;
- float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
- float tlx = eIt->mLeft;
- float brx = eIt->mRight;
+ float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - (thickness * HALF);
+ float tlx = eIt->mLeft;
+ float brx = eIt->mRight;
- vert.mPosition.x = tlx;
- vert.mPosition.y = baseLine;
+ vert.mPosition.x = tlx;
+ vert.mPosition.y = baseLine;
vert.mTexCoords.x = ZERO;
vert.mTexCoords.y = ZERO;
- vert.mColor = underlineColor;
- newMesh.mVertices.PushBack( vert );
+ vert.mColor = underlineColor;
+ newMesh.mVertices.PushBack(vert);
- vert.mPosition.x = brx;
- vert.mPosition.y = baseLine;
+ vert.mPosition.x = brx;
+ vert.mPosition.y = baseLine;
vert.mTexCoords.x = u;
- vert.mColor = underlineColor;
- newMesh.mVertices.PushBack( vert );
+ vert.mColor = underlineColor;
+ newMesh.mVertices.PushBack(vert);
- vert.mPosition.x = tlx;
- vert.mPosition.y = baseLine + thickness;
+ vert.mPosition.x = tlx;
+ vert.mPosition.y = baseLine + thickness;
vert.mTexCoords.x = ZERO;
vert.mTexCoords.y = v;
- vert.mColor = underlineColor;
- newMesh.mVertices.PushBack( vert );
+ vert.mColor = underlineColor;
+ newMesh.mVertices.PushBack(vert);
- vert.mPosition.x = brx;
- vert.mPosition.y = baseLine + thickness;
+ vert.mPosition.x = brx;
+ vert.mPosition.y = baseLine + thickness;
vert.mTexCoords.x = u;
- vert.mColor = underlineColor;
- newMesh.mVertices.PushBack( vert );
+ vert.mColor = underlineColor;
+ newMesh.mVertices.PushBack(vert);
// Six indices in counter clockwise winding
- newMesh.mIndices.PushBack( faceIndex + 1u );
- newMesh.mIndices.PushBack( faceIndex );
- newMesh.mIndices.PushBack( faceIndex + 2u );
- newMesh.mIndices.PushBack( faceIndex + 2u );
- newMesh.mIndices.PushBack( faceIndex + 3u );
- newMesh.mIndices.PushBack( faceIndex + 1u );
+ newMesh.mIndices.PushBack(faceIndex + 1u);
+ newMesh.mIndices.PushBack(faceIndex);
+ newMesh.mIndices.PushBack(faceIndex + 2u);
+ newMesh.mIndices.PushBack(faceIndex + 2u);
+ newMesh.mIndices.PushBack(faceIndex + 3u);
+ newMesh.mIndices.PushBack(faceIndex + 1u);
faceIndex += 4;
- Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
+ Toolkit::Internal::AtlasMeshFactory::AppendMesh(meshRecords[index].mMesh, newMesh);
}
}
- Actor mActor; ///< The actor parent which renders the text
- AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
- TextAbstraction::FontClient mFontClient; ///< The font client used to supply glyph information
- Shader mShaderL8; ///< The shader for glyphs and emoji's shadows.
- Shader mShaderRgba; ///< The shader for emojis.
- std::vector< MaxBlockSize > mBlockSizes; ///< Maximum size needed to contain a glyph in a block within a new atlas
- Vector< TextCacheEntry > mTextCache; ///< Caches data from previous render
- Property::Map mQuadVertexFormat; ///< Describes the vertex format for text
- int mDepth; ///< DepthIndex passed by control when connect to stage
+ Actor mActor; ///< The actor parent which renders the text
+ AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
+ TextAbstraction::FontClient mFontClient; ///< The font client used to supply glyph information
+ Shader mShaderL8; ///< The shader for glyphs and emoji's shadows.
+ Shader mShaderRgba; ///< The shader for emojis.
+ std::vector<MaxBlockSize> mBlockSizes; ///< Maximum size needed to contain a glyph in a block within a new atlas
+ Vector<TextCacheEntry> mTextCache; ///< Caches data from previous render
+ Property::Map mQuadVertexFormat; ///< Describes the vertex format for text
+ int mDepth; ///< DepthIndex passed by control when connect to stage
};
Text::RendererPtr AtlasRenderer::New()
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n");
- return Text::RendererPtr( new AtlasRenderer() );
+ return Text::RendererPtr(new AtlasRenderer());
}
-Actor AtlasRenderer::Render( Text::ViewInterface& view,
- Actor textControl,
- Property::Index animatablePropertyIndex,
- float& alignmentOffset,
- int depth )
+Actor AtlasRenderer::Render(Text::ViewInterface& view,
+ Actor textControl,
+ Property::Index animatablePropertyIndex,
+ float& alignmentOffset,
+ int depth)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Text::AtlasRenderer::Render()\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Text::AtlasRenderer::Render()\n");
- UnparentAndReset( mImpl->mActor );
+ UnparentAndReset(mImpl->mActor);
Length numberOfGlyphs = view.GetNumberOfGlyphs();
- if( numberOfGlyphs > 0u )
+ if(numberOfGlyphs > 0u)
{
Vector<GlyphInfo> glyphs;
- glyphs.Resize( numberOfGlyphs );
+ glyphs.Resize(numberOfGlyphs);
Vector<Vector2> positions;
- positions.Resize( numberOfGlyphs );
+ positions.Resize(numberOfGlyphs);
- numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
- positions.Begin(),
- alignmentOffset,
- 0u,
- numberOfGlyphs );
+ numberOfGlyphs = view.GetGlyphs(glyphs.Begin(),
+ positions.Begin(),
+ alignmentOffset,
+ 0u,
+ numberOfGlyphs);
- glyphs.Resize( numberOfGlyphs );
- positions.Resize( numberOfGlyphs );
+ glyphs.Resize(numberOfGlyphs);
+ positions.Resize(numberOfGlyphs);
- const Vector4* const colorsBuffer = view.GetColors();
+ const Vector4* const colorsBuffer = view.GetColors();
const ColorIndex* const colorIndicesBuffer = view.GetColorIndices();
- const Vector4& defaultColor = view.GetTextColor();
-
- mImpl->AddGlyphs( view,
- textControl,
- animatablePropertyIndex,
- positions,
- glyphs,
- defaultColor,
- colorsBuffer,
- colorIndicesBuffer,
- depth,
- alignmentOffset );
+ const Vector4& defaultColor = view.GetTextColor();
+
+ mImpl->AddGlyphs(view,
+ textControl,
+ animatablePropertyIndex,
+ positions,
+ glyphs,
+ defaultColor,
+ colorsBuffer,
+ colorIndicesBuffer,
+ depth,
+ alignmentOffset);
/* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
/* This renderable actor is used to position the text, other "decorations" can rely on there always being an Actor regardless of it is whitespace or regular text. */
- if ( !mImpl->mActor )
+ if(!mImpl->mActor)
{
mImpl->mActor = Actor::New();
}
AtlasRenderer::AtlasRenderer()
{
mImpl = new Impl();
-
}
AtlasRenderer::~AtlasRenderer()
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/rendering/text-backend-impl.h>
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
#include <dali/devel-api/common/singleton-service.h>
+#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/text/rendering-backend.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace Internal
{
-
struct Backend::Impl
{
int temp; // placeholder for future backend implemenations
};
Backend::Backend()
-: mImpl( NULL )
+: mImpl(NULL)
{
mImpl = new Impl();
}
{
Dali::Toolkit::Text::Backend backendHandle;
- Dali::SingletonService service( SingletonService::Get() );
- if ( service )
+ Dali::SingletonService service(SingletonService::Get());
+ if(service)
{
// Check whether the singleton is already created
- Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Toolkit::Text::Backend ) );
+ Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::Toolkit::Text::Backend));
if(handle)
{
// If so, downcast the handle
- Backend* impl = dynamic_cast< Dali::Toolkit::Text::Internal::Backend* >( handle.GetObjectPtr() );
- backendHandle = Dali::Toolkit::Text::Backend( impl );
+ Backend* impl = dynamic_cast<Dali::Toolkit::Text::Internal::Backend*>(handle.GetObjectPtr());
+ backendHandle = Dali::Toolkit::Text::Backend(impl);
}
else // create and register the object
{
- backendHandle = Dali::Toolkit::Text::Backend( new Backend );
- service.Register( typeid( backendHandle ), backendHandle );
+ backendHandle = Dali::Toolkit::Text::Backend(new Backend);
+ service.Register(typeid(backendHandle), backendHandle);
}
}
return backendHandle;
}
-RendererPtr Backend::NewRenderer( unsigned int renderingType )
+RendererPtr Backend::NewRenderer(unsigned int renderingType)
{
RendererPtr renderer;
- switch( renderingType )
+ switch(renderingType)
{
case Dali::Toolkit::DevelText::RENDERING_SHARED_ATLAS:
{
default:
{
- DALI_LOG_WARNING( "Unknown renderer type: %d\n", renderingType );
+ DALI_LOG_WARNING("Unknown renderer type: %d\n", renderingType);
break;
}
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
Backend Backend::Get()
{
return Internal::Backend::Get();
}
-RendererPtr Backend::NewRenderer( unsigned int renderingType )
+RendererPtr Backend::NewRenderer(unsigned int renderingType)
{
- return GetImplementation(*this).NewRenderer( renderingType );
+ return GetImplementation(*this).NewRenderer(renderingType);
}
Backend::Backend()
{
}
-Backend::Backend( const Backend& handle )
-: BaseHandle( handle )
+Backend::Backend(const Backend& handle)
+: BaseHandle(handle)
{
}
-Backend& Backend::operator=( const Backend& handle )
+Backend& Backend::operator=(const Backend& handle)
{
- BaseHandle::operator=( handle );
+ BaseHandle::operator=(handle);
return *this;
}
-Backend::Backend( Internal::Backend* internal )
-: BaseHandle( internal )
+Backend::Backend(Internal::Backend* internal)
+: BaseHandle(internal)
{
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
Renderer::Renderer()
{
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/rendering/text-typesetter.h>
// EXTERNAL INCLUDES
-#include <memory.h>
#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali/public-api/common/constants.h>
+#include <memory.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/text/rendering/view-model.h>
#include <dali-toolkit/devel-api/controls/text-controls/text-label-devel.h>
+#include <dali-toolkit/internal/text/rendering/view-model.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
-
/**
* @brief Data struct used to set the buffer of the glyph's bitmap into the final bitmap's buffer.
*/
* @param[in] style The style of the text.
* @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
*/
-void TypesetGlyph( GlyphData& data,
- const Vector2* const position,
- const Vector4* const color,
- Typesetter::Style style,
- Pixel::Format pixelFormat )
+void TypesetGlyph(GlyphData& data,
+ const Vector2* const position,
+ const Vector4* const color,
+ Typesetter::Style style,
+ Pixel::Format pixelFormat)
{
- if( ( 0u == data.glyphBitmap.width ) || ( 0u == data.glyphBitmap.height ) )
+ if((0u == data.glyphBitmap.width) || (0u == data.glyphBitmap.height))
{
// Nothing to do if the width or height of the buffer is zero.
return;
}
- const int widthMinusOne = static_cast<int>( data.width - 1u );
- const int heightMinusOne = static_cast<int>( data.height - 1u );
+ const int widthMinusOne = static_cast<int>(data.width - 1u);
+ const int heightMinusOne = static_cast<int>(data.height - 1u);
- if ( Pixel::RGBA8888 == pixelFormat )
+ if(Pixel::RGBA8888 == pixelFormat)
{
// Whether the given glyph is a color one.
- const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap;
- const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel( data.glyphBitmap.format );
- const uint32_t alphaIndex = glyphPixelSize - 1u;
- const bool swapChannelsBR = Pixel::BGRA8888 == data.glyphBitmap.format;
+ const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap;
+ const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel(data.glyphBitmap.format);
+ const uint32_t alphaIndex = glyphPixelSize - 1u;
+ const bool swapChannelsBR = Pixel::BGRA8888 == data.glyphBitmap.format;
// Pointer to the color glyph if there is one.
- const uint32_t* const colorGlyphBuffer = isColorGlyph ? reinterpret_cast<uint32_t*>( data.glyphBitmap.buffer ) : NULL;
+ const uint32_t* const colorGlyphBuffer = isColorGlyph ? reinterpret_cast<uint32_t*>(data.glyphBitmap.buffer) : NULL;
// Initial vertical offset.
const int yOffset = data.verticalOffset + position->y;
- uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( data.bitmapBuffer.GetBuffer() );
+ uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(data.bitmapBuffer.GetBuffer());
// Traverse the pixels of the glyph line per line.
- for( int lineIndex = 0, glyphHeight = static_cast<int>( data.glyphBitmap.height ); lineIndex < glyphHeight; ++lineIndex )
+ for(int lineIndex = 0, glyphHeight = static_cast<int>(data.glyphBitmap.height); lineIndex < glyphHeight; ++lineIndex)
{
const int yOffsetIndex = yOffset + lineIndex;
- if( ( 0 > yOffsetIndex ) || ( yOffsetIndex > heightMinusOne ) )
+ if((0 > yOffsetIndex) || (yOffsetIndex > heightMinusOne))
{
// Do not write out of bounds.
continue;
}
- const int verticalOffset = yOffsetIndex * data.width;
- const int xOffset = data.horizontalOffset + position->x;
- const int glyphBufferOffset = lineIndex * static_cast<int>( data.glyphBitmap.width );
- for( int index = 0, glyphWidth = static_cast<int>( data.glyphBitmap.width ); index < glyphWidth; ++index )
+ const int verticalOffset = yOffsetIndex * data.width;
+ const int xOffset = data.horizontalOffset + position->x;
+ const int glyphBufferOffset = lineIndex * static_cast<int>(data.glyphBitmap.width);
+ for(int index = 0, glyphWidth = static_cast<int>(data.glyphBitmap.width); index < glyphWidth; ++index)
{
const int xOffsetIndex = xOffset + index;
- if( ( 0 > xOffsetIndex ) || ( xOffsetIndex > widthMinusOne ) )
+ if((0 > xOffsetIndex) || (xOffsetIndex > widthMinusOne))
{
// Don't write out of bounds.
continue;
}
- if( isColorGlyph )
+ if(isColorGlyph)
{
// Retrieves the color from the color glyph.
- uint32_t packedColorGlyph = *( colorGlyphBuffer + glyphBufferOffset + index );
- uint8_t* packedColorGlyphBuffer = reinterpret_cast<uint8_t*>( &packedColorGlyph );
+ uint32_t packedColorGlyph = *(colorGlyphBuffer + glyphBufferOffset + index);
+ uint8_t* packedColorGlyphBuffer = reinterpret_cast<uint8_t*>(&packedColorGlyph);
// Update the alpha channel.
- if( Typesetter::STYLE_MASK == style || Typesetter::STYLE_OUTLINE == style ) // Outline not shown for color glyph
+ if(Typesetter::STYLE_MASK == style || Typesetter::STYLE_OUTLINE == style) // Outline not shown for color glyph
{
// Create an alpha mask for color glyph.
- *( packedColorGlyphBuffer + 3u ) = 0u;
- *( packedColorGlyphBuffer + 2u ) = 0u;
- *( packedColorGlyphBuffer + 1u ) = 0u;
- *packedColorGlyphBuffer = 0u;
+ *(packedColorGlyphBuffer + 3u) = 0u;
+ *(packedColorGlyphBuffer + 2u) = 0u;
+ *(packedColorGlyphBuffer + 1u) = 0u;
+ *packedColorGlyphBuffer = 0u;
}
else
{
- const uint8_t colorAlpha = static_cast<uint8_t>( color->a * static_cast<float>( *( packedColorGlyphBuffer + 3u ) ) );
- *( packedColorGlyphBuffer + 3u ) = colorAlpha;
+ const uint8_t colorAlpha = static_cast<uint8_t>(color->a * static_cast<float>(*(packedColorGlyphBuffer + 3u)));
+ *(packedColorGlyphBuffer + 3u) = colorAlpha;
- if( Typesetter::STYLE_SHADOW == style )
+ if(Typesetter::STYLE_SHADOW == style)
{
// The shadow of color glyph needs to have the shadow color.
- *( packedColorGlyphBuffer + 2u ) = static_cast<uint8_t>( color->b * colorAlpha );
- *( packedColorGlyphBuffer + 1u ) = static_cast<uint8_t>( color->g * colorAlpha );
- *packedColorGlyphBuffer = static_cast<uint8_t>( color->r * colorAlpha );
+ *(packedColorGlyphBuffer + 2u) = static_cast<uint8_t>(color->b * colorAlpha);
+ *(packedColorGlyphBuffer + 1u) = static_cast<uint8_t>(color->g * colorAlpha);
+ *packedColorGlyphBuffer = static_cast<uint8_t>(color->r * colorAlpha);
}
else
{
- if( swapChannelsBR )
+ if(swapChannelsBR)
{
- std::swap( *packedColorGlyphBuffer, *( packedColorGlyphBuffer + 2u ) ); // Swap B and R.
+ std::swap(*packedColorGlyphBuffer, *(packedColorGlyphBuffer + 2u)); // Swap B and R.
}
- *( packedColorGlyphBuffer + 2u ) = ( *( packedColorGlyphBuffer + 2u ) * colorAlpha / 255 );
- *( packedColorGlyphBuffer + 1u ) = ( *( packedColorGlyphBuffer + 1u ) * colorAlpha / 255 );
- *packedColorGlyphBuffer = ( *( packedColorGlyphBuffer ) * colorAlpha / 255 );
+ *(packedColorGlyphBuffer + 2u) = (*(packedColorGlyphBuffer + 2u) * colorAlpha / 255);
+ *(packedColorGlyphBuffer + 1u) = (*(packedColorGlyphBuffer + 1u) * colorAlpha / 255);
+ *packedColorGlyphBuffer = (*(packedColorGlyphBuffer)*colorAlpha / 255);
- if( data.glyphBitmap.isColorBitmap )
+ if(data.glyphBitmap.isColorBitmap)
{
- *( packedColorGlyphBuffer + 2u ) = static_cast<uint8_t>( *( packedColorGlyphBuffer + 2u ) * color->b );
- *( packedColorGlyphBuffer + 1u ) = static_cast<uint8_t>( *( packedColorGlyphBuffer + 1u ) * color->g );
- *packedColorGlyphBuffer = static_cast<uint8_t>( *packedColorGlyphBuffer * color->r );
+ *(packedColorGlyphBuffer + 2u) = static_cast<uint8_t>(*(packedColorGlyphBuffer + 2u) * color->b);
+ *(packedColorGlyphBuffer + 1u) = static_cast<uint8_t>(*(packedColorGlyphBuffer + 1u) * color->g);
+ *packedColorGlyphBuffer = static_cast<uint8_t>(*packedColorGlyphBuffer * color->r);
}
}
}
// Set the color into the final pixel buffer.
- *( bitmapBuffer + verticalOffset + xOffsetIndex ) = packedColorGlyph;
+ *(bitmapBuffer + verticalOffset + xOffsetIndex) = packedColorGlyph;
}
else
{
// Pack the given color into a 32bit buffer. The alpha channel will be updated later for each pixel.
// The format is RGBA8888.
- uint32_t packedColor = 0u;
- uint8_t* packedColorBuffer = reinterpret_cast<uint8_t*>( &packedColor );
+ uint32_t packedColor = 0u;
+ uint8_t* packedColorBuffer = reinterpret_cast<uint8_t*>(&packedColor);
// Update the alpha channel.
- const uint8_t alpha = *( data.glyphBitmap.buffer + glyphPixelSize * ( glyphBufferOffset + index ) + alphaIndex );
+ const uint8_t alpha = *(data.glyphBitmap.buffer + glyphPixelSize * (glyphBufferOffset + index) + alphaIndex);
// Copy non-transparent pixels only
- if ( alpha > 0u )
+ if(alpha > 0u)
{
// Check alpha of overlapped pixels
- uint32_t& currentColor = *( bitmapBuffer + verticalOffset + xOffsetIndex );
- uint8_t* packedCurrentColorBuffer = reinterpret_cast<uint8_t*>( ¤tColor );
+ uint32_t& currentColor = *(bitmapBuffer + verticalOffset + xOffsetIndex);
+ uint8_t* packedCurrentColorBuffer = reinterpret_cast<uint8_t*>(¤tColor);
// For any pixel overlapped with the pixel in previous glyphs, make sure we don't
// overwrite a previous bigger alpha with a smaller alpha (in order to avoid
// semi-transparent gaps between joint glyphs with overlapped pixels, which could
// happen, for example, in the RTL text when we copy glyphs from right to left).
- uint8_t currentAlpha = *( packedCurrentColorBuffer + 3u );
- currentAlpha = std::max( currentAlpha, alpha );
+ uint8_t currentAlpha = *(packedCurrentColorBuffer + 3u);
+ currentAlpha = std::max(currentAlpha, alpha);
// Color is pre-muliplied with its alpha.
- *( packedColorBuffer + 3u ) = static_cast<uint8_t>( color->a * currentAlpha );
- *( packedColorBuffer + 2u ) = static_cast<uint8_t>( color->b * currentAlpha );
- *( packedColorBuffer + 1u ) = static_cast<uint8_t>( color->g * currentAlpha );
- *( packedColorBuffer ) = static_cast<uint8_t>( color->r * currentAlpha );
+ *(packedColorBuffer + 3u) = static_cast<uint8_t>(color->a * currentAlpha);
+ *(packedColorBuffer + 2u) = static_cast<uint8_t>(color->b * currentAlpha);
+ *(packedColorBuffer + 1u) = static_cast<uint8_t>(color->g * currentAlpha);
+ *(packedColorBuffer) = static_cast<uint8_t>(color->r * currentAlpha);
// Set the color into the final pixel buffer.
currentColor = packedColor;
else
{
// Whether the given glyph is a color one.
- const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap;
- const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel( data.glyphBitmap.format );
- const uint32_t alphaIndex = glyphPixelSize - 1u;
+ const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap;
+ const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel(data.glyphBitmap.format);
+ const uint32_t alphaIndex = glyphPixelSize - 1u;
// Initial vertical offset.
const int yOffset = data.verticalOffset + position->y;
- uint8_t* bitmapBuffer = reinterpret_cast< uint8_t* >( data.bitmapBuffer.GetBuffer() );
+ uint8_t* bitmapBuffer = reinterpret_cast<uint8_t*>(data.bitmapBuffer.GetBuffer());
// Traverse the pixels of the glyph line per line.
- for( int lineIndex = 0, glyphHeight = static_cast<int>( data.glyphBitmap.height ); lineIndex < glyphHeight; ++lineIndex )
+ for(int lineIndex = 0, glyphHeight = static_cast<int>(data.glyphBitmap.height); lineIndex < glyphHeight; ++lineIndex)
{
const int yOffsetIndex = yOffset + lineIndex;
- if( ( 0 > yOffsetIndex ) || ( yOffsetIndex > heightMinusOne ) )
+ if((0 > yOffsetIndex) || (yOffsetIndex > heightMinusOne))
{
// Do not write out of bounds.
continue;
}
- const int verticalOffset = yOffsetIndex * data.width;
- const int xOffset = data.horizontalOffset + position->x;
- const int glyphBufferOffset = lineIndex * static_cast<int>( data.glyphBitmap.width );
- for( int index = 0, glyphWidth = static_cast<int>( data.glyphBitmap.width ); index < glyphWidth; ++index )
+ const int verticalOffset = yOffsetIndex * data.width;
+ const int xOffset = data.horizontalOffset + position->x;
+ const int glyphBufferOffset = lineIndex * static_cast<int>(data.glyphBitmap.width);
+ for(int index = 0, glyphWidth = static_cast<int>(data.glyphBitmap.width); index < glyphWidth; ++index)
{
const int xOffsetIndex = xOffset + index;
- if( ( 0 > xOffsetIndex ) || ( xOffsetIndex > widthMinusOne ) )
+ if((0 > xOffsetIndex) || (xOffsetIndex > widthMinusOne))
{
// Don't write out of bounds.
continue;
}
- if ( !isColorGlyph )
+ if(!isColorGlyph)
{
// Update the alpha channel.
- const uint8_t alpha = *( data.glyphBitmap.buffer + glyphPixelSize * ( glyphBufferOffset + index ) + alphaIndex );
+ const uint8_t alpha = *(data.glyphBitmap.buffer + glyphPixelSize * (glyphBufferOffset + index) + alphaIndex);
// Copy non-transparent pixels only
- if ( alpha > 0u )
+ if(alpha > 0u)
{
// Check alpha of overlapped pixels
- uint8_t& currentAlpha = *( bitmapBuffer + verticalOffset + xOffsetIndex );
+ uint8_t& currentAlpha = *(bitmapBuffer + verticalOffset + xOffsetIndex);
// For any pixel overlapped with the pixel in previous glyphs, make sure we don't
// overwrite a previous bigger alpha with a smaller alpha (in order to avoid
// semi-transparent gaps between joint glyphs with overlapped pixels, which could
// happen, for example, in the RTL text when we copy glyphs from right to left).
- currentAlpha = std::max( currentAlpha, alpha );
+ currentAlpha = std::max(currentAlpha, alpha);
}
}
}
}
}
-bool IsGlyphUnderlined( GlyphIndex index,
- const Vector<GlyphRun>& underlineRuns )
+bool IsGlyphUnderlined(GlyphIndex index,
+ const Vector<GlyphRun>& underlineRuns)
{
- for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
- endIt = underlineRuns.End();
- it != endIt;
- ++it )
+ for(Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
+ endIt = underlineRuns.End();
+ it != endIt;
+ ++it)
{
const GlyphRun& run = *it;
- if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
+ if((run.glyphIndex <= index) && (index < run.glyphIndex + run.numberOfGlyphs))
{
return true;
}
/// Helper method to fetch the underline metrics for the specified font glyph
void FetchFontUnderlineMetrics(
- TextAbstraction::FontClient& fontClient,
- const GlyphInfo* const glyphInfo,
- float& currentUnderlinePosition,
- const float underlineHeight,
- float& currentUnderlineThickness,
- float& maxUnderlineThickness,
- FontId& lastUnderlinedFontId)
+ TextAbstraction::FontClient& fontClient,
+ const GlyphInfo* const glyphInfo,
+ float& currentUnderlinePosition,
+ const float underlineHeight,
+ float& currentUnderlineThickness,
+ float& maxUnderlineThickness,
+ FontId& lastUnderlinedFontId)
{
FontMetrics fontMetrics;
- fontClient.GetFontMetrics( glyphInfo->fontId, fontMetrics );
- currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
- const float descender = ceil( fabsf( fontMetrics.descender ) );
+ fontClient.GetFontMetrics(glyphInfo->fontId, fontMetrics);
+ currentUnderlinePosition = ceil(fabsf(fontMetrics.underlinePosition));
+ const float descender = ceil(fabsf(fontMetrics.descender));
- if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
+ if(fabsf(underlineHeight) < Math::MACHINE_EPSILON_1000)
{
currentUnderlineThickness = fontMetrics.underlineThickness;
// Ensure underline will be at least a pixel high
- if ( currentUnderlineThickness < 1.0f )
+ if(currentUnderlineThickness < 1.0f)
{
currentUnderlineThickness = 1.0f;
}
else
{
- currentUnderlineThickness = ceil( currentUnderlineThickness );
+ currentUnderlineThickness = ceil(currentUnderlineThickness);
}
}
// The underline thickness should be the max underline thickness of all glyphs of the line.
- if ( currentUnderlineThickness > maxUnderlineThickness )
+ if(currentUnderlineThickness > maxUnderlineThickness)
{
maxUnderlineThickness = currentUnderlineThickness;
}
// Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
- if( currentUnderlinePosition > descender )
+ if(currentUnderlinePosition > descender)
{
currentUnderlinePosition = descender;
}
- if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
+ if(fabsf(currentUnderlinePosition) < Math::MACHINE_EPSILON_1000)
{
// Move offset down by one ( EFL behavior )
currentUnderlinePosition = 1.0f;
/// Draws the specified color to the pixel buffer
void WriteColorToPixelBuffer(
- GlyphData& glyphData,
- uint32_t* bitmapBuffer,
- const Vector4& color,
- const unsigned int x,
- const unsigned int y)
+ GlyphData& glyphData,
+ uint32_t* bitmapBuffer,
+ const Vector4& color,
+ const unsigned int x,
+ const unsigned int y)
{
// Always RGBA image for text with styles
- uint32_t pixel = *( bitmapBuffer + y * glyphData.width + x );
- uint8_t* pixelBuffer = reinterpret_cast<uint8_t*>( &pixel );
+ uint32_t pixel = *(bitmapBuffer + y * glyphData.width + x);
+ uint8_t* pixelBuffer = reinterpret_cast<uint8_t*>(&pixel);
// Write the color to the pixel buffer
- uint8_t colorAlpha = static_cast< uint8_t >( color.a * 255.f );
- *( pixelBuffer + 3u ) = colorAlpha;
- *( pixelBuffer + 2u ) = static_cast< uint8_t >( color.b * colorAlpha );
- *( pixelBuffer + 1u ) = static_cast< uint8_t >( color.g * colorAlpha );
- *( pixelBuffer ) = static_cast< uint8_t >( color.r * colorAlpha );
+ uint8_t colorAlpha = static_cast<uint8_t>(color.a * 255.f);
+ *(pixelBuffer + 3u) = colorAlpha;
+ *(pixelBuffer + 2u) = static_cast<uint8_t>(color.b * colorAlpha);
+ *(pixelBuffer + 1u) = static_cast<uint8_t>(color.g * colorAlpha);
+ *(pixelBuffer) = static_cast<uint8_t>(color.r * colorAlpha);
- *( bitmapBuffer + y * glyphData.width + x ) = pixel;
+ *(bitmapBuffer + y * glyphData.width + x) = pixel;
}
/// Draws the specified underline color to the buffer
void DrawUnderline(
- const Vector4& underlineColor,
- const unsigned int bufferWidth,
- const unsigned int bufferHeight,
- GlyphData& glyphData,
- const float baseline,
- const float currentUnderlinePosition,
- const float maxUnderlineThickness,
- const float lineExtentLeft,
- const float lineExtentRight)
+ const Vector4& underlineColor,
+ const unsigned int bufferWidth,
+ const unsigned int bufferHeight,
+ GlyphData& glyphData,
+ const float baseline,
+ const float currentUnderlinePosition,
+ const float maxUnderlineThickness,
+ const float lineExtentLeft,
+ const float lineExtentRight)
{
- int underlineYOffset = glyphData.verticalOffset + baseline + currentUnderlinePosition;
- uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( glyphData.bitmapBuffer.GetBuffer() );
+ int underlineYOffset = glyphData.verticalOffset + baseline + currentUnderlinePosition;
+ uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer());
- for( unsigned int y = underlineYOffset; y < underlineYOffset + maxUnderlineThickness; y++ )
+ for(unsigned int y = underlineYOffset; y < underlineYOffset + maxUnderlineThickness; y++)
{
- if( y > bufferHeight - 1 )
+ if(y > bufferHeight - 1)
{
// Do not write out of bounds.
break;
}
- for( unsigned int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++ )
+ for(unsigned int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++)
{
- if( x > bufferWidth - 1 )
+ if(x > bufferWidth - 1)
{
// Do not write out of bounds.
break;
/// Draws the background color to the buffer
void DrawBackgroundColor(
- Vector4 backgroundColor,
- const unsigned int bufferWidth,
- const unsigned int bufferHeight,
- GlyphData& glyphData,
- const float baseline,
- const LineRun& line,
- const float lineExtentLeft,
- const float lineExtentRight)
+ Vector4 backgroundColor,
+ const unsigned int bufferWidth,
+ const unsigned int bufferHeight,
+ GlyphData& glyphData,
+ const float baseline,
+ const LineRun& line,
+ const float lineExtentLeft,
+ const float lineExtentRight)
{
- uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( glyphData.bitmapBuffer.GetBuffer() );
+ uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer());
- for( int y = glyphData.verticalOffset + baseline - line.ascender; y < glyphData.verticalOffset + baseline - line.descender; y++ )
+ for(int y = glyphData.verticalOffset + baseline - line.ascender; y < glyphData.verticalOffset + baseline - line.descender; y++)
{
- if( ( y < 0 ) || ( y > static_cast<int>(bufferHeight - 1) ) )
+ if((y < 0) || (y > static_cast<int>(bufferHeight - 1)))
{
// Do not write out of bounds.
continue;
}
- for( int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++ )
+ for(int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++)
{
- if( ( x < 0 ) || ( x > static_cast<int>(bufferWidth - 1) ) )
+ if((x < 0) || (x > static_cast<int>(bufferWidth - 1)))
{
// Do not write out of bounds.
continue;
} // namespace
-TypesetterPtr Typesetter::New( const ModelInterface* const model )
+TypesetterPtr Typesetter::New(const ModelInterface* const model)
{
- return TypesetterPtr( new Typesetter( model ) );
+ return TypesetterPtr(new Typesetter(model));
}
ViewModel* Typesetter::GetViewModel()
return mModel;
}
-PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirection::Type textDirection, RenderBehaviour behaviour, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat )
+PixelData Typesetter::Render(const Vector2& size, Toolkit::DevelText::TextDirection::Type textDirection, RenderBehaviour behaviour, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat)
{
// @todo. This initial implementation for a TextLabel has only one visible page.
// Retrieves the layout size.
const Size& layoutSize = mModel->GetLayoutSize();
- const int outlineWidth = static_cast<int>( mModel->GetOutlineWidth() );
+ const int outlineWidth = static_cast<int>(mModel->GetOutlineWidth());
// Set the offset for the horizontal alignment according to the text direction and outline width.
int penX = 0;
- switch( mModel->GetHorizontalAlignment() )
+ switch(mModel->GetHorizontalAlignment())
{
case HorizontalAlignment::BEGIN:
{
}
case HorizontalAlignment::CENTER:
{
- penX += ( textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT ) ? -outlineWidth : outlineWidth;
+ penX += (textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT) ? -outlineWidth : outlineWidth;
break;
}
case HorizontalAlignment::END:
{
- penX += ( textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT ) ? -outlineWidth * 2 : outlineWidth * 2;
+ penX += (textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT) ? -outlineWidth * 2 : outlineWidth * 2;
break;
}
}
// Set the offset for the vertical alignment.
int penY = 0u;
- switch( mModel->GetVerticalAlignment() )
+ switch(mModel->GetVerticalAlignment())
{
case VerticalAlignment::TOP:
{
}
case VerticalAlignment::CENTER:
{
- penY = static_cast<int>( 0.5f * ( size.height - layoutSize.height ) );
+ penY = static_cast<int>(0.5f * (size.height - layoutSize.height));
penY = penY < 0.f ? 0.f : penY;
break;
}
case VerticalAlignment::BOTTOM:
{
- penY = static_cast<int>( size.height - layoutSize.height );
+ penY = static_cast<int>(size.height - layoutSize.height);
break;
}
}
// Calculate vertical line alignment
- switch( mModel->GetVerticalLineAlignment() )
+ switch(mModel->GetVerticalLineAlignment())
{
case DevelText::VerticalLineAlignment::TOP:
{
{
const auto& line = *mModel->GetLines();
penY -= line.descender;
- penY += static_cast<int>(line.lineSpacing*0.5f + line.descender);
+ penY += static_cast<int>(line.lineSpacing * 0.5f + line.descender);
break;
}
case DevelText::VerticalLineAlignment::BOTTOM:
{
- const auto& line = *mModel->GetLines();
- const auto lineHeight = line.ascender + (-line.descender) + line.lineSpacing;
+ const auto& line = *mModel->GetLines();
+ const auto lineHeight = line.ascender + (-line.descender) + line.lineSpacing;
penY += static_cast<int>(lineHeight - (line.ascender - line.descender));
break;
}
// do all of these in CPU only, so that once the final texture is generated,
// no calculation is needed in GPU during each frame.
- const unsigned int bufferWidth = static_cast<unsigned int>( size.width );
- const unsigned int bufferHeight = static_cast<unsigned int>( size.height );
+ const unsigned int bufferWidth = static_cast<unsigned int>(size.width);
+ const unsigned int bufferHeight = static_cast<unsigned int>(size.height);
- const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
+ const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
const unsigned int bufferSizeChar = 4u * bufferSizeInt;
Length numberOfGlyphs = mModel->GetNumberOfGlyphs();
Devel::PixelBuffer imageBuffer;
- if( RENDER_MASK == behaviour )
+ if(RENDER_MASK == behaviour)
{
// Generate the image buffer as an alpha mask for color glyphs.
- imageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_MASK, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 );
+ imageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_MASK, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1);
}
- else if( RENDER_NO_TEXT == behaviour )
+ else if(RENDER_NO_TEXT == behaviour)
{
// Generate an empty image buffer so that it can been combined with the image buffers for styles
- imageBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 );
- memset( imageBuffer.GetBuffer(), 0u, bufferSizeChar );
+ imageBuffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, Pixel::RGBA8888);
+ memset(imageBuffer.GetBuffer(), 0u, bufferSizeChar);
}
else
{
// Generate the image buffer for the text with no style.
- imageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_NONE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 );
+ imageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_NONE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1);
}
- if ( ( RENDER_NO_STYLES != behaviour ) && ( RENDER_MASK != behaviour ) )
+ if((RENDER_NO_STYLES != behaviour) && (RENDER_MASK != behaviour))
{
-
// Generate the outline if enabled
const uint16_t outlineWidth = mModel->GetOutlineWidth();
- if ( outlineWidth != 0u )
+ if(outlineWidth != 0u)
{
// Create the image buffer for outline
- Devel::PixelBuffer outlineImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_OUTLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 );
+ Devel::PixelBuffer outlineImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_OUTLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1);
// Combine the two buffers
- imageBuffer = CombineImageBuffer( imageBuffer, outlineImageBuffer, bufferWidth, bufferHeight );
+ imageBuffer = CombineImageBuffer(imageBuffer, outlineImageBuffer, bufferWidth, bufferHeight);
}
// @todo. Support shadow and underline for partial text later on.
// Generate the shadow if enabled
const Vector2& shadowOffset = mModel->GetShadowOffset();
- if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
+ if(fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1)
{
// Create the image buffer for shadow
- Devel::PixelBuffer shadowImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_SHADOW, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 );
+ Devel::PixelBuffer shadowImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_SHADOW, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1);
// Check whether it will be a soft shadow
const float& blurRadius = mModel->GetShadowBlurRadius();
- if ( blurRadius > Math::MACHINE_EPSILON_1 )
+ if(blurRadius > Math::MACHINE_EPSILON_1)
{
- shadowImageBuffer.ApplyGaussianBlur( blurRadius );
+ shadowImageBuffer.ApplyGaussianBlur(blurRadius);
}
// Combine the two buffers
- imageBuffer = CombineImageBuffer( imageBuffer, shadowImageBuffer, bufferWidth, bufferHeight );
+ imageBuffer = CombineImageBuffer(imageBuffer, shadowImageBuffer, bufferWidth, bufferHeight);
}
// Generate the underline if enabled
const bool underlineEnabled = mModel->IsUnderlineEnabled();
- if ( underlineEnabled )
+ if(underlineEnabled)
{
// Create the image buffer for underline
- Devel::PixelBuffer underlineImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 );
+ Devel::PixelBuffer underlineImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1);
// Combine the two buffers
- imageBuffer = CombineImageBuffer( imageBuffer, underlineImageBuffer, bufferWidth, bufferHeight );
+ imageBuffer = CombineImageBuffer(imageBuffer, underlineImageBuffer, bufferWidth, bufferHeight);
}
// Generate the background if enabled
const bool backgroundEnabled = mModel->IsBackgroundEnabled();
- if ( backgroundEnabled )
+ if(backgroundEnabled)
{
- Devel::PixelBuffer backgroundImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_BACKGROUND, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 );
+ Devel::PixelBuffer backgroundImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_BACKGROUND, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1);
// Combine the two buffers
- imageBuffer = CombineImageBuffer( imageBuffer, backgroundImageBuffer, bufferWidth, bufferHeight );
+ imageBuffer = CombineImageBuffer(imageBuffer, backgroundImageBuffer, bufferWidth, bufferHeight);
}
}
// Create the final PixelData for the combined image buffer
- PixelData pixelData = Devel::PixelBuffer::Convert( imageBuffer );
+ PixelData pixelData = Devel::PixelBuffer::Convert(imageBuffer);
return pixelData;
}
-Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth, const unsigned int bufferHeight, Typesetter::Style style, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat, int horizontalOffset, int verticalOffset, GlyphIndex fromGlyphIndex, GlyphIndex toGlyphIndex )
+Devel::PixelBuffer Typesetter::CreateImageBuffer(const unsigned int bufferWidth, const unsigned int bufferHeight, Typesetter::Style style, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat, int horizontalOffset, int verticalOffset, GlyphIndex fromGlyphIndex, GlyphIndex toGlyphIndex)
{
// Retrieve lines, glyphs, positions and colors from the view model.
- const Length modelNumberOfLines = mModel->GetNumberOfLines();
- const LineRun* const modelLinesBuffer = mModel->GetLines();
- const Length numberOfGlyphs = mModel->GetNumberOfGlyphs();
- const GlyphInfo* const glyphsBuffer = mModel->GetGlyphs();
- const Vector2* const positionBuffer = mModel->GetLayout();
- const Vector4* const colorsBuffer = mModel->GetColors();
- const ColorIndex* const colorIndexBuffer = mModel->GetColorIndices();
+ const Length modelNumberOfLines = mModel->GetNumberOfLines();
+ const LineRun* const modelLinesBuffer = mModel->GetLines();
+ const Length numberOfGlyphs = mModel->GetNumberOfGlyphs();
+ const GlyphInfo* const glyphsBuffer = mModel->GetGlyphs();
+ const Vector2* const positionBuffer = mModel->GetLayout();
+ const Vector4* const colorsBuffer = mModel->GetColors();
+ const ColorIndex* const colorIndexBuffer = mModel->GetColorIndices();
// Whether to use the default color.
- const bool useDefaultColor = ( NULL == colorsBuffer );
- const Vector4& defaultColor = mModel->GetDefaultColor();
+ const bool useDefaultColor = (NULL == colorsBuffer);
+ const Vector4& defaultColor = mModel->GetDefaultColor();
// Create and initialize the pixel buffer.
GlyphData glyphData;
- glyphData.verticalOffset = verticalOffset;
- glyphData.width = bufferWidth;
- glyphData.height = bufferHeight;
- glyphData.bitmapBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, pixelFormat );
+ glyphData.verticalOffset = verticalOffset;
+ glyphData.width = bufferWidth;
+ glyphData.height = bufferHeight;
+ glyphData.bitmapBuffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, pixelFormat);
glyphData.horizontalOffset = 0;
- if ( Pixel::RGBA8888 == pixelFormat )
+ if(Pixel::RGBA8888 == pixelFormat)
{
- const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
+ const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
const unsigned int bufferSizeChar = 4u * bufferSizeInt;
- memset( glyphData.bitmapBuffer.GetBuffer(), 0u, bufferSizeChar );
+ memset(glyphData.bitmapBuffer.GetBuffer(), 0u, bufferSizeChar);
}
else
{
- memset( glyphData.bitmapBuffer.GetBuffer(), 0, bufferWidth * bufferHeight );
+ memset(glyphData.bitmapBuffer.GetBuffer(), 0, bufferWidth * bufferHeight);
}
// Get a handle of the font client. Used to retrieve the bitmaps of the glyphs.
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
// Traverses the lines of the text.
- for( LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex )
+ for(LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex)
{
- const LineRun& line = *( modelLinesBuffer + lineIndex );
+ const LineRun& line = *(modelLinesBuffer + lineIndex);
// Sets the horizontal offset of the line.
- glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast<int>( line.alignmentOffset );
+ glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast<int>(line.alignmentOffset);
glyphData.horizontalOffset += horizontalOffset;
// Increases the vertical offset with the line's ascender.
- glyphData.verticalOffset += static_cast<int>( line.ascender );
+ glyphData.verticalOffset += static_cast<int>(line.ascender);
// Include line spacing after first line
- if( lineIndex > 0u )
+ if(lineIndex > 0u)
{
- glyphData.verticalOffset += static_cast<int>( line.lineSpacing );
+ glyphData.verticalOffset += static_cast<int>(line.lineSpacing);
}
// Retrieves the glyph's outline width
- float outlineWidth = static_cast<float>( mModel->GetOutlineWidth() );
+ float outlineWidth = static_cast<float>(mModel->GetOutlineWidth());
- if( style == Typesetter::STYLE_OUTLINE )
+ if(style == Typesetter::STYLE_OUTLINE)
{
glyphData.horizontalOffset -= outlineWidth;
- if( lineIndex == 0u )
+ if(lineIndex == 0u)
{
// Only need to add the vertical outline offset for the first line
glyphData.verticalOffset -= outlineWidth;
}
}
- else if ( style == Typesetter::STYLE_SHADOW )
+ else if(style == Typesetter::STYLE_SHADOW)
{
const Vector2& shadowOffset = mModel->GetShadowOffset();
glyphData.horizontalOffset += shadowOffset.x - outlineWidth; // if outline enabled then shadow should offset from outline
- if ( lineIndex == 0u )
+ if(lineIndex == 0u)
{
// Only need to add the vertical shadow offset for first line
glyphData.verticalOffset += shadowOffset.y - outlineWidth;
}
}
- const bool underlineEnabled = mModel->IsUnderlineEnabled();
- const Vector4& underlineColor = mModel->GetUnderlineColor();
- const float underlineHeight = mModel->GetUnderlineHeight();
+ const bool underlineEnabled = mModel->IsUnderlineEnabled();
+ const Vector4& underlineColor = mModel->GetUnderlineColor();
+ const float underlineHeight = mModel->GetUnderlineHeight();
// Get the underline runs.
- const Length numberOfUnderlineRuns = mModel->GetNumberOfUnderlineRuns();
+ const Length numberOfUnderlineRuns = mModel->GetNumberOfUnderlineRuns();
Vector<GlyphRun> underlineRuns;
- underlineRuns.Resize( numberOfUnderlineRuns );
- mModel->GetUnderlineRuns( underlineRuns.Begin(), 0u, numberOfUnderlineRuns );
+ underlineRuns.Resize(numberOfUnderlineRuns);
+ mModel->GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns);
bool thereAreUnderlinedGlyphs = false;
- float currentUnderlinePosition = 0.0f;
+ float currentUnderlinePosition = 0.0f;
float currentUnderlineThickness = underlineHeight;
- float maxUnderlineThickness = currentUnderlineThickness;
+ float maxUnderlineThickness = currentUnderlineThickness;
FontId lastUnderlinedFontId = 0;
- float lineExtentLeft = bufferWidth;
+ float lineExtentLeft = bufferWidth;
float lineExtentRight = 0.0f;
- float baseline = 0.0f;
+ float baseline = 0.0f;
// Traverses the glyphs of the line.
- const GlyphIndex endGlyphIndex = std::min( numberOfGlyphs, line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs );
- for( GlyphIndex glyphIndex = line.glyphRun.glyphIndex; glyphIndex < endGlyphIndex; ++glyphIndex )
+ const GlyphIndex endGlyphIndex = std::min(numberOfGlyphs, line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs);
+ for(GlyphIndex glyphIndex = line.glyphRun.glyphIndex; glyphIndex < endGlyphIndex; ++glyphIndex)
{
- if ( glyphIndex < fromGlyphIndex || glyphIndex > toGlyphIndex )
+ if(glyphIndex < fromGlyphIndex || glyphIndex > toGlyphIndex)
{
// Ignore any glyph that out of the specified range
continue;
// Retrieve the glyph's info.
const GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
- if( ( glyphInfo->width < Math::MACHINE_EPSILON_1000 ) ||
- ( glyphInfo->height < Math::MACHINE_EPSILON_1000 ) )
+ if((glyphInfo->width < Math::MACHINE_EPSILON_1000) ||
+ (glyphInfo->height < Math::MACHINE_EPSILON_1000))
{
// Nothing to do if the glyph's width or height is zero.
continue;
}
- const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( glyphIndex, underlineRuns );
- thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
+ const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined(glyphIndex, underlineRuns);
+ thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
// Are we still using the same fontId as previous
- if( underlineGlyph && ( glyphInfo->fontId != lastUnderlinedFontId ) )
+ if(underlineGlyph && (glyphInfo->fontId != lastUnderlinedFontId))
{
// We need to fetch fresh font underline metrics
FetchFontUnderlineMetrics(fontClient, glyphInfo, currentUnderlinePosition, underlineHeight, currentUnderlineThickness, maxUnderlineThickness, lastUnderlinedFontId);
// Retrieves the glyph's position.
const Vector2* const position = positionBuffer + glyphIndex;
- if ( baseline < position->y + glyphInfo->yBearing )
+ if(baseline < position->y + glyphInfo->yBearing)
{
baseline = position->y + glyphInfo->yBearing;
}
// Calculate the positions of leftmost and rightmost glyphs in the current line
- if ( position->x < lineExtentLeft)
+ if(position->x < lineExtentLeft)
{
lineExtentLeft = position->x;
}
- if ( position->x + glyphInfo->width > lineExtentRight)
+ if(position->x + glyphInfo->width > lineExtentRight)
{
lineExtentRight = position->x + glyphInfo->width;
}
// Retrieves the glyph's color.
- const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndexBuffer + glyphIndex );
+ const ColorIndex colorIndex = useDefaultColor ? 0u : *(colorIndexBuffer + glyphIndex);
Vector4 color;
- if ( style == Typesetter::STYLE_SHADOW )
+ if(style == Typesetter::STYLE_SHADOW)
{
color = mModel->GetShadowColor();
}
- else if ( style == Typesetter::STYLE_OUTLINE )
+ else if(style == Typesetter::STYLE_OUTLINE)
{
color = mModel->GetOutlineColor();
}
else
{
- color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + ( colorIndex - 1u ) );
+ color = (useDefaultColor || (0u == colorIndex)) ? defaultColor : *(colorsBuffer + (colorIndex - 1u));
}
// Premultiply alpha
// Retrieves the glyph's bitmap.
glyphData.glyphBitmap.buffer = NULL;
- glyphData.glyphBitmap.width = glyphInfo->width; // Desired width and height.
+ glyphData.glyphBitmap.width = glyphInfo->width; // Desired width and height.
glyphData.glyphBitmap.height = glyphInfo->height;
- if( style != Typesetter::STYLE_OUTLINE && style != Typesetter::STYLE_SHADOW )
+ if(style != Typesetter::STYLE_OUTLINE && style != Typesetter::STYLE_SHADOW)
{
// Don't render outline for other styles
outlineWidth = 0.0f;
}
- if( style != Typesetter::STYLE_UNDERLINE )
+ if(style != Typesetter::STYLE_UNDERLINE)
{
- fontClient.CreateBitmap( glyphInfo->fontId,
- glyphInfo->index,
- glyphInfo->isItalicRequired,
- glyphInfo->isBoldRequired,
- glyphData.glyphBitmap,
- static_cast<int>( outlineWidth ) );
+ fontClient.CreateBitmap(glyphInfo->fontId,
+ glyphInfo->index,
+ glyphInfo->isItalicRequired,
+ glyphInfo->isBoldRequired,
+ glyphData.glyphBitmap,
+ static_cast<int>(outlineWidth));
}
// Sets the glyph's bitmap into the bitmap of the whole text.
- if( NULL != glyphData.glyphBitmap.buffer )
+ if(NULL != glyphData.glyphBitmap.buffer)
{
- if ( style == Typesetter::STYLE_OUTLINE )
+ if(style == Typesetter::STYLE_OUTLINE)
{
// Set the position offset for the current glyph
glyphData.horizontalOffset -= glyphData.glyphBitmap.outlineOffsetX;
}
// Set the buffer of the glyph's bitmap into the final bitmap's buffer
- TypesetGlyph( glyphData,
- position,
- &color,
- style,
- pixelFormat);
+ TypesetGlyph(glyphData,
+ position,
+ &color,
+ style,
+ pixelFormat);
- if ( style == Typesetter::STYLE_OUTLINE )
+ if(style == Typesetter::STYLE_OUTLINE)
{
// Reset the position offset for the next glyph
glyphData.horizontalOffset += glyphData.glyphBitmap.outlineOffsetX;
}
// delete the glyphBitmap.buffer as it is now copied into glyphData.bitmapBuffer
- delete []glyphData.glyphBitmap.buffer;
+ delete[] glyphData.glyphBitmap.buffer;
glyphData.glyphBitmap.buffer = NULL;
}
}
// Draw the underline from the leftmost glyph to the rightmost glyph
- if ( thereAreUnderlinedGlyphs && style == Typesetter::STYLE_UNDERLINE )
+ if(thereAreUnderlinedGlyphs && style == Typesetter::STYLE_UNDERLINE)
{
DrawUnderline(underlineColor, bufferWidth, bufferHeight, glyphData, baseline, currentUnderlinePosition, maxUnderlineThickness, lineExtentLeft, lineExtentRight);
}
// Draw the background color from the leftmost glyph to the rightmost glyph
- if ( style == Typesetter::STYLE_BACKGROUND )
+ if(style == Typesetter::STYLE_BACKGROUND)
{
DrawBackgroundColor(mModel->GetBackgroundColor(), bufferWidth, bufferHeight, glyphData, baseline, line, lineExtentLeft, lineExtentRight);
}
// Increases the vertical offset with the line's descender.
- glyphData.verticalOffset += static_cast<int>( -line.descender );
+ glyphData.verticalOffset += static_cast<int>(-line.descender);
}
return glyphData.bitmapBuffer;
}
-Devel::PixelBuffer Typesetter::CombineImageBuffer( Devel::PixelBuffer topPixelBuffer, Devel::PixelBuffer bottomPixelBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight )
+Devel::PixelBuffer Typesetter::CombineImageBuffer(Devel::PixelBuffer topPixelBuffer, Devel::PixelBuffer bottomPixelBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight)
{
- unsigned char* topBuffer = topPixelBuffer.GetBuffer();
+ unsigned char* topBuffer = topPixelBuffer.GetBuffer();
unsigned char* bottomBuffer = bottomPixelBuffer.GetBuffer();
Devel::PixelBuffer combinedPixelBuffer;
- if ( topBuffer == NULL && bottomBuffer == NULL )
+ if(topBuffer == NULL && bottomBuffer == NULL)
{
// Nothing to do if both buffers are empty.
return combinedPixelBuffer;
}
- if ( topBuffer == NULL )
+ if(topBuffer == NULL)
{
// Nothing to do if topBuffer is empty.
return bottomPixelBuffer;
}
- if ( bottomBuffer == NULL )
+ if(bottomBuffer == NULL)
{
// Nothing to do if bottomBuffer is empty.
return topPixelBuffer;
}
// Always combine two RGBA images
- const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
+ const unsigned int bufferSizeInt = bufferWidth * bufferHeight;
const unsigned int bufferSizeChar = 4u * bufferSizeInt;
- combinedPixelBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 );
- uint8_t* combinedBuffer = reinterpret_cast< uint8_t* >( combinedPixelBuffer.GetBuffer() );
- memset( combinedBuffer, 0u, bufferSizeChar );
+ combinedPixelBuffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, Pixel::RGBA8888);
+ uint8_t* combinedBuffer = reinterpret_cast<uint8_t*>(combinedPixelBuffer.GetBuffer());
+ memset(combinedBuffer, 0u, bufferSizeChar);
- for (unsigned int pixelIndex = 0; pixelIndex < bufferSizeInt; pixelIndex++)
+ for(unsigned int pixelIndex = 0; pixelIndex < bufferSizeInt; pixelIndex++)
{
// If the alpha of the pixel in either buffer is not fully opaque, blend the two pixels.
// Otherwise, copy pixel from topBuffer to combinedBuffer.
- unsigned int alphaBuffer1 = topBuffer[pixelIndex*4+3];
+ unsigned int alphaBuffer1 = topBuffer[pixelIndex * 4 + 3];
- if ( alphaBuffer1 != 255 )
+ if(alphaBuffer1 != 255)
{
// At least one pixel is not fully opaque
// "Over" blend the the pixel from topBuffer with the pixel in bottomBuffer
- combinedBuffer[pixelIndex*4] = topBuffer[pixelIndex*4] + ( bottomBuffer[pixelIndex*4] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
- combinedBuffer[pixelIndex*4+1] = topBuffer[pixelIndex*4+1] + ( bottomBuffer[pixelIndex*4+1] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
- combinedBuffer[pixelIndex*4+2] = topBuffer[pixelIndex*4+2] + ( bottomBuffer[pixelIndex*4+2] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
- combinedBuffer[pixelIndex*4+3] = topBuffer[pixelIndex*4+3] + ( bottomBuffer[pixelIndex*4+3] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 );
+ combinedBuffer[pixelIndex * 4] = topBuffer[pixelIndex * 4] + (bottomBuffer[pixelIndex * 4] * (255 - topBuffer[pixelIndex * 4 + 3]) / 255);
+ combinedBuffer[pixelIndex * 4 + 1] = topBuffer[pixelIndex * 4 + 1] + (bottomBuffer[pixelIndex * 4 + 1] * (255 - topBuffer[pixelIndex * 4 + 3]) / 255);
+ combinedBuffer[pixelIndex * 4 + 2] = topBuffer[pixelIndex * 4 + 2] + (bottomBuffer[pixelIndex * 4 + 2] * (255 - topBuffer[pixelIndex * 4 + 3]) / 255);
+ combinedBuffer[pixelIndex * 4 + 3] = topBuffer[pixelIndex * 4 + 3] + (bottomBuffer[pixelIndex * 4 + 3] * (255 - topBuffer[pixelIndex * 4 + 3]) / 255);
}
else
{
// Copy the pixel from topBuffer to combinedBuffer
- combinedBuffer[pixelIndex*4] = topBuffer[pixelIndex*4];
- combinedBuffer[pixelIndex*4+1] = topBuffer[pixelIndex*4+1];
- combinedBuffer[pixelIndex*4+2] = topBuffer[pixelIndex*4+2];
- combinedBuffer[pixelIndex*4+3] = topBuffer[pixelIndex*4+3];
+ combinedBuffer[pixelIndex * 4] = topBuffer[pixelIndex * 4];
+ combinedBuffer[pixelIndex * 4 + 1] = topBuffer[pixelIndex * 4 + 1];
+ combinedBuffer[pixelIndex * 4 + 2] = topBuffer[pixelIndex * 4 + 2];
+ combinedBuffer[pixelIndex * 4 + 3] = topBuffer[pixelIndex * 4 + 3];
}
}
return combinedPixelBuffer;
}
-Typesetter::Typesetter( const ModelInterface* const model )
-: mModel( new ViewModel( model ) )
+Typesetter::Typesetter(const ModelInterface* const model)
+: mModel(new ViewModel(model))
{
}
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace
{
-
const char* const ENABLE_EXTENSION_PREFIX =
-"#extension GL_OES_standard_derivatives : enable\n"
-"precision highp float;\n"
-"precision highp int;\n";
+ "#extension GL_OES_standard_derivatives : enable\n"
+ "precision highp float;\n"
+ "precision highp int;\n";
const char* const VERTEX_SHADER_MAIN =
-"uniform mediump mat4 uProjection;\n"
-"uniform mediump mat4 uModelView;\n"
-"uniform mediump mat4 uMvpMatrix;\n"
-"uniform bool uTextureMapped;\n"
-"uniform mediump vec4 uCustomTextureCoords;\n"
-"attribute highp vec2 aTexCoord;\n"
-"varying mediump vec2 vTexCoord;\n"
-"uniform mat3 uModelViewIT;\n"
-"attribute mediump vec3 aNormal;\n"
-"varying mediump vec3 vNormal;\n"
-"attribute mediump vec2 aPosition;\n"
-"varying mediump vec4 vVertex;\n"
-"attribute mediump vec4 aColor;\n"
-"varying mediump vec4 vColor;\n"
-"varying vec4 v_glyph;\n"
-"\n"
-"vec4\n"
-"glyph_vertex_transcode (vec2 v)\n"
-"{\n"
-" ivec2 g = ivec2 (v);\n"
-" ivec2 corner = ivec2 (mod (v, 2.));\n"
-" g /= 2;\n"
-" ivec2 nominal_size = ivec2 (mod (vec2(g), 64.));\n"
-" return vec4 (corner * nominal_size, g * 4);\n"
-"}\n"
-"\n"
-"void\n"
-"main()\n"
-"{\n"
-" gl_Position = uMvpMatrix * vec4 (aPosition, 0.0, 1.0);\n"
-" v_glyph = glyph_vertex_transcode (aTexCoord);\n"
-" vColor = aColor;\n"
-"}\n"
-;
+ "uniform mediump mat4 uProjection;\n"
+ "uniform mediump mat4 uModelView;\n"
+ "uniform mediump mat4 uMvpMatrix;\n"
+ "uniform bool uTextureMapped;\n"
+ "uniform mediump vec4 uCustomTextureCoords;\n"
+ "attribute highp vec2 aTexCoord;\n"
+ "varying mediump vec2 vTexCoord;\n"
+ "uniform mat3 uModelViewIT;\n"
+ "attribute mediump vec3 aNormal;\n"
+ "varying mediump vec3 vNormal;\n"
+ "attribute mediump vec2 aPosition;\n"
+ "varying mediump vec4 vVertex;\n"
+ "attribute mediump vec4 aColor;\n"
+ "varying mediump vec4 vColor;\n"
+ "varying vec4 v_glyph;\n"
+ "\n"
+ "vec4\n"
+ "glyph_vertex_transcode (vec2 v)\n"
+ "{\n"
+ " ivec2 g = ivec2 (v);\n"
+ " ivec2 corner = ivec2 (mod (v, 2.));\n"
+ " g /= 2;\n"
+ " ivec2 nominal_size = ivec2 (mod (vec2(g), 64.));\n"
+ " return vec4 (corner * nominal_size, g * 4);\n"
+ "}\n"
+ "\n"
+ "void\n"
+ "main()\n"
+ "{\n"
+ " gl_Position = uMvpMatrix * vec4 (aPosition, 0.0, 1.0);\n"
+ " v_glyph = glyph_vertex_transcode (aTexCoord);\n"
+ " vColor = aColor;\n"
+ "}\n";
const char* const FRAGMENT_SHADER_PREFIX =
-"struct Material\n"
-"{\n"
-" mediump float mOpacity;\n"
-" mediump float mShininess;\n"
-" lowp vec4 mAmbient;\n"
-" lowp vec4 mDiffuse;\n"
-" lowp vec4 mSpecular;\n"
-" lowp vec4 mEmissive;\n"
-"};\n"
-"uniform sampler2D sTexture;\n"
-"uniform sampler2D sOpacityTexture;\n"
-"uniform sampler2D sNormalMapTexture;\n"
-"uniform sampler2D sEffect;\n"
-"varying mediump vec2 vTexCoord;\n"
-"uniform Material uMaterial;\n"
-"uniform lowp vec4 uColor;\n"
-"varying highp vec4 vVertex;\n"
-"varying highp vec3 vNormal;\n"
-"varying mediump vec4 vColor;\n"
-"uniform vec4 u_atlas_info;\n"
-"\n"
-"#define GLYPHY_TEXTURE1D_EXTRA_DECLS , sampler2D _tex, ivec4 _atlas_info, ivec2 _atlas_pos\n"
-"#define GLYPHY_TEXTURE1D_EXTRA_ARGS , _tex, _atlas_info, _atlas_pos\n"
-"#define GLYPHY_DEMO_EXTRA_ARGS , sTexture, uu_atlas_info, gi.atlas_pos\n"
-"\n"
-"vec4\n"
-"glyphy_texture1D_func (int offset GLYPHY_TEXTURE1D_EXTRA_DECLS)\n"
-"{\n"
-" ivec2 item_geom = _atlas_info.zw;\n"
-" vec2 pos = (vec2 (_atlas_pos.xy * item_geom +\n"
-" ivec2 (mod (float (offset), float (item_geom.x)), offset / item_geom.x)) +\n"
-" + vec2 (.5, .5)) / vec2(_atlas_info.xy);\n"
-" return texture2D (_tex, pos);\n"
-"}\n"
-;
+ "struct Material\n"
+ "{\n"
+ " mediump float mOpacity;\n"
+ " mediump float mShininess;\n"
+ " lowp vec4 mAmbient;\n"
+ " lowp vec4 mDiffuse;\n"
+ " lowp vec4 mSpecular;\n"
+ " lowp vec4 mEmissive;\n"
+ "};\n"
+ "uniform sampler2D sTexture;\n"
+ "uniform sampler2D sOpacityTexture;\n"
+ "uniform sampler2D sNormalMapTexture;\n"
+ "uniform sampler2D sEffect;\n"
+ "varying mediump vec2 vTexCoord;\n"
+ "uniform Material uMaterial;\n"
+ "uniform lowp vec4 uColor;\n"
+ "varying highp vec4 vVertex;\n"
+ "varying highp vec3 vNormal;\n"
+ "varying mediump vec4 vColor;\n"
+ "uniform vec4 u_atlas_info;\n"
+ "\n"
+ "#define GLYPHY_TEXTURE1D_EXTRA_DECLS , sampler2D _tex, ivec4 _atlas_info, ivec2 _atlas_pos\n"
+ "#define GLYPHY_TEXTURE1D_EXTRA_ARGS , _tex, _atlas_info, _atlas_pos\n"
+ "#define GLYPHY_DEMO_EXTRA_ARGS , sTexture, uu_atlas_info, gi.atlas_pos\n"
+ "\n"
+ "vec4\n"
+ "glyphy_texture1D_func (int offset GLYPHY_TEXTURE1D_EXTRA_DECLS)\n"
+ "{\n"
+ " ivec2 item_geom = _atlas_info.zw;\n"
+ " vec2 pos = (vec2 (_atlas_pos.xy * item_geom +\n"
+ " ivec2 (mod (float (offset), float (item_geom.x)), offset / item_geom.x)) +\n"
+ " + vec2 (.5, .5)) / vec2(_atlas_info.xy);\n"
+ " return texture2D (_tex, pos);\n"
+ "}\n";
static const char* FRAGMENT_SHADER_MAIN =
-"uniform float u_contrast;\n"
-"uniform float u_gamma_adjust;\n"
-"uniform float u_outline_thickness;\n"
-"uniform float u_outline;\n"
-"uniform float u_boldness;\n"
-"\n"
-"varying vec4 v_glyph;\n"
-"\n"
-"\n"
-"#define SQRT2_2 0.70711 /* 1 / sqrt(2.) */\n"
-"#define SQRT2 1.41421\n"
-"\n"
-"struct glyph_info_t {\n"
-" ivec2 nominal_size;\n"
-" ivec2 atlas_pos;\n"
-"};\n"
-"\n"
-"glyph_info_t\n"
-"glyph_info_decode (vec4 v)\n"
-"{\n"
-" glyph_info_t gi;\n"
-" gi.nominal_size = (ivec2 (mod (v.zw, 256.)) + 2) / 4;\n"
-" gi.atlas_pos = ivec2 (v_glyph.zw) / 256;\n"
-" return gi;\n"
-"}\n"
-"\n"
-"\n"
-"float\n"
-"antialias (float d)\n"
-"{\n"
-" return smoothstep (-.75, +.75, d);\n"
-"}\n"
-"\n"
-"vec4\n"
-"source_over (const vec4 src, const vec4 dst)\n"
-"{\n"
-" // http://dev.w3.org/fxtf/compositing-1/#porterduffcompositingoperators_srcover\n"
-" float alpha = src.a + (dst.a * (1. - src.a));\n"
-" return vec4 (((src.rgb * src.a) + (dst.rgb * dst.a * (1. - src.a))) / alpha, alpha);\n"
-"}\n"
-"\n"
-"void\n"
-"main()\n"
-"{\n"
-" vec2 p = v_glyph.xy;\n"
-" glyph_info_t gi = glyph_info_decode (v_glyph);\n"
-"\n"
-" /* isotropic antialiasing */\n"
-" vec2 dpdx = dFdx (p);\n"
-" vec2 dpdy = dFdy (p);\n"
-" float m = length (vec2 (length (dpdx), length (dpdy))) * SQRT2_2;\n"
-"\n"
-" vec4 color = vec4( vColor.rgb * uColor.rgb, vColor.a * uColor.a );\n"
-"\n"
-" ivec4 uu_atlas_info = ivec4( u_atlas_info );"
-" float gsdist = glyphy_sdf (p, gi.nominal_size GLYPHY_DEMO_EXTRA_ARGS);\n"
-" float sdist = gsdist / m * u_contrast;\n"
-"\n"
-" sdist -= u_boldness * 10.;\n"
-" if ( glyphy_iszero( u_outline ) )\n"
-" sdist = abs (sdist) - u_outline_thickness * .5;\n"
-" if (sdist > 1.)\n"
-" discard;\n"
-" float alpha = antialias (-sdist);\n"
-" if (u_gamma_adjust != 1.)\n"
-" alpha = pow (alpha, 1./u_gamma_adjust);\n"
-" color = vec4 (color.rgb,color.a * alpha);\n"
-"\n"
-" gl_FragColor = color;\n"
-"}\n"
-;
+ "uniform float u_contrast;\n"
+ "uniform float u_gamma_adjust;\n"
+ "uniform float u_outline_thickness;\n"
+ "uniform float u_outline;\n"
+ "uniform float u_boldness;\n"
+ "\n"
+ "varying vec4 v_glyph;\n"
+ "\n"
+ "\n"
+ "#define SQRT2_2 0.70711 /* 1 / sqrt(2.) */\n"
+ "#define SQRT2 1.41421\n"
+ "\n"
+ "struct glyph_info_t {\n"
+ " ivec2 nominal_size;\n"
+ " ivec2 atlas_pos;\n"
+ "};\n"
+ "\n"
+ "glyph_info_t\n"
+ "glyph_info_decode (vec4 v)\n"
+ "{\n"
+ " glyph_info_t gi;\n"
+ " gi.nominal_size = (ivec2 (mod (v.zw, 256.)) + 2) / 4;\n"
+ " gi.atlas_pos = ivec2 (v_glyph.zw) / 256;\n"
+ " return gi;\n"
+ "}\n"
+ "\n"
+ "\n"
+ "float\n"
+ "antialias (float d)\n"
+ "{\n"
+ " return smoothstep (-.75, +.75, d);\n"
+ "}\n"
+ "\n"
+ "vec4\n"
+ "source_over (const vec4 src, const vec4 dst)\n"
+ "{\n"
+ " // http://dev.w3.org/fxtf/compositing-1/#porterduffcompositingoperators_srcover\n"
+ " float alpha = src.a + (dst.a * (1. - src.a));\n"
+ " return vec4 (((src.rgb * src.a) + (dst.rgb * dst.a * (1. - src.a))) / alpha, alpha);\n"
+ "}\n"
+ "\n"
+ "void\n"
+ "main()\n"
+ "{\n"
+ " vec2 p = v_glyph.xy;\n"
+ " glyph_info_t gi = glyph_info_decode (v_glyph);\n"
+ "\n"
+ " /* isotropic antialiasing */\n"
+ " vec2 dpdx = dFdx (p);\n"
+ " vec2 dpdy = dFdy (p);\n"
+ " float m = length (vec2 (length (dpdx), length (dpdy))) * SQRT2_2;\n"
+ "\n"
+ " vec4 color = vec4( vColor.rgb * uColor.rgb, vColor.a * uColor.a );\n"
+ "\n"
+ " ivec4 uu_atlas_info = ivec4( u_atlas_info );"
+ " float gsdist = glyphy_sdf (p, gi.nominal_size GLYPHY_DEMO_EXTRA_ARGS);\n"
+ " float sdist = gsdist / m * u_contrast;\n"
+ "\n"
+ " sdist -= u_boldness * 10.;\n"
+ " if ( glyphy_iszero( u_outline ) )\n"
+ " sdist = abs (sdist) - u_outline_thickness * .5;\n"
+ " if (sdist > 1.)\n"
+ " discard;\n"
+ " float alpha = antialias (-sdist);\n"
+ " if (u_gamma_adjust != 1.)\n"
+ " alpha = pow (alpha, 1./u_gamma_adjust);\n"
+ " color = vec4 (color.rgb,color.a * alpha);\n"
+ "\n"
+ " gl_FragColor = color;\n"
+ "}\n";
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
GlyphyShader::GlyphyShader()
{
}
-GlyphyShader::GlyphyShader( Shader handle )
-: Shader( handle )
+GlyphyShader::GlyphyShader(Shader handle)
+: Shader(handle)
{
}
{
}
-GlyphyShader GlyphyShader::New( const Dali::Vector4& atlasInfo )
+GlyphyShader GlyphyShader::New(const Dali::Vector4& atlasInfo)
{
std::ostringstream vertexShaderStringStream;
std::ostringstream fragmentShaderStringStream;
<< glyphy_sdf_glsl
<< FRAGMENT_SHADER_MAIN;
- Shader shaderEffectCustom = Shader::New( vertexShaderStringStream.str(),
- fragmentShaderStringStream.str(),
- Shader::Hint::OUTPUT_IS_TRANSPARENT );
+ Shader shaderEffectCustom = Shader::New(vertexShaderStringStream.str(),
+ fragmentShaderStringStream.str(),
+ Shader::Hint::OUTPUT_IS_TRANSPARENT);
- GlyphyShader handle( shaderEffectCustom );
+ GlyphyShader handle(shaderEffectCustom);
- handle.RegisterProperty( "u_atlas_info", atlasInfo );
- handle.RegisterProperty( "u_contrast", 1.f );
- handle.RegisterProperty( "u_gamma_adjust", 1.f );
- handle.RegisterProperty( "u_outline_thickness", 1.f );
- handle.RegisterProperty( "u_outline", 1.f );
- handle.RegisterProperty( "u_boldness", 0.f );
+ handle.RegisterProperty("u_atlas_info", atlasInfo);
+ handle.RegisterProperty("u_contrast", 1.f);
+ handle.RegisterProperty("u_gamma_adjust", 1.f);
+ handle.RegisterProperty("u_outline_thickness", 1.f);
+ handle.RegisterProperty("u_outline", 1.f);
+ handle.RegisterProperty("u_boldness", 0.f);
return handle;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/rendering/vector-based/vector-based-renderer.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/rendering/geometry.h>
-#include <dali/public-api/rendering/renderer.h>
#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/rendering/geometry.h>
+#include <dali/public-api/rendering/renderer.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/glyph-run.h>
-#include <dali-toolkit/internal/text/text-view.h>
#include <dali-toolkit/internal/text/rendering/vector-based/glyphy-shader/glyphy-shader.h>
-#include <dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.h>
#include <dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas-share.h>
+#include <dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.h>
+#include <dali-toolkit/internal/text/text-view.h>
using namespace Dali;
using namespace Dali::Toolkit;
namespace
{
-
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
#endif
const float DEFAULT_POINT_SIZE = 13.f;
struct Vertex2D
{
- float x;
- float y;
- float u;
- float v;
+ float x;
+ float y;
+ float u;
+ float v;
Vector4 color;
};
-void AddVertex( Vector<Vertex2D>& vertices, float x, float y, float u, float v, const Vector4& color )
+void AddVertex(Vector<Vertex2D>& vertices, float x, float y, float u, float v, const Vector4& color)
{
Vertex2D meshVertex;
- meshVertex.x = x;
- meshVertex.y = y;
- meshVertex.u = u;
- meshVertex.v = v;
+ meshVertex.x = x;
+ meshVertex.y = y;
+ meshVertex.u = u;
+ meshVertex.v = v;
meshVertex.color = color;
- vertices.PushBack( meshVertex );
+ vertices.PushBack(meshVertex);
}
-void AddTriangle( Vector<unsigned short>& indices, unsigned int v0, unsigned int v1, unsigned int v2 )
+void AddTriangle(Vector<unsigned short>& indices, unsigned int v0, unsigned int v1, unsigned int v2)
{
- indices.PushBack( v0 );
- indices.PushBack( v1 );
- indices.PushBack( v2 );
+ indices.PushBack(v0);
+ indices.PushBack(v1);
+ indices.PushBack(v2);
}
-bool CreateGeometry( const Vector<GlyphInfo>& glyphs,
- unsigned int numberOfGlyphs,
- const Vector<Vector2>& positions,
- float xOffset,
- float yOffset,
- VectorBlobAtlas& atlas,
- Dali::TextAbstraction::FontClient& fontClient,
- Vector< Vertex2D >& vertices,
- Vector< unsigned short >& indices,
- const Vector4* const colorsBuffer,
- const ColorIndex* const colorIndicesBuffer,
- const Vector4& defaultColor )
+bool CreateGeometry(const Vector<GlyphInfo>& glyphs,
+ unsigned int numberOfGlyphs,
+ const Vector<Vector2>& positions,
+ float xOffset,
+ float yOffset,
+ VectorBlobAtlas& atlas,
+ Dali::TextAbstraction::FontClient& fontClient,
+ Vector<Vertex2D>& vertices,
+ Vector<unsigned short>& indices,
+ const Vector4* const colorsBuffer,
+ const ColorIndex* const colorIndicesBuffer,
+ const Vector4& defaultColor)
{
// Whether the default color is used.
- const bool useDefaultColor = ( NULL == colorsBuffer );
+ const bool useDefaultColor = (NULL == colorsBuffer);
- bool atlasFull( false );
+ bool atlasFull(false);
- for( unsigned int i=0, idx=0; i<numberOfGlyphs && !atlasFull; ++i )
+ for(unsigned int i = 0, idx = 0; i < numberOfGlyphs && !atlasFull; ++i)
{
- if( glyphs[i].width > 0 &&
- glyphs[i].height > 0 )
+ if(glyphs[i].width > 0 &&
+ glyphs[i].height > 0)
{
- bool foundBlob( true );
+ bool foundBlob(true);
BlobCoordinate blobCoords[4];
- if( ! atlas.FindGlyph( glyphs[i].fontId, glyphs[i].index, blobCoords ) )
+ if(!atlas.FindGlyph(glyphs[i].fontId, glyphs[i].index, blobCoords))
{
// Add blob to atlas
- VectorBlob* blob( NULL );
- unsigned int blobLength( 0 );
- unsigned int nominalWidth( 0 );
- unsigned int nominalHeight( 0 );
- fontClient.CreateVectorBlob( glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight );
+ VectorBlob* blob(NULL);
+ unsigned int blobLength(0);
+ unsigned int nominalWidth(0);
+ unsigned int nominalHeight(0);
+ fontClient.CreateVectorBlob(glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight);
- if( 0 != blobLength )
+ if(0 != blobLength)
{
- bool glyphAdded = atlas.AddGlyph( glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight, blobCoords );
+ bool glyphAdded = atlas.AddGlyph(glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight, blobCoords);
foundBlob = glyphAdded;
atlasFull = !glyphAdded;
}
}
- if( foundBlob )
+ if(foundBlob)
{
// Get the color of the character.
- const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndicesBuffer + i );
- const Vector4& color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + colorIndex - 1u );
-
- const float x1( xOffset + positions[i].x );
- const float x2( xOffset + positions[i].x + glyphs[i].width );
- const float y1( yOffset + positions[i].y );
- const float y2( yOffset + positions[i].y + glyphs[i].height );
-
- AddVertex( vertices, x1, y2, blobCoords[0].u, blobCoords[0].v, color );
- AddVertex( vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color );
- AddVertex( vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color );
- AddTriangle( indices, idx, idx+1, idx+2 );
- idx+=3;
-
- AddVertex( vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color );
- AddVertex( vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color );
- AddVertex( vertices, x2, y1, blobCoords[3].u, blobCoords[3].v, color );
- AddTriangle( indices, idx, idx+1, idx+2 );
- idx+=3;
+ const ColorIndex colorIndex = useDefaultColor ? 0u : *(colorIndicesBuffer + i);
+ const Vector4& color = (useDefaultColor || (0u == colorIndex)) ? defaultColor : *(colorsBuffer + colorIndex - 1u);
+
+ const float x1(xOffset + positions[i].x);
+ const float x2(xOffset + positions[i].x + glyphs[i].width);
+ const float y1(yOffset + positions[i].y);
+ const float y2(yOffset + positions[i].y + glyphs[i].height);
+
+ AddVertex(vertices, x1, y2, blobCoords[0].u, blobCoords[0].v, color);
+ AddVertex(vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color);
+ AddVertex(vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color);
+ AddTriangle(indices, idx, idx + 1, idx + 2);
+ idx += 3;
+
+ AddVertex(vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color);
+ AddVertex(vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color);
+ AddVertex(vertices, x2, y1, blobCoords[3].u, blobCoords[3].v, color);
+ AddTriangle(indices, idx, idx + 1, idx + 2);
+ idx += 3;
}
}
}
{
mFontClient = TextAbstraction::FontClient::Get();
- mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
- mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2;
- mQuadVertexFormat[ "aColor" ] = Property::VECTOR4;
+ mQuadVertexFormat["aPosition"] = Property::VECTOR2;
+ mQuadVertexFormat["aTexCoord"] = Property::VECTOR2;
+ mQuadVertexFormat["aColor"] = Property::VECTOR4;
}
- Actor mActor; ///< The actor parent which renders the text
+ Actor mActor; ///< The actor parent which renders the text
TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
- Property::Map mQuadVertexFormat; ///> Describes the vertex format for text
+ Property::Map mQuadVertexFormat; ///> Describes the vertex format for text
Shader mShaderEffect;
Text::RendererPtr VectorBasedRenderer::New()
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::VectorBasedRenderer::New()\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::VectorBasedRenderer::New()\n");
- return Text::RendererPtr( new VectorBasedRenderer() );
+ return Text::RendererPtr(new VectorBasedRenderer());
}
-Actor VectorBasedRenderer::Render( Text::ViewInterface& view,
- Actor textControl,
- Property::Index animatablePropertyIndex,
- float& alignmentOffset,
- int /*depth*/ )
+Actor VectorBasedRenderer::Render(Text::ViewInterface& view,
+ Actor textControl,
+ Property::Index animatablePropertyIndex,
+ float& alignmentOffset,
+ int /*depth*/)
{
- UnparentAndReset( mImpl->mActor );
+ UnparentAndReset(mImpl->mActor);
mImpl->mActor = Actor::New();
- mImpl->mActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mImpl->mActor.SetProperty( Actor::Property::SIZE, Vector2( view.GetControlSize() ) );
- mImpl->mActor.SetProperty( Actor::Property::COLOR, Color::WHITE );
+ mImpl->mActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mImpl->mActor.SetProperty(Actor::Property::SIZE, Vector2(view.GetControlSize()));
+ mImpl->mActor.SetProperty(Actor::Property::COLOR, Color::WHITE);
#if defined(DEBUG_ENABLED)
- mImpl->mActor.SetProperty( Dali::Actor::Property::NAME, "Text renderable actor" );
+ mImpl->mActor.SetProperty(Dali::Actor::Property::NAME, "Text renderable actor");
#endif
Length numberOfGlyphs = view.GetNumberOfGlyphs();
- if( numberOfGlyphs > 0u )
+ if(numberOfGlyphs > 0u)
{
Vector<GlyphInfo> glyphs;
- glyphs.Resize( numberOfGlyphs );
+ glyphs.Resize(numberOfGlyphs);
Vector<Vector2> positions;
- positions.Resize( numberOfGlyphs );
+ positions.Resize(numberOfGlyphs);
- numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
- positions.Begin(),
- alignmentOffset,
- 0u,
- numberOfGlyphs );
+ numberOfGlyphs = view.GetGlyphs(glyphs.Begin(),
+ positions.Begin(),
+ alignmentOffset,
+ 0u,
+ numberOfGlyphs);
- glyphs.Resize( numberOfGlyphs );
- positions.Resize( numberOfGlyphs );
+ glyphs.Resize(numberOfGlyphs);
+ positions.Resize(numberOfGlyphs);
- const Vector4* const colorsBuffer = view.GetColors();
+ const Vector4* const colorsBuffer = view.GetColors();
const ColorIndex* const colorIndicesBuffer = view.GetColorIndices();
- const Vector4& defaultColor = view.GetTextColor();
+ const Vector4& defaultColor = view.GetTextColor();
- Vector< Vertex2D > vertices;
- Vector< unsigned short > indices;
+ Vector<Vertex2D> vertices;
+ Vector<unsigned short> indices;
const Vector2& controlSize = view.GetControlSize();
- float xOffset = -alignmentOffset + controlSize.width * -0.5f;
- float yOffset = controlSize.height * -0.5f;
+ float xOffset = -alignmentOffset + controlSize.width * -0.5f;
+ float yOffset = controlSize.height * -0.5f;
- if( ! mImpl->mAtlas ||
- mImpl->mAtlas->IsFull() )
+ if(!mImpl->mAtlas ||
+ mImpl->mAtlas->IsFull())
{
VectorBlobAtlasShare atlasShare = VectorBlobAtlasShare::Get();
- mImpl->mAtlas = atlasShare.GetCurrentAtlas();
+ mImpl->mAtlas = atlasShare.GetCurrentAtlas();
}
// First try adding the glyphs to the previous shared atlas
- bool allGlyphsAdded = CreateGeometry( glyphs,
- numberOfGlyphs,
- positions,
- xOffset,
- yOffset,
- *mImpl->mAtlas,
- mImpl->mFontClient,
- vertices,
- indices,
- colorsBuffer,
- colorIndicesBuffer,
- defaultColor );
-
- if( ! allGlyphsAdded )
+ bool allGlyphsAdded = CreateGeometry(glyphs,
+ numberOfGlyphs,
+ positions,
+ xOffset,
+ yOffset,
+ *mImpl->mAtlas,
+ mImpl->mFontClient,
+ vertices,
+ indices,
+ colorsBuffer,
+ colorIndicesBuffer,
+ defaultColor);
+
+ if(!allGlyphsAdded)
{
// The current atlas is full, abandon it and use a new one
mImpl->mAtlas.Reset();
indices.Clear();
VectorBlobAtlasShare atlasShare = VectorBlobAtlasShare::Get();
- mImpl->mAtlas = atlasShare.GetNewAtlas();
-
- CreateGeometry( glyphs,
- numberOfGlyphs,
- positions,
- xOffset,
- yOffset,
- *mImpl->mAtlas,
- mImpl->mFontClient,
- vertices,
- indices,
- colorsBuffer,
- colorIndicesBuffer,
- defaultColor );
+ mImpl->mAtlas = atlasShare.GetNewAtlas();
+
+ CreateGeometry(glyphs,
+ numberOfGlyphs,
+ positions,
+ xOffset,
+ yOffset,
+ *mImpl->mAtlas,
+ mImpl->mFontClient,
+ vertices,
+ indices,
+ colorsBuffer,
+ colorIndicesBuffer,
+ defaultColor);
// Return value ignored; using more than an entire new atlas is not supported
}
- if( 0 != vertices.Count() )
+ if(0 != vertices.Count())
{
- VertexBuffer quadVertices = VertexBuffer::New( mImpl->mQuadVertexFormat );
-
- quadVertices.SetData( &vertices[ 0 ], vertices.Size() );
+ VertexBuffer quadVertices = VertexBuffer::New(mImpl->mQuadVertexFormat);
+ quadVertices.SetData(&vertices[0], vertices.Size());
Geometry quadGeometry = Geometry::New();
- quadGeometry.AddVertexBuffer( quadVertices );
- quadGeometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
+ quadGeometry.AddVertexBuffer(quadVertices);
+ quadGeometry.SetIndexBuffer(&indices[0], indices.Size());
TextureSet texture = mImpl->mAtlas->GetTextureSet();
const Vector4 atlasInfo = mImpl->mAtlas->GetInfo();
- mImpl->mShaderEffect = GlyphyShader::New( atlasInfo );
+ mImpl->mShaderEffect = GlyphyShader::New(atlasInfo);
- Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, mImpl->mShaderEffect );
- renderer.SetTextures( texture );
- mImpl->mActor.AddRenderer( renderer );
+ Dali::Renderer renderer = Dali::Renderer::New(quadGeometry, mImpl->mShaderEffect);
+ renderer.SetTextures(texture);
+ mImpl->mActor.AddRenderer(renderer);
}
}
- /*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas-share.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/object/base-object.h>
#include <dali/devel-api/common/singleton-service.h>
+#include <dali/public-api/object/base-object.h>
namespace
{
-
-const int INITIAL_VECTOR_BLOB_ATLAS_WIDTH = 512;
+const int INITIAL_VECTOR_BLOB_ATLAS_WIDTH = 512;
const int INITIAL_VECTOR_BLOB_ATLAS_HEIGHT = 512;
-const int NEW_VECTOR_BLOB_ATLAS_WIDTH = 1024;
+const int NEW_VECTOR_BLOB_ATLAS_WIDTH = 1024;
const int NEW_VECTOR_BLOB_ATLAS_HEIGHT = 1024;
-const int VECTOR_BLOB_ATLAS_ITEM_WIDTH = 64;
+const int VECTOR_BLOB_ATLAS_ITEM_WIDTH = 64;
const int VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM = 8;
} // unnamed namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
class VectorBlobAtlasShare::Impl : public Dali::BaseObject
{
public:
-
/**
* @brief Constructor
*/
VectorBlobAtlas* GetCurrentAtlas()
{
- if( ! mCurrentAtlas )
+ if(!mCurrentAtlas)
{
- mCurrentAtlas = new VectorBlobAtlas( INITIAL_VECTOR_BLOB_ATLAS_WIDTH, INITIAL_VECTOR_BLOB_ATLAS_HEIGHT, VECTOR_BLOB_ATLAS_ITEM_WIDTH, VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM );
+ mCurrentAtlas = new VectorBlobAtlas(INITIAL_VECTOR_BLOB_ATLAS_WIDTH, INITIAL_VECTOR_BLOB_ATLAS_HEIGHT, VECTOR_BLOB_ATLAS_ITEM_WIDTH, VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM);
}
return mCurrentAtlas.Get();
VectorBlobAtlas* GetNewAtlas()
{
// The current atlas should have been filled, before asking for a new one
- DALI_ASSERT_DEBUG( mCurrentAtlas->IsFull() && "Current atlas is not full yet" );
+ DALI_ASSERT_DEBUG(mCurrentAtlas->IsFull() && "Current atlas is not full yet");
- mCurrentAtlas = new VectorBlobAtlas( NEW_VECTOR_BLOB_ATLAS_WIDTH, NEW_VECTOR_BLOB_ATLAS_HEIGHT, VECTOR_BLOB_ATLAS_ITEM_WIDTH, VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM );
+ mCurrentAtlas = new VectorBlobAtlas(NEW_VECTOR_BLOB_ATLAS_WIDTH, NEW_VECTOR_BLOB_ATLAS_HEIGHT, VECTOR_BLOB_ATLAS_ITEM_WIDTH, VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM);
return mCurrentAtlas.Get();
}
protected:
-
/**
* A reference counted object may only be deleted by calling Unreference()
*/
}
private:
-
IntrusivePtr<VectorBlobAtlas> mCurrentAtlas;
};
VectorBlobAtlasShare manager;
// Check whether the VectorBlobAtlasShare is already created
- SingletonService singletonService( SingletonService::Get() );
- if ( singletonService )
+ SingletonService singletonService(SingletonService::Get());
+ if(singletonService)
{
- Dali::BaseHandle handle = singletonService.GetSingleton( typeid( VectorBlobAtlasShare ) );
- if( handle )
+ Dali::BaseHandle handle = singletonService.GetSingleton(typeid(VectorBlobAtlasShare));
+ if(handle)
{
// If so, downcast the handle of singleton to VectorBlobAtlasShare
- manager = VectorBlobAtlasShare( dynamic_cast<VectorBlobAtlasShare::Impl*>( handle.GetObjectPtr() ) );
+ manager = VectorBlobAtlasShare(dynamic_cast<VectorBlobAtlasShare::Impl*>(handle.GetObjectPtr()));
}
- if( !manager )
+ if(!manager)
{
// If not, create the VectorBlobAtlasShare and register it as a singleton
- manager = VectorBlobAtlasShare( new VectorBlobAtlasShare::Impl() );
- singletonService.Register( typeid( manager ), manager );
+ manager = VectorBlobAtlasShare(new VectorBlobAtlasShare::Impl());
+ singletonService.Register(typeid(manager), manager);
}
}
return manager;
}
-VectorBlobAtlasShare::VectorBlobAtlasShare( VectorBlobAtlasShare::Impl* impl )
-: BaseHandle( impl )
+VectorBlobAtlasShare::VectorBlobAtlasShare(VectorBlobAtlasShare::Impl* impl)
+: BaseHandle(impl)
{
}
VectorBlobAtlas* VectorBlobAtlasShare::GetCurrentAtlas()
{
- VectorBlobAtlasShare::Impl& impl = static_cast<VectorBlobAtlasShare::Impl&>( GetBaseObject() );
+ VectorBlobAtlasShare::Impl& impl = static_cast<VectorBlobAtlasShare::Impl&>(GetBaseObject());
return impl.GetCurrentAtlas();
}
VectorBlobAtlas* VectorBlobAtlasShare::GetNewAtlas()
{
- VectorBlobAtlasShare::Impl& impl = static_cast<VectorBlobAtlasShare::Impl&>( GetBaseObject() );
+ VectorBlobAtlasShare::Impl& impl = static_cast<VectorBlobAtlasShare::Impl&>(GetBaseObject());
return impl.GetNewAtlas();
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace
{
-
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
#endif
-}
+} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
static void
-EncodeBlobCoordinate( unsigned int cornerX, unsigned int cornerY,
- unsigned int atlasX, unsigned int atlasY,
- unsigned int nominalWidth, unsigned int nominalHeight,
- BlobCoordinate* v )
+EncodeBlobCoordinate(unsigned int cornerX, unsigned int cornerY, unsigned int atlasX, unsigned int atlasY, unsigned int nominalWidth, unsigned int nominalHeight, BlobCoordinate* v)
{
DALI_ASSERT_DEBUG(0 == (atlasX & ~0x7F));
DALI_ASSERT_DEBUG(0 == (atlasY & ~0x7F));
DALI_ASSERT_DEBUG(0 == (nominalWidth & ~0x3F));
DALI_ASSERT_DEBUG(0 == (nominalHeight & ~0x3F));
- unsigned int x = (((atlasX << 6) | nominalWidth) << 1) | cornerX;
+ unsigned int x = (((atlasX << 6) | nominalWidth) << 1) | cornerX;
unsigned int y = (((atlasY << 6) | nominalHeight) << 1) | cornerY;
unsigned int encoded = (x << 16) | y;
v->v = encoded & 0xFFFF;
}
-VectorBlobAtlas::VectorBlobAtlas( unsigned int textureWidth,
- unsigned int textureHeight,
- unsigned int itemWidth,
- unsigned int itemHeightQuantum )
-: mTextureWidth( textureWidth ),
- mTextureHeight( textureHeight ),
- mItemWidth( itemWidth ),
- mItemHeightQuantum( itemHeightQuantum ),
- mCursorX( 0 ),
- mCursorY( 0 ),
- mIsFull( false )
+VectorBlobAtlas::VectorBlobAtlas(unsigned int textureWidth,
+ unsigned int textureHeight,
+ unsigned int itemWidth,
+ unsigned int itemHeightQuantum)
+: mTextureWidth(textureWidth),
+ mTextureHeight(textureHeight),
+ mItemWidth(itemWidth),
+ mItemHeightQuantum(itemHeightQuantum),
+ mCursorX(0),
+ mCursorY(0),
+ mIsFull(false)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Blob atlas %p size %dx%d, item width %d, height quantum %d\n", this, textureWidth, textureHeight, itemWidth, itemHeightQuantum );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p size %dx%d, item width %d, height quantum %d\n", this, textureWidth, textureHeight, itemWidth, itemHeightQuantum);
- mAtlasTexture = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, textureWidth, textureHeight );
+ mAtlasTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, textureWidth, textureHeight);
mTextureSet = TextureSet::New();
mTextureSet.SetTexture(0, mAtlasTexture);
return mIsFull;
}
-bool VectorBlobAtlas::FindGlyph( FontId fontId,
- GlyphIndex glyphIndex,
- BlobCoordinate* coords )
+bool VectorBlobAtlas::FindGlyph(FontId fontId,
+ GlyphIndex glyphIndex,
+ BlobCoordinate* coords)
{
- const unsigned int size( mItemLookup.size() );
+ const unsigned int size(mItemLookup.size());
- for( unsigned int i=0; i<size; ++i )
+ for(unsigned int i = 0; i < size; ++i)
{
- if( mItemLookup[i].fontId == fontId &&
- mItemLookup[i].glyphIndex == glyphIndex )
+ if(mItemLookup[i].fontId == fontId &&
+ mItemLookup[i].glyphIndex == glyphIndex)
{
- const Item& item = mItemCache[ mItemLookup[i].cacheIndex ];
+ const Item& item = mItemCache[mItemLookup[i].cacheIndex];
coords[0] = item.coords[0];
coords[1] = item.coords[1];
return false;
}
-bool VectorBlobAtlas::AddGlyph( unsigned int fontId,
- unsigned int glyphIndex,
- VectorBlob* blob,
- unsigned int length,
- unsigned int nominalWidth,
- unsigned int nominalHeight,
- BlobCoordinate* coords )
+bool VectorBlobAtlas::AddGlyph(unsigned int fontId,
+ unsigned int glyphIndex,
+ VectorBlob* blob,
+ unsigned int length,
+ unsigned int nominalWidth,
+ unsigned int nominalHeight,
+ BlobCoordinate* coords)
{
- if( mIsFull )
+ if(mIsFull)
{
return false;
}
w = mItemWidth;
h = (length + w - 1) / w;
- if( mCursorY + h > mTextureHeight )
+ if(mCursorY + h > mTextureHeight)
{
// Go to next column
mCursorX += mItemWidth;
mCursorY = 0;
}
- if( mCursorX + w <= mTextureWidth && mCursorY + h <= mTextureHeight )
+ if(mCursorX + w <= mTextureWidth && mCursorY + h <= mTextureHeight)
{
x = mCursorX;
y = mCursorY;
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Blob atlas %p is now FULL\n", this );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p is now FULL\n", this);
// The atlas is now considered to be full
mIsFull = true;
return false;
}
- if (w * h == length)
+ if(w * h == length)
{
- TexSubImage( x, y, w, h, blob );
+ TexSubImage(x, y, w, h, blob);
}
else
{
- TexSubImage( x, y, w, h-1, blob );
+ TexSubImage(x, y, w, h - 1, blob);
// Upload the last row separately
- TexSubImage( x, y + h - 1, length - (w * (h - 1)), 1 , blob + w * (h - 1));
+ TexSubImage(x, y + h - 1, length - (w * (h - 1)), 1, blob + w * (h - 1));
}
- DALI_LOG_INFO( gLogFilter, Debug::General, "Blob atlas %p capacity %d filled %d %f\%\n",
- this,
- mTextureWidth*mTextureHeight,
- mCursorY*mItemWidth + mCursorX*mTextureHeight,
- 100.0f * (float)(mCursorY*mItemWidth + mCursorX*mTextureHeight) / (float)(mTextureWidth*mTextureHeight) );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p capacity %d filled %d %f\%\n", this, mTextureWidth * mTextureHeight, mCursorY * mItemWidth + mCursorX * mTextureHeight, 100.0f * (float)(mCursorY * mItemWidth + mCursorX * mTextureHeight) / (float)(mTextureWidth * mTextureHeight));
Key key;
- key.fontId = fontId;
+ key.fontId = fontId;
key.glyphIndex = glyphIndex;
key.cacheIndex = mItemCache.size();
- mItemLookup.push_back( key );
+ mItemLookup.push_back(key);
x /= mItemWidth;
y /= mItemHeightQuantum;
Item item;
- EncodeBlobCoordinate( 0, 0, x, y, nominalWidth, nominalHeight, &item.coords[0] ); // BOTTOM_LEFT
- EncodeBlobCoordinate( 0, 1, x, y, nominalWidth, nominalHeight, &item.coords[1] ); // TOP_LEFT
- EncodeBlobCoordinate( 1, 0, x, y, nominalWidth, nominalHeight, &item.coords[2] ); // BOTTOM_RIGHT
- EncodeBlobCoordinate( 1, 1, x, y, nominalWidth, nominalHeight, &item.coords[3] ); // TOP_RIGHT
- mItemCache.push_back( item );
+ EncodeBlobCoordinate(0, 0, x, y, nominalWidth, nominalHeight, &item.coords[0]); // BOTTOM_LEFT
+ EncodeBlobCoordinate(0, 1, x, y, nominalWidth, nominalHeight, &item.coords[1]); // TOP_LEFT
+ EncodeBlobCoordinate(1, 0, x, y, nominalWidth, nominalHeight, &item.coords[2]); // BOTTOM_RIGHT
+ EncodeBlobCoordinate(1, 1, x, y, nominalWidth, nominalHeight, &item.coords[3]); // TOP_RIGHT
+ mItemCache.push_back(item);
coords[0] = item.coords[0];
coords[1] = item.coords[1];
return true;
}
-void VectorBlobAtlas::TexSubImage( unsigned int offsetX,
- unsigned int offsetY,
- unsigned int width,
- unsigned int height,
- VectorBlob* blob )
+void VectorBlobAtlas::TexSubImage(unsigned int offsetX,
+ unsigned int offsetY,
+ unsigned int width,
+ unsigned int height,
+ VectorBlob* blob)
{
- const size_t size = width * height * 4;
- uint8_t* pixbuf = new uint8_t[size];
+ const size_t size = width * height * 4;
+ uint8_t* pixbuf = new uint8_t[size];
size_t pos;
size_t dataIndex = 0;
- for( size_t y = 0; y < height; y++ )
+ for(size_t y = 0; y < height; y++)
{
pos = y * mTextureWidth * 4;
- for( size_t x = 0; x < width; x++ )
+ for(size_t x = 0; x < width; x++)
{
- pixbuf[pos+x*4] = 0xFF & blob[dataIndex].r;
- pixbuf[pos+x*4+1] = 0xFF & blob[dataIndex].g;
- pixbuf[pos+x*4+2] = 0xFF & blob[dataIndex].b;
- pixbuf[pos+x*4+3] = 0xFF & blob[dataIndex].a;
+ pixbuf[pos + x * 4] = 0xFF & blob[dataIndex].r;
+ pixbuf[pos + x * 4 + 1] = 0xFF & blob[dataIndex].g;
+ pixbuf[pos + x * 4 + 2] = 0xFF & blob[dataIndex].b;
+ pixbuf[pos + x * 4 + 3] = 0xFF & blob[dataIndex].a;
dataIndex++;
}
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/rendering/view-model.h>
// EXTERNAL INCLUDES
-#include <memory.h>
#include <dali/devel-api/text-abstraction/font-client.h>
+#include <memory.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/line-run.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-ViewModel::ViewModel( const ModelInterface* const model )
-: mModel( model ),
+ViewModel::ViewModel(const ModelInterface* const model)
+: mModel(model),
mElidedGlyphs(),
mElidedLayout(),
- mIsTextElided( false )
+ mIsTextElided(false)
{
}
Length ViewModel::GetNumberOfGlyphs() const
{
- if( mIsTextElided && mModel->IsTextElideEnabled() )
+ if(mIsTextElided && mModel->IsTextElideEnabled())
{
- return mElidedGlyphs.Count();
+ return mElidedGlyphs.Count();
}
else
{
const GlyphInfo* const ViewModel::GetGlyphs() const
{
- if( mIsTextElided && mModel->IsTextElideEnabled() )
+ if(mIsTextElided && mModel->IsTextElideEnabled())
{
return mElidedGlyphs.Begin();
}
const Vector2* const ViewModel::GetLayout() const
{
- if( mIsTextElided && mModel->IsTextElideEnabled() )
+ if(mIsTextElided && mModel->IsTextElideEnabled())
{
return mElidedLayout.Begin();
}
return mModel->GetNumberOfUnderlineRuns();
}
-void ViewModel::GetUnderlineRuns( GlyphRun* underlineRuns, UnderlineRunIndex index, Length numberOfRuns ) const
+void ViewModel::GetUnderlineRuns(GlyphRun* underlineRuns, UnderlineRunIndex index, Length numberOfRuns) const
{
- mModel->GetUnderlineRuns( underlineRuns, index, numberOfRuns );
+ mModel->GetUnderlineRuns(underlineRuns, index, numberOfRuns);
}
const Vector4& ViewModel::GetOutlineColor() const
{
mIsTextElided = false;
- if( mModel->IsTextElideEnabled() )
+ if(mModel->IsTextElideEnabled())
{
const Length numberOfLines = mModel->GetNumberOfLines();
- if( 0u != numberOfLines )
+ if(0u != numberOfLines)
{
const LineRun* const lines = mModel->GetLines();
- const LineRun& lastLine = *( lines + ( numberOfLines - 1u ) );
- const Length numberOfLaidOutGlyphs = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs;
+ const LineRun& lastLine = *(lines + (numberOfLines - 1u));
+ const Length numberOfLaidOutGlyphs = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs;
- if( lastLine.ellipsis && ( 0u != numberOfLaidOutGlyphs ) )
+ if(lastLine.ellipsis && (0u != numberOfLaidOutGlyphs))
{
- mIsTextElided = true;
+ mIsTextElided = true;
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
- const GlyphInfo* const glyphs = mModel->GetGlyphs();
- const Vector2* const positions = mModel->GetLayout();
+ const GlyphInfo* const glyphs = mModel->GetGlyphs();
+ const Vector2* const positions = mModel->GetLayout();
// Copy the glyphs to be elided.
- mElidedGlyphs.Resize( numberOfLaidOutGlyphs );
- mElidedLayout.Resize( numberOfLaidOutGlyphs );
+ mElidedGlyphs.Resize(numberOfLaidOutGlyphs);
+ mElidedLayout.Resize(numberOfLaidOutGlyphs);
- GlyphInfo* elidedGlyphsBuffer = mElidedGlyphs.Begin();
- Vector2* elidedPositionsBuffer = mElidedLayout.Begin();
+ GlyphInfo* elidedGlyphsBuffer = mElidedGlyphs.Begin();
+ Vector2* elidedPositionsBuffer = mElidedLayout.Begin();
- memcpy( elidedGlyphsBuffer, glyphs, numberOfLaidOutGlyphs * sizeof( GlyphInfo ) );
- memcpy( elidedPositionsBuffer, positions, numberOfLaidOutGlyphs * sizeof( Vector2 ) );
+ memcpy(elidedGlyphsBuffer, glyphs, numberOfLaidOutGlyphs * sizeof(GlyphInfo));
+ memcpy(elidedPositionsBuffer, positions, numberOfLaidOutGlyphs * sizeof(Vector2));
const Size& controlSize = mModel->GetControlSize();
- if( ( 1u == numberOfLines ) &&
- ( lastLine.ascender - lastLine.descender > controlSize.height ) )
+ if((1u == numberOfLines) &&
+ (lastLine.ascender - lastLine.descender > controlSize.height))
{
// Get the first glyph which is going to be replaced and the ellipsis glyph.
- GlyphInfo& glyphToRemove = *elidedGlyphsBuffer;
- const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph( fontClient.GetPointSize( glyphToRemove.fontId ) );
+ GlyphInfo& glyphToRemove = *elidedGlyphsBuffer;
+ const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph(fontClient.GetPointSize(glyphToRemove.fontId));
// Change the 'x' and 'y' position of the ellipsis glyph.
Vector2& position = *elidedPositionsBuffer;
// Replace the glyph by the ellipsis glyph and resize the buffers.
glyphToRemove = ellipsisGlyph;
- mElidedGlyphs.Resize( 1u );
- mElidedLayout.Resize( 1u );
+ mElidedGlyphs.Resize(1u);
+ mElidedLayout.Resize(1u);
return;
}
// firstPenX, penY and firstPenSet are used to position the ellipsis glyph if needed.
- float firstPenX = 0.f; // Used if rtl text is elided.
- float penY = 0.f;
- bool firstPenSet = false;
+ float firstPenX = 0.f; // Used if rtl text is elided.
+ float penY = 0.f;
+ bool firstPenSet = false;
// Add the ellipsis glyph.
- bool inserted = false;
- float removedGlypsWidth = 0.f;
- Length numberOfRemovedGlyphs = 0u;
- GlyphIndex index = numberOfLaidOutGlyphs - 1u;
+ bool inserted = false;
+ float removedGlypsWidth = 0.f;
+ Length numberOfRemovedGlyphs = 0u;
+ GlyphIndex index = numberOfLaidOutGlyphs - 1u;
// The ellipsis glyph has to fit in the place where the last glyph(s) is(are) removed.
- while( !inserted )
+ while(!inserted)
{
- const GlyphInfo& glyphToRemove = *( elidedGlyphsBuffer + index );
+ const GlyphInfo& glyphToRemove = *(elidedGlyphsBuffer + index);
- if( 0u != glyphToRemove.fontId )
+ if(0u != glyphToRemove.fontId)
{
// i.e. The font id of the glyph shaped from the '\n' character is zero.
// Need to reshape the glyph as the font may be different in size.
- const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph( fontClient.GetPointSize( glyphToRemove.fontId ) );
+ const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph(fontClient.GetPointSize(glyphToRemove.fontId));
- if( !firstPenSet || EqualsZero( glyphToRemove.advance ) )
+ if(!firstPenSet || EqualsZero(glyphToRemove.advance))
{
- const Vector2& position = *( elidedPositionsBuffer + index );
+ const Vector2& position = *(elidedPositionsBuffer + index);
// Calculates the penY of the current line. It will be used to position the ellipsis glyph.
penY = position.y + glyphToRemove.yBearing;
// Calculates the first penX which will be used if rtl text is elided.
firstPenX = position.x - glyphToRemove.xBearing;
- if( firstPenX < -ellipsisGlyph.xBearing )
+ if(firstPenX < -ellipsisGlyph.xBearing)
{
// Avoids to exceed the bounding box when rtl text is elided.
firstPenX = -ellipsisGlyph.xBearing;
removedGlypsWidth = -ellipsisGlyph.xBearing;
- if( !EqualsZero( firstPenX ) )
+ if(!EqualsZero(firstPenX))
{
firstPenSet = true;
}
}
- removedGlypsWidth += std::min( glyphToRemove.advance, ( glyphToRemove.xBearing + glyphToRemove.width ) );
+ removedGlypsWidth += std::min(glyphToRemove.advance, (glyphToRemove.xBearing + glyphToRemove.width));
// Calculate the width of the ellipsis glyph and check if it fits.
const float ellipsisGlyphWidth = ellipsisGlyph.width + ellipsisGlyph.xBearing;
// If it is the last glyph to remove, add the ellipsis glyph without checking its width.
- if( ( ellipsisGlyphWidth < removedGlypsWidth ) || ( index == 0u ) )
+ if((ellipsisGlyphWidth < removedGlypsWidth) || (index == 0u))
{
- GlyphInfo& glyphInfo = *( elidedGlyphsBuffer + index );
- Vector2& position = *( elidedPositionsBuffer + index );
- position.x -= ( 0.f > glyphInfo.xBearing ) ? glyphInfo.xBearing : 0.f;
+ GlyphInfo& glyphInfo = *(elidedGlyphsBuffer + index);
+ Vector2& position = *(elidedPositionsBuffer + index);
+ position.x -= (0.f > glyphInfo.xBearing) ? glyphInfo.xBearing : 0.f;
// Replace the glyph by the ellipsis glyph.
glyphInfo = ellipsisGlyph;
// Change the 'x' and 'y' position of the ellipsis glyph.
- if( position.x > firstPenX )
+ if(position.x > firstPenX)
{
position.x = firstPenX;
- if (ellipsisGlyphWidth < removedGlypsWidth)
+ if(ellipsisGlyphWidth < removedGlypsWidth)
{
position.x += removedGlypsWidth - ellipsisGlyphWidth;
}
}
}
- if( !inserted )
+ if(!inserted)
{
- if( index > 0u )
+ if(index > 0u)
{
--index;
}
}
} // while( !inserted )
- // 'Removes' all the glyphs after the ellipsis glyph.
+ // 'Removes' all the glyphs after the ellipsis glyph.
const Length numberOfGlyphs = numberOfLaidOutGlyphs - numberOfRemovedGlyphs;
- mElidedGlyphs.Resize( numberOfGlyphs );
- mElidedLayout.Resize( numberOfGlyphs );
+ mElidedGlyphs.Resize(numberOfGlyphs);
+ mElidedLayout.Resize(numberOfGlyphs);
}
}
}
// EXTERNAL INCLUDES
#include <dali/devel-api/text-abstraction/segmentation.h>
#ifdef DEBUG_ENABLED
-#include <string>
#include <dali/integration-api/debug.h>
+#include <string>
#endif
// INTERNAL INCLUDES
namespace
{
-
#if defined(DEBUG_ENABLED)
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_SEGMENTATION");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_SEGMENTATION");
#endif
} // namespace
-
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-void SetLineBreakInfo( const Vector<Character>& text,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<LineBreakInfo>& lineBreakInfo )
+void SetLineBreakInfo(const Vector<Character>& text,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<LineBreakInfo>& lineBreakInfo)
{
const Length totalNumberOfCharacters = text.Count();
- if( 0u == totalNumberOfCharacters )
+ if(0u == totalNumberOfCharacters)
{
// Nothing to do if there are no characters.
return;
}
// Retrieve the line break info.
- lineBreakInfo.Resize( totalNumberOfCharacters );
+ lineBreakInfo.Resize(totalNumberOfCharacters);
// Whether the current buffer is being updated or is set from scratch.
const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters;
- LineBreakInfo* lineBreakInfoBuffer = NULL;
+ LineBreakInfo* lineBreakInfoBuffer = NULL;
Vector<LineBreakInfo> newLineBreakInfo;
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- newLineBreakInfo.Resize( numberOfCharacters );
+ newLineBreakInfo.Resize(numberOfCharacters);
lineBreakInfoBuffer = newLineBreakInfo.Begin();
}
else
}
// Retrieve the line break info.
- TextAbstraction::Segmentation::Get().GetLineBreakPositions( text.Begin() + startIndex,
- numberOfCharacters,
- lineBreakInfoBuffer );
+ TextAbstraction::Segmentation::Get().GetLineBreakPositions(text.Begin() + startIndex,
+ numberOfCharacters,
+ lineBreakInfoBuffer);
// If the line break info is updated, it needs to be inserted in the model.
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- lineBreakInfo.Insert( lineBreakInfo.Begin() + startIndex,
- newLineBreakInfo.Begin(),
- newLineBreakInfo.End() );
- lineBreakInfo.Resize( totalNumberOfCharacters );
+ lineBreakInfo.Insert(lineBreakInfo.Begin() + startIndex,
+ newLineBreakInfo.Begin(),
+ newLineBreakInfo.End());
+ lineBreakInfo.Resize(totalNumberOfCharacters);
}
#ifdef DEBUG_ENABLED
- if( gLogFilter->IsEnabledFor(Debug::Verbose) )
+ if(gLogFilter->IsEnabledFor(Debug::Verbose))
{
std::string utf8;
- Utf32ToUtf8( text.Begin(), numberOfCharacters, utf8 );
+ Utf32ToUtf8(text.Begin(), numberOfCharacters, utf8);
std::string info;
- info.reserve( numberOfCharacters );
- for( unsigned int i=0; i<lineBreakInfo.Count(); ++i )
+ info.reserve(numberOfCharacters);
+ for(unsigned int i = 0; i < lineBreakInfo.Count(); ++i)
{
- info.push_back( static_cast<char>('0' + lineBreakInfo[i]) );
+ info.push_back(static_cast<char>('0' + lineBreakInfo[i]));
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SetLineBreakInfo Characters: %s\n", utf8.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SetLineBreakInfo Break info: %s\n", info.c_str() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "SetLineBreakInfo Characters: %s\n", utf8.c_str());
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "SetLineBreakInfo Break info: %s\n", info.c_str());
}
#endif
}
-void SetWordBreakInfo( const Vector<Character>& text,
- CharacterIndex startIndex,
- Length numberOfCharacters,
- Vector<WordBreakInfo>& wordBreakInfo )
+void SetWordBreakInfo(const Vector<Character>& text,
+ CharacterIndex startIndex,
+ Length numberOfCharacters,
+ Vector<WordBreakInfo>& wordBreakInfo)
{
const Length totalNumberOfCharacters = text.Count();
- if( 0u == totalNumberOfCharacters )
+ if(0u == totalNumberOfCharacters)
{
// Nothing to do if there are no characters.
return;
}
// Resize the vector.
- wordBreakInfo.Resize( totalNumberOfCharacters );
+ wordBreakInfo.Resize(totalNumberOfCharacters);
// Whether the current buffer is being updated or is set from scratch.
const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters;
- WordBreakInfo* wordBreakInfoBuffer = NULL;
+ WordBreakInfo* wordBreakInfoBuffer = NULL;
Vector<WordBreakInfo> newWordBreakInfo;
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- newWordBreakInfo.Resize( numberOfCharacters );
+ newWordBreakInfo.Resize(numberOfCharacters);
wordBreakInfoBuffer = newWordBreakInfo.Begin();
}
else
}
// Retrieve the word break info.
- TextAbstraction::Segmentation::Get().GetWordBreakPositions( text.Begin() + startIndex,
- numberOfCharacters,
- wordBreakInfoBuffer );
+ TextAbstraction::Segmentation::Get().GetWordBreakPositions(text.Begin() + startIndex,
+ numberOfCharacters,
+ wordBreakInfoBuffer);
// If the word break info is updated, it needs to be inserted in the model.
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- wordBreakInfo.Insert( wordBreakInfo.Begin() + startIndex,
- newWordBreakInfo.Begin(),
- newWordBreakInfo.End() );
- wordBreakInfo.Resize( totalNumberOfCharacters );
+ wordBreakInfo.Insert(wordBreakInfo.Begin() + startIndex,
+ newWordBreakInfo.Begin(),
+ newWordBreakInfo.End());
+ wordBreakInfo.Resize(totalNumberOfCharacters);
}
#ifdef DEBUG_ENABLED
- if( gLogFilter->IsEnabledFor(Debug::Verbose) )
+ if(gLogFilter->IsEnabledFor(Debug::Verbose))
{
std::string utf8;
- Utf32ToUtf8( text.Begin(), totalNumberOfCharacters, utf8 );
+ Utf32ToUtf8(text.Begin(), totalNumberOfCharacters, utf8);
std::string info;
- info.reserve( totalNumberOfCharacters );
- for( unsigned int i=0; i<wordBreakInfo.Count(); ++i )
+ info.reserve(totalNumberOfCharacters);
+ for(unsigned int i = 0; i < wordBreakInfo.Count(); ++i)
{
- info.push_back( static_cast<char>('0' + wordBreakInfo[i]) );
+ info.push_back(static_cast<char>('0' + wordBreakInfo[i]));
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SetWordBreakInfo Characters: %s\n", utf8.c_str() );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SetWordBreakInfo Break info: %s\n", info.c_str() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "SetWordBreakInfo Characters: %s\n", utf8.c_str());
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "SetWordBreakInfo Break info: %s\n", info.c_str());
}
#endif
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-CharacterIndex min( CharacterIndex index0,
- CharacterIndex index1 )
+CharacterIndex min(CharacterIndex index0,
+ CharacterIndex index1)
{
- return ( index0 < index1 ) ? index0 : index1;
+ return (index0 < index1) ? index0 : index1;
}
-void ShapeText( const Vector<Character>& text,
- const Vector<LineBreakInfo>& lineBreakInfo,
- const Vector<ScriptRun>& scripts,
- const Vector<FontRun>& fonts,
- CharacterIndex startCharacterIndex,
- GlyphIndex startGlyphIndex,
- Length numberOfCharacters,
- Vector<GlyphInfo>& glyphs,
- Vector<CharacterIndex>& glyphToCharacterMap,
- Vector<Length>& charactersPerGlyph,
- Vector<GlyphIndex>& newParagraphGlyphs )
+void ShapeText(const Vector<Character>& text,
+ const Vector<LineBreakInfo>& lineBreakInfo,
+ const Vector<ScriptRun>& scripts,
+ const Vector<FontRun>& fonts,
+ CharacterIndex startCharacterIndex,
+ GlyphIndex startGlyphIndex,
+ Length numberOfCharacters,
+ Vector<GlyphInfo>& glyphs,
+ Vector<CharacterIndex>& glyphToCharacterMap,
+ Vector<Length>& charactersPerGlyph,
+ Vector<GlyphIndex>& newParagraphGlyphs)
{
- if( 0u == numberOfCharacters )
+ if(0u == numberOfCharacters)
{
// Nothing to do if there are no characters.
return;
}
#ifdef DEBUG_ENABLED
- const Length numberOfFontRuns = fonts.Count();
- const Length numberOfScriptRuns = scripts.Count();
+ const Length numberOfFontRuns = fonts.Count();
+ const Length numberOfScriptRuns = scripts.Count();
const Length totalNumberOfCharacters = text.Count();
#endif
- DALI_ASSERT_DEBUG( ( 0u != numberOfFontRuns ) &&
- ( totalNumberOfCharacters == fonts[numberOfFontRuns - 1u].characterRun.characterIndex + fonts[numberOfFontRuns - 1u].characterRun.numberOfCharacters ) &&
- "Toolkit::Text::ShapeText. All characters must have a font set." );
+ DALI_ASSERT_DEBUG((0u != numberOfFontRuns) &&
+ (totalNumberOfCharacters == fonts[numberOfFontRuns - 1u].characterRun.characterIndex + fonts[numberOfFontRuns - 1u].characterRun.numberOfCharacters) &&
+ "Toolkit::Text::ShapeText. All characters must have a font set.");
- DALI_ASSERT_DEBUG( ( 0u != numberOfScriptRuns ) &&
- ( totalNumberOfCharacters == scripts[numberOfScriptRuns - 1u].characterRun.characterIndex + scripts[numberOfScriptRuns - 1u].characterRun.numberOfCharacters ) &&
- "Toolkit::Text::ShapeText. All characters must have a script set." );
+ DALI_ASSERT_DEBUG((0u != numberOfScriptRuns) &&
+ (totalNumberOfCharacters == scripts[numberOfScriptRuns - 1u].characterRun.characterIndex + scripts[numberOfScriptRuns - 1u].characterRun.numberOfCharacters) &&
+ "Toolkit::Text::ShapeText. All characters must have a script set.");
// The text needs to be split in chunks of consecutive characters.
// Each chunk must contain characters with the same font id and script set.
// Get the font run containing the startCharacterIndex character.
Vector<FontRun>::ConstIterator fontRunIt = fonts.Begin();
- for( Vector<FontRun>::ConstIterator endIt = fonts.End(); fontRunIt < endIt; ++fontRunIt )
+ for(Vector<FontRun>::ConstIterator endIt = fonts.End(); fontRunIt < endIt; ++fontRunIt)
{
const FontRun& run = *fontRunIt;
- if( startCharacterIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters )
+ if(startCharacterIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters)
{
// Found.
break;
// Get the script run containing the startCharacterIndex character.
Vector<ScriptRun>::ConstIterator scriptRunIt = scripts.Begin();
- for( Vector<ScriptRun>::ConstIterator endIt = scripts.End(); scriptRunIt < endIt; ++scriptRunIt )
+ for(Vector<ScriptRun>::ConstIterator endIt = scripts.End(); scriptRunIt < endIt; ++scriptRunIt)
{
const ScriptRun& run = *scriptRunIt;
- if( startCharacterIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters )
+ if(startCharacterIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters)
{
// Found.
break;
GlyphInfo glyphInfo;
glyphInfo.isItalicRequired = false;
- glyphInfo.isBoldRequired = false;
+ glyphInfo.isBoldRequired = false;
- const Length currentNumberOfGlyphs = glyphs.Count();
- const Length numberOfGlyphsReserved = static_cast<Length>( numberOfCharacters * 1.3f );
- glyphs.Reserve( currentNumberOfGlyphs + numberOfGlyphsReserved );
- glyphToCharacterMap.Reserve( currentNumberOfGlyphs + numberOfGlyphsReserved );
+ const Length currentNumberOfGlyphs = glyphs.Count();
+ const Length numberOfGlyphsReserved = static_cast<Length>(numberOfCharacters * 1.3f);
+ glyphs.Reserve(currentNumberOfGlyphs + numberOfGlyphsReserved);
+ glyphToCharacterMap.Reserve(currentNumberOfGlyphs + numberOfGlyphsReserved);
// The actual number of glyphs.
Length totalNumberOfGlyphs = currentNumberOfGlyphs;
// The number of new glyphs.
Length numberOfNewGlyphs = 0u;
- const Character* const textBuffer = text.Begin();
- const LineBreakInfo* const lineBreakInfoBuffer = lineBreakInfo.Begin();
- CharacterIndex* glyphToCharacterMapBuffer = glyphToCharacterMap.Begin();
+ const Character* const textBuffer = text.Begin();
+ const LineBreakInfo* const lineBreakInfoBuffer = lineBreakInfo.Begin();
+ CharacterIndex* glyphToCharacterMapBuffer = glyphToCharacterMap.Begin();
Length glyphIndex = startGlyphIndex;
// Traverse the characters and shape the text.
const CharacterIndex lastCharacter = startCharacterIndex + numberOfCharacters;
- for( previousIndex = startCharacterIndex; previousIndex < lastCharacter; )
+ for(previousIndex = startCharacterIndex; previousIndex < lastCharacter;)
{
// Get the font id and the script.
- const FontRun& fontRun = *fontRunIt;
+ const FontRun& fontRun = *fontRunIt;
const ScriptRun& scriptRun = *scriptRunIt;
- currentFontId = fontRun.fontId;
- currentScript = scriptRun.script;
+ currentFontId = fontRun.fontId;
+ currentScript = scriptRun.script;
const bool isItalicRequired = fontRun.isItalicRequired;
- const bool isBoldRequired = fontRun.isBoldRequired;
+ const bool isBoldRequired = fontRun.isBoldRequired;
// Get the min index to the last character of both runs.
- CharacterIndex currentIndex = min( fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters,
- scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters );
+ CharacterIndex currentIndex = min(fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters,
+ scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters);
// Check if there is a line must break.
bool mustBreak = false;
// However, the metrics need to be changed in order to not to draw a square.
bool isNewParagraph = false;
- for( CharacterIndex index = previousIndex; index < currentIndex; ++index )
+ for(CharacterIndex index = previousIndex; index < currentIndex; ++index)
{
- mustBreak = TextAbstraction::LINE_MUST_BREAK == *( lineBreakInfoBuffer + index );
- if( mustBreak )
+ mustBreak = TextAbstraction::LINE_MUST_BREAK == *(lineBreakInfoBuffer + index);
+ if(mustBreak)
{
- isNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + index ) );
- currentIndex = index + 1u;
+ isNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + index));
+ currentIndex = index + 1u;
break;
}
}
// Shape the text for the current chunk.
- const Length numberOfGlyphs = shaping.Shape( textBuffer + previousIndex,
- ( currentIndex - previousIndex ), // The number of characters to shape.
- currentFontId,
- currentScript );
+ const Length numberOfGlyphs = shaping.Shape(textBuffer + previousIndex,
+ (currentIndex - previousIndex), // The number of characters to shape.
+ currentFontId,
+ currentScript);
// Retrieve the glyphs and the glyph to character conversion map.
- Vector<GlyphInfo> tmpGlyphs;
+ Vector<GlyphInfo> tmpGlyphs;
Vector<CharacterIndex> tmpGlyphToCharacterMap;
GlyphInfo glyphInfo;
glyphInfo.isItalicRequired = isItalicRequired;
- glyphInfo.isBoldRequired = isBoldRequired;
+ glyphInfo.isBoldRequired = isBoldRequired;
- tmpGlyphs.Resize( numberOfGlyphs, glyphInfo );
- tmpGlyphToCharacterMap.Resize( numberOfGlyphs );
- shaping.GetGlyphs( tmpGlyphs.Begin(),
- tmpGlyphToCharacterMap.Begin() );
+ tmpGlyphs.Resize(numberOfGlyphs, glyphInfo);
+ tmpGlyphToCharacterMap.Resize(numberOfGlyphs);
+ shaping.GetGlyphs(tmpGlyphs.Begin(),
+ tmpGlyphToCharacterMap.Begin());
// Update the new indices of the glyph to character map.
- if( 0u != totalNumberOfGlyphs )
+ if(0u != totalNumberOfGlyphs)
{
- for( Vector<CharacterIndex>::Iterator it = tmpGlyphToCharacterMap.Begin(),
- endIt = tmpGlyphToCharacterMap.End();
- it != endIt;
- ++it )
+ for(Vector<CharacterIndex>::Iterator it = tmpGlyphToCharacterMap.Begin(),
+ endIt = tmpGlyphToCharacterMap.End();
+ it != endIt;
+ ++it)
{
*it += previousIndex;
}
totalNumberOfGlyphs += numberOfGlyphs;
numberOfNewGlyphs += numberOfGlyphs;
- glyphs.Insert( glyphs.Begin() + glyphIndex, tmpGlyphs.Begin(), tmpGlyphs.End() );
- glyphToCharacterMap.Insert( glyphToCharacterMap.Begin() + glyphIndex, tmpGlyphToCharacterMap.Begin(), tmpGlyphToCharacterMap.End() );
+ glyphs.Insert(glyphs.Begin() + glyphIndex, tmpGlyphs.Begin(), tmpGlyphs.End());
+ glyphToCharacterMap.Insert(glyphToCharacterMap.Begin() + glyphIndex, tmpGlyphToCharacterMap.Begin(), tmpGlyphToCharacterMap.End());
glyphIndex += numberOfGlyphs;
// Set the buffer pointers again.
glyphToCharacterMapBuffer = glyphToCharacterMap.Begin();
- if( isNewParagraph )
+ if(isNewParagraph)
{
// Add the index of the new paragraph glyph to a vector.
// Their metrics will be updated in a following step.
- newParagraphGlyphs.PushBack( glyphIndex - 1u );
+ newParagraphGlyphs.PushBack(glyphIndex - 1u);
}
// Update the iterators to get the next font or script run.
- if( currentIndex == fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters )
+ if(currentIndex == fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters)
{
++fontRunIt;
}
- if( currentIndex == scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters )
+ if(currentIndex == scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters)
{
++scriptRunIt;
}
}
// Update indices.
- for( Length index = startGlyphIndex + numberOfNewGlyphs; index < totalNumberOfGlyphs; ++index )
+ for(Length index = startGlyphIndex + numberOfNewGlyphs; index < totalNumberOfGlyphs; ++index)
{
- CharacterIndex& characterIndex = *( glyphToCharacterMapBuffer + index );
+ CharacterIndex& characterIndex = *(glyphToCharacterMapBuffer + index);
characterIndex += numberOfCharacters;
}
// Add the number of characters per glyph.
- charactersPerGlyph.Reserve( totalNumberOfGlyphs );
+ charactersPerGlyph.Reserve(totalNumberOfGlyphs);
Length* charactersPerGlyphBuffer = charactersPerGlyph.Begin();
const GlyphIndex lastGlyph = startGlyphIndex + numberOfNewGlyphs;
- previousIndex = startCharacterIndex;
- for( Length index = startGlyphIndex + 1u; index < lastGlyph; ++index )
+ previousIndex = startCharacterIndex;
+ for(Length index = startGlyphIndex + 1u; index < lastGlyph; ++index)
{
- const CharacterIndex characterIndex = *( glyphToCharacterMapBuffer + index );
+ const CharacterIndex characterIndex = *(glyphToCharacterMapBuffer + index);
- charactersPerGlyph.Insert( charactersPerGlyphBuffer + index - 1u, characterIndex - previousIndex );
+ charactersPerGlyph.Insert(charactersPerGlyphBuffer + index - 1u, characterIndex - previousIndex);
previousIndex = characterIndex;
}
- charactersPerGlyph.Insert( charactersPerGlyphBuffer + lastGlyph - 1u, numberOfCharacters + startCharacterIndex - previousIndex );
+ charactersPerGlyph.Insert(charactersPerGlyphBuffer + lastGlyph - 1u, numberOfCharacters + startCharacterIndex - previousIndex);
// Resize the vectors to set the right number of items.
- glyphs.Resize( totalNumberOfGlyphs );
- glyphToCharacterMap.Resize( totalNumberOfGlyphs );
+ glyphs.Resize(totalNumberOfGlyphs);
+ glyphToCharacterMap.Resize(totalNumberOfGlyphs);
}
} // namespace Text
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/text-controller-event-handler.h>
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
#include <dali/devel-api/adaptor-framework/clipboard-event-notifier.h>
#include <dali/devel-api/adaptor-framework/key-devel.h>
+#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/text-controller-impl.h>
namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
-const std::string KEY_C_NAME = "c";
-const std::string KEY_V_NAME = "v";
-const std::string KEY_X_NAME = "x";
-const std::string KEY_A_NAME = "a";
+const std::string KEY_C_NAME = "c";
+const std::string KEY_V_NAME = "v";
+const std::string KEY_X_NAME = "x";
+const std::string KEY_A_NAME = "a";
const std::string KEY_INSERT_NAME = "Insert";
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
void Controller::EventHandler::KeyboardFocusGainEvent(Controller& controller)
{
- DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" );
+ DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected KeyboardFocusGainEvent");
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( ( EventData::INACTIVE == controller.mImpl->mEventData->mState ) ||
- ( EventData::INTERRUPTED == controller.mImpl->mEventData->mState ) )
+ if((EventData::INACTIVE == controller.mImpl->mEventData->mState) ||
+ (EventData::INTERRUPTED == controller.mImpl->mEventData->mState))
{
- controller.mImpl->ChangeState( EventData::EDITING );
- controller.mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
- controller.mImpl->mEventData->mUpdateInputStyle = true;
+ controller.mImpl->ChangeState(EventData::EDITING);
+ controller.mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered.
+ controller.mImpl->mEventData->mUpdateInputStyle = true;
controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
}
controller.mImpl->NotifyInputMethodContextMultiLineStatus();
- if( controller.mImpl->IsShowingPlaceholderText() )
+ if(controller.mImpl->IsShowingPlaceholderText())
{
// Show alternative placeholder-text when editing
controller.ShowPlaceholderText();
void Controller::EventHandler::KeyboardFocusLostEvent(Controller& controller)
{
- DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" );
+ DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected KeyboardFocusLostEvent");
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( EventData::INTERRUPTED != controller.mImpl->mEventData->mState )
+ if(EventData::INTERRUPTED != controller.mImpl->mEventData->mState)
{
- controller.mImpl->ChangeState( EventData::INACTIVE );
+ controller.mImpl->ChangeState(EventData::INACTIVE);
- if( !controller.mImpl->IsShowingRealText() )
+ if(!controller.mImpl->IsShowingRealText())
{
// Revert to regular placeholder-text when not editing
controller.ShowPlaceholderText();
bool Controller::EventHandler::KeyEvent(Controller& controller, const Dali::KeyEvent& keyEvent)
{
- DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected KeyEvent" );
+ DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected KeyEvent");
- bool textChanged = false;
+ bool textChanged = false;
bool relayoutNeeded = false;
- if( ( NULL != controller.mImpl->mEventData ) &&
- ( keyEvent.GetState() == KeyEvent::DOWN ) )
+ if((NULL != controller.mImpl->mEventData) &&
+ (keyEvent.GetState() == KeyEvent::DOWN))
{
- int keyCode = keyEvent.GetKeyCode();
+ int keyCode = keyEvent.GetKeyCode();
const std::string& keyString = keyEvent.GetKeyString();
- const std::string keyName = keyEvent.GetKeyName();
+ const std::string keyName = keyEvent.GetKeyName();
// Key will produce same logical-key value when ctrl
// is down, regardless of language layout
const std::string logicalKey = keyEvent.GetLogicalKey();
- const bool isNullKey = ( 0 == keyCode ) && ( keyString.empty() );
+ const bool isNullKey = (0 == keyCode) && (keyString.empty());
// Pre-process to separate modifying events from non-modifying input events.
- if( isNullKey )
+ if(isNullKey)
{
// In some platforms arrive key events with no key code.
// Do nothing.
return false;
}
- else if( Dali::DALI_KEY_ESCAPE == keyCode || Dali::DALI_KEY_BACK == keyCode || Dali::DALI_KEY_SEARCH == keyCode )
+ else if(Dali::DALI_KEY_ESCAPE == keyCode || Dali::DALI_KEY_BACK == keyCode || Dali::DALI_KEY_SEARCH == keyCode)
{
// Do nothing
return false;
}
- else if( ( Dali::DALI_KEY_CURSOR_LEFT == keyCode ) ||
- ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) ||
- ( Dali::DALI_KEY_CURSOR_UP == keyCode ) ||
- ( Dali::DALI_KEY_CURSOR_DOWN == keyCode ) )
+ else if((Dali::DALI_KEY_CURSOR_LEFT == keyCode) ||
+ (Dali::DALI_KEY_CURSOR_RIGHT == keyCode) ||
+ (Dali::DALI_KEY_CURSOR_UP == keyCode) ||
+ (Dali::DALI_KEY_CURSOR_DOWN == keyCode))
{
// If don't have any text, do nothing.
- if( !controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters )
+ if(!controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters)
{
return false;
}
- uint32_t cursorPosition = controller.mImpl->mEventData->mPrimaryCursorPosition;
+ uint32_t cursorPosition = controller.mImpl->mEventData->mPrimaryCursorPosition;
uint32_t numberOfCharacters = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
- uint32_t cursorLine = controller.mImpl->mModel->mVisualModel->GetLineOfCharacter( cursorPosition );
- uint32_t numberOfLines = controller.mImpl->mModel->GetNumberOfLines();
+ uint32_t cursorLine = controller.mImpl->mModel->mVisualModel->GetLineOfCharacter(cursorPosition);
+ uint32_t numberOfLines = controller.mImpl->mModel->GetNumberOfLines();
// Logic to determine whether this text control will lose focus or not.
- if( ( Dali::DALI_KEY_CURSOR_LEFT == keyCode && 0 == cursorPosition && !keyEvent.IsShiftModifier() ) ||
- ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode && numberOfCharacters == cursorPosition && !keyEvent.IsShiftModifier() ) ||
- ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && cursorLine == numberOfLines -1 ) ||
- ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && numberOfCharacters == cursorPosition && cursorLine -1 == numberOfLines -1 ) ||
- ( Dali::DALI_KEY_CURSOR_UP == keyCode && cursorLine == 0 ) ||
- ( Dali::DALI_KEY_CURSOR_UP == keyCode && numberOfCharacters == cursorPosition && cursorLine == 1 ) )
+ if((Dali::DALI_KEY_CURSOR_LEFT == keyCode && 0 == cursorPosition && !keyEvent.IsShiftModifier()) ||
+ (Dali::DALI_KEY_CURSOR_RIGHT == keyCode && numberOfCharacters == cursorPosition && !keyEvent.IsShiftModifier()) ||
+ (Dali::DALI_KEY_CURSOR_DOWN == keyCode && cursorLine == numberOfLines - 1) ||
+ (Dali::DALI_KEY_CURSOR_DOWN == keyCode && numberOfCharacters == cursorPosition && cursorLine - 1 == numberOfLines - 1) ||
+ (Dali::DALI_KEY_CURSOR_UP == keyCode && cursorLine == 0) ||
+ (Dali::DALI_KEY_CURSOR_UP == keyCode && numberOfCharacters == cursorPosition && cursorLine == 1))
{
// Release the active highlight.
- if( controller.mImpl->mEventData->mState == EventData::SELECTING )
+ if(controller.mImpl->mEventData->mState == EventData::SELECTING)
{
- controller.mImpl->ChangeState( EventData::EDITING );
+ controller.mImpl->ChangeState(EventData::EDITING);
// Update selection position.
- controller.mImpl->mEventData->mLeftSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition;
+ controller.mImpl->mEventData->mLeftSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition;
controller.mImpl->mEventData->mRightSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition;
- controller.mImpl->mEventData->mUpdateCursorPosition = true;
+ controller.mImpl->mEventData->mUpdateCursorPosition = true;
controller.mImpl->RequestRelayout();
}
return false;
}
controller.mImpl->mEventData->mCheckScrollAmount = true;
- Event event( Event::CURSOR_KEY_EVENT );
- event.p1.mInt = keyCode;
+ Event event(Event::CURSOR_KEY_EVENT);
+ event.p1.mInt = keyCode;
event.p2.mBool = keyEvent.IsShiftModifier();
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
// Will request for relayout.
relayoutNeeded = true;
}
- else if ( Dali::DevelKey::DALI_KEY_CONTROL_LEFT == keyCode || Dali::DevelKey::DALI_KEY_CONTROL_RIGHT == keyCode )
+ else if(Dali::DevelKey::DALI_KEY_CONTROL_LEFT == keyCode || Dali::DevelKey::DALI_KEY_CONTROL_RIGHT == keyCode)
{
// Left or Right Control key event is received before Ctrl-C/V/X key event is received
// If not handle it here, any selected text will be deleted
// Do nothing
return false;
}
- else if ( keyEvent.IsCtrlModifier() && !keyEvent.IsShiftModifier())
+ else if(keyEvent.IsCtrlModifier() && !keyEvent.IsShiftModifier())
{
bool consumed = false;
- if (keyName == KEY_C_NAME || keyName == KEY_INSERT_NAME || logicalKey == KEY_C_NAME || logicalKey == KEY_INSERT_NAME)
+ if(keyName == KEY_C_NAME || keyName == KEY_INSERT_NAME || logicalKey == KEY_C_NAME || logicalKey == KEY_INSERT_NAME)
{
// Ctrl-C or Ctrl+Insert to copy the selected text
- controller.TextPopupButtonTouched( Toolkit::TextSelectionPopup::COPY );
+ controller.TextPopupButtonTouched(Toolkit::TextSelectionPopup::COPY);
consumed = true;
}
- else if (keyName == KEY_V_NAME || logicalKey == KEY_V_NAME)
+ else if(keyName == KEY_V_NAME || logicalKey == KEY_V_NAME)
{
// Ctrl-V to paste the copied text
- controller.TextPopupButtonTouched( Toolkit::TextSelectionPopup::PASTE );
+ controller.TextPopupButtonTouched(Toolkit::TextSelectionPopup::PASTE);
consumed = true;
}
- else if (keyName == KEY_X_NAME || logicalKey == KEY_X_NAME)
+ else if(keyName == KEY_X_NAME || logicalKey == KEY_X_NAME)
{
// Ctrl-X to cut the selected text
- controller.TextPopupButtonTouched( Toolkit::TextSelectionPopup::CUT );
+ controller.TextPopupButtonTouched(Toolkit::TextSelectionPopup::CUT);
consumed = true;
}
- else if (keyName == KEY_A_NAME || logicalKey == KEY_A_NAME)
+ else if(keyName == KEY_A_NAME || logicalKey == KEY_A_NAME)
{
// Ctrl-A to select All the text
- controller.TextPopupButtonTouched( Toolkit::TextSelectionPopup::SELECT_ALL );
+ controller.TextPopupButtonTouched(Toolkit::TextSelectionPopup::SELECT_ALL);
consumed = true;
}
return consumed;
}
- else if( ( Dali::DALI_KEY_BACKSPACE == keyCode ) ||
- ( Dali::DevelKey::DALI_KEY_DELETE == keyCode ) )
+ else if((Dali::DALI_KEY_BACKSPACE == keyCode) ||
+ (Dali::DevelKey::DALI_KEY_DELETE == keyCode))
{
- textChanged = controller.DeleteEvent( keyCode );
+ textChanged = controller.DeleteEvent(keyCode);
// Will request for relayout.
relayoutNeeded = true;
}
- else if( IsKey( keyEvent, Dali::DALI_KEY_POWER ) ||
- IsKey( keyEvent, Dali::DALI_KEY_MENU ) ||
- IsKey( keyEvent, Dali::DALI_KEY_HOME ) )
+ else if(IsKey(keyEvent, Dali::DALI_KEY_POWER) ||
+ IsKey(keyEvent, Dali::DALI_KEY_MENU) ||
+ IsKey(keyEvent, Dali::DALI_KEY_HOME))
{
// Power key/Menu/Home key behaviour does not allow edit mode to resume.
- controller.mImpl->ChangeState( EventData::INACTIVE );
+ controller.mImpl->ChangeState(EventData::INACTIVE);
// Will request for relayout.
relayoutNeeded = true;
// This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
}
- else if( ( Dali::DALI_KEY_SHIFT_LEFT == keyCode ) || ( Dali::DALI_KEY_SHIFT_RIGHT == keyCode ) )
+ else if((Dali::DALI_KEY_SHIFT_LEFT == keyCode) || (Dali::DALI_KEY_SHIFT_RIGHT == keyCode))
{
// DALI_KEY_SHIFT_LEFT or DALI_KEY_SHIFT_RIGHT is the key code for Shift. It's sent (by the InputMethodContext?) when the predictive text is enabled
// and a character is typed after the type of a upper case latin character.
// Do nothing.
return false;
}
- else if( ( Dali::DALI_KEY_VOLUME_UP == keyCode ) || ( Dali::DALI_KEY_VOLUME_DOWN == keyCode ) )
+ else if((Dali::DALI_KEY_VOLUME_UP == keyCode) || (Dali::DALI_KEY_VOLUME_DOWN == keyCode))
{
// This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text.
// Do nothing.
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", &controller, keyString.c_str() );
- if (!controller.IsEditable()) return false;
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", &controller, keyString.c_str());
+ if(!controller.IsEditable()) return false;
- if( !keyString.empty() )
+ if(!keyString.empty())
{
// InputMethodContext is no longer handling key-events
controller.mImpl->ClearPreEditFlag();
- controller.InsertText( keyString, COMMIT );
+ controller.InsertText(keyString, COMMIT);
textChanged = true;
// Will request for relayout.
relayoutNeeded = true;
}
-
}
- if ( ( controller.mImpl->mEventData->mState != EventData::INTERRUPTED ) &&
- ( controller.mImpl->mEventData->mState != EventData::INACTIVE ) &&
- ( !isNullKey ) &&
- ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) &&
- ( Dali::DALI_KEY_SHIFT_RIGHT != keyCode ) &&
- ( Dali::DALI_KEY_VOLUME_UP != keyCode ) &&
- ( Dali::DALI_KEY_VOLUME_DOWN != keyCode ) )
+ if((controller.mImpl->mEventData->mState != EventData::INTERRUPTED) &&
+ (controller.mImpl->mEventData->mState != EventData::INACTIVE) &&
+ (!isNullKey) &&
+ (Dali::DALI_KEY_SHIFT_LEFT != keyCode) &&
+ (Dali::DALI_KEY_SHIFT_RIGHT != keyCode) &&
+ (Dali::DALI_KEY_VOLUME_UP != keyCode) &&
+ (Dali::DALI_KEY_VOLUME_DOWN != keyCode))
{
// Should not change the state if the key is the shift send by the InputMethodContext.
// Otherwise, when the state is SELECTING the text controller can't send the right
// surrounding info to the InputMethodContext.
- controller.mImpl->ChangeState( EventData::EDITING );
+ controller.mImpl->ChangeState(EventData::EDITING);
// Will request for relayout.
relayoutNeeded = true;
}
- if( relayoutNeeded )
+ if(relayoutNeeded)
{
controller.mImpl->RequestRelayout();
}
}
- if( textChanged &&
- ( NULL != controller.mImpl->mEditableControlInterface ) )
+ if(textChanged &&
+ (NULL != controller.mImpl->mEditableControlInterface))
{
// Do this last since it provides callbacks into application code
controller.mImpl->mEditableControlInterface->TextChanged();
void Controller::EventHandler::TapEvent(Controller& controller, unsigned int tapCount, float x, float y)
{
- DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected TapEvent" );
+ DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected TapEvent");
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", controller.mImpl->mEventData->mState );
- EventData::State state( controller.mImpl->mEventData->mState );
- bool relayoutNeeded( false ); // to avoid unnecessary relayouts when tapping an empty text-field
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "TapEvent state:%d \n", controller.mImpl->mEventData->mState);
+ EventData::State state(controller.mImpl->mEventData->mState);
+ bool relayoutNeeded(false); // to avoid unnecessary relayouts when tapping an empty text-field
- if( controller.mImpl->IsClipboardVisible() )
+ if(controller.mImpl->IsClipboardVisible())
{
- if( EventData::INACTIVE == state || EventData::EDITING == state)
+ if(EventData::INACTIVE == state || EventData::EDITING == state)
{
- controller.mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
+ controller.mImpl->ChangeState(EventData::EDITING_WITH_GRAB_HANDLE);
}
relayoutNeeded = true;
}
- else if( 1u == tapCount )
+ else if(1u == tapCount)
{
- if( EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state )
+ if(EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state)
{
- controller.mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE ); // If Popup shown hide it here so can be shown again if required.
+ controller.mImpl->ChangeState(EventData::EDITING_WITH_GRAB_HANDLE); // If Popup shown hide it here so can be shown again if required.
}
- if( controller.mImpl->IsShowingRealText() && ( EventData::INACTIVE != state ) )
+ if(controller.mImpl->IsShowingRealText() && (EventData::INACTIVE != state))
{
- controller.mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE );
+ controller.mImpl->ChangeState(EventData::EDITING_WITH_GRAB_HANDLE);
relayoutNeeded = true;
}
else
{
- if( controller.mImpl->IsShowingPlaceholderText() && !controller.mImpl->IsFocusedPlaceholderAvailable() )
+ if(controller.mImpl->IsShowingPlaceholderText() && !controller.mImpl->IsFocusedPlaceholderAvailable())
{
// Hide placeholder text
controller.ResetText();
}
- if( EventData::INACTIVE == state )
+ if(EventData::INACTIVE == state)
{
- controller.mImpl->ChangeState( EventData::EDITING );
+ controller.mImpl->ChangeState(EventData::EDITING);
}
- else if( !controller.mImpl->IsClipboardEmpty() )
+ else if(!controller.mImpl->IsClipboardEmpty())
{
- controller.mImpl->ChangeState( EventData::EDITING_WITH_POPUP );
+ controller.mImpl->ChangeState(EventData::EDITING_WITH_POPUP);
}
relayoutNeeded = true;
}
}
- else if( 2u == tapCount )
+ else if(2u == tapCount)
{
- if( controller.mImpl->mEventData->mSelectionEnabled &&
- controller.mImpl->IsShowingRealText() )
+ if(controller.mImpl->mEventData->mSelectionEnabled &&
+ controller.mImpl->IsShowingRealText())
{
- relayoutNeeded = true;
- controller.mImpl->mEventData->mIsLeftHandleSelected = true;
+ relayoutNeeded = true;
+ controller.mImpl->mEventData->mIsLeftHandleSelected = true;
controller.mImpl->mEventData->mIsRightHandleSelected = true;
}
}
// Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated
- if( relayoutNeeded )
+ if(relayoutNeeded)
{
- Event event( Event::TAP_EVENT );
- event.p1.mUint = tapCount;
+ Event event(Event::TAP_EVENT);
+ event.p1.mUint = tapCount;
event.p2.mFloat = x;
event.p3.mFloat = y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
controller.mImpl->RequestRelayout();
}
void Controller::EventHandler::PanEvent(Controller& controller, GestureState state, const Vector2& displacement)
{
- DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected PanEvent" );
+ DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected PanEvent");
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- Event event( Event::PAN_EVENT );
- event.p1.mInt = static_cast<int>( state );
+ Event event(Event::PAN_EVENT);
+ event.p1.mInt = static_cast<int>(state);
event.p2.mFloat = displacement.x;
event.p3.mFloat = displacement.y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
controller.mImpl->RequestRelayout();
}
void Controller::EventHandler::LongPressEvent(Controller& controller, GestureState state, float x, float y)
{
- DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected LongPressEvent" );
+ DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected LongPressEvent");
- if( ( state == GestureState::STARTED ) &&
- ( NULL != controller.mImpl->mEventData ) )
+ if((state == GestureState::STARTED) &&
+ (NULL != controller.mImpl->mEventData))
{
// The 1st long-press on inactive text-field is treated as tap
- if( EventData::INACTIVE == controller.mImpl->mEventData->mState )
+ if(EventData::INACTIVE == controller.mImpl->mEventData->mState)
{
- controller.mImpl->ChangeState( EventData::EDITING );
+ controller.mImpl->ChangeState(EventData::EDITING);
- Event event( Event::TAP_EVENT );
- event.p1.mUint = 1;
+ Event event(Event::TAP_EVENT);
+ event.p1.mUint = 1;
event.p2.mFloat = x;
event.p3.mFloat = y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
controller.mImpl->RequestRelayout();
}
- else if( !controller.mImpl->IsShowingRealText() )
+ else if(!controller.mImpl->IsShowingRealText())
{
- Event event( Event::LONG_PRESS_EVENT );
- event.p1.mInt = static_cast<int>( state );
+ Event event(Event::LONG_PRESS_EVENT);
+ event.p1.mInt = static_cast<int>(state);
event.p2.mFloat = x;
event.p3.mFloat = y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
controller.mImpl->RequestRelayout();
}
- else if( !controller.mImpl->IsClipboardVisible() )
+ else if(!controller.mImpl->IsClipboardVisible())
{
// Reset the InputMethodContext to commit the pre-edit before selecting the text.
controller.mImpl->ResetInputMethodContext();
- Event event( Event::LONG_PRESS_EVENT );
- event.p1.mInt = static_cast<int>( state );
+ Event event(Event::LONG_PRESS_EVENT);
+ event.p1.mInt = static_cast<int>(state);
event.p2.mFloat = x;
event.p3.mFloat = y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
controller.mImpl->RequestRelayout();
- controller.mImpl->mEventData->mIsLeftHandleSelected = true;
+ controller.mImpl->mEventData->mIsLeftHandleSelected = true;
controller.mImpl->mEventData->mIsRightHandleSelected = true;
}
}
void Controller::EventHandler::SelectEvent(Controller& controller, float x, float y, SelectionType selectType)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::SelectEvent\n");
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( selectType == SelectionType::ALL )
+ if(selectType == SelectionType::ALL)
{
- Event event( Event::SELECT_ALL );
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ Event event(Event::SELECT_ALL);
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
}
- else if( selectType == SelectionType::NONE )
+ else if(selectType == SelectionType::NONE)
{
- Event event( Event::SELECT_NONE );
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ Event event(Event::SELECT_NONE);
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
}
else
{
- Event event( Event::SELECT );
+ Event event(Event::SELECT);
event.p2.mFloat = x;
event.p3.mFloat = y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
}
- controller.mImpl->mEventData->mCheckScrollAmount = true;
- controller.mImpl->mEventData->mIsLeftHandleSelected = true;
+ controller.mImpl->mEventData->mCheckScrollAmount = true;
+ controller.mImpl->mEventData->mIsLeftHandleSelected = true;
controller.mImpl->mEventData->mIsRightHandleSelected = true;
controller.mImpl->RequestRelayout();
}
{
Vector<ModifyEvent>& events = controller.mImpl->mModifyEvents;
- if( 0u == events.Count() )
+ if(0u == events.Count())
{
// Nothing to do.
return;
}
- for( Vector<ModifyEvent>::ConstIterator it = events.Begin(),
- endIt = events.End();
- it != endIt;
- ++it )
+ for(Vector<ModifyEvent>::ConstIterator it = events.Begin(),
+ endIt = events.End();
+ it != endIt;
+ ++it)
{
const ModifyEvent& event = *it;
- if( ModifyEvent::TEXT_REPLACED == event.type )
+ if(ModifyEvent::TEXT_REPLACED == event.type)
{
// A (single) replace event should come first, otherwise we wasted time processing NOOP events
- DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" );
+ DALI_ASSERT_DEBUG(it == events.Begin() && "Unexpected TEXT_REPLACED event");
controller.TextReplacedEvent();
}
- else if( ModifyEvent::TEXT_INSERTED == event.type )
+ else if(ModifyEvent::TEXT_INSERTED == event.type)
{
controller.TextInsertedEvent();
}
- else if( ModifyEvent::TEXT_DELETED == event.type )
+ else if(ModifyEvent::TEXT_DELETED == event.type)
{
// Placeholder-text cannot be deleted
- if( !controller.mImpl->IsShowingPlaceholderText() )
+ if(!controller.mImpl->IsShowingPlaceholderText())
{
controller.TextDeletedEvent();
}
}
}
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
// When the text is being modified, delay cursor blinking
controller.mImpl->mEventData->mDecorator->DelayCursorBlink();
// Update selection position after modifying the text
- controller.mImpl->mEventData->mLeftSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition;
+ controller.mImpl->mEventData->mLeftSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition;
controller.mImpl->mEventData->mRightSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition;
}
void Controller::EventHandler::TextInsertedEvent(Controller& controller)
{
- DALI_ASSERT_DEBUG( NULL != controller.mImpl->mEventData && "Unexpected TextInsertedEvent" );
+ DALI_ASSERT_DEBUG(NULL != controller.mImpl->mEventData && "Unexpected TextInsertedEvent");
- if( NULL == controller.mImpl->mEventData )
+ if(NULL == controller.mImpl->mEventData)
{
return;
}
void Controller::EventHandler::TextDeletedEvent(Controller& controller)
{
- DALI_ASSERT_DEBUG( NULL != controller.mImpl->mEventData && "Unexpected TextDeletedEvent" );
+ DALI_ASSERT_DEBUG(NULL != controller.mImpl->mEventData && "Unexpected TextDeletedEvent");
- if( NULL == controller.mImpl->mEventData )
+ if(NULL == controller.mImpl->mEventData)
{
return;
}
- if (!controller.IsEditable()) return;
+ if(!controller.IsEditable()) return;
controller.mImpl->mEventData->mCheckScrollAmount = true;
bool Controller::EventHandler::DeleteEvent(Controller& controller, int keyCode)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p KeyCode : %d \n", &controller, keyCode );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::KeyEvent %p KeyCode : %d \n", &controller, keyCode);
bool removed = false;
- if( NULL == controller.mImpl->mEventData )
+ if(NULL == controller.mImpl->mEventData)
{
return removed;
}
- if (!controller.IsEditable()) return false;
+ if(!controller.IsEditable()) return false;
// InputMethodContext is no longer handling key-events
controller.mImpl->ClearPreEditFlag();
- if( EventData::SELECTING == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState)
{
removed = controller.RemoveSelectedText();
}
- else if( ( controller.mImpl->mEventData->mPrimaryCursorPosition > 0 ) && ( keyCode == Dali::DALI_KEY_BACKSPACE) )
+ else if((controller.mImpl->mEventData->mPrimaryCursorPosition > 0) && (keyCode == Dali::DALI_KEY_BACKSPACE))
{
// Remove the character before the current cursor position
- removed = controller.RemoveText( -1,
- 1,
- UPDATE_INPUT_STYLE );
+ removed = controller.RemoveText(-1,
+ 1,
+ UPDATE_INPUT_STYLE);
}
- else if( keyCode == Dali::DevelKey::DALI_KEY_DELETE )
+ else if(keyCode == Dali::DevelKey::DALI_KEY_DELETE)
{
// Remove the character after the current cursor position
- removed = controller.RemoveText( 0,
- 1,
- UPDATE_INPUT_STYLE );
+ removed = controller.RemoveText(0,
+ 1,
+ UPDATE_INPUT_STYLE);
}
- if( removed )
+ if(removed)
{
- if( ( 0u != controller.mImpl->mModel->mLogicalModel->mText.Count() ) ||
- !controller.mImpl->IsPlaceholderAvailable() )
+ if((0u != controller.mImpl->mModel->mLogicalModel->mText.Count()) ||
+ !controller.mImpl->IsPlaceholderAvailable())
{
- controller.mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
+ controller.mImpl->QueueModifyEvent(ModifyEvent::TEXT_DELETED);
}
else
{
controller.ShowPlaceholderText();
}
controller.mImpl->mEventData->mUpdateCursorPosition = true;
- controller.mImpl->mEventData->mScrollAfterDelete = true;
+ controller.mImpl->mEventData->mScrollAfterDelete = true;
}
return removed;
bool requestRelayout = false;
// Whether to retrieve the text and cursor position to be sent to the InputMethodContext.
- bool retrieveText = false;
+ bool retrieveText = false;
bool retrieveCursor = false;
- switch( inputMethodContextEvent.eventName )
+ switch(inputMethodContextEvent.eventName)
{
case InputMethodContext::COMMIT:
{
- controller.InsertText( inputMethodContextEvent.predictiveString, Text::Controller::COMMIT );
+ controller.InsertText(inputMethodContextEvent.predictiveString, Text::Controller::COMMIT);
requestRelayout = true;
- retrieveCursor = true;
+ retrieveCursor = true;
break;
}
case InputMethodContext::PRE_EDIT:
{
- controller.InsertText( inputMethodContextEvent.predictiveString, Text::Controller::PRE_EDIT );
+ controller.InsertText(inputMethodContextEvent.predictiveString, Text::Controller::PRE_EDIT);
requestRelayout = true;
- retrieveCursor = true;
+ retrieveCursor = true;
break;
}
case InputMethodContext::DELETE_SURROUNDING:
{
- const bool textDeleted = controller.RemoveText( inputMethodContextEvent.cursorOffset,
- inputMethodContextEvent.numberOfChars,
- DONT_UPDATE_INPUT_STYLE );
+ const bool textDeleted = controller.RemoveText(inputMethodContextEvent.cursorOffset,
+ inputMethodContextEvent.numberOfChars,
+ DONT_UPDATE_INPUT_STYLE);
- if( textDeleted )
+ if(textDeleted)
{
- if( ( 0u != controller.mImpl->mModel->mLogicalModel->mText.Count() ) ||
- !controller.mImpl->IsPlaceholderAvailable() )
+ if((0u != controller.mImpl->mModel->mLogicalModel->mText.Count()) ||
+ !controller.mImpl->IsPlaceholderAvailable())
{
- controller.mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
+ controller.mImpl->QueueModifyEvent(ModifyEvent::TEXT_DELETED);
}
else
{
controller.ShowPlaceholderText();
}
controller.mImpl->mEventData->mUpdateCursorPosition = true;
- controller.mImpl->mEventData->mScrollAfterDelete = true;
+ controller.mImpl->mEventData->mScrollAfterDelete = true;
requestRelayout = true;
}
}
case InputMethodContext::GET_SURROUNDING:
{
- retrieveText = true;
+ retrieveText = true;
retrieveCursor = true;
break;
}
case InputMethodContext::PRIVATE_COMMAND:
{
// PRIVATECOMMAND event is just for getting the private command message
- retrieveText = true;
+ retrieveText = true;
retrieveCursor = true;
break;
}
}
} // end switch
- if( requestRelayout )
+ if(requestRelayout)
{
controller.mImpl->mOperationsPending = ALL_OPERATIONS;
controller.mImpl->RequestRelayout();
}
- std::string text;
- CharacterIndex cursorPosition = 0u;
- Length numberOfWhiteSpaces = 0u;
+ std::string text;
+ CharacterIndex cursorPosition = 0u;
+ Length numberOfWhiteSpaces = 0u;
- if( retrieveCursor )
+ if(retrieveCursor)
{
- numberOfWhiteSpaces = controller.mImpl->GetNumberOfWhiteSpaces( 0u );
+ numberOfWhiteSpaces = controller.mImpl->GetNumberOfWhiteSpaces(0u);
cursorPosition = controller.mImpl->GetLogicalCursorPosition();
- if( cursorPosition < numberOfWhiteSpaces )
+ if(cursorPosition < numberOfWhiteSpaces)
{
cursorPosition = 0u;
}
}
}
- if( retrieveText )
+ if(retrieveText)
{
- if( !controller.mImpl->IsShowingPlaceholderText() )
+ if(!controller.mImpl->IsShowingPlaceholderText())
{
// Retrieves the normal text string.
- controller.mImpl->GetText( numberOfWhiteSpaces, text );
+ controller.mImpl->GetText(numberOfWhiteSpaces, text);
}
else
{
}
}
- InputMethodContext::CallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false );
+ InputMethodContext::CallbackData callbackData((retrieveText || retrieveCursor), cursorPosition, text, false);
- if( requestRelayout &&
- ( NULL != controller.mImpl->mEditableControlInterface ) )
+ if(requestRelayout &&
+ (NULL != controller.mImpl->mEditableControlInterface))
{
// Do this last since it provides callbacks into application code
controller.mImpl->mEditableControlInterface->TextChanged();
void Controller::EventHandler::PasteClipboardItemEvent(Controller& controller)
{
// Retrieve the clipboard contents first
- ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() );
- std::string stringToPaste( notifier.GetContent() );
+ ClipboardEventNotifier notifier(ClipboardEventNotifier::Get());
+ std::string stringToPaste(notifier.GetContent());
// Commit the current pre-edit text; the contents of the clipboard should be appended
controller.mImpl->ResetInputMethodContext();
// Temporary disable hiding clipboard
- controller.mImpl->SetClipboardHideEnable( false );
+ controller.mImpl->SetClipboardHideEnable(false);
// Paste
- controller.PasteText( stringToPaste );
+ controller.PasteText(stringToPaste);
- controller.mImpl->SetClipboardHideEnable( true );
+ controller.mImpl->SetClipboardHideEnable(true);
}
void Controller::EventHandler::DecorationEvent(Controller& controller, HandleType handleType, HandleState state, float x, float y)
{
- DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected DecorationEvent" );
+ DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected DecorationEvent");
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- switch( handleType )
+ switch(handleType)
{
case GRAB_HANDLE:
{
- Event event( Event::GRAB_HANDLE_EVENT );
+ Event event(Event::GRAB_HANDLE_EVENT);
event.p1.mUint = state;
event.p2.mFloat = x;
event.p3.mFloat = y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
break;
}
case LEFT_SELECTION_HANDLE:
{
- Event event( Event::LEFT_SELECTION_HANDLE_EVENT );
+ Event event(Event::LEFT_SELECTION_HANDLE_EVENT);
event.p1.mUint = state;
event.p2.mFloat = x;
event.p3.mFloat = y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
break;
}
case RIGHT_SELECTION_HANDLE:
{
- Event event( Event::RIGHT_SELECTION_HANDLE_EVENT );
+ Event event(Event::RIGHT_SELECTION_HANDLE_EVENT);
event.p1.mUint = state;
event.p2.mFloat = x;
event.p3.mFloat = y;
- controller.mImpl->mEventData->mEventQueue.push_back( event );
+ controller.mImpl->mEventData->mEventQueue.push_back(event);
break;
}
case LEFT_SELECTION_HANDLE_MARKER:
}
case HANDLE_TYPE_COUNT:
{
- DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" );
+ DALI_ASSERT_DEBUG(!"Controller::HandleEvent. Unexpected handle type");
}
}
void Controller::EventHandler::TextPopupButtonTouched(Controller& controller, Dali::Toolkit::TextSelectionPopup::Buttons button)
{
- if( NULL == controller.mImpl->mEventData )
+ if(NULL == controller.mImpl->mEventData)
{
return;
}
- switch( button )
+ switch(button)
{
case Toolkit::TextSelectionPopup::CUT:
{
- if (!controller.IsEditable()) return;
- controller.mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text
+ if(!controller.IsEditable()) return;
+ controller.mImpl->SendSelectionToClipboard(true); // Synchronous call to modify text
controller.mImpl->mOperationsPending = ALL_OPERATIONS;
- if( ( 0u != controller.mImpl->mModel->mLogicalModel->mText.Count() ) ||
- !controller.mImpl->IsPlaceholderAvailable() )
+ if((0u != controller.mImpl->mModel->mLogicalModel->mText.Count()) ||
+ !controller.mImpl->IsPlaceholderAvailable())
{
- controller.mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED );
+ controller.mImpl->QueueModifyEvent(ModifyEvent::TEXT_DELETED);
}
else
{
}
controller.mImpl->mEventData->mUpdateCursorPosition = true;
- controller.mImpl->mEventData->mScrollAfterDelete = true;
+ controller.mImpl->mEventData->mScrollAfterDelete = true;
controller.mImpl->RequestRelayout();
- if( NULL != controller.mImpl->mEditableControlInterface )
+ if(NULL != controller.mImpl->mEditableControlInterface)
{
controller.mImpl->mEditableControlInterface->TextChanged();
}
}
case Toolkit::TextSelectionPopup::COPY:
{
- controller.mImpl->SendSelectionToClipboard( false ); // Text not modified
+ controller.mImpl->SendSelectionToClipboard(false); // Text not modified
controller.mImpl->mEventData->mUpdateCursorPosition = true;
}
case Toolkit::TextSelectionPopup::SELECT:
{
- const Vector2& currentCursorPosition = controller.mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
+ const Vector2& currentCursorPosition = controller.mImpl->mEventData->mDecorator->GetPosition(PRIMARY_CURSOR);
- if( controller.mImpl->mEventData->mSelectionEnabled )
+ if(controller.mImpl->mEventData->mSelectionEnabled)
{
// Creates a SELECT event.
- controller.SelectEvent( currentCursorPosition.x, currentCursorPosition.y, SelectionType::INTERACTIVE );
+ controller.SelectEvent(currentCursorPosition.x, currentCursorPosition.y, SelectionType::INTERACTIVE);
}
break;
}
case Toolkit::TextSelectionPopup::SELECT_ALL:
{
// Creates a SELECT_ALL event
- controller.SelectEvent( 0.f, 0.f, SelectionType::ALL );
+ controller.SelectEvent(0.f, 0.f, SelectionType::ALL);
break;
}
case Toolkit::TextSelectionPopup::CLIPBOARD:
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/text-controller-impl-event-handler.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/adaptor-framework/key.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/adaptor-framework/key.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/cursor-helper-functions.h>
namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
bool ControllerImplEventHandler::ProcessInputEvents(Controller::Impl& impl)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::ProcessInputEvents\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::ProcessInputEvents\n");
EventData*& eventData = impl.mEventData;
- if( NULL == eventData )
+ if(NULL == eventData)
{
// Nothing to do if there is no text input.
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::ProcessInputEvents no event data\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::ProcessInputEvents no event data\n");
return false;
}
- if( eventData->mDecorator )
+ if(eventData->mDecorator)
{
- for( std::vector<Event>::iterator iter = eventData->mEventQueue.begin();
- iter != eventData->mEventQueue.end();
- ++iter )
+ for(std::vector<Event>::iterator iter = eventData->mEventQueue.begin();
+ iter != eventData->mEventQueue.end();
+ ++iter)
{
- switch( iter->type )
+ switch(iter->type)
{
case Event::CURSOR_KEY_EVENT:
{
}
}
- if( eventData->mUpdateCursorPosition ||
- eventData->mUpdateHighlightBox )
+ if(eventData->mUpdateCursorPosition ||
+ eventData->mUpdateHighlightBox)
{
impl.NotifyInputMethodContext();
}
// The cursor must also be repositioned after inserts into the model
- if( eventData->mUpdateCursorPosition )
+ if(eventData->mUpdateCursorPosition)
{
// Updates the cursor position and scrolls the text to make it visible.
CursorInfo cursorInfo;
if(nullptr != impl.mEditableControlInterface)
{
- impl.mEditableControlInterface->CaretMoved( eventData->mPrimaryCursorPosition );
+ impl.mEditableControlInterface->CaretMoved(eventData->mPrimaryCursorPosition);
}
- if( eventData->mUpdateCursorHookPosition )
+ if(eventData->mUpdateCursorHookPosition)
{
// Update the cursor hook position. Used to move the cursor with the keys 'up' and 'down'.
- eventData->mCursorHookPositionX = cursorInfo.primaryPosition.x;
+ eventData->mCursorHookPositionX = cursorInfo.primaryPosition.x;
eventData->mUpdateCursorHookPosition = false;
}
// Scroll first the text after delete ...
- if( eventData->mScrollAfterDelete )
+ if(eventData->mScrollAfterDelete)
{
impl.ScrollTextToMatchCursor(cursorInfo);
}
// ... then, text can be scrolled to make the cursor visible.
- if( eventData->mScrollAfterUpdatePosition )
+ if(eventData->mScrollAfterUpdatePosition)
{
- const Vector2 currentCursorPosition( cursorInfo.primaryPosition.x, cursorInfo.lineOffset );
- impl.ScrollToMakePositionVisible( currentCursorPosition, cursorInfo.lineHeight );
+ const Vector2 currentCursorPosition(cursorInfo.primaryPosition.x, cursorInfo.lineOffset);
+ impl.ScrollToMakePositionVisible(currentCursorPosition, cursorInfo.lineHeight);
}
eventData->mScrollAfterUpdatePosition = false;
- eventData->mScrollAfterDelete = false;
+ eventData->mScrollAfterDelete = false;
- impl.UpdateCursorPosition( cursorInfo );
+ impl.UpdateCursorPosition(cursorInfo);
- eventData->mDecoratorUpdated = true;
- eventData->mUpdateCursorPosition = false;
+ eventData->mDecoratorUpdated = true;
+ eventData->mUpdateCursorPosition = false;
eventData->mUpdateGrabHandlePosition = false;
}
else
CursorInfo leftHandleInfo;
CursorInfo rightHandleInfo;
- if( eventData->mUpdateHighlightBox )
+ if(eventData->mUpdateHighlightBox)
{
impl.GetCursorPosition(eventData->mLeftSelectionPosition, leftHandleInfo);
impl.GetCursorPosition(eventData->mRightSelectionPosition, rightHandleInfo);
- if( eventData->mScrollAfterUpdatePosition && ( eventData->mIsLeftHandleSelected ? eventData->mUpdateLeftSelectionPosition : eventData->mUpdateRightSelectionPosition ) )
+ if(eventData->mScrollAfterUpdatePosition && (eventData->mIsLeftHandleSelected ? eventData->mUpdateLeftSelectionPosition : eventData->mUpdateRightSelectionPosition))
{
- if( eventData->mIsLeftHandleSelected && eventData->mIsRightHandleSelected )
+ if(eventData->mIsLeftHandleSelected && eventData->mIsRightHandleSelected)
{
CursorInfo& infoLeft = leftHandleInfo;
- const Vector2 currentCursorPositionLeft( infoLeft.primaryPosition.x, infoLeft.lineOffset );
- impl.ScrollToMakePositionVisible( currentCursorPositionLeft, infoLeft.lineHeight );
+ const Vector2 currentCursorPositionLeft(infoLeft.primaryPosition.x, infoLeft.lineOffset);
+ impl.ScrollToMakePositionVisible(currentCursorPositionLeft, infoLeft.lineHeight);
CursorInfo& infoRight = rightHandleInfo;
- const Vector2 currentCursorPositionRight( infoRight.primaryPosition.x, infoRight.lineOffset );
- impl.ScrollToMakePositionVisible( currentCursorPositionRight, infoRight.lineHeight );
+ const Vector2 currentCursorPositionRight(infoRight.primaryPosition.x, infoRight.lineOffset);
+ impl.ScrollToMakePositionVisible(currentCursorPositionRight, infoRight.lineHeight);
}
else
{
CursorInfo& info = eventData->mIsLeftHandleSelected ? leftHandleInfo : rightHandleInfo;
- const Vector2 currentCursorPosition( info.primaryPosition.x, info.lineOffset );
- impl. ScrollToMakePositionVisible( currentCursorPosition, info.lineHeight );
+ const Vector2 currentCursorPosition(info.primaryPosition.x, info.lineOffset);
+ impl.ScrollToMakePositionVisible(currentCursorPosition, info.lineHeight);
}
}
}
- if( eventData->mUpdateLeftSelectionPosition )
+ if(eventData->mUpdateLeftSelectionPosition)
{
impl.UpdateSelectionHandle(LEFT_SELECTION_HANDLE, leftHandleInfo);
impl.SetPopupButtons();
- eventData->mDecoratorUpdated = true;
+ eventData->mDecoratorUpdated = true;
eventData->mUpdateLeftSelectionPosition = false;
}
- if( eventData->mUpdateRightSelectionPosition )
+ if(eventData->mUpdateRightSelectionPosition)
{
impl.UpdateSelectionHandle(RIGHT_SELECTION_HANDLE, rightHandleInfo);
impl.SetPopupButtons();
- eventData->mDecoratorUpdated = true;
+ eventData->mDecoratorUpdated = true;
eventData->mUpdateRightSelectionPosition = false;
}
- if( eventData->mUpdateHighlightBox )
+ if(eventData->mUpdateHighlightBox)
{
impl.RepositionSelectionHandles();
- eventData->mUpdateLeftSelectionPosition = false;
+ eventData->mUpdateLeftSelectionPosition = false;
eventData->mUpdateRightSelectionPosition = false;
- eventData->mUpdateHighlightBox = false;
- eventData->mIsLeftHandleSelected = false;
- eventData->mIsRightHandleSelected = false;
+ eventData->mUpdateHighlightBox = false;
+ eventData->mIsLeftHandleSelected = false;
+ eventData->mIsRightHandleSelected = false;
}
eventData->mScrollAfterUpdatePosition = false;
}
- if( eventData->mUpdateInputStyle )
+ if(eventData->mUpdateInputStyle)
{
// Keep a copy of the current input style.
InputStyle currentInputStyle;
- currentInputStyle.Copy( eventData->mInputStyle );
+ currentInputStyle.Copy(eventData->mInputStyle);
// Set the default style first.
- impl.RetrieveDefaultInputStyle( eventData->mInputStyle );
+ impl.RetrieveDefaultInputStyle(eventData->mInputStyle);
// Get the character index from the cursor index.
- const CharacterIndex styleIndex = ( eventData->mPrimaryCursorPosition > 0u ) ? eventData->mPrimaryCursorPosition - 1u : 0u;
+ const CharacterIndex styleIndex = (eventData->mPrimaryCursorPosition > 0u) ? eventData->mPrimaryCursorPosition - 1u : 0u;
// Retrieve the style from the style runs stored in the logical model.
- impl.mModel->mLogicalModel->RetrieveStyle( styleIndex, eventData->mInputStyle );
+ impl.mModel->mLogicalModel->RetrieveStyle(styleIndex, eventData->mInputStyle);
// Compare if the input style has changed.
- const bool hasInputStyleChanged = !currentInputStyle.Equal( eventData->mInputStyle );
+ const bool hasInputStyleChanged = !currentInputStyle.Equal(eventData->mInputStyle);
- if( hasInputStyleChanged )
+ if(hasInputStyleChanged)
{
- const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( eventData->mInputStyle );
+ const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask(eventData->mInputStyle);
// Queue the input style changed signal.
- eventData->mInputStyleChangedQueue.PushBack( styleChangedMask );
+ eventData->mInputStyleChangedQueue.PushBack(styleChangedMask);
}
eventData->mUpdateInputStyle = false;
eventData->mEventQueue.clear();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::ProcessInputEvents\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::ProcessInputEvents\n");
- const bool decoratorUpdated = eventData->mDecoratorUpdated;
+ const bool decoratorUpdated = eventData->mDecoratorUpdated;
eventData->mDecoratorUpdated = false;
return decoratorUpdated;
}
-
void ControllerImplEventHandler::OnCursorKeyEvent(Controller::Impl& impl, const Event& event)
{
- if( NULL == impl.mEventData || !impl.IsShowingRealText() )
+ if(NULL == impl.mEventData || !impl.IsShowingRealText())
{
// Nothing to do if there is no text input.
return;
}
- int keyCode = event.p1.mInt;
- bool isShiftModifier = event.p2.mBool;
- EventData& eventData = *impl.mEventData;
- ModelPtr& model = impl.mModel;
- LogicalModelPtr& logicalModel = model->mLogicalModel;
- VisualModelPtr& visualModel = model->mVisualModel;
+ int keyCode = event.p1.mInt;
+ bool isShiftModifier = event.p2.mBool;
+ EventData& eventData = *impl.mEventData;
+ ModelPtr& model = impl.mModel;
+ LogicalModelPtr& logicalModel = model->mLogicalModel;
+ VisualModelPtr& visualModel = model->mVisualModel;
- CharacterIndex& primaryCursorPosition = eventData.mPrimaryCursorPosition;
- CharacterIndex previousPrimaryCursorPosition = primaryCursorPosition;
+ CharacterIndex& primaryCursorPosition = eventData.mPrimaryCursorPosition;
+ CharacterIndex previousPrimaryCursorPosition = primaryCursorPosition;
- if( Dali::DALI_KEY_CURSOR_LEFT == keyCode )
+ if(Dali::DALI_KEY_CURSOR_LEFT == keyCode)
{
- if( primaryCursorPosition > 0u )
+ if(primaryCursorPosition > 0u)
{
- if ( !isShiftModifier && eventData.mDecorator->IsHighlightVisible() )
+ if(!isShiftModifier && eventData.mDecorator->IsHighlightVisible())
{
primaryCursorPosition = std::min(eventData.mLeftSelectionPosition, eventData.mRightSelectionPosition);
}
else
{
- primaryCursorPosition = impl.CalculateNewCursorIndex( primaryCursorPosition - 1u );
+ primaryCursorPosition = impl.CalculateNewCursorIndex(primaryCursorPosition - 1u);
}
}
}
- else if( Dali::DALI_KEY_CURSOR_RIGHT == keyCode )
+ else if(Dali::DALI_KEY_CURSOR_RIGHT == keyCode)
{
- if( logicalModel->mText.Count() > primaryCursorPosition )
+ if(logicalModel->mText.Count() > primaryCursorPosition)
{
- if ( !isShiftModifier && eventData.mDecorator->IsHighlightVisible() )
+ if(!isShiftModifier && eventData.mDecorator->IsHighlightVisible())
{
primaryCursorPosition = std::max(eventData.mLeftSelectionPosition, eventData.mRightSelectionPosition);
}
else
{
- primaryCursorPosition = impl.CalculateNewCursorIndex( primaryCursorPosition );
+ primaryCursorPosition = impl.CalculateNewCursorIndex(primaryCursorPosition);
}
}
}
- else if( Dali::DALI_KEY_CURSOR_UP == keyCode && !isShiftModifier )
+ else if(Dali::DALI_KEY_CURSOR_UP == keyCode && !isShiftModifier)
{
// Ignore Shift-Up for text selection for now.
// Get first the line index of the current cursor position index.
CharacterIndex characterIndex = 0u;
- if( primaryCursorPosition > 0u )
+ if(primaryCursorPosition > 0u)
{
characterIndex = primaryCursorPosition - 1u;
}
- const LineIndex lineIndex = visualModel->GetLineOfCharacter( characterIndex );
- const LineIndex previousLineIndex = ( lineIndex > 0 ? lineIndex - 1u : lineIndex );
+ const LineIndex lineIndex = visualModel->GetLineOfCharacter(characterIndex);
+ const LineIndex previousLineIndex = (lineIndex > 0 ? lineIndex - 1u : lineIndex);
// Retrieve the cursor position info.
CursorInfo cursorInfo;
- impl.GetCursorPosition( primaryCursorPosition,
- cursorInfo );
+ impl.GetCursorPosition(primaryCursorPosition,
+ cursorInfo);
// Get the line above.
- const LineRun& line = *( visualModel->mLines.Begin() + previousLineIndex );
+ const LineRun& line = *(visualModel->mLines.Begin() + previousLineIndex);
// Get the next hit 'y' point.
- const float hitPointY = cursorInfo.lineOffset - 0.5f * ( line.ascender - line.descender );
+ const float hitPointY = cursorInfo.lineOffset - 0.5f * (line.ascender - line.descender);
// Use the cursor hook position 'x' and the next hit 'y' position to calculate the new cursor index.
bool matchedCharacter = false;
- primaryCursorPosition = Text::GetClosestCursorIndex( visualModel,
- logicalModel,
- impl.mMetrics,
- eventData.mCursorHookPositionX,
- hitPointY,
- CharacterHitTest::TAP,
- matchedCharacter );
+ primaryCursorPosition = Text::GetClosestCursorIndex(visualModel,
+ logicalModel,
+ impl.mMetrics,
+ eventData.mCursorHookPositionX,
+ hitPointY,
+ CharacterHitTest::TAP,
+ matchedCharacter);
}
- else if( Dali::DALI_KEY_CURSOR_DOWN == keyCode && !isShiftModifier )
+ else if(Dali::DALI_KEY_CURSOR_DOWN == keyCode && !isShiftModifier)
{
// Ignore Shift-Down for text selection for now.
// Get first the line index of the current cursor position index.
CharacterIndex characterIndex = 0u;
- if( primaryCursorPosition > 0u )
+ if(primaryCursorPosition > 0u)
{
characterIndex = primaryCursorPosition - 1u;
}
- const LineIndex lineIndex = visualModel->GetLineOfCharacter( characterIndex );
+ const LineIndex lineIndex = visualModel->GetLineOfCharacter(characterIndex);
- if( lineIndex + 1u < visualModel->mLines.Count() )
+ if(lineIndex + 1u < visualModel->mLines.Count())
{
// Retrieve the cursor position info.
CursorInfo cursorInfo;
- impl.GetCursorPosition( primaryCursorPosition, cursorInfo );
+ impl.GetCursorPosition(primaryCursorPosition, cursorInfo);
// Get the line below.
- const LineRun& line = *( visualModel->mLines.Begin() + lineIndex + 1u );
+ const LineRun& line = *(visualModel->mLines.Begin() + lineIndex + 1u);
// Get the next hit 'y' point.
- const float hitPointY = cursorInfo.lineOffset + cursorInfo.lineHeight + 0.5f * ( line.ascender - line.descender );
+ const float hitPointY = cursorInfo.lineOffset + cursorInfo.lineHeight + 0.5f * (line.ascender - line.descender);
// Use the cursor hook position 'x' and the next hit 'y' position to calculate the new cursor index.
bool matchedCharacter = false;
- primaryCursorPosition = Text::GetClosestCursorIndex( visualModel,
- logicalModel,
- impl.mMetrics,
- eventData.mCursorHookPositionX,
- hitPointY,
- CharacterHitTest::TAP,
- matchedCharacter );
+ primaryCursorPosition = Text::GetClosestCursorIndex(visualModel,
+ logicalModel,
+ impl.mMetrics,
+ eventData.mCursorHookPositionX,
+ hitPointY,
+ CharacterHitTest::TAP,
+ matchedCharacter);
}
}
- if ( !isShiftModifier && eventData.mState != EventData::SELECTING )
+ if(!isShiftModifier && eventData.mState != EventData::SELECTING)
{
// Update selection position after moving the cursor
- eventData.mLeftSelectionPosition = primaryCursorPosition;
+ eventData.mLeftSelectionPosition = primaryCursorPosition;
eventData.mRightSelectionPosition = primaryCursorPosition;
}
- if ( isShiftModifier && impl.IsShowingRealText() && eventData.mShiftSelectionFlag )
+ if(isShiftModifier && impl.IsShowingRealText() && eventData.mShiftSelectionFlag)
{
// Handle text selection
bool selecting = false;
- if ( Dali::DALI_KEY_CURSOR_LEFT == keyCode || Dali::DALI_KEY_CURSOR_RIGHT == keyCode )
+ if(Dali::DALI_KEY_CURSOR_LEFT == keyCode || Dali::DALI_KEY_CURSOR_RIGHT == keyCode)
{
// Shift-Left/Right to select the text
int cursorPositionDelta = primaryCursorPosition - previousPrimaryCursorPosition;
- if ( cursorPositionDelta > 0 || eventData.mRightSelectionPosition > 0u ) // Check the boundary
+ if(cursorPositionDelta > 0 || eventData.mRightSelectionPosition > 0u) // Check the boundary
{
eventData.mRightSelectionPosition += cursorPositionDelta;
}
selecting = true;
}
- else if ( eventData.mLeftSelectionPosition != eventData.mRightSelectionPosition )
+ else if(eventData.mLeftSelectionPosition != eventData.mRightSelectionPosition)
{
// Show no grab handles and text highlight if Shift-Up/Down pressed but no selected text
selecting = true;
}
- if ( selecting )
+ if(selecting)
{
// Notify the cursor position to the InputMethodContext.
- if( eventData.mInputMethodContext )
+ if(eventData.mInputMethodContext)
{
- eventData.mInputMethodContext.SetCursorPosition( primaryCursorPosition );
+ eventData.mInputMethodContext.SetCursorPosition(primaryCursorPosition);
eventData.mInputMethodContext.NotifyCursorPosition();
}
- impl.ChangeState( EventData::SELECTING );
+ impl.ChangeState(EventData::SELECTING);
- eventData.mUpdateLeftSelectionPosition = true;
+ eventData.mUpdateLeftSelectionPosition = true;
eventData.mUpdateRightSelectionPosition = true;
- eventData.mUpdateGrabHandlePosition = true;
- eventData.mUpdateHighlightBox = true;
+ eventData.mUpdateGrabHandlePosition = true;
+ eventData.mUpdateHighlightBox = true;
// Hide the text selection popup if select the text using keyboard instead of moving grab handles
- if( eventData.mGrabHandlePopupEnabled )
+ if(eventData.mGrabHandlePopupEnabled)
{
- eventData.mDecorator->SetPopupActive( false );
+ eventData.mDecorator->SetPopupActive(false);
}
}
}
else
{
// Handle normal cursor move
- impl.ChangeState( EventData::EDITING );
+ impl.ChangeState(EventData::EDITING);
eventData.mUpdateCursorPosition = true;
}
- eventData.mUpdateInputStyle = true;
+ eventData.mUpdateInputStyle = true;
eventData.mScrollAfterUpdatePosition = true;
}
void ControllerImplEventHandler::OnTapEvent(Controller::Impl& impl, const Event& event)
{
- if( impl.mEventData )
+ if(impl.mEventData)
{
- const unsigned int tapCount = event.p1.mUint;
- EventData& eventData = *impl.mEventData;
- ModelPtr& model = impl.mModel;
- LogicalModelPtr& logicalModel = model->mLogicalModel;
- VisualModelPtr& visualModel = model->mVisualModel;
+ const unsigned int tapCount = event.p1.mUint;
+ EventData& eventData = *impl.mEventData;
+ ModelPtr& model = impl.mModel;
+ LogicalModelPtr& logicalModel = model->mLogicalModel;
+ VisualModelPtr& visualModel = model->mVisualModel;
- if( 1u == tapCount )
+ if(1u == tapCount)
{
- if( impl.IsShowingRealText() )
+ if(impl.IsShowingRealText())
{
// Convert from control's coords to text's coords.
const float xPosition = event.p2.mFloat - model->mScrollPosition.x;
eventData.mCursorHookPositionX = xPosition;
// Whether to touch point hits on a glyph.
- bool matchedCharacter = false;
- eventData.mPrimaryCursorPosition = Text::GetClosestCursorIndex( visualModel,
- logicalModel,
- impl.mMetrics,
- xPosition,
- yPosition,
- CharacterHitTest::TAP,
- matchedCharacter );
+ bool matchedCharacter = false;
+ eventData.mPrimaryCursorPosition = Text::GetClosestCursorIndex(visualModel,
+ logicalModel,
+ impl.mMetrics,
+ xPosition,
+ yPosition,
+ CharacterHitTest::TAP,
+ matchedCharacter);
// When the cursor position is changing, delay cursor blinking
eventData.mDecorator->DelayCursorBlink();
}
// Update selection position after tapping
- eventData.mLeftSelectionPosition = eventData.mPrimaryCursorPosition;
+ eventData.mLeftSelectionPosition = eventData.mPrimaryCursorPosition;
eventData.mRightSelectionPosition = eventData.mPrimaryCursorPosition;
- eventData.mUpdateCursorPosition = true;
- eventData.mUpdateGrabHandlePosition = true;
+ eventData.mUpdateCursorPosition = true;
+ eventData.mUpdateGrabHandlePosition = true;
eventData.mScrollAfterUpdatePosition = true;
- eventData.mUpdateInputStyle = true;
+ eventData.mUpdateInputStyle = true;
// Notify the cursor position to the InputMethodContext.
- if( eventData.mInputMethodContext )
+ if(eventData.mInputMethodContext)
{
- eventData.mInputMethodContext.SetCursorPosition( eventData.mPrimaryCursorPosition );
+ eventData.mInputMethodContext.SetCursorPosition(eventData.mPrimaryCursorPosition);
eventData.mInputMethodContext.NotifyCursorPosition();
}
}
- else if( 2u == tapCount )
+ else if(2u == tapCount)
{
- if( eventData.mSelectionEnabled )
+ if(eventData.mSelectionEnabled)
{
// Convert from control's coords to text's coords.
const float xPosition = event.p2.mFloat - model->mScrollPosition.x;
const float yPosition = event.p3.mFloat - model->mScrollPosition.y;
// Calculates the logical position from the x,y coords.
- impl.RepositionSelectionHandles( xPosition, yPosition, eventData.mDoubleTapAction );
+ impl.RepositionSelectionHandles(xPosition, yPosition, eventData.mDoubleTapAction);
}
}
}
void ControllerImplEventHandler::OnPanEvent(Controller::Impl& impl, const Event& event)
{
- if( impl.mEventData )
+ if(impl.mEventData)
{
- EventData& eventData = *impl.mEventData;
+ EventData& eventData = *impl.mEventData;
DecoratorPtr& decorator = eventData.mDecorator;
const bool isHorizontalScrollEnabled = decorator->IsHorizontalScrollEnabled();
- const bool isVerticalScrollEnabled = decorator->IsVerticalScrollEnabled();
+ const bool isVerticalScrollEnabled = decorator->IsVerticalScrollEnabled();
- if( !isHorizontalScrollEnabled && !isVerticalScrollEnabled )
+ if(!isHorizontalScrollEnabled && !isVerticalScrollEnabled)
{
// Nothing to do if scrolling is not enabled.
return;
}
- const GestureState state = static_cast<GestureState>( event.p1.mInt );
- switch( state )
+ const GestureState state = static_cast<GestureState>(event.p1.mInt);
+ switch(state)
{
case GestureState::STARTED:
{
// Will remove the cursor, handles or text's popup, ...
- impl.ChangeState( EventData::TEXT_PANNING );
+ impl.ChangeState(EventData::TEXT_PANNING);
break;
}
case GestureState::CONTINUING:
{
ModelPtr& model = impl.mModel;
- const Vector2& layoutSize = model->mVisualModel->GetLayoutSize();
- Vector2& scrollPosition = model->mScrollPosition;
- const Vector2 currentScroll = scrollPosition;
+ const Vector2& layoutSize = model->mVisualModel->GetLayoutSize();
+ Vector2& scrollPosition = model->mScrollPosition;
+ const Vector2 currentScroll = scrollPosition;
- if( isHorizontalScrollEnabled )
+ if(isHorizontalScrollEnabled)
{
const float displacementX = event.p2.mFloat;
scrollPosition.x += displacementX;
- impl.ClampHorizontalScroll( layoutSize );
+ impl.ClampHorizontalScroll(layoutSize);
}
- if( isVerticalScrollEnabled )
+ if(isVerticalScrollEnabled)
{
const float displacementY = event.p3.mFloat;
scrollPosition.y += displacementY;
- impl.ClampVerticalScroll( layoutSize );
+ impl.ClampVerticalScroll(layoutSize);
}
- decorator->UpdatePositions( scrollPosition - currentScroll );
+ decorator->UpdatePositions(scrollPosition - currentScroll);
break;
}
case GestureState::FINISHED:
case GestureState::CANCELLED: // FALLTHROUGH
{
// Will go back to the previous state to show the cursor, handles, the text's popup, ...
- impl.ChangeState( eventData.mPreviousState );
+ impl.ChangeState(eventData.mPreviousState);
break;
}
default:
void ControllerImplEventHandler::OnLongPressEvent(Controller::Impl& impl, const Event& event)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::OnLongPressEvent\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::OnLongPressEvent\n");
- if( impl.mEventData )
+ if(impl.mEventData)
{
EventData& eventData = *impl.mEventData;
- if( !impl.IsShowingRealText() && ( EventData::EDITING == eventData.mState ) )
+ if(!impl.IsShowingRealText() && (EventData::EDITING == eventData.mState))
{
- impl.ChangeState( EventData::EDITING_WITH_POPUP );
+ impl.ChangeState(EventData::EDITING_WITH_POPUP);
eventData.mDecoratorUpdated = true;
eventData.mUpdateInputStyle = true;
}
else
{
- if( eventData.mSelectionEnabled )
+ if(eventData.mSelectionEnabled)
{
ModelPtr& model = impl.mModel;
const float yPosition = event.p3.mFloat - model->mScrollPosition.y;
// Calculates the logical position from the x,y coords.
- impl.RepositionSelectionHandles( xPosition, yPosition, eventData.mLongPressAction );
+ impl.RepositionSelectionHandles(xPosition, yPosition, eventData.mLongPressAction);
}
}
}
void ControllerImplEventHandler::OnHandleEvent(Controller::Impl& impl, const Event& event)
{
- if( impl.mEventData )
+ if(impl.mEventData)
{
- const unsigned int state = event.p1.mUint;
- const bool handleStopScrolling = ( HANDLE_STOP_SCROLLING == state );
- const bool isSmoothHandlePanEnabled = impl.mEventData->mDecorator->IsSmoothHandlePanEnabled();
+ const unsigned int state = event.p1.mUint;
+ const bool handleStopScrolling = (HANDLE_STOP_SCROLLING == state);
+ const bool isSmoothHandlePanEnabled = impl.mEventData->mDecorator->IsSmoothHandlePanEnabled();
- if( HANDLE_PRESSED == state )
+ if(HANDLE_PRESSED == state)
{
OnHandlePressed(impl, event, isSmoothHandlePanEnabled);
} // end ( HANDLE_PRESSED == state )
- else if( ( HANDLE_RELEASED == state ) ||
- handleStopScrolling )
+ else if((HANDLE_RELEASED == state) ||
+ handleStopScrolling)
{
OnHandleReleased(impl, event, isSmoothHandlePanEnabled, handleStopScrolling);
} // end ( ( HANDLE_RELEASED == state ) || ( HANDLE_STOP_SCROLLING == state ) )
- else if( HANDLE_SCROLLING == state )
+ else if(HANDLE_SCROLLING == state)
{
OnHandleScrolling(impl, event, isSmoothHandlePanEnabled);
} // end ( HANDLE_SCROLLING == state )
}
}
-void ControllerImplEventHandler::OnSelectEvent(Controller::Impl& impl, const Event& event )
+void ControllerImplEventHandler::OnSelectEvent(Controller::Impl& impl, const Event& event)
{
- if( impl.mEventData && impl.mEventData->mSelectionEnabled )
+ if(impl.mEventData && impl.mEventData->mSelectionEnabled)
{
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
const Vector2& scrollPosition = model->mScrollPosition;
// Convert from control's coords to text's coords.
const float yPosition = event.p3.mFloat - scrollPosition.y;
// Calculates the logical position from the x,y coords.
- impl.RepositionSelectionHandles( xPosition, yPosition, Controller::NoTextTap::HIGHLIGHT );
+ impl.RepositionSelectionHandles(xPosition, yPosition, Controller::NoTextTap::HIGHLIGHT);
}
}
void ControllerImplEventHandler::OnSelectAllEvent(Controller::Impl& impl)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "OnSelectAllEvent mEventData->mSelectionEnabled%s \n", impl.mEventData->mSelectionEnabled?"true":"false");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "OnSelectAllEvent mEventData->mSelectionEnabled%s \n", impl.mEventData->mSelectionEnabled ? "true" : "false");
- if( impl.mEventData )
+ if(impl.mEventData)
{
EventData& eventData = *impl.mEventData;
- if( eventData.mSelectionEnabled )
+ if(eventData.mSelectionEnabled)
{
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
const Vector2& scrollPosition = model->mScrollPosition;
// Calculates the logical position from the start.
- impl.RepositionSelectionHandles( 0.f - scrollPosition.x,
- 0.f - scrollPosition.y,
- Controller::NoTextTap::HIGHLIGHT );
+ impl.RepositionSelectionHandles(0.f - scrollPosition.x,
+ 0.f - scrollPosition.y,
+ Controller::NoTextTap::HIGHLIGHT);
- eventData.mLeftSelectionPosition = 0u;
+ eventData.mLeftSelectionPosition = 0u;
eventData.mRightSelectionPosition = model->mLogicalModel->mText.Count();
}
}
void ControllerImplEventHandler::OnSelectNoneEvent(Controller::Impl& impl)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "OnSelectNoneEvent mEventData->mSelectionEnabled%s \n", impl.mEventData->mSelectionEnabled?"true":"false");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "OnSelectNoneEvent mEventData->mSelectionEnabled%s \n", impl.mEventData->mSelectionEnabled ? "true" : "false");
- if( impl.mEventData )
+ if(impl.mEventData)
{
EventData& eventData = *impl.mEventData;
- if( eventData.mSelectionEnabled && eventData.mState == EventData::SELECTING)
+ if(eventData.mSelectionEnabled && eventData.mState == EventData::SELECTING)
{
eventData.mPrimaryCursorPosition = 0u;
eventData.mLeftSelectionPosition = eventData.mRightSelectionPosition = eventData.mPrimaryCursorPosition;
- impl.ChangeState( EventData::INACTIVE );
- eventData.mUpdateCursorPosition = true;
- eventData.mUpdateInputStyle = true;
+ impl.ChangeState(EventData::INACTIVE);
+ eventData.mUpdateCursorPosition = true;
+ eventData.mUpdateInputStyle = true;
eventData.mScrollAfterUpdatePosition = true;
}
}
void ControllerImplEventHandler::OnHandlePressed(Controller::Impl& impl, const Event& event, const bool isSmoothHandlePanEnabled)
{
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
const Vector2& scrollPosition = model->mScrollPosition;
// Convert from decorator's coords to text's coords.
const float yPosition = event.p3.mFloat - scrollPosition.y;
// Need to calculate the handle's new position.
- bool matchedCharacter = false;
- const CharacterIndex handleNewPosition = Text::GetClosestCursorIndex( model->mVisualModel,
- model->mLogicalModel,
- impl.mMetrics,
- xPosition,
- yPosition,
- CharacterHitTest::SCROLL,
- matchedCharacter );
+ bool matchedCharacter = false;
+ const CharacterIndex handleNewPosition = Text::GetClosestCursorIndex(model->mVisualModel,
+ model->mLogicalModel,
+ impl.mMetrics,
+ xPosition,
+ yPosition,
+ CharacterHitTest::SCROLL,
+ matchedCharacter);
EventData& eventData = *impl.mEventData;
- if( Event::GRAB_HANDLE_EVENT == event.type )
+ if(Event::GRAB_HANDLE_EVENT == event.type)
{
- impl.ChangeState ( EventData::GRAB_HANDLE_PANNING );
+ impl.ChangeState(EventData::GRAB_HANDLE_PANNING);
- if( handleNewPosition != eventData.mPrimaryCursorPosition )
+ if(handleNewPosition != eventData.mPrimaryCursorPosition)
{
// Updates the cursor position if the handle's new position is different than the current one.
eventData.mUpdateCursorPosition = true;
// Does not update the grab handle position if the smooth panning is enabled. (The decorator does it smooth).
eventData.mUpdateGrabHandlePosition = !isSmoothHandlePanEnabled;
- eventData.mPrimaryCursorPosition = handleNewPosition;
+ eventData.mPrimaryCursorPosition = handleNewPosition;
}
// Updates the decorator if the soft handle panning is enabled. It triggers a relayout in the decorator and the new position of the handle is set.
eventData.mDecoratorUpdated = isSmoothHandlePanEnabled;
}
- else if( Event::LEFT_SELECTION_HANDLE_EVENT == event.type )
+ else if(Event::LEFT_SELECTION_HANDLE_EVENT == event.type)
{
- impl.ChangeState ( EventData::SELECTION_HANDLE_PANNING );
+ impl.ChangeState(EventData::SELECTION_HANDLE_PANNING);
- if( ( handleNewPosition != eventData.mLeftSelectionPosition ) &&
- ( handleNewPosition != eventData.mRightSelectionPosition ) )
+ if((handleNewPosition != eventData.mLeftSelectionPosition) &&
+ (handleNewPosition != eventData.mRightSelectionPosition))
{
// Updates the highlight box if the handle's new position is different than the current one.
eventData.mUpdateHighlightBox = true;
// Does not update the selection handle position if the smooth panning is enabled. (The decorator does it smooth).
eventData.mUpdateLeftSelectionPosition = !isSmoothHandlePanEnabled;
- eventData.mLeftSelectionPosition = handleNewPosition;
+ eventData.mLeftSelectionPosition = handleNewPosition;
}
// Updates the decorator if the soft handle panning is enabled. It triggers a relayout in the decorator and the new position of the handle is set.
eventData.mDecoratorUpdated = isSmoothHandlePanEnabled;
// Will define the order to scroll the text to match the handle position.
- eventData.mIsLeftHandleSelected = true;
+ eventData.mIsLeftHandleSelected = true;
eventData.mIsRightHandleSelected = false;
}
- else if( Event::RIGHT_SELECTION_HANDLE_EVENT == event.type )
+ else if(Event::RIGHT_SELECTION_HANDLE_EVENT == event.type)
{
- impl.ChangeState ( EventData::SELECTION_HANDLE_PANNING );
+ impl.ChangeState(EventData::SELECTION_HANDLE_PANNING);
- if( ( handleNewPosition != eventData.mRightSelectionPosition ) &&
- ( handleNewPosition != eventData.mLeftSelectionPosition ) )
+ if((handleNewPosition != eventData.mRightSelectionPosition) &&
+ (handleNewPosition != eventData.mLeftSelectionPosition))
{
// Updates the highlight box if the handle's new position is different than the current one.
eventData.mUpdateHighlightBox = true;
// Does not update the selection handle position if the smooth panning is enabled. (The decorator does it smooth).
eventData.mUpdateRightSelectionPosition = !isSmoothHandlePanEnabled;
- eventData.mRightSelectionPosition = handleNewPosition;
+ eventData.mRightSelectionPosition = handleNewPosition;
}
// Updates the decorator if the soft handle panning is enabled. It triggers a relayout in the decorator and the new position of the handle is set.
eventData.mDecoratorUpdated = isSmoothHandlePanEnabled;
// Will define the order to scroll the text to match the handle position.
- eventData.mIsLeftHandleSelected = false;
+ eventData.mIsLeftHandleSelected = false;
eventData.mIsRightHandleSelected = true;
}
}
void ControllerImplEventHandler::OnHandleReleased(Controller::Impl& impl, const Event& event, const bool isSmoothHandlePanEnabled, const bool handleStopScrolling)
{
CharacterIndex handlePosition = 0u;
- if( handleStopScrolling || isSmoothHandlePanEnabled )
+ if(handleStopScrolling || isSmoothHandlePanEnabled)
{
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
const Vector2& scrollPosition = model->mScrollPosition;
// Convert from decorator's coords to text's coords.
const float yPosition = event.p3.mFloat - scrollPosition.y;
bool matchedCharacter = false;
- handlePosition = Text::GetClosestCursorIndex( model->mVisualModel,
- model->mLogicalModel,
- impl.mMetrics,
- xPosition,
- yPosition,
- CharacterHitTest::SCROLL,
- matchedCharacter );
+ handlePosition = Text::GetClosestCursorIndex(model->mVisualModel,
+ model->mLogicalModel,
+ impl.mMetrics,
+ xPosition,
+ yPosition,
+ CharacterHitTest::SCROLL,
+ matchedCharacter);
}
EventData& eventData = *impl.mEventData;
- if( Event::GRAB_HANDLE_EVENT == event.type )
+ if(Event::GRAB_HANDLE_EVENT == event.type)
{
- eventData.mUpdateCursorPosition = true;
+ eventData.mUpdateCursorPosition = true;
eventData.mUpdateGrabHandlePosition = true;
- eventData.mUpdateInputStyle = true;
+ eventData.mUpdateInputStyle = true;
- if( !impl.IsClipboardEmpty() )
+ if(!impl.IsClipboardEmpty())
{
- impl.ChangeState( EventData::EDITING_WITH_PASTE_POPUP ); // Moving grabhandle will show Paste Popup
+ impl.ChangeState(EventData::EDITING_WITH_PASTE_POPUP); // Moving grabhandle will show Paste Popup
}
- if( handleStopScrolling || isSmoothHandlePanEnabled )
+ if(handleStopScrolling || isSmoothHandlePanEnabled)
{
eventData.mScrollAfterUpdatePosition = true;
- eventData.mPrimaryCursorPosition = handlePosition;
+ eventData.mPrimaryCursorPosition = handlePosition;
}
}
- else if( Event::LEFT_SELECTION_HANDLE_EVENT == event.type )
+ else if(Event::LEFT_SELECTION_HANDLE_EVENT == event.type)
{
- impl.ChangeState( EventData::SELECTING );
+ impl.ChangeState(EventData::SELECTING);
- eventData.mUpdateHighlightBox = true;
- eventData.mUpdateLeftSelectionPosition = true;
+ eventData.mUpdateHighlightBox = true;
+ eventData.mUpdateLeftSelectionPosition = true;
eventData.mUpdateRightSelectionPosition = true;
- if( handleStopScrolling || isSmoothHandlePanEnabled )
+ if(handleStopScrolling || isSmoothHandlePanEnabled)
{
eventData.mScrollAfterUpdatePosition = true;
- if( ( handlePosition != eventData.mRightSelectionPosition ) &&
- ( handlePosition != eventData.mLeftSelectionPosition ) )
+ if((handlePosition != eventData.mRightSelectionPosition) &&
+ (handlePosition != eventData.mLeftSelectionPosition))
{
eventData.mLeftSelectionPosition = handlePosition;
}
}
}
- else if( Event::RIGHT_SELECTION_HANDLE_EVENT == event.type )
+ else if(Event::RIGHT_SELECTION_HANDLE_EVENT == event.type)
{
- impl.ChangeState( EventData::SELECTING );
+ impl.ChangeState(EventData::SELECTING);
- eventData.mUpdateHighlightBox = true;
+ eventData.mUpdateHighlightBox = true;
eventData.mUpdateRightSelectionPosition = true;
- eventData.mUpdateLeftSelectionPosition = true;
+ eventData.mUpdateLeftSelectionPosition = true;
- if( handleStopScrolling || isSmoothHandlePanEnabled )
+ if(handleStopScrolling || isSmoothHandlePanEnabled)
{
eventData.mScrollAfterUpdatePosition = true;
- if( ( handlePosition != eventData.mRightSelectionPosition ) &&
- ( handlePosition != eventData.mLeftSelectionPosition ) )
+ if((handlePosition != eventData.mRightSelectionPosition) &&
+ (handlePosition != eventData.mLeftSelectionPosition))
{
eventData.mRightSelectionPosition = handlePosition;
}
void ControllerImplEventHandler::OnHandleScrolling(Controller::Impl& impl, const Event& event, const bool isSmoothHandlePanEnabled)
{
- ModelPtr& model = impl.mModel;
- Vector2& scrollPosition = model->mScrollPosition;
- VisualModelPtr& visualModel = model->mVisualModel;
+ ModelPtr& model = impl.mModel;
+ Vector2& scrollPosition = model->mScrollPosition;
+ VisualModelPtr& visualModel = model->mVisualModel;
- const float xSpeed = event.p2.mFloat;
- const float ySpeed = event.p3.mFloat;
- const Vector2& layoutSize = visualModel->GetLayoutSize();
- const Vector2 currentScrollPosition = scrollPosition;
+ const float xSpeed = event.p2.mFloat;
+ const float ySpeed = event.p3.mFloat;
+ const Vector2& layoutSize = visualModel->GetLayoutSize();
+ const Vector2 currentScrollPosition = scrollPosition;
scrollPosition.x += xSpeed;
scrollPosition.y += ySpeed;
- impl.ClampHorizontalScroll( layoutSize );
- impl.ClampVerticalScroll( layoutSize );
+ impl.ClampHorizontalScroll(layoutSize);
+ impl.ClampVerticalScroll(layoutSize);
- EventData& eventData = *impl.mEventData;
+ EventData& eventData = *impl.mEventData;
DecoratorPtr& decorator = eventData.mDecorator;
bool endOfScroll = false;
- if( Vector2::ZERO == ( currentScrollPosition - scrollPosition ) )
+ if(Vector2::ZERO == (currentScrollPosition - scrollPosition))
{
// Notify the decorator there is no more text to scroll.
// The decorator won't send more scroll events.
}
// Set the position of the handle.
- const bool scrollRightDirection = xSpeed > 0.f;
- const bool scrollBottomDirection = ySpeed > 0.f;
- const bool leftSelectionHandleEvent = Event::LEFT_SELECTION_HANDLE_EVENT == event.type;
+ const bool scrollRightDirection = xSpeed > 0.f;
+ const bool scrollBottomDirection = ySpeed > 0.f;
+ const bool leftSelectionHandleEvent = Event::LEFT_SELECTION_HANDLE_EVENT == event.type;
const bool rightSelectionHandleEvent = Event::RIGHT_SELECTION_HANDLE_EVENT == event.type;
- if( Event::GRAB_HANDLE_EVENT == event.type )
+ if(Event::GRAB_HANDLE_EVENT == event.type)
{
- impl.ChangeState( EventData::GRAB_HANDLE_PANNING );
+ impl.ChangeState(EventData::GRAB_HANDLE_PANNING);
// Get the grab handle position in decorator coords.
- Vector2 position = decorator->GetPosition( GRAB_HANDLE );
+ Vector2 position = decorator->GetPosition(GRAB_HANDLE);
- if( decorator->IsHorizontalScrollEnabled() )
+ if(decorator->IsHorizontalScrollEnabled())
{
// Position the grag handle close to either the left or right edge.
position.x = scrollRightDirection ? 0.f : visualModel->mControlSize.width;
}
- if( decorator->IsVerticalScrollEnabled() )
+ if(decorator->IsVerticalScrollEnabled())
{
position.x = eventData.mCursorHookPositionX;
// Get the new handle position.
// The grab handle's position is in decorator's coords. Need to transforms to text's coords.
- bool matchedCharacter = false;
- const CharacterIndex handlePosition = Text::GetClosestCursorIndex( visualModel,
- impl.mModel->mLogicalModel,
- impl.mMetrics,
- position.x - scrollPosition.x,
- position.y - scrollPosition.y,
- CharacterHitTest::SCROLL,
- matchedCharacter );
-
- if( eventData.mPrimaryCursorPosition != handlePosition )
- {
- eventData.mUpdateCursorPosition = true;
- eventData.mUpdateGrabHandlePosition = !isSmoothHandlePanEnabled;
+ bool matchedCharacter = false;
+ const CharacterIndex handlePosition = Text::GetClosestCursorIndex(visualModel,
+ impl.mModel->mLogicalModel,
+ impl.mMetrics,
+ position.x - scrollPosition.x,
+ position.y - scrollPosition.y,
+ CharacterHitTest::SCROLL,
+ matchedCharacter);
+
+ if(eventData.mPrimaryCursorPosition != handlePosition)
+ {
+ eventData.mUpdateCursorPosition = true;
+ eventData.mUpdateGrabHandlePosition = !isSmoothHandlePanEnabled;
eventData.mScrollAfterUpdatePosition = true;
- eventData.mPrimaryCursorPosition = handlePosition;
+ eventData.mPrimaryCursorPosition = handlePosition;
}
eventData.mUpdateInputStyle = eventData.mUpdateCursorPosition;
// Updates the decorator if the soft handle panning is enabled.
eventData.mDecoratorUpdated = isSmoothHandlePanEnabled;
}
- else if( leftSelectionHandleEvent || rightSelectionHandleEvent )
+ else if(leftSelectionHandleEvent || rightSelectionHandleEvent)
{
- impl.ChangeState( EventData::SELECTION_HANDLE_PANNING );
+ impl.ChangeState(EventData::SELECTION_HANDLE_PANNING);
// Get the selection handle position in decorator coords.
- Vector2 position = decorator->GetPosition( leftSelectionHandleEvent ? Text::LEFT_SELECTION_HANDLE : Text::RIGHT_SELECTION_HANDLE );
+ Vector2 position = decorator->GetPosition(leftSelectionHandleEvent ? Text::LEFT_SELECTION_HANDLE : Text::RIGHT_SELECTION_HANDLE);
- if( decorator->IsHorizontalScrollEnabled() )
+ if(decorator->IsHorizontalScrollEnabled())
{
// Position the selection handle close to either the left or right edge.
position.x = scrollRightDirection ? 0.f : visualModel->mControlSize.width;
}
- if( decorator->IsVerticalScrollEnabled() )
+ if(decorator->IsVerticalScrollEnabled())
{
position.x = eventData.mCursorHookPositionX;
// Get the new handle position.
// The selection handle's position is in decorator's coords. Need to transform to text's coords.
- bool matchedCharacter = false;
- const CharacterIndex handlePosition = Text::GetClosestCursorIndex( visualModel,
- impl.mModel->mLogicalModel,
- impl.mMetrics,
- position.x - scrollPosition.x,
- position.y - scrollPosition.y,
- CharacterHitTest::SCROLL,
- matchedCharacter );
+ bool matchedCharacter = false;
+ const CharacterIndex handlePosition = Text::GetClosestCursorIndex(visualModel,
+ impl.mModel->mLogicalModel,
+ impl.mMetrics,
+ position.x - scrollPosition.x,
+ position.y - scrollPosition.y,
+ CharacterHitTest::SCROLL,
+ matchedCharacter);
- if( leftSelectionHandleEvent )
+ if(leftSelectionHandleEvent)
{
- const bool differentHandles = ( eventData.mLeftSelectionPosition != handlePosition ) && ( eventData.mRightSelectionPosition != handlePosition );
+ const bool differentHandles = (eventData.mLeftSelectionPosition != handlePosition) && (eventData.mRightSelectionPosition != handlePosition);
- if( differentHandles || endOfScroll )
+ if(differentHandles || endOfScroll)
{
- eventData.mUpdateHighlightBox = true;
- eventData.mUpdateLeftSelectionPosition = !isSmoothHandlePanEnabled;
+ eventData.mUpdateHighlightBox = true;
+ eventData.mUpdateLeftSelectionPosition = !isSmoothHandlePanEnabled;
eventData.mUpdateRightSelectionPosition = isSmoothHandlePanEnabled;
- eventData.mLeftSelectionPosition = handlePosition;
+ eventData.mLeftSelectionPosition = handlePosition;
}
}
else
{
- const bool differentHandles = ( eventData.mRightSelectionPosition != handlePosition ) && ( eventData.mLeftSelectionPosition != handlePosition );
- if( differentHandles || endOfScroll )
+ const bool differentHandles = (eventData.mRightSelectionPosition != handlePosition) && (eventData.mLeftSelectionPosition != handlePosition);
+ if(differentHandles || endOfScroll)
{
- eventData.mUpdateHighlightBox = true;
+ eventData.mUpdateHighlightBox = true;
eventData.mUpdateRightSelectionPosition = !isSmoothHandlePanEnabled;
- eventData.mUpdateLeftSelectionPosition = isSmoothHandlePanEnabled;
- eventData.mRightSelectionPosition = handlePosition;
+ eventData.mUpdateLeftSelectionPosition = isSmoothHandlePanEnabled;
+ eventData.mRightSelectionPosition = handlePosition;
}
}
- if( eventData.mUpdateLeftSelectionPosition || eventData.mUpdateRightSelectionPosition )
+ if(eventData.mUpdateLeftSelectionPosition || eventData.mUpdateRightSelectionPosition)
{
impl.RepositionSelectionHandles();
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/text-controller-impl.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/rendering/renderer.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/rendering/renderer.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
#include <dali-toolkit/internal/text/bidirectional-support.h>
#include <dali-toolkit/internal/text/character-set-conversion.h>
#include <dali-toolkit/internal/text/color-segmentation.h>
#include <dali-toolkit/internal/text/text-controller-impl-event-handler.h>
#include <dali-toolkit/internal/text/text-run-container.h>
#include <dali-toolkit/internal/text/text-selection-handle-controller.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
using namespace Dali;
namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
struct BackgroundVertex
{
- Vector2 mPosition; ///< Vertex posiiton
- Vector4 mColor; ///< Vertex color
+ Vector2 mPosition; ///< Vertex posiiton
+ Vector4 mColor; ///< Vertex color
};
struct BackgroundMesh
{
- Vector< BackgroundVertex > mVertices; ///< container of vertices
- Vector< unsigned short > mIndices; ///< container of indices
+ Vector<BackgroundVertex> mVertices; ///< container of vertices
+ Vector<unsigned short> mIndices; ///< container of indices
};
-const Dali::Vector4 LIGHT_BLUE( 0.75f, 0.96f, 1.f, 1.f );
-const Dali::Vector4 BACKGROUND_SUB4( 0.58f, 0.87f, 0.96f, 1.f );
-const Dali::Vector4 BACKGROUND_SUB5( 0.83f, 0.94f, 0.98f, 1.f );
-const Dali::Vector4 BACKGROUND_SUB6( 1.f, 0.5f, 0.5f, 1.f );
-const Dali::Vector4 BACKGROUND_SUB7( 1.f, 0.8f, 0.8f, 1.f );
+const Dali::Vector4 LIGHT_BLUE(0.75f, 0.96f, 1.f, 1.f);
+const Dali::Vector4 BACKGROUND_SUB4(0.58f, 0.87f, 0.96f, 1.f);
+const Dali::Vector4 BACKGROUND_SUB5(0.83f, 0.94f, 0.98f, 1.f);
+const Dali::Vector4 BACKGROUND_SUB6(1.f, 0.5f, 0.5f, 1.f);
+const Dali::Vector4 BACKGROUND_SUB7(1.f, 0.8f, 0.8f, 1.f);
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-EventData::EventData( DecoratorPtr decorator, InputMethodContext& inputMethodContext )
-: mDecorator( decorator ),
- mInputMethodContext( inputMethodContext ),
- mPlaceholderFont( NULL ),
+EventData::EventData(DecoratorPtr decorator, InputMethodContext& inputMethodContext)
+: mDecorator(decorator),
+ mInputMethodContext(inputMethodContext),
+ mPlaceholderFont(NULL),
mPlaceholderTextActive(),
mPlaceholderTextInactive(),
- mPlaceholderTextColor( 0.8f, 0.8f, 0.8f, 0.8f ), // This color has been published in the Public API (placeholder-properties.h).
+ mPlaceholderTextColor(0.8f, 0.8f, 0.8f, 0.8f), // This color has been published in the Public API (placeholder-properties.h).
mEventQueue(),
mInputStyleChangedQueue(),
- mPreviousState( INACTIVE ),
- mState( INACTIVE ),
- mPrimaryCursorPosition( 0u ),
- mLeftSelectionPosition( 0u ),
- mRightSelectionPosition( 0u ),
- mPreEditStartPosition( 0u ),
- mPreEditLength( 0u ),
- mCursorHookPositionX( 0.f ),
- mDoubleTapAction( Controller::NoTextTap::NO_ACTION ),
- mLongPressAction( Controller::NoTextTap::SHOW_SELECTION_POPUP ),
- mIsShowingPlaceholderText( false ),
- mPreEditFlag( false ),
- mDecoratorUpdated( false ),
- mCursorBlinkEnabled( true ),
- mGrabHandleEnabled( true ),
- mGrabHandlePopupEnabled( true ),
- mSelectionEnabled( true ),
- mUpdateCursorHookPosition( false ),
- mUpdateCursorPosition( false ),
- mUpdateGrabHandlePosition( false ),
- mUpdateLeftSelectionPosition( false ),
- mUpdateRightSelectionPosition( false ),
- mIsLeftHandleSelected( false ),
- mIsRightHandleSelected( false ),
- mUpdateHighlightBox( false ),
- mScrollAfterUpdatePosition( false ),
- mScrollAfterDelete( false ),
- mAllTextSelected( false ),
- mUpdateInputStyle( false ),
- mPasswordInput( false ),
- mCheckScrollAmount( false ),
- mIsPlaceholderPixelSize( false ),
- mIsPlaceholderElideEnabled( false ),
- mPlaceholderEllipsisFlag( false ),
- mShiftSelectionFlag( true ),
- mUpdateAlignment( false ),
- mEditingEnabled( true )
+ mPreviousState(INACTIVE),
+ mState(INACTIVE),
+ mPrimaryCursorPosition(0u),
+ mLeftSelectionPosition(0u),
+ mRightSelectionPosition(0u),
+ mPreEditStartPosition(0u),
+ mPreEditLength(0u),
+ mCursorHookPositionX(0.f),
+ mDoubleTapAction(Controller::NoTextTap::NO_ACTION),
+ mLongPressAction(Controller::NoTextTap::SHOW_SELECTION_POPUP),
+ mIsShowingPlaceholderText(false),
+ mPreEditFlag(false),
+ mDecoratorUpdated(false),
+ mCursorBlinkEnabled(true),
+ mGrabHandleEnabled(true),
+ mGrabHandlePopupEnabled(true),
+ mSelectionEnabled(true),
+ mUpdateCursorHookPosition(false),
+ mUpdateCursorPosition(false),
+ mUpdateGrabHandlePosition(false),
+ mUpdateLeftSelectionPosition(false),
+ mUpdateRightSelectionPosition(false),
+ mIsLeftHandleSelected(false),
+ mIsRightHandleSelected(false),
+ mUpdateHighlightBox(false),
+ mScrollAfterUpdatePosition(false),
+ mScrollAfterDelete(false),
+ mAllTextSelected(false),
+ mUpdateInputStyle(false),
+ mPasswordInput(false),
+ mCheckScrollAmount(false),
+ mIsPlaceholderPixelSize(false),
+ mIsPlaceholderElideEnabled(false),
+ mPlaceholderEllipsisFlag(false),
+ mShiftSelectionFlag(true),
+ mUpdateAlignment(false),
+ mEditingEnabled(true)
{
}
void Controller::Impl::NotifyInputMethodContext()
{
- if( mEventData && mEventData->mInputMethodContext )
+ if(mEventData && mEventData->mInputMethodContext)
{
CharacterIndex cursorPosition = GetLogicalCursorPosition();
- const Length numberOfWhiteSpaces = GetNumberOfWhiteSpaces( 0u );
+ const Length numberOfWhiteSpaces = GetNumberOfWhiteSpaces(0u);
// Update the cursor position by removing the initial white spaces.
- if( cursorPosition < numberOfWhiteSpaces )
+ if(cursorPosition < numberOfWhiteSpaces)
{
cursorPosition = 0u;
}
cursorPosition -= numberOfWhiteSpaces;
}
- mEventData->mInputMethodContext.SetCursorPosition( cursorPosition );
+ mEventData->mInputMethodContext.SetCursorPosition(cursorPosition);
mEventData->mInputMethodContext.NotifyCursorPosition();
}
}
void Controller::Impl::NotifyInputMethodContextMultiLineStatus()
{
- if ( mEventData && mEventData->mInputMethodContext )
+ if(mEventData && mEventData->mInputMethodContext)
{
Text::Layout::Engine::Type layout = mLayoutEngine.GetLayout();
- mEventData->mInputMethodContext.NotifyTextInputMultiLine( layout == Text::Layout::Engine::MULTI_LINE_BOX );
+ mEventData->mInputMethodContext.NotifyTextInputMultiLine(layout == Text::Layout::Engine::MULTI_LINE_BOX);
}
}
{
CharacterIndex cursorPosition = 0u;
- if( mEventData )
+ if(mEventData)
{
- if( ( EventData::SELECTING == mEventData->mState ) ||
- ( EventData::SELECTION_HANDLE_PANNING == mEventData->mState ) )
+ if((EventData::SELECTING == mEventData->mState) ||
+ (EventData::SELECTION_HANDLE_PANNING == mEventData->mState))
{
- cursorPosition = std::min( mEventData->mRightSelectionPosition, mEventData->mLeftSelectionPosition );
+ cursorPosition = std::min(mEventData->mRightSelectionPosition, mEventData->mLeftSelectionPosition);
}
else
{
return cursorPosition;
}
-Length Controller::Impl::GetNumberOfWhiteSpaces( CharacterIndex index ) const
+Length Controller::Impl::GetNumberOfWhiteSpaces(CharacterIndex index) const
{
Length numberOfWhiteSpaces = 0u;
Character* utf32CharacterBuffer = mModel->mLogicalModel->mText.Begin();
const Length totalNumberOfCharacters = mModel->mLogicalModel->mText.Count();
- for( ; index < totalNumberOfCharacters; ++index, ++numberOfWhiteSpaces )
+ for(; index < totalNumberOfCharacters; ++index, ++numberOfWhiteSpaces)
{
- if( !TextAbstraction::IsWhiteSpace( *( utf32CharacterBuffer + index ) ) )
+ if(!TextAbstraction::IsWhiteSpace(*(utf32CharacterBuffer + index)))
{
break;
}
return numberOfWhiteSpaces;
}
-void Controller::Impl::GetText( CharacterIndex index, std::string& text ) const
+void Controller::Impl::GetText(CharacterIndex index, std::string& text) const
{
// Get the total number of characters.
Length numberOfCharacters = mModel->mLogicalModel->mText.Count();
// Retrieve the text.
- if( 0u != numberOfCharacters )
+ if(0u != numberOfCharacters)
{
- Utf32ToUtf8( mModel->mLogicalModel->mText.Begin() + index, numberOfCharacters - index, text );
+ Utf32ToUtf8(mModel->mLogicalModel->mText.Begin() + index, numberOfCharacters - index, text);
}
}
-void Controller::Impl::CalculateTextUpdateIndices( Length& numberOfCharacters )
+void Controller::Impl::CalculateTextUpdateIndices(Length& numberOfCharacters)
{
mTextUpdateInfo.mParagraphCharacterIndex = 0u;
- mTextUpdateInfo.mStartGlyphIndex = 0u;
- mTextUpdateInfo.mStartLineIndex = 0u;
- numberOfCharacters = 0u;
+ mTextUpdateInfo.mStartGlyphIndex = 0u;
+ mTextUpdateInfo.mStartLineIndex = 0u;
+ numberOfCharacters = 0u;
const Length numberOfParagraphs = mModel->mLogicalModel->mParagraphInfo.Count();
- if( 0u == numberOfParagraphs )
+ if(0u == numberOfParagraphs)
{
mTextUpdateInfo.mParagraphCharacterIndex = 0u;
- numberOfCharacters = 0u;
+ numberOfCharacters = 0u;
mTextUpdateInfo.mRequestedNumberOfCharacters = mTextUpdateInfo.mNumberOfCharactersToAdd - mTextUpdateInfo.mNumberOfCharactersToRemove;
// Find the paragraphs to be updated.
Vector<ParagraphRunIndex> paragraphsToBeUpdated;
- if( mTextUpdateInfo.mCharacterIndex >= mTextUpdateInfo.mPreviousNumberOfCharacters )
+ if(mTextUpdateInfo.mCharacterIndex >= mTextUpdateInfo.mPreviousNumberOfCharacters)
{
// Text is being added at the end of the current text.
- if( mTextUpdateInfo.mIsLastCharacterNewParagraph )
+ if(mTextUpdateInfo.mIsLastCharacterNewParagraph)
{
// Text is being added in a new paragraph after the last character of the text.
- mTextUpdateInfo.mParagraphCharacterIndex = mTextUpdateInfo.mPreviousNumberOfCharacters;
- numberOfCharacters = 0u;
+ mTextUpdateInfo.mParagraphCharacterIndex = mTextUpdateInfo.mPreviousNumberOfCharacters;
+ numberOfCharacters = 0u;
mTextUpdateInfo.mRequestedNumberOfCharacters = mTextUpdateInfo.mNumberOfCharactersToAdd - mTextUpdateInfo.mNumberOfCharactersToRemove;
mTextUpdateInfo.mStartGlyphIndex = mModel->mVisualModel->mGlyphs.Count();
- mTextUpdateInfo.mStartLineIndex = mModel->mVisualModel->mLines.Count() - 1u;
+ mTextUpdateInfo.mStartLineIndex = mModel->mVisualModel->mLines.Count() - 1u;
// Nothing else to do;
return;
}
- paragraphsToBeUpdated.PushBack( numberOfParagraphs - 1u );
+ paragraphsToBeUpdated.PushBack(numberOfParagraphs - 1u);
}
else
{
Length numberOfCharactersToUpdate = 0u;
- if( mTextUpdateInfo.mFullRelayoutNeeded )
+ if(mTextUpdateInfo.mFullRelayoutNeeded)
{
numberOfCharactersToUpdate = mTextUpdateInfo.mPreviousNumberOfCharacters;
}
else
{
- numberOfCharactersToUpdate = ( mTextUpdateInfo.mNumberOfCharactersToRemove > 0u ) ? mTextUpdateInfo.mNumberOfCharactersToRemove : 1u;
+ numberOfCharactersToUpdate = (mTextUpdateInfo.mNumberOfCharactersToRemove > 0u) ? mTextUpdateInfo.mNumberOfCharactersToRemove : 1u;
}
- mModel->mLogicalModel->FindParagraphs( mTextUpdateInfo.mCharacterIndex,
- numberOfCharactersToUpdate,
- paragraphsToBeUpdated );
+ mModel->mLogicalModel->FindParagraphs(mTextUpdateInfo.mCharacterIndex,
+ numberOfCharactersToUpdate,
+ paragraphsToBeUpdated);
}
- if( 0u != paragraphsToBeUpdated.Count() )
+ if(0u != paragraphsToBeUpdated.Count())
{
- const ParagraphRunIndex firstParagraphIndex = *( paragraphsToBeUpdated.Begin() );
- const ParagraphRun& firstParagraph = *( mModel->mLogicalModel->mParagraphInfo.Begin() + firstParagraphIndex );
- mTextUpdateInfo.mParagraphCharacterIndex = firstParagraph.characterRun.characterIndex;
+ const ParagraphRunIndex firstParagraphIndex = *(paragraphsToBeUpdated.Begin());
+ const ParagraphRun& firstParagraph = *(mModel->mLogicalModel->mParagraphInfo.Begin() + firstParagraphIndex);
+ mTextUpdateInfo.mParagraphCharacterIndex = firstParagraph.characterRun.characterIndex;
- ParagraphRunIndex lastParagraphIndex = *( paragraphsToBeUpdated.End() - 1u );
- const ParagraphRun& lastParagraph = *( mModel->mLogicalModel->mParagraphInfo.Begin() + lastParagraphIndex );
+ ParagraphRunIndex lastParagraphIndex = *(paragraphsToBeUpdated.End() - 1u);
+ const ParagraphRun& lastParagraph = *(mModel->mLogicalModel->mParagraphInfo.Begin() + lastParagraphIndex);
- if( ( mTextUpdateInfo.mNumberOfCharactersToRemove > 0u ) && // Some character are removed.
- ( lastParagraphIndex < numberOfParagraphs - 1u ) && // There is a next paragraph.
- ( ( lastParagraph.characterRun.characterIndex + lastParagraph.characterRun.numberOfCharacters ) == // The last removed character is the new paragraph character.
- ( mTextUpdateInfo.mCharacterIndex + mTextUpdateInfo.mNumberOfCharactersToRemove ) ) )
+ if((mTextUpdateInfo.mNumberOfCharactersToRemove > 0u) && // Some character are removed.
+ (lastParagraphIndex < numberOfParagraphs - 1u) && // There is a next paragraph.
+ ((lastParagraph.characterRun.characterIndex + lastParagraph.characterRun.numberOfCharacters) == // The last removed character is the new paragraph character.
+ (mTextUpdateInfo.mCharacterIndex + mTextUpdateInfo.mNumberOfCharactersToRemove)))
{
// The new paragraph character of the last updated paragraph has been removed so is going to be merged with the next one.
- const ParagraphRun& lastParagraph = *( mModel->mLogicalModel->mParagraphInfo.Begin() + lastParagraphIndex + 1u );
+ const ParagraphRun& lastParagraph = *(mModel->mLogicalModel->mParagraphInfo.Begin() + lastParagraphIndex + 1u);
numberOfCharacters = lastParagraph.characterRun.characterIndex + lastParagraph.characterRun.numberOfCharacters - mTextUpdateInfo.mParagraphCharacterIndex;
}
}
mTextUpdateInfo.mRequestedNumberOfCharacters = numberOfCharacters + mTextUpdateInfo.mNumberOfCharactersToAdd - mTextUpdateInfo.mNumberOfCharactersToRemove;
- mTextUpdateInfo.mStartGlyphIndex = *( mModel->mVisualModel->mCharactersToGlyph.Begin() + mTextUpdateInfo.mParagraphCharacterIndex );
+ mTextUpdateInfo.mStartGlyphIndex = *(mModel->mVisualModel->mCharactersToGlyph.Begin() + mTextUpdateInfo.mParagraphCharacterIndex);
}
-void Controller::Impl::ClearFullModelData( OperationsMask operations )
+void Controller::Impl::ClearFullModelData(OperationsMask operations)
{
- if( NO_OPERATION != ( GET_LINE_BREAKS & operations ) )
+ if(NO_OPERATION != (GET_LINE_BREAKS & operations))
{
mModel->mLogicalModel->mLineBreakInfo.Clear();
mModel->mLogicalModel->mParagraphInfo.Clear();
}
- if( NO_OPERATION != ( GET_SCRIPTS & operations ) )
+ if(NO_OPERATION != (GET_SCRIPTS & operations))
{
mModel->mLogicalModel->mScriptRuns.Clear();
}
- if( NO_OPERATION != ( VALIDATE_FONTS & operations ) )
+ if(NO_OPERATION != (VALIDATE_FONTS & operations))
{
mModel->mLogicalModel->mFontRuns.Clear();
}
- if( 0u != mModel->mLogicalModel->mBidirectionalParagraphInfo.Count() )
+ if(0u != mModel->mLogicalModel->mBidirectionalParagraphInfo.Count())
{
- if( NO_OPERATION != ( BIDI_INFO & operations ) )
+ if(NO_OPERATION != (BIDI_INFO & operations))
{
mModel->mLogicalModel->mBidirectionalParagraphInfo.Clear();
mModel->mLogicalModel->mCharacterDirections.Clear();
}
- if( NO_OPERATION != ( REORDER & operations ) )
+ if(NO_OPERATION != (REORDER & operations))
{
// Free the allocated memory used to store the conversion table in the bidirectional line info run.
- for( Vector<BidirectionalLineInfoRun>::Iterator it = mModel->mLogicalModel->mBidirectionalLineInfo.Begin(),
- endIt = mModel->mLogicalModel->mBidirectionalLineInfo.End();
- it != endIt;
- ++it )
+ for(Vector<BidirectionalLineInfoRun>::Iterator it = mModel->mLogicalModel->mBidirectionalLineInfo.Begin(),
+ endIt = mModel->mLogicalModel->mBidirectionalLineInfo.End();
+ it != endIt;
+ ++it)
{
BidirectionalLineInfoRun& bidiLineInfo = *it;
- free( bidiLineInfo.visualToLogicalMap );
+ free(bidiLineInfo.visualToLogicalMap);
bidiLineInfo.visualToLogicalMap = NULL;
}
mModel->mLogicalModel->mBidirectionalLineInfo.Clear();
}
}
- if( NO_OPERATION != ( SHAPE_TEXT & operations ) )
+ if(NO_OPERATION != (SHAPE_TEXT & operations))
{
mModel->mVisualModel->mGlyphs.Clear();
mModel->mVisualModel->mGlyphsToCharacters.Clear();
mModel->mVisualModel->mGlyphPositions.Clear();
}
- if( NO_OPERATION != ( LAYOUT & operations ) )
+ if(NO_OPERATION != (LAYOUT & operations))
{
mModel->mVisualModel->mLines.Clear();
}
- if( NO_OPERATION != ( COLOR & operations ) )
+ if(NO_OPERATION != (COLOR & operations))
{
mModel->mVisualModel->mColorIndices.Clear();
mModel->mVisualModel->mBackgroundColorIndices.Clear();
}
}
-void Controller::Impl::ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations )
+void Controller::Impl::ClearCharacterModelData(CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations)
{
const CharacterIndex endIndexPlusOne = endIndex + 1u;
- if( NO_OPERATION != ( GET_LINE_BREAKS & operations ) )
+ if(NO_OPERATION != (GET_LINE_BREAKS & operations))
{
// Clear the line break info.
LineBreakInfo* lineBreakInfoBuffer = mModel->mLogicalModel->mLineBreakInfo.Begin();
- mModel->mLogicalModel->mLineBreakInfo.Erase( lineBreakInfoBuffer + startIndex,
- lineBreakInfoBuffer + endIndexPlusOne );
+ mModel->mLogicalModel->mLineBreakInfo.Erase(lineBreakInfoBuffer + startIndex,
+ lineBreakInfoBuffer + endIndexPlusOne);
// Clear the paragraphs.
- ClearCharacterRuns( startIndex,
- endIndex,
- mModel->mLogicalModel->mParagraphInfo );
+ ClearCharacterRuns(startIndex,
+ endIndex,
+ mModel->mLogicalModel->mParagraphInfo);
}
- if( NO_OPERATION != ( GET_SCRIPTS & operations ) )
+ if(NO_OPERATION != (GET_SCRIPTS & operations))
{
// Clear the scripts.
- ClearCharacterRuns( startIndex,
- endIndex,
- mModel->mLogicalModel->mScriptRuns );
+ ClearCharacterRuns(startIndex,
+ endIndex,
+ mModel->mLogicalModel->mScriptRuns);
}
- if( NO_OPERATION != ( VALIDATE_FONTS & operations ) )
+ if(NO_OPERATION != (VALIDATE_FONTS & operations))
{
// Clear the fonts.
- ClearCharacterRuns( startIndex,
- endIndex,
- mModel->mLogicalModel->mFontRuns );
+ ClearCharacterRuns(startIndex,
+ endIndex,
+ mModel->mLogicalModel->mFontRuns);
}
- if( 0u != mModel->mLogicalModel->mBidirectionalParagraphInfo.Count() )
+ if(0u != mModel->mLogicalModel->mBidirectionalParagraphInfo.Count())
{
- if( NO_OPERATION != ( BIDI_INFO & operations ) )
+ if(NO_OPERATION != (BIDI_INFO & operations))
{
// Clear the bidirectional paragraph info.
- ClearCharacterRuns( startIndex,
- endIndex,
- mModel->mLogicalModel->mBidirectionalParagraphInfo );
+ ClearCharacterRuns(startIndex,
+ endIndex,
+ mModel->mLogicalModel->mBidirectionalParagraphInfo);
// Clear the character's directions.
CharacterDirection* characterDirectionsBuffer = mModel->mLogicalModel->mCharacterDirections.Begin();
- mModel->mLogicalModel->mCharacterDirections.Erase( characterDirectionsBuffer + startIndex,
- characterDirectionsBuffer + endIndexPlusOne );
+ mModel->mLogicalModel->mCharacterDirections.Erase(characterDirectionsBuffer + startIndex,
+ characterDirectionsBuffer + endIndexPlusOne);
}
- if( NO_OPERATION != ( REORDER & operations ) )
+ if(NO_OPERATION != (REORDER & operations))
{
uint32_t startRemoveIndex = mModel->mLogicalModel->mBidirectionalLineInfo.Count();
- uint32_t endRemoveIndex = startRemoveIndex;
- ClearCharacterRuns( startIndex,
- endIndex,
- mModel->mLogicalModel->mBidirectionalLineInfo,
- startRemoveIndex,
- endRemoveIndex );
+ uint32_t endRemoveIndex = startRemoveIndex;
+ ClearCharacterRuns(startIndex,
+ endIndex,
+ mModel->mLogicalModel->mBidirectionalLineInfo,
+ startRemoveIndex,
+ endRemoveIndex);
BidirectionalLineInfoRun* bidirectionalLineInfoBuffer = mModel->mLogicalModel->mBidirectionalLineInfo.Begin();
// Free the allocated memory used to store the conversion table in the bidirectional line info run.
- for( Vector<BidirectionalLineInfoRun>::Iterator it = bidirectionalLineInfoBuffer + startRemoveIndex,
- endIt = bidirectionalLineInfoBuffer + endRemoveIndex;
- it != endIt;
- ++it )
+ for(Vector<BidirectionalLineInfoRun>::Iterator it = bidirectionalLineInfoBuffer + startRemoveIndex,
+ endIt = bidirectionalLineInfoBuffer + endRemoveIndex;
+ it != endIt;
+ ++it)
{
BidirectionalLineInfoRun& bidiLineInfo = *it;
- free( bidiLineInfo.visualToLogicalMap );
+ free(bidiLineInfo.visualToLogicalMap);
bidiLineInfo.visualToLogicalMap = NULL;
}
- mModel->mLogicalModel->mBidirectionalLineInfo.Erase( bidirectionalLineInfoBuffer + startRemoveIndex,
- bidirectionalLineInfoBuffer + endRemoveIndex );
+ mModel->mLogicalModel->mBidirectionalLineInfo.Erase(bidirectionalLineInfoBuffer + startRemoveIndex,
+ bidirectionalLineInfoBuffer + endRemoveIndex);
}
}
}
-void Controller::Impl::ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations )
+void Controller::Impl::ClearGlyphModelData(CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations)
{
- const CharacterIndex endIndexPlusOne = endIndex + 1u;
- const Length numberOfCharactersRemoved = endIndexPlusOne - startIndex;
+ const CharacterIndex endIndexPlusOne = endIndex + 1u;
+ const Length numberOfCharactersRemoved = endIndexPlusOne - startIndex;
// Convert the character index to glyph index before deleting the character to glyph and the glyphs per character buffers.
- GlyphIndex* charactersToGlyphBuffer = mModel->mVisualModel->mCharactersToGlyph.Begin();
- Length* glyphsPerCharacterBuffer = mModel->mVisualModel->mGlyphsPerCharacter.Begin();
+ GlyphIndex* charactersToGlyphBuffer = mModel->mVisualModel->mCharactersToGlyph.Begin();
+ Length* glyphsPerCharacterBuffer = mModel->mVisualModel->mGlyphsPerCharacter.Begin();
- const GlyphIndex endGlyphIndexPlusOne = *( charactersToGlyphBuffer + endIndex ) + *( glyphsPerCharacterBuffer + endIndex );
- const Length numberOfGlyphsRemoved = endGlyphIndexPlusOne - mTextUpdateInfo.mStartGlyphIndex;
+ const GlyphIndex endGlyphIndexPlusOne = *(charactersToGlyphBuffer + endIndex) + *(glyphsPerCharacterBuffer + endIndex);
+ const Length numberOfGlyphsRemoved = endGlyphIndexPlusOne - mTextUpdateInfo.mStartGlyphIndex;
- if( NO_OPERATION != ( SHAPE_TEXT & operations ) )
+ if(NO_OPERATION != (SHAPE_TEXT & operations))
{
// Update the character to glyph indices.
- for( Vector<GlyphIndex>::Iterator it = charactersToGlyphBuffer + endIndexPlusOne,
- endIt = charactersToGlyphBuffer + mModel->mVisualModel->mCharactersToGlyph.Count();
- it != endIt;
- ++it )
+ for(Vector<GlyphIndex>::Iterator it = charactersToGlyphBuffer + endIndexPlusOne,
+ endIt = charactersToGlyphBuffer + mModel->mVisualModel->mCharactersToGlyph.Count();
+ it != endIt;
+ ++it)
{
CharacterIndex& index = *it;
index -= numberOfGlyphsRemoved;
}
// Clear the character to glyph conversion table.
- mModel->mVisualModel->mCharactersToGlyph.Erase( charactersToGlyphBuffer + startIndex,
- charactersToGlyphBuffer + endIndexPlusOne );
+ mModel->mVisualModel->mCharactersToGlyph.Erase(charactersToGlyphBuffer + startIndex,
+ charactersToGlyphBuffer + endIndexPlusOne);
// Clear the glyphs per character table.
- mModel->mVisualModel->mGlyphsPerCharacter.Erase( glyphsPerCharacterBuffer + startIndex,
- glyphsPerCharacterBuffer + endIndexPlusOne );
+ mModel->mVisualModel->mGlyphsPerCharacter.Erase(glyphsPerCharacterBuffer + startIndex,
+ glyphsPerCharacterBuffer + endIndexPlusOne);
// Clear the glyphs buffer.
GlyphInfo* glyphsBuffer = mModel->mVisualModel->mGlyphs.Begin();
- mModel->mVisualModel->mGlyphs.Erase( glyphsBuffer + mTextUpdateInfo.mStartGlyphIndex,
- glyphsBuffer + endGlyphIndexPlusOne );
+ mModel->mVisualModel->mGlyphs.Erase(glyphsBuffer + mTextUpdateInfo.mStartGlyphIndex,
+ glyphsBuffer + endGlyphIndexPlusOne);
CharacterIndex* glyphsToCharactersBuffer = mModel->mVisualModel->mGlyphsToCharacters.Begin();
// Update the glyph to character indices.
- for( Vector<CharacterIndex>::Iterator it = glyphsToCharactersBuffer + endGlyphIndexPlusOne,
- endIt = glyphsToCharactersBuffer + mModel->mVisualModel->mGlyphsToCharacters.Count();
- it != endIt;
- ++it )
+ for(Vector<CharacterIndex>::Iterator it = glyphsToCharactersBuffer + endGlyphIndexPlusOne,
+ endIt = glyphsToCharactersBuffer + mModel->mVisualModel->mGlyphsToCharacters.Count();
+ it != endIt;
+ ++it)
{
CharacterIndex& index = *it;
index -= numberOfCharactersRemoved;
}
// Clear the glyphs to characters buffer.
- mModel->mVisualModel->mGlyphsToCharacters.Erase( glyphsToCharactersBuffer + mTextUpdateInfo.mStartGlyphIndex,
- glyphsToCharactersBuffer + endGlyphIndexPlusOne );
+ mModel->mVisualModel->mGlyphsToCharacters.Erase(glyphsToCharactersBuffer + mTextUpdateInfo.mStartGlyphIndex,
+ glyphsToCharactersBuffer + endGlyphIndexPlusOne);
// Clear the characters per glyph buffer.
Length* charactersPerGlyphBuffer = mModel->mVisualModel->mCharactersPerGlyph.Begin();
- mModel->mVisualModel->mCharactersPerGlyph.Erase( charactersPerGlyphBuffer + mTextUpdateInfo.mStartGlyphIndex,
- charactersPerGlyphBuffer + endGlyphIndexPlusOne );
+ mModel->mVisualModel->mCharactersPerGlyph.Erase(charactersPerGlyphBuffer + mTextUpdateInfo.mStartGlyphIndex,
+ charactersPerGlyphBuffer + endGlyphIndexPlusOne);
// Clear the positions buffer.
Vector2* positionsBuffer = mModel->mVisualModel->mGlyphPositions.Begin();
- mModel->mVisualModel->mGlyphPositions.Erase( positionsBuffer + mTextUpdateInfo.mStartGlyphIndex,
- positionsBuffer + endGlyphIndexPlusOne );
+ mModel->mVisualModel->mGlyphPositions.Erase(positionsBuffer + mTextUpdateInfo.mStartGlyphIndex,
+ positionsBuffer + endGlyphIndexPlusOne);
}
- if( NO_OPERATION != ( LAYOUT & operations ) )
+ if(NO_OPERATION != (LAYOUT & operations))
{
// Clear the lines.
uint32_t startRemoveIndex = mModel->mVisualModel->mLines.Count();
- uint32_t endRemoveIndex = startRemoveIndex;
- ClearCharacterRuns( startIndex,
- endIndex,
- mModel->mVisualModel->mLines,
- startRemoveIndex,
- endRemoveIndex );
+ uint32_t endRemoveIndex = startRemoveIndex;
+ ClearCharacterRuns(startIndex,
+ endIndex,
+ mModel->mVisualModel->mLines,
+ startRemoveIndex,
+ endRemoveIndex);
// Will update the glyph runs.
startRemoveIndex = mModel->mVisualModel->mLines.Count();
- endRemoveIndex = startRemoveIndex;
- ClearGlyphRuns( mTextUpdateInfo.mStartGlyphIndex,
- endGlyphIndexPlusOne - 1u,
- mModel->mVisualModel->mLines,
- startRemoveIndex,
- endRemoveIndex );
+ endRemoveIndex = startRemoveIndex;
+ ClearGlyphRuns(mTextUpdateInfo.mStartGlyphIndex,
+ endGlyphIndexPlusOne - 1u,
+ mModel->mVisualModel->mLines,
+ startRemoveIndex,
+ endRemoveIndex);
// Set the line index from where to insert the new laid-out lines.
mTextUpdateInfo.mStartLineIndex = startRemoveIndex;
LineRun* linesBuffer = mModel->mVisualModel->mLines.Begin();
- mModel->mVisualModel->mLines.Erase( linesBuffer + startRemoveIndex,
- linesBuffer + endRemoveIndex );
+ mModel->mVisualModel->mLines.Erase(linesBuffer + startRemoveIndex,
+ linesBuffer + endRemoveIndex);
}
- if( NO_OPERATION != ( COLOR & operations ) )
+ if(NO_OPERATION != (COLOR & operations))
{
- if( 0u != mModel->mVisualModel->mColorIndices.Count() )
+ if(0u != mModel->mVisualModel->mColorIndices.Count())
{
ColorIndex* colorIndexBuffer = mModel->mVisualModel->mColorIndices.Begin();
- mModel->mVisualModel->mColorIndices.Erase( colorIndexBuffer + mTextUpdateInfo.mStartGlyphIndex,
- colorIndexBuffer + endGlyphIndexPlusOne );
+ mModel->mVisualModel->mColorIndices.Erase(colorIndexBuffer + mTextUpdateInfo.mStartGlyphIndex,
+ colorIndexBuffer + endGlyphIndexPlusOne);
}
- if( 0u != mModel->mVisualModel->mBackgroundColorIndices.Count() )
+ if(0u != mModel->mVisualModel->mBackgroundColorIndices.Count())
{
ColorIndex* backgroundColorIndexBuffer = mModel->mVisualModel->mBackgroundColorIndices.Begin();
- mModel->mVisualModel->mBackgroundColorIndices.Erase( backgroundColorIndexBuffer + mTextUpdateInfo.mStartGlyphIndex,
- backgroundColorIndexBuffer + endGlyphIndexPlusOne );
+ mModel->mVisualModel->mBackgroundColorIndices.Erase(backgroundColorIndexBuffer + mTextUpdateInfo.mStartGlyphIndex,
+ backgroundColorIndexBuffer + endGlyphIndexPlusOne);
}
}
}
-void Controller::Impl::ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations )
+void Controller::Impl::ClearModelData(CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations)
{
- if( mTextUpdateInfo.mClearAll ||
- ( ( 0u == startIndex ) &&
- ( mTextUpdateInfo.mPreviousNumberOfCharacters == endIndex + 1u ) ) )
+ if(mTextUpdateInfo.mClearAll ||
+ ((0u == startIndex) &&
+ (mTextUpdateInfo.mPreviousNumberOfCharacters == endIndex + 1u)))
{
- ClearFullModelData( operations );
+ ClearFullModelData(operations);
}
else
{
// Clear the model data related with characters.
- ClearCharacterModelData( startIndex, endIndex, operations );
+ ClearCharacterModelData(startIndex, endIndex, operations);
// Clear the model data related with glyphs.
- ClearGlyphModelData( startIndex, endIndex, operations );
+ ClearGlyphModelData(startIndex, endIndex, operations);
}
// The estimated number of lines. Used to avoid reallocations when layouting.
- mTextUpdateInfo.mEstimatedNumberOfLines = std::max( mModel->mVisualModel->mLines.Count(), mModel->mLogicalModel->mParagraphInfo.Count() );
+ mTextUpdateInfo.mEstimatedNumberOfLines = std::max(mModel->mVisualModel->mLines.Count(), mModel->mLogicalModel->mParagraphInfo.Count());
mModel->mVisualModel->ClearCaches();
}
-bool Controller::Impl::UpdateModel( OperationsMask operationsRequired )
+bool Controller::Impl::UpdateModel(OperationsMask operationsRequired)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::UpdateModel\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::UpdateModel\n");
// Calculate the operations to be done.
- const OperationsMask operations = static_cast<OperationsMask>( mOperationsPending & operationsRequired );
+ const OperationsMask operations = static_cast<OperationsMask>(mOperationsPending & operationsRequired);
- if( NO_OPERATION == operations )
+ if(NO_OPERATION == operations)
{
// Nothing to do if no operations are pending and required.
return false;
}
Vector<Character>& srcCharacters = mModel->mLogicalModel->mText;
- Vector<Character> displayCharacters;
- bool useHiddenText = false;
- if ( mHiddenInput && mEventData != NULL && !mEventData->mIsShowingPlaceholderText)
+ Vector<Character> displayCharacters;
+ bool useHiddenText = false;
+ if(mHiddenInput && mEventData != NULL && !mEventData->mIsShowingPlaceholderText)
{
- mHiddenInput->Substitute( srcCharacters,displayCharacters );
+ mHiddenInput->Substitute(srcCharacters, displayCharacters);
useHiddenText = true;
}
- Vector<Character>& utf32Characters = useHiddenText ? displayCharacters : srcCharacters;
- const Length numberOfCharacters = utf32Characters.Count();
+ Vector<Character>& utf32Characters = useHiddenText ? displayCharacters : srcCharacters;
+ const Length numberOfCharacters = utf32Characters.Count();
// Index to the first character of the first paragraph to be updated.
CharacterIndex startIndex = 0u;
// Number of characters of the paragraphs to be removed.
Length paragraphCharacters = 0u;
- CalculateTextUpdateIndices( paragraphCharacters );
+ CalculateTextUpdateIndices(paragraphCharacters);
// Check whether the indices for updating the text is valid
- if ( numberOfCharacters > 0u &&
- ( mTextUpdateInfo.mParagraphCharacterIndex > numberOfCharacters ||
- mTextUpdateInfo.mRequestedNumberOfCharacters > numberOfCharacters ) )
+ if(numberOfCharacters > 0u &&
+ (mTextUpdateInfo.mParagraphCharacterIndex > numberOfCharacters ||
+ mTextUpdateInfo.mRequestedNumberOfCharacters > numberOfCharacters))
{
std::string currentText;
- Utf32ToUtf8( mModel->mLogicalModel->mText.Begin(), numberOfCharacters, currentText );
+ Utf32ToUtf8(mModel->mLogicalModel->mText.Begin(), numberOfCharacters, currentText);
- DALI_LOG_ERROR( "Controller::Impl::UpdateModel: mTextUpdateInfo has invalid indices\n" );
- DALI_LOG_ERROR( "Number of characters: %d, current text is: %s\n", numberOfCharacters, currentText.c_str() );
+ DALI_LOG_ERROR("Controller::Impl::UpdateModel: mTextUpdateInfo has invalid indices\n");
+ DALI_LOG_ERROR("Number of characters: %d, current text is: %s\n", numberOfCharacters, currentText.c_str());
// Dump mTextUpdateInfo
- DALI_LOG_ERROR( "Dump mTextUpdateInfo:\n" );
- DALI_LOG_ERROR( " mTextUpdateInfo.mCharacterIndex = %u\n", mTextUpdateInfo.mCharacterIndex );
- DALI_LOG_ERROR( " mTextUpdateInfo.mNumberOfCharactersToRemove = %u\n", mTextUpdateInfo.mNumberOfCharactersToRemove );
- DALI_LOG_ERROR( " mTextUpdateInfo.mNumberOfCharactersToAdd = %u\n", mTextUpdateInfo.mNumberOfCharactersToAdd );
- DALI_LOG_ERROR( " mTextUpdateInfo.mPreviousNumberOfCharacters = %u\n", mTextUpdateInfo.mPreviousNumberOfCharacters );
- DALI_LOG_ERROR( " mTextUpdateInfo.mParagraphCharacterIndex = %u\n", mTextUpdateInfo.mParagraphCharacterIndex );
- DALI_LOG_ERROR( " mTextUpdateInfo.mRequestedNumberOfCharacters = %u\n", mTextUpdateInfo.mRequestedNumberOfCharacters );
- DALI_LOG_ERROR( " mTextUpdateInfo.mStartGlyphIndex = %u\n", mTextUpdateInfo.mStartGlyphIndex );
- DALI_LOG_ERROR( " mTextUpdateInfo.mStartLineIndex = %u\n", mTextUpdateInfo.mStartLineIndex );
- DALI_LOG_ERROR( " mTextUpdateInfo.mEstimatedNumberOfLines = %u\n", mTextUpdateInfo.mEstimatedNumberOfLines );
- DALI_LOG_ERROR( " mTextUpdateInfo.mClearAll = %d\n", mTextUpdateInfo.mClearAll );
- DALI_LOG_ERROR( " mTextUpdateInfo.mFullRelayoutNeeded = %d\n", mTextUpdateInfo.mFullRelayoutNeeded );
- DALI_LOG_ERROR( " mTextUpdateInfo.mIsLastCharacterNewParagraph = %d\n", mTextUpdateInfo.mIsLastCharacterNewParagraph );
+ DALI_LOG_ERROR("Dump mTextUpdateInfo:\n");
+ DALI_LOG_ERROR(" mTextUpdateInfo.mCharacterIndex = %u\n", mTextUpdateInfo.mCharacterIndex);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mNumberOfCharactersToRemove = %u\n", mTextUpdateInfo.mNumberOfCharactersToRemove);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mNumberOfCharactersToAdd = %u\n", mTextUpdateInfo.mNumberOfCharactersToAdd);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mPreviousNumberOfCharacters = %u\n", mTextUpdateInfo.mPreviousNumberOfCharacters);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mParagraphCharacterIndex = %u\n", mTextUpdateInfo.mParagraphCharacterIndex);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mRequestedNumberOfCharacters = %u\n", mTextUpdateInfo.mRequestedNumberOfCharacters);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mStartGlyphIndex = %u\n", mTextUpdateInfo.mStartGlyphIndex);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mStartLineIndex = %u\n", mTextUpdateInfo.mStartLineIndex);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mEstimatedNumberOfLines = %u\n", mTextUpdateInfo.mEstimatedNumberOfLines);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mClearAll = %d\n", mTextUpdateInfo.mClearAll);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mFullRelayoutNeeded = %d\n", mTextUpdateInfo.mFullRelayoutNeeded);
+ DALI_LOG_ERROR(" mTextUpdateInfo.mIsLastCharacterNewParagraph = %d\n", mTextUpdateInfo.mIsLastCharacterNewParagraph);
return false;
}
startIndex = mTextUpdateInfo.mParagraphCharacterIndex;
- if( mTextUpdateInfo.mClearAll ||
- ( 0u != paragraphCharacters ) )
+ if(mTextUpdateInfo.mClearAll ||
+ (0u != paragraphCharacters))
{
- ClearModelData( startIndex, startIndex + ( ( paragraphCharacters > 0u ) ? paragraphCharacters - 1u : 0u ), operations );
+ ClearModelData(startIndex, startIndex + ((paragraphCharacters > 0u) ? paragraphCharacters - 1u : 0u), operations);
}
mTextUpdateInfo.mClearAll = false;
// Whether the model is updated.
bool updated = false;
- Vector<LineBreakInfo>& lineBreakInfo = mModel->mLogicalModel->mLineBreakInfo;
- const Length requestedNumberOfCharacters = mTextUpdateInfo.mRequestedNumberOfCharacters;
+ Vector<LineBreakInfo>& lineBreakInfo = mModel->mLogicalModel->mLineBreakInfo;
+ const Length requestedNumberOfCharacters = mTextUpdateInfo.mRequestedNumberOfCharacters;
- if( NO_OPERATION != ( GET_LINE_BREAKS & operations ) )
+ if(NO_OPERATION != (GET_LINE_BREAKS & operations))
{
// Retrieves the line break info. The line break info is used to split the text in 'paragraphs' to
// calculate the bidirectional info for each 'paragraph'.
// It's also used to layout the text (where it should be a new line) or to shape the text (text in different lines
// is not shaped together).
- lineBreakInfo.Resize( numberOfCharacters, TextAbstraction::LINE_NO_BREAK );
+ lineBreakInfo.Resize(numberOfCharacters, TextAbstraction::LINE_NO_BREAK);
- SetLineBreakInfo( utf32Characters,
- startIndex,
- requestedNumberOfCharacters,
- lineBreakInfo );
+ SetLineBreakInfo(utf32Characters,
+ startIndex,
+ requestedNumberOfCharacters,
+ lineBreakInfo);
// Create the paragraph info.
- mModel->mLogicalModel->CreateParagraphInfo( startIndex,
- requestedNumberOfCharacters );
+ mModel->mLogicalModel->CreateParagraphInfo(startIndex,
+ requestedNumberOfCharacters);
updated = true;
}
- const bool getScripts = NO_OPERATION != ( GET_SCRIPTS & operations );
- const bool validateFonts = NO_OPERATION != ( VALIDATE_FONTS & operations );
+ const bool getScripts = NO_OPERATION != (GET_SCRIPTS & operations);
+ const bool validateFonts = NO_OPERATION != (VALIDATE_FONTS & operations);
- Vector<ScriptRun>& scripts = mModel->mLogicalModel->mScriptRuns;
- Vector<FontRun>& validFonts = mModel->mLogicalModel->mFontRuns;
+ Vector<ScriptRun>& scripts = mModel->mLogicalModel->mScriptRuns;
+ Vector<FontRun>& validFonts = mModel->mLogicalModel->mFontRuns;
- if( getScripts || validateFonts )
+ if(getScripts || validateFonts)
{
// Validates the fonts assigned by the application or assigns default ones.
// It makes sure all the characters are going to be rendered by the correct font.
MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get();
- if( getScripts )
+ if(getScripts)
{
// Retrieves the scripts used in the text.
- multilanguageSupport.SetScripts( utf32Characters,
- startIndex,
- requestedNumberOfCharacters,
- scripts );
+ multilanguageSupport.SetScripts(utf32Characters,
+ startIndex,
+ requestedNumberOfCharacters,
+ scripts);
}
- if( validateFonts )
+ if(validateFonts)
{
// Validate the fonts set through the mark-up string.
Vector<FontDescriptionRun>& fontDescriptionRuns = mModel->mLogicalModel->mFontDescriptionRuns;
TextAbstraction::FontDescription defaultFontDescription;
TextAbstraction::PointSize26Dot6 defaultPointSize = TextAbstraction::FontClient::DEFAULT_POINT_SIZE * mFontSizeScale;
- if( IsShowingPlaceholderText() && mEventData && ( NULL != mEventData->mPlaceholderFont ) )
+ if(IsShowingPlaceholderText() && mEventData && (NULL != mEventData->mPlaceholderFont))
{
// If the placeholder font is set specifically, only placeholder font is changed.
defaultFontDescription = mEventData->mPlaceholderFont->mFontDescription;
- if( mEventData->mPlaceholderFont->sizeDefined )
+ if(mEventData->mPlaceholderFont->sizeDefined)
{
defaultPointSize = mEventData->mPlaceholderFont->mDefaultPointSize * mFontSizeScale * 64u;
}
}
- else if( NULL != mFontDefaults )
+ else if(NULL != mFontDefaults)
{
// Set the normal font and the placeholder font.
defaultFontDescription = mFontDefaults->mFontDescription;
- if( mTextFitEnabled )
+ if(mTextFitEnabled)
{
defaultPointSize = mFontDefaults->mFitPointSize * 64u;
}
// Validates the fonts. If there is a character with no assigned font it sets a default one.
// After this call, fonts are validated.
- multilanguageSupport.ValidateFonts( utf32Characters,
- scripts,
- fontDescriptionRuns,
- defaultFontDescription,
- defaultPointSize,
- startIndex,
- requestedNumberOfCharacters,
- validFonts );
+ multilanguageSupport.ValidateFonts(utf32Characters,
+ scripts,
+ fontDescriptionRuns,
+ defaultFontDescription,
+ defaultPointSize,
+ startIndex,
+ requestedNumberOfCharacters,
+ validFonts);
}
updated = true;
}
Vector<Character> mirroredUtf32Characters;
- bool textMirrored = false;
- const Length numberOfParagraphs = mModel->mLogicalModel->mParagraphInfo.Count();
- if( NO_OPERATION != ( BIDI_INFO & operations ) )
+ bool textMirrored = false;
+ const Length numberOfParagraphs = mModel->mLogicalModel->mParagraphInfo.Count();
+ if(NO_OPERATION != (BIDI_INFO & operations))
{
Vector<BidirectionalParagraphInfoRun>& bidirectionalInfo = mModel->mLogicalModel->mBidirectionalParagraphInfo;
- bidirectionalInfo.Reserve( numberOfParagraphs );
+ bidirectionalInfo.Reserve(numberOfParagraphs);
// Calculates the bidirectional info for the whole paragraph if it contains right to left scripts.
- SetBidirectionalInfo( utf32Characters,
- scripts,
- lineBreakInfo,
- startIndex,
- requestedNumberOfCharacters,
- bidirectionalInfo,
- mModel->mMatchSystemLanguageDirection,
- mLayoutDirection );
-
- if( 0u != bidirectionalInfo.Count() )
+ SetBidirectionalInfo(utf32Characters,
+ scripts,
+ lineBreakInfo,
+ startIndex,
+ requestedNumberOfCharacters,
+ bidirectionalInfo,
+ mModel->mMatchSystemLanguageDirection,
+ mLayoutDirection);
+
+ if(0u != bidirectionalInfo.Count())
{
// Only set the character directions if there is right to left characters.
Vector<CharacterDirection>& directions = mModel->mLogicalModel->mCharacterDirections;
- GetCharactersDirection( bidirectionalInfo,
- numberOfCharacters,
- startIndex,
- requestedNumberOfCharacters,
- directions );
+ GetCharactersDirection(bidirectionalInfo,
+ numberOfCharacters,
+ startIndex,
+ requestedNumberOfCharacters,
+ directions);
// This paragraph has right to left text. Some characters may need to be mirrored.
// TODO: consider if the mirrored string can be stored as well.
- textMirrored = GetMirroredText( utf32Characters,
- directions,
- bidirectionalInfo,
- startIndex,
- requestedNumberOfCharacters,
- mirroredUtf32Characters );
+ textMirrored = GetMirroredText(utf32Characters,
+ directions,
+ bidirectionalInfo,
+ startIndex,
+ requestedNumberOfCharacters,
+ mirroredUtf32Characters);
}
else
{
updated = true;
}
- Vector<GlyphInfo>& glyphs = mModel->mVisualModel->mGlyphs;
+ Vector<GlyphInfo>& glyphs = mModel->mVisualModel->mGlyphs;
Vector<CharacterIndex>& glyphsToCharactersMap = mModel->mVisualModel->mGlyphsToCharacters;
- Vector<Length>& charactersPerGlyph = mModel->mVisualModel->mCharactersPerGlyph;
- Vector<GlyphIndex> newParagraphGlyphs;
- newParagraphGlyphs.Reserve( numberOfParagraphs );
+ Vector<Length>& charactersPerGlyph = mModel->mVisualModel->mCharactersPerGlyph;
+ Vector<GlyphIndex> newParagraphGlyphs;
+ newParagraphGlyphs.Reserve(numberOfParagraphs);
const Length currentNumberOfGlyphs = glyphs.Count();
- if( NO_OPERATION != ( SHAPE_TEXT & operations ) )
+ if(NO_OPERATION != (SHAPE_TEXT & operations))
{
const Vector<Character>& textToShape = textMirrored ? mirroredUtf32Characters : utf32Characters;
// Shapes the text.
- ShapeText( textToShape,
- lineBreakInfo,
- scripts,
- validFonts,
- startIndex,
- mTextUpdateInfo.mStartGlyphIndex,
- requestedNumberOfCharacters,
- glyphs,
- glyphsToCharactersMap,
- charactersPerGlyph,
- newParagraphGlyphs );
+ ShapeText(textToShape,
+ lineBreakInfo,
+ scripts,
+ validFonts,
+ startIndex,
+ mTextUpdateInfo.mStartGlyphIndex,
+ requestedNumberOfCharacters,
+ glyphs,
+ glyphsToCharactersMap,
+ charactersPerGlyph,
+ newParagraphGlyphs);
// Create the 'number of glyphs' per character and the glyph to character conversion tables.
- mModel->mVisualModel->CreateGlyphsPerCharacterTable( startIndex, mTextUpdateInfo.mStartGlyphIndex, requestedNumberOfCharacters );
- mModel->mVisualModel->CreateCharacterToGlyphTable( startIndex, mTextUpdateInfo.mStartGlyphIndex, requestedNumberOfCharacters );
+ mModel->mVisualModel->CreateGlyphsPerCharacterTable(startIndex, mTextUpdateInfo.mStartGlyphIndex, requestedNumberOfCharacters);
+ mModel->mVisualModel->CreateCharacterToGlyphTable(startIndex, mTextUpdateInfo.mStartGlyphIndex, requestedNumberOfCharacters);
updated = true;
}
const Length numberOfGlyphs = glyphs.Count() - currentNumberOfGlyphs;
- if( NO_OPERATION != ( GET_GLYPH_METRICS & operations ) )
+ if(NO_OPERATION != (GET_GLYPH_METRICS & operations))
{
GlyphInfo* glyphsBuffer = glyphs.Begin();
- mMetrics->GetGlyphMetrics( glyphsBuffer + mTextUpdateInfo.mStartGlyphIndex, numberOfGlyphs );
+ mMetrics->GetGlyphMetrics(glyphsBuffer + mTextUpdateInfo.mStartGlyphIndex, numberOfGlyphs);
// Update the width and advance of all new paragraph characters.
- for( Vector<GlyphIndex>::ConstIterator it = newParagraphGlyphs.Begin(), endIt = newParagraphGlyphs.End(); it != endIt; ++it )
+ for(Vector<GlyphIndex>::ConstIterator it = newParagraphGlyphs.Begin(), endIt = newParagraphGlyphs.End(); it != endIt; ++it)
{
const GlyphIndex index = *it;
- GlyphInfo& glyph = *( glyphsBuffer + index );
+ GlyphInfo& glyph = *(glyphsBuffer + index);
glyph.xBearing = 0.f;
- glyph.width = 0.f;
- glyph.advance = 0.f;
+ glyph.width = 0.f;
+ glyph.advance = 0.f;
}
updated = true;
}
- if( ( NULL != mEventData ) &&
- mEventData->mPreEditFlag &&
- ( 0u != mModel->mVisualModel->mCharactersToGlyph.Count() ) )
+ if((NULL != mEventData) &&
+ mEventData->mPreEditFlag &&
+ (0u != mModel->mVisualModel->mCharactersToGlyph.Count()))
{
Dali::InputMethodContext::PreEditAttributeDataContainer attrs;
- mEventData->mInputMethodContext.GetPreeditStyle( attrs );
+ mEventData->mInputMethodContext.GetPreeditStyle(attrs);
Dali::InputMethodContext::PreeditStyle type = Dali::InputMethodContext::PreeditStyle::NONE;
// Check the type of preedit and run it.
- for( Dali::InputMethodContext::PreEditAttributeDataContainer::Iterator it = attrs.Begin(), endIt = attrs.End(); it != endIt; it++ )
+ for(Dali::InputMethodContext::PreEditAttributeDataContainer::Iterator it = attrs.Begin(), endIt = attrs.End(); it != endIt; it++)
{
Dali::InputMethodContext::PreeditAttributeData attrData = *it;
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::UpdateModel PreeditStyle type : %d start %d end %d \n", attrData.preeditType, attrData.startIndex, attrData.endIndex );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::UpdateModel PreeditStyle type : %d start %d end %d \n", attrData.preeditType, attrData.startIndex, attrData.endIndex);
type = attrData.preeditType;
// Check the number of commit characters for the start position.
- unsigned int numberOfCommit = mEventData->mPrimaryCursorPosition - mEventData->mPreEditLength;
- Length numberOfIndices = attrData.endIndex - attrData.startIndex;
+ unsigned int numberOfCommit = mEventData->mPrimaryCursorPosition - mEventData->mPreEditLength;
+ Length numberOfIndices = attrData.endIndex - attrData.startIndex;
- switch( type )
+ switch(type)
{
case Dali::InputMethodContext::PreeditStyle::UNDERLINE:
{
// Add the underline for the pre-edit text.
GlyphRun underlineRun;
- underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
+ underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
underlineRun.numberOfGlyphs = numberOfIndices;
- mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun );
+ mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun);
break;
}
case Dali::InputMethodContext::PreeditStyle::REVERSE:
{
- Vector4 textColor = mModel->mVisualModel->GetTextColor();
+ Vector4 textColor = mModel->mVisualModel->GetTextColor();
ColorRun backgroundColorRun;
- backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
+ backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices;
- backgroundColorRun.color = textColor;
- mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun );
-
- Vector4 backgroundColor = mModel->mVisualModel->GetBackgroundColor();
- Vector<ColorRun> colorRuns;
- colorRuns.Resize( 1u );
- ColorRun& colorRun = *( colorRuns.Begin() );
- colorRun.color = backgroundColor;
- colorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
+ backgroundColorRun.color = textColor;
+ mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun);
+
+ Vector4 backgroundColor = mModel->mVisualModel->GetBackgroundColor();
+ Vector<ColorRun> colorRuns;
+ colorRuns.Resize(1u);
+ ColorRun& colorRun = *(colorRuns.Begin());
+ colorRun.color = backgroundColor;
+ colorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
colorRun.characterRun.numberOfCharacters = numberOfIndices;
- mModel->mLogicalModel->mColorRuns.PushBack( colorRun );
+ mModel->mLogicalModel->mColorRuns.PushBack(colorRun);
break;
}
case Dali::InputMethodContext::PreeditStyle::HIGHLIGHT:
{
ColorRun backgroundColorRun;
- backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
+ backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices;
- backgroundColorRun.color = LIGHT_BLUE;
- mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun );
+ backgroundColorRun.color = LIGHT_BLUE;
+ mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun);
break;
}
case Dali::InputMethodContext::PreeditStyle::CUSTOM_PLATFORM_STYLE_1:
{
// CUSTOM_PLATFORM_STYLE_1 should be drawn with background and underline together.
ColorRun backgroundColorRun;
- backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
+ backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices;
- backgroundColorRun.color = BACKGROUND_SUB4;
- mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun );
+ backgroundColorRun.color = BACKGROUND_SUB4;
+ mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun);
GlyphRun underlineRun;
- underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
+ underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
underlineRun.numberOfGlyphs = numberOfIndices;
- mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun );
+ mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun);
break;
}
case Dali::InputMethodContext::PreeditStyle::CUSTOM_PLATFORM_STYLE_2:
{
// CUSTOM_PLATFORM_STYLE_2 should be drawn with background and underline together.
ColorRun backgroundColorRun;
- backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
+ backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices;
- backgroundColorRun.color = BACKGROUND_SUB5;
- mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun );
+ backgroundColorRun.color = BACKGROUND_SUB5;
+ mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun);
GlyphRun underlineRun;
- underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
+ underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
underlineRun.numberOfGlyphs = numberOfIndices;
- mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun );
+ mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun);
break;
}
case Dali::InputMethodContext::PreeditStyle::CUSTOM_PLATFORM_STYLE_3:
{
// CUSTOM_PLATFORM_STYLE_3 should be drawn with background and underline together.
ColorRun backgroundColorRun;
- backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
+ backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices;
- backgroundColorRun.color = BACKGROUND_SUB6;
- mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun );
+ backgroundColorRun.color = BACKGROUND_SUB6;
+ mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun);
GlyphRun underlineRun;
- underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
+ underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
underlineRun.numberOfGlyphs = numberOfIndices;
- mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun );
+ mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun);
break;
}
case Dali::InputMethodContext::PreeditStyle::CUSTOM_PLATFORM_STYLE_4:
{
// CUSTOM_PLATFORM_STYLE_4 should be drawn with background and underline together.
ColorRun backgroundColorRun;
- backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
+ backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit;
backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices;
- backgroundColorRun.color = BACKGROUND_SUB7;
- mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun );
+ backgroundColorRun.color = BACKGROUND_SUB7;
+ mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun);
GlyphRun underlineRun;
- underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
+ underlineRun.glyphIndex = attrData.startIndex + numberOfCommit;
underlineRun.numberOfGlyphs = numberOfIndices;
- mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun );
+ mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun);
break;
}
case Dali::InputMethodContext::PreeditStyle::NONE:
updated = true;
}
- if( NO_OPERATION != ( COLOR & operations ) )
+ if(NO_OPERATION != (COLOR & operations))
{
// Set the color runs in glyphs.
- SetColorSegmentationInfo( mModel->mLogicalModel->mColorRuns,
- mModel->mVisualModel->mCharactersToGlyph,
- mModel->mVisualModel->mGlyphsPerCharacter,
- startIndex,
- mTextUpdateInfo.mStartGlyphIndex,
- requestedNumberOfCharacters,
- mModel->mVisualModel->mColors,
- mModel->mVisualModel->mColorIndices );
+ SetColorSegmentationInfo(mModel->mLogicalModel->mColorRuns,
+ mModel->mVisualModel->mCharactersToGlyph,
+ mModel->mVisualModel->mGlyphsPerCharacter,
+ startIndex,
+ mTextUpdateInfo.mStartGlyphIndex,
+ requestedNumberOfCharacters,
+ mModel->mVisualModel->mColors,
+ mModel->mVisualModel->mColorIndices);
// Set the background color runs in glyphs.
- SetColorSegmentationInfo( mModel->mLogicalModel->mBackgroundColorRuns,
- mModel->mVisualModel->mCharactersToGlyph,
- mModel->mVisualModel->mGlyphsPerCharacter,
- startIndex,
- mTextUpdateInfo.mStartGlyphIndex,
- requestedNumberOfCharacters,
- mModel->mVisualModel->mBackgroundColors,
- mModel->mVisualModel->mBackgroundColorIndices );
+ SetColorSegmentationInfo(mModel->mLogicalModel->mBackgroundColorRuns,
+ mModel->mVisualModel->mCharactersToGlyph,
+ mModel->mVisualModel->mGlyphsPerCharacter,
+ startIndex,
+ mTextUpdateInfo.mStartGlyphIndex,
+ requestedNumberOfCharacters,
+ mModel->mVisualModel->mBackgroundColors,
+ mModel->mVisualModel->mBackgroundColorIndices);
updated = true;
}
-
// The estimated number of lines. Used to avoid reallocations when layouting.
- mTextUpdateInfo.mEstimatedNumberOfLines = std::max( mModel->mVisualModel->mLines.Count(), mModel->mLogicalModel->mParagraphInfo.Count() );
+ mTextUpdateInfo.mEstimatedNumberOfLines = std::max(mModel->mVisualModel->mLines.Count(), mModel->mLogicalModel->mParagraphInfo.Count());
// Set the previous number of characters for the next time the text is updated.
mTextUpdateInfo.mPreviousNumberOfCharacters = numberOfCharacters;
return updated;
}
-void Controller::Impl::RetrieveDefaultInputStyle( InputStyle& inputStyle )
+void Controller::Impl::RetrieveDefaultInputStyle(InputStyle& inputStyle)
{
// Sets the default text's color.
- inputStyle.textColor = mTextColor;
+ inputStyle.textColor = mTextColor;
inputStyle.isDefaultColor = true;
inputStyle.familyName.clear();
inputStyle.weight = TextAbstraction::FontWeight::NORMAL;
- inputStyle.width = TextAbstraction::FontWidth::NORMAL;
- inputStyle.slant = TextAbstraction::FontSlant::NORMAL;
- inputStyle.size = 0.f;
+ inputStyle.width = TextAbstraction::FontWidth::NORMAL;
+ inputStyle.slant = TextAbstraction::FontSlant::NORMAL;
+ inputStyle.size = 0.f;
inputStyle.lineSpacing = 0.f;
inputStyle.isFamilyDefined = false;
inputStyle.isWeightDefined = false;
- inputStyle.isWidthDefined = false;
- inputStyle.isSlantDefined = false;
- inputStyle.isSizeDefined = false;
+ inputStyle.isWidthDefined = false;
+ inputStyle.isSlantDefined = false;
+ inputStyle.isSizeDefined = false;
inputStyle.isLineSpacingDefined = false;
inputStyle.isUnderlineDefined = false;
- inputStyle.isShadowDefined = false;
- inputStyle.isEmbossDefined = false;
- inputStyle.isOutlineDefined = false;
+ inputStyle.isShadowDefined = false;
+ inputStyle.isEmbossDefined = false;
+ inputStyle.isOutlineDefined = false;
// Sets the default font's family name, weight, width, slant and size.
- if( mFontDefaults )
+ if(mFontDefaults)
{
- if( mFontDefaults->familyDefined )
+ if(mFontDefaults->familyDefined)
{
- inputStyle.familyName = mFontDefaults->mFontDescription.family;
+ inputStyle.familyName = mFontDefaults->mFontDescription.family;
inputStyle.isFamilyDefined = true;
}
- if( mFontDefaults->weightDefined )
+ if(mFontDefaults->weightDefined)
{
- inputStyle.weight = mFontDefaults->mFontDescription.weight;
+ inputStyle.weight = mFontDefaults->mFontDescription.weight;
inputStyle.isWeightDefined = true;
}
- if( mFontDefaults->widthDefined )
+ if(mFontDefaults->widthDefined)
{
- inputStyle.width = mFontDefaults->mFontDescription.width;
+ inputStyle.width = mFontDefaults->mFontDescription.width;
inputStyle.isWidthDefined = true;
}
- if( mFontDefaults->slantDefined )
+ if(mFontDefaults->slantDefined)
{
- inputStyle.slant = mFontDefaults->mFontDescription.slant;
+ inputStyle.slant = mFontDefaults->mFontDescription.slant;
inputStyle.isSlantDefined = true;
}
- if( mFontDefaults->sizeDefined )
+ if(mFontDefaults->sizeDefined)
{
- inputStyle.size = mFontDefaults->mDefaultPointSize;
+ inputStyle.size = mFontDefaults->mDefaultPointSize;
inputStyle.isSizeDefined = true;
}
}
float Controller::Impl::GetDefaultFontLineHeight()
{
FontId defaultFontId = 0u;
- if( NULL == mFontDefaults )
+ if(NULL == mFontDefaults)
{
TextAbstraction::FontDescription fontDescription;
- defaultFontId = mFontClient.GetFontId( fontDescription, TextAbstraction::FontClient::DEFAULT_POINT_SIZE * mFontSizeScale );
+ defaultFontId = mFontClient.GetFontId(fontDescription, TextAbstraction::FontClient::DEFAULT_POINT_SIZE * mFontSizeScale);
}
else
{
- defaultFontId = mFontDefaults->GetFontId( mFontClient, mFontDefaults->mDefaultPointSize * mFontSizeScale );
+ defaultFontId = mFontDefaults->GetFontId(mFontClient, mFontDefaults->mDefaultPointSize * mFontSizeScale);
}
Text::FontMetrics fontMetrics;
- mMetrics->GetFontMetrics( defaultFontId, fontMetrics );
+ mMetrics->GetFontMetrics(defaultFontId, fontMetrics);
- return( fontMetrics.ascender - fontMetrics.descender );
+ return (fontMetrics.ascender - fontMetrics.descender);
}
-void Controller::Impl::SetTextSelectionRange(const uint32_t *pStart, const uint32_t *pEnd)
+void Controller::Impl::SetTextSelectionRange(const uint32_t* pStart, const uint32_t* pEnd)
{
- if( nullptr == mEventData )
+ if(nullptr == mEventData)
{
// Nothing to do if there is no text.
return;
}
- if( mEventData->mSelectionEnabled && (pStart || pEnd))
+ if(mEventData->mSelectionEnabled && (pStart || pEnd))
{
uint32_t length = static_cast<uint32_t>(mModel->mLogicalModel->mText.Count());
- if (pStart)
+ if(pStart)
{
mEventData->mLeftSelectionPosition = std::min(*pStart, length);
}
- if (pEnd)
+ if(pEnd)
{
mEventData->mRightSelectionPosition = std::min(*pEnd, length);
}
- if (mEventData->mLeftSelectionPosition == mEventData->mRightSelectionPosition)
+ if(mEventData->mLeftSelectionPosition == mEventData->mRightSelectionPosition)
{
- ChangeState( EventData::EDITING );
+ ChangeState(EventData::EDITING);
mEventData->mPrimaryCursorPosition = mEventData->mLeftSelectionPosition = mEventData->mRightSelectionPosition;
- mEventData->mUpdateCursorPosition = true;
+ mEventData->mUpdateCursorPosition = true;
}
else
{
- ChangeState( EventData::SELECTING );
- mEventData->mUpdateHighlightBox = true;
- mEventData->mUpdateLeftSelectionPosition = true;
+ ChangeState(EventData::SELECTING);
+ mEventData->mUpdateHighlightBox = true;
+ mEventData->mUpdateLeftSelectionPosition = true;
mEventData->mUpdateRightSelectionPosition = true;
}
}
CharacterIndex Controller::Impl::GetPrimaryCursorPosition() const
{
- if( nullptr == mEventData )
+ if(nullptr == mEventData)
{
return 0;
}
return mEventData->mPrimaryCursorPosition;
}
-bool Controller::Impl::SetPrimaryCursorPosition( CharacterIndex index )
+bool Controller::Impl::SetPrimaryCursorPosition(CharacterIndex index)
{
- if( nullptr == mEventData )
+ if(nullptr == mEventData)
{
// Nothing to do if there is no text.
return false;
}
- if( mEventData->mPrimaryCursorPosition == index )
+ if(mEventData->mPrimaryCursorPosition == index)
{
// Nothing for same cursor position.
return false;
}
- uint32_t length = static_cast<uint32_t>(mModel->mLogicalModel->mText.Count());
+ uint32_t length = static_cast<uint32_t>(mModel->mLogicalModel->mText.Count());
mEventData->mPrimaryCursorPosition = std::min(index, length);
- ChangeState( EventData::EDITING );
+ ChangeState(EventData::EDITING);
mEventData->mLeftSelectionPosition = mEventData->mRightSelectionPosition = mEventData->mPrimaryCursorPosition;
- mEventData->mUpdateCursorPosition = true;
+ mEventData->mUpdateCursorPosition = true;
ScrollTextToMatchCursor();
return true;
}
{
Uint32Pair range;
- if( mEventData )
+ if(mEventData)
{
- range.first = mEventData->mLeftSelectionPosition;
+ range.first = mEventData->mLeftSelectionPosition;
range.second = mEventData->mRightSelectionPosition;
}
return mEventData && mEventData->mEditingEnabled;
}
-void Controller::Impl::SetEditable( bool editable )
+void Controller::Impl::SetEditable(bool editable)
{
- if( mEventData)
+ if(mEventData)
{
mEventData->mEditingEnabled = editable;
}
}
-void Controller::Impl::RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval )
+void Controller::Impl::RetrieveSelection(std::string& selectedText, bool deleteAfterRetrieval)
{
- if( mEventData->mLeftSelectionPosition == mEventData->mRightSelectionPosition )
+ if(mEventData->mLeftSelectionPosition == mEventData->mRightSelectionPosition)
{
// Nothing to select if handles are in the same place.
selectedText.clear();
const bool handlesCrossed = mEventData->mLeftSelectionPosition > mEventData->mRightSelectionPosition;
//Get start and end position of selection
- const CharacterIndex startOfSelectedText = handlesCrossed ? mEventData->mRightSelectionPosition : mEventData->mLeftSelectionPosition;
- const Length lengthOfSelectedText = ( handlesCrossed ? mEventData->mLeftSelectionPosition : mEventData->mRightSelectionPosition ) - startOfSelectedText;
+ const CharacterIndex startOfSelectedText = handlesCrossed ? mEventData->mRightSelectionPosition : mEventData->mLeftSelectionPosition;
+ const Length lengthOfSelectedText = (handlesCrossed ? mEventData->mLeftSelectionPosition : mEventData->mRightSelectionPosition) - startOfSelectedText;
- Vector<Character>& utf32Characters = mModel->mLogicalModel->mText;
- const Length numberOfCharacters = utf32Characters.Count();
+ Vector<Character>& utf32Characters = mModel->mLogicalModel->mText;
+ const Length numberOfCharacters = utf32Characters.Count();
// Validate the start and end selection points
- if( ( startOfSelectedText + lengthOfSelectedText ) <= numberOfCharacters )
+ if((startOfSelectedText + lengthOfSelectedText) <= numberOfCharacters)
{
//Get text as a UTF8 string
- Utf32ToUtf8( &utf32Characters[startOfSelectedText], lengthOfSelectedText, selectedText );
+ Utf32ToUtf8(&utf32Characters[startOfSelectedText], lengthOfSelectedText, selectedText);
- if( deleteAfterRetrieval ) // Only delete text if copied successfully
+ if(deleteAfterRetrieval) // Only delete text if copied successfully
{
// Keep a copy of the current input style.
InputStyle currentInputStyle;
- currentInputStyle.Copy( mEventData->mInputStyle );
+ currentInputStyle.Copy(mEventData->mInputStyle);
// Set as input style the style of the first deleted character.
- mModel->mLogicalModel->RetrieveStyle( startOfSelectedText, mEventData->mInputStyle );
+ mModel->mLogicalModel->RetrieveStyle(startOfSelectedText, mEventData->mInputStyle);
// Compare if the input style has changed.
- const bool hasInputStyleChanged = !currentInputStyle.Equal( mEventData->mInputStyle );
+ const bool hasInputStyleChanged = !currentInputStyle.Equal(mEventData->mInputStyle);
- if( hasInputStyleChanged )
+ if(hasInputStyleChanged)
{
- const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( mEventData->mInputStyle );
+ const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask(mEventData->mInputStyle);
// Queue the input style changed signal.
- mEventData->mInputStyleChangedQueue.PushBack( styleChangedMask );
+ mEventData->mInputStyleChangedQueue.PushBack(styleChangedMask);
}
- mModel->mLogicalModel->UpdateTextStyleRuns( startOfSelectedText, -static_cast<int>( lengthOfSelectedText ) );
+ mModel->mLogicalModel->UpdateTextStyleRuns(startOfSelectedText, -static_cast<int>(lengthOfSelectedText));
// Mark the paragraphs to be updated.
- if( Layout::Engine::SINGLE_LINE_BOX == mLayoutEngine.GetLayout() )
+ if(Layout::Engine::SINGLE_LINE_BOX == mLayoutEngine.GetLayout())
{
- mTextUpdateInfo.mCharacterIndex = 0;
+ mTextUpdateInfo.mCharacterIndex = 0;
mTextUpdateInfo.mNumberOfCharactersToRemove = mTextUpdateInfo.mPreviousNumberOfCharacters;
- mTextUpdateInfo.mNumberOfCharactersToAdd = mTextUpdateInfo.mPreviousNumberOfCharacters - lengthOfSelectedText;
- mTextUpdateInfo.mClearAll = true;
+ mTextUpdateInfo.mNumberOfCharactersToAdd = mTextUpdateInfo.mPreviousNumberOfCharacters - lengthOfSelectedText;
+ mTextUpdateInfo.mClearAll = true;
}
else
{
- mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
+ mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
}
// Delete text between handles
Vector<Character>::Iterator first = utf32Characters.Begin() + startOfSelectedText;
Vector<Character>::Iterator last = first + lengthOfSelectedText;
- utf32Characters.Erase( first, last );
+ utf32Characters.Erase(first, last);
// Will show the cursor at the first character of the selection.
mEventData->mPrimaryCursorPosition = handlesCrossed ? mEventData->mRightSelectionPosition : mEventData->mLeftSelectionPosition;
}
}
-void Controller::Impl::SetSelection( int start, int end )
+void Controller::Impl::SetSelection(int start, int end)
{
- mEventData->mLeftSelectionPosition = start;
+ mEventData->mLeftSelectionPosition = start;
mEventData->mRightSelectionPosition = end;
- mEventData->mUpdateCursorPosition = true;
+ mEventData->mUpdateCursorPosition = true;
}
-std::pair< int, int > Controller::Impl::GetSelectionIndexes() const
+std::pair<int, int> Controller::Impl::GetSelectionIndexes() const
{
- return { mEventData->mLeftSelectionPosition, mEventData->mRightSelectionPosition };
+ return {mEventData->mLeftSelectionPosition, mEventData->mRightSelectionPosition};
}
void Controller::Impl::ShowClipboard()
{
- if( mClipboard )
+ if(mClipboard)
{
mClipboard.ShowClipboard();
}
void Controller::Impl::HideClipboard()
{
- if( mClipboard && mClipboardHideEnabled )
+ if(mClipboard && mClipboardHideEnabled)
{
mClipboard.HideClipboard();
}
mClipboardHideEnabled = enable;
}
-bool Controller::Impl::CopyStringToClipboard( const std::string& source )
+bool Controller::Impl::CopyStringToClipboard(const std::string& source)
{
//Send string to clipboard
- return ( mClipboard && mClipboard.SetItem( source ) );
+ return (mClipboard && mClipboard.SetItem(source));
}
-void Controller::Impl::SendSelectionToClipboard( bool deleteAfterSending )
+void Controller::Impl::SendSelectionToClipboard(bool deleteAfterSending)
{
std::string selectedText;
- RetrieveSelection( selectedText, deleteAfterSending );
- CopyStringToClipboard( selectedText );
- ChangeState( EventData::EDITING );
+ RetrieveSelection(selectedText, deleteAfterSending);
+ CopyStringToClipboard(selectedText);
+ ChangeState(EventData::EDITING);
}
void Controller::Impl::RequestGetTextFromClipboard()
{
- if ( mClipboard )
+ if(mClipboard)
{
mClipboard.RequestItem();
}
{
SelectionHandleController::Reposition(*this);
}
-void Controller::Impl::RepositionSelectionHandles( float visualX, float visualY, Controller::NoTextTap::Action action )
+void Controller::Impl::RepositionSelectionHandles(float visualX, float visualY, Controller::NoTextTap::Action action)
{
SelectionHandleController::Reposition(*this, visualX, visualY, action);
}
* If EDITING_WITH_POPUP : SELECT & SELECT_ALL
*/
- bool isEditable = IsEditable();
+ bool isEditable = IsEditable();
TextSelectionPopup::Buttons buttonsToShow = TextSelectionPopup::NONE;
- if( EventData::SELECTING == mEventData->mState )
+ if(EventData::SELECTING == mEventData->mState)
{
- buttonsToShow = TextSelectionPopup::Buttons( TextSelectionPopup::COPY );
+ buttonsToShow = TextSelectionPopup::Buttons(TextSelectionPopup::COPY);
if(isEditable)
{
- buttonsToShow = TextSelectionPopup::Buttons( buttonsToShow | TextSelectionPopup::CUT );
+ buttonsToShow = TextSelectionPopup::Buttons(buttonsToShow | TextSelectionPopup::CUT);
}
- if( !IsClipboardEmpty() )
+ if(!IsClipboardEmpty())
{
if(isEditable)
{
- buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::PASTE ) );
+ buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::PASTE));
}
- buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::CLIPBOARD ) );
+ buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::CLIPBOARD));
}
- if( !mEventData->mAllTextSelected )
+ if(!mEventData->mAllTextSelected)
{
- buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::SELECT_ALL ) );
+ buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::SELECT_ALL));
}
}
- else if( EventData::EDITING_WITH_POPUP == mEventData->mState )
+ else if(EventData::EDITING_WITH_POPUP == mEventData->mState)
{
- if( mModel->mLogicalModel->mText.Count() && !IsShowingPlaceholderText() )
+ if(mModel->mLogicalModel->mText.Count() && !IsShowingPlaceholderText())
{
- buttonsToShow = TextSelectionPopup::Buttons( TextSelectionPopup::SELECT | TextSelectionPopup::SELECT_ALL );
+ buttonsToShow = TextSelectionPopup::Buttons(TextSelectionPopup::SELECT | TextSelectionPopup::SELECT_ALL);
}
- if( !IsClipboardEmpty() )
+ if(!IsClipboardEmpty())
{
if(isEditable)
{
- buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::PASTE ) );
+ buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::PASTE));
}
- buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::CLIPBOARD ) );
+ buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::CLIPBOARD));
}
}
- else if( EventData::EDITING_WITH_PASTE_POPUP == mEventData->mState )
+ else if(EventData::EDITING_WITH_PASTE_POPUP == mEventData->mState)
{
- if ( !IsClipboardEmpty() )
+ if(!IsClipboardEmpty())
{
if(isEditable)
{
- buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::PASTE ) );
+ buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::PASTE));
}
- buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::CLIPBOARD ) );
+ buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::CLIPBOARD));
}
}
- mEventData->mDecorator->SetEnabledPopupButtons( buttonsToShow );
+ mEventData->mDecorator->SetEnabledPopupButtons(buttonsToShow);
}
-void Controller::Impl::ChangeState( EventData::State newState )
+void Controller::Impl::ChangeState(EventData::State newState)
{
- if( NULL == mEventData )
+ if(NULL == mEventData)
{
// Nothing to do if there is no text input.
return;
}
- DALI_LOG_INFO( gLogFilter, Debug::General, "ChangeState state:%d newstate:%d\n", mEventData->mState, newState );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "ChangeState state:%d newstate:%d\n", mEventData->mState, newState);
- if( mEventData->mState != newState )
+ if(mEventData->mState != newState)
{
mEventData->mPreviousState = mEventData->mState;
- mEventData->mState = newState;
+ mEventData->mState = newState;
- switch( mEventData->mState )
+ switch(mEventData->mState)
{
case EventData::INACTIVE:
{
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE );
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE);
mEventData->mDecorator->StopCursorBlink();
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHighlightActive( false );
- mEventData->mDecorator->SetPopupActive( false );
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHighlightActive(false);
+ mEventData->mDecorator->SetPopupActive(false);
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::INTERRUPTED:
{
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHighlightActive( false );
- mEventData->mDecorator->SetPopupActive( false );
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHighlightActive(false);
+ mEventData->mDecorator->SetPopupActive(false);
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::SELECTING:
{
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE );
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE);
mEventData->mDecorator->StopCursorBlink();
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
- if ( mEventData->mGrabHandleEnabled )
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false);
+ if(mEventData->mGrabHandleEnabled)
{
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, true );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, true );
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, true);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, true);
}
- mEventData->mDecorator->SetHighlightActive( true );
- if( mEventData->mGrabHandlePopupEnabled )
+ mEventData->mDecorator->SetHighlightActive(true);
+ if(mEventData->mGrabHandlePopupEnabled)
{
SetPopupButtons();
- mEventData->mDecorator->SetPopupActive( true );
+ mEventData->mDecorator->SetPopupActive(true);
}
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::EDITING:
{
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY );
- if( mEventData->mCursorBlinkEnabled )
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY);
+ if(mEventData->mCursorBlinkEnabled)
{
mEventData->mDecorator->StartCursorBlink();
}
// Grab handle is not shown until a tap is received whilst EDITING
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHighlightActive( false );
- if( mEventData->mGrabHandlePopupEnabled )
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHighlightActive(false);
+ if(mEventData->mGrabHandlePopupEnabled)
{
- mEventData->mDecorator->SetPopupActive( false );
+ mEventData->mDecorator->SetPopupActive(false);
}
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::EDITING_WITH_POPUP:
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "EDITING_WITH_POPUP \n", newState );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "EDITING_WITH_POPUP \n", newState);
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY );
- if( mEventData->mCursorBlinkEnabled )
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY);
+ if(mEventData->mCursorBlinkEnabled)
{
mEventData->mDecorator->StartCursorBlink();
}
- if( mEventData->mSelectionEnabled )
+ if(mEventData->mSelectionEnabled)
{
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHighlightActive( false );
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHighlightActive(false);
}
- else if ( mEventData->mGrabHandleEnabled )
+ else if(mEventData->mGrabHandleEnabled)
{
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, true );
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, true);
}
- if( mEventData->mGrabHandlePopupEnabled )
+ if(mEventData->mGrabHandlePopupEnabled)
{
SetPopupButtons();
- mEventData->mDecorator->SetPopupActive( true );
+ mEventData->mDecorator->SetPopupActive(true);
}
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::EDITING_WITH_GRAB_HANDLE:
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "EDITING_WITH_GRAB_HANDLE \n", newState );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "EDITING_WITH_GRAB_HANDLE \n", newState);
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY );
- if( mEventData->mCursorBlinkEnabled )
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY);
+ if(mEventData->mCursorBlinkEnabled)
{
mEventData->mDecorator->StartCursorBlink();
}
// Grab handle is not shown until a tap is received whilst EDITING
- if ( mEventData->mGrabHandleEnabled )
+ if(mEventData->mGrabHandleEnabled)
{
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, true );
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, true);
}
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHighlightActive( false );
- if( mEventData->mGrabHandlePopupEnabled )
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHighlightActive(false);
+ if(mEventData->mGrabHandlePopupEnabled)
{
- mEventData->mDecorator->SetPopupActive( false );
+ mEventData->mDecorator->SetPopupActive(false);
}
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::SELECTION_HANDLE_PANNING:
{
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE );
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE);
mEventData->mDecorator->StopCursorBlink();
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
- if ( mEventData->mGrabHandleEnabled )
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false);
+ if(mEventData->mGrabHandleEnabled)
{
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, true );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, true );
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, true);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, true);
}
- mEventData->mDecorator->SetHighlightActive( true );
- if( mEventData->mGrabHandlePopupEnabled )
+ mEventData->mDecorator->SetHighlightActive(true);
+ if(mEventData->mGrabHandlePopupEnabled)
{
- mEventData->mDecorator->SetPopupActive( false );
+ mEventData->mDecorator->SetPopupActive(false);
}
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::GRAB_HANDLE_PANNING:
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GRAB_HANDLE_PANNING \n", newState );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GRAB_HANDLE_PANNING \n", newState);
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY );
- if( mEventData->mCursorBlinkEnabled )
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY);
+ if(mEventData->mCursorBlinkEnabled)
{
mEventData->mDecorator->StartCursorBlink();
}
- if ( mEventData->mGrabHandleEnabled )
+ if(mEventData->mGrabHandleEnabled)
{
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, true );
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, true);
}
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHighlightActive( false );
- if( mEventData->mGrabHandlePopupEnabled )
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHighlightActive(false);
+ if(mEventData->mGrabHandlePopupEnabled)
{
- mEventData->mDecorator->SetPopupActive( false );
+ mEventData->mDecorator->SetPopupActive(false);
}
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::EDITING_WITH_PASTE_POPUP:
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "EDITING_WITH_PASTE_POPUP \n", newState );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "EDITING_WITH_PASTE_POPUP \n", newState);
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY );
- if( mEventData->mCursorBlinkEnabled )
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY);
+ if(mEventData->mCursorBlinkEnabled)
{
mEventData->mDecorator->StartCursorBlink();
}
- if ( mEventData->mGrabHandleEnabled )
+ if(mEventData->mGrabHandleEnabled)
{
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, true );
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, true);
}
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHighlightActive( false );
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHighlightActive(false);
- if( mEventData->mGrabHandlePopupEnabled )
+ if(mEventData->mGrabHandlePopupEnabled)
{
SetPopupButtons();
- mEventData->mDecorator->SetPopupActive( true );
+ mEventData->mDecorator->SetPopupActive(true);
}
mEventData->mDecoratorUpdated = true;
break;
}
case EventData::TEXT_PANNING:
{
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE );
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE);
mEventData->mDecorator->StopCursorBlink();
- mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false );
- if( mEventData->mDecorator->IsHandleActive( LEFT_SELECTION_HANDLE ) ||
- mEventData->mDecorator->IsHandleActive( RIGHT_SELECTION_HANDLE ) )
+ mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false);
+ if(mEventData->mDecorator->IsHandleActive(LEFT_SELECTION_HANDLE) ||
+ mEventData->mDecorator->IsHandleActive(RIGHT_SELECTION_HANDLE))
{
- mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
- mEventData->mDecorator->SetHighlightActive( true );
+ mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
+ mEventData->mDecorator->SetHighlightActive(true);
}
- if( mEventData->mGrabHandlePopupEnabled )
+ if(mEventData->mGrabHandlePopupEnabled)
{
- mEventData->mDecorator->SetPopupActive( false );
+ mEventData->mDecorator->SetPopupActive(false);
}
mEventData->mDecoratorUpdated = true;
}
}
-void Controller::Impl::GetCursorPosition( CharacterIndex logical,
- CursorInfo& cursorInfo )
+void Controller::Impl::GetCursorPosition(CharacterIndex logical,
+ CursorInfo& cursorInfo)
{
- if( !IsShowingRealText() )
+ if(!IsShowingRealText())
{
// Do not want to use the place-holder text to set the cursor position.
// If there is no font's family set, use the default font.
// Use the current alignment to place the cursor at the beginning, center or end of the box.
- cursorInfo.lineOffset = 0.f;
- cursorInfo.lineHeight = GetDefaultFontLineHeight();
+ cursorInfo.lineOffset = 0.f;
+ cursorInfo.lineHeight = GetDefaultFontLineHeight();
cursorInfo.primaryCursorHeight = cursorInfo.lineHeight;
bool isRTL = false;
- if( mModel->mMatchSystemLanguageDirection )
+ if(mModel->mMatchSystemLanguageDirection)
{
isRTL = mLayoutDirection == LayoutDirection::RIGHT_TO_LEFT;
}
- switch( mModel->mHorizontalAlignment )
+ switch(mModel->mHorizontalAlignment)
{
- case Text::HorizontalAlignment::BEGIN :
+ case Text::HorizontalAlignment::BEGIN:
{
- if( isRTL )
+ if(isRTL)
{
cursorInfo.primaryPosition.x = mModel->mVisualModel->mControlSize.width - mEventData->mDecorator->GetCursorWidth();
}
}
case Text::HorizontalAlignment::CENTER:
{
- cursorInfo.primaryPosition.x = floorf( 0.5f * mModel->mVisualModel->mControlSize.width );
+ cursorInfo.primaryPosition.x = floorf(0.5f * mModel->mVisualModel->mControlSize.width);
break;
}
case Text::HorizontalAlignment::END:
{
- if( isRTL )
+ if(isRTL)
{
cursorInfo.primaryPosition.x = 0.f;
}
return;
}
- const bool isMultiLine = ( Layout::Engine::MULTI_LINE_BOX == mLayoutEngine.GetLayout() );
+ const bool isMultiLine = (Layout::Engine::MULTI_LINE_BOX == mLayoutEngine.GetLayout());
GetCursorPositionParameters parameters;
- parameters.visualModel = mModel->mVisualModel;
+ parameters.visualModel = mModel->mVisualModel;
parameters.logicalModel = mModel->mLogicalModel;
- parameters.metrics = mMetrics;
- parameters.logical = logical;
- parameters.isMultiline = isMultiLine;
+ parameters.metrics = mMetrics;
+ parameters.logical = logical;
+ parameters.isMultiline = isMultiLine;
- Text::GetCursorPosition( parameters,
- cursorInfo );
+ Text::GetCursorPosition(parameters,
+ cursorInfo);
// Adds Outline offset.
- const float outlineWidth = static_cast<float>( mModel->GetOutlineWidth() );
+ const float outlineWidth = static_cast<float>(mModel->GetOutlineWidth());
cursorInfo.primaryPosition.x += outlineWidth;
cursorInfo.primaryPosition.y += outlineWidth;
cursorInfo.secondaryPosition.x += outlineWidth;
cursorInfo.secondaryPosition.y += outlineWidth;
- if( isMultiLine )
+ if(isMultiLine)
{
// If the text is editable and multi-line, the cursor position after a white space shouldn't exceed the boundaries of the text control.
// Note the white spaces laid-out at the end of the line might exceed the boundaries of the control.
// The reason is a wrapped line must not start with a white space so they are laid-out at the end of the line.
- if( 0.f > cursorInfo.primaryPosition.x )
+ if(0.f > cursorInfo.primaryPosition.x)
{
cursorInfo.primaryPosition.x = 0.f;
}
- const float edgeWidth = mModel->mVisualModel->mControlSize.width - static_cast<float>( mEventData->mDecorator->GetCursorWidth() );
- if( cursorInfo.primaryPosition.x > edgeWidth )
+ const float edgeWidth = mModel->mVisualModel->mControlSize.width - static_cast<float>(mEventData->mDecorator->GetCursorWidth());
+ if(cursorInfo.primaryPosition.x > edgeWidth)
{
cursorInfo.primaryPosition.x = edgeWidth;
}
}
}
-CharacterIndex Controller::Impl::CalculateNewCursorIndex( CharacterIndex index ) const
+CharacterIndex Controller::Impl::CalculateNewCursorIndex(CharacterIndex index) const
{
- if( NULL == mEventData )
+ if(NULL == mEventData)
{
// Nothing to do if there is no text input.
return 0u;
CharacterIndex cursorIndex = mEventData->mPrimaryCursorPosition;
- const GlyphIndex* const charactersToGlyphBuffer = mModel->mVisualModel->mCharactersToGlyph.Begin();
- const Length* const charactersPerGlyphBuffer = mModel->mVisualModel->mCharactersPerGlyph.Begin();
+ const GlyphIndex* const charactersToGlyphBuffer = mModel->mVisualModel->mCharactersToGlyph.Begin();
+ const Length* const charactersPerGlyphBuffer = mModel->mVisualModel->mCharactersPerGlyph.Begin();
- GlyphIndex glyphIndex = *( charactersToGlyphBuffer + index );
- Length numberOfCharacters = *( charactersPerGlyphBuffer + glyphIndex );
+ GlyphIndex glyphIndex = *(charactersToGlyphBuffer + index);
+ Length numberOfCharacters = *(charactersPerGlyphBuffer + glyphIndex);
- if( numberOfCharacters > 1u )
+ if(numberOfCharacters > 1u)
{
- const Script script = mModel->mLogicalModel->GetScript( index );
- if( HasLigatureMustBreak( script ) )
+ const Script script = mModel->mLogicalModel->GetScript(index);
+ if(HasLigatureMustBreak(script))
{
// Prevents to jump the whole Latin ligatures like fi, ff, or Arabic ﻻ, ...
numberOfCharacters = 1u;
}
else
{
- while( 0u == numberOfCharacters )
+ while(0u == numberOfCharacters)
{
++glyphIndex;
- numberOfCharacters = *( charactersPerGlyphBuffer + glyphIndex );
+ numberOfCharacters = *(charactersPerGlyphBuffer + glyphIndex);
}
}
- if( index < mEventData->mPrimaryCursorPosition )
+ if(index < mEventData->mPrimaryCursorPosition)
{
cursorIndex -= numberOfCharacters;
}
return cursorIndex;
}
-void Controller::Impl::UpdateCursorPosition( const CursorInfo& cursorInfo )
+void Controller::Impl::UpdateCursorPosition(const CursorInfo& cursorInfo)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::UpdateCursorPosition %p\n", this );
- if( NULL == mEventData )
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::UpdateCursorPosition %p\n", this);
+ if(NULL == mEventData)
{
// Nothing to do if there is no text input.
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::UpdateCursorPosition no event data\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::UpdateCursorPosition no event data\n");
return;
}
const Vector2 cursorPosition = cursorInfo.primaryPosition + mModel->mScrollPosition;
- mEventData->mDecorator->SetGlyphOffset( PRIMARY_CURSOR, cursorInfo.glyphOffset );
+ mEventData->mDecorator->SetGlyphOffset(PRIMARY_CURSOR, cursorInfo.glyphOffset);
// Sets the cursor position.
- mEventData->mDecorator->SetPosition( PRIMARY_CURSOR,
- cursorPosition.x,
- cursorPosition.y,
- cursorInfo.primaryCursorHeight,
- cursorInfo.lineHeight );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Primary cursor position: %f,%f\n", cursorPosition.x, cursorPosition.y );
+ mEventData->mDecorator->SetPosition(PRIMARY_CURSOR,
+ cursorPosition.x,
+ cursorPosition.y,
+ cursorInfo.primaryCursorHeight,
+ cursorInfo.lineHeight);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Primary cursor position: %f,%f\n", cursorPosition.x, cursorPosition.y);
- if( mEventData->mUpdateGrabHandlePosition )
+ if(mEventData->mUpdateGrabHandlePosition)
{
// Sets the grab handle position.
- mEventData->mDecorator->SetPosition( GRAB_HANDLE,
- cursorPosition.x,
- cursorInfo.lineOffset + mModel->mScrollPosition.y,
- cursorInfo.lineHeight );
+ mEventData->mDecorator->SetPosition(GRAB_HANDLE,
+ cursorPosition.x,
+ cursorInfo.lineOffset + mModel->mScrollPosition.y,
+ cursorInfo.lineHeight);
}
- if( cursorInfo.isSecondaryCursor )
+ if(cursorInfo.isSecondaryCursor)
{
- mEventData->mDecorator->SetPosition( SECONDARY_CURSOR,
- cursorInfo.secondaryPosition.x + mModel->mScrollPosition.x,
- cursorInfo.secondaryPosition.y + mModel->mScrollPosition.y,
- cursorInfo.secondaryCursorHeight,
- cursorInfo.lineHeight );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Secondary cursor position: %f,%f\n", cursorInfo.secondaryPosition.x + mModel->mScrollPosition.x, cursorInfo.secondaryPosition.y + mModel->mScrollPosition.y );
+ mEventData->mDecorator->SetPosition(SECONDARY_CURSOR,
+ cursorInfo.secondaryPosition.x + mModel->mScrollPosition.x,
+ cursorInfo.secondaryPosition.y + mModel->mScrollPosition.y,
+ cursorInfo.secondaryCursorHeight,
+ cursorInfo.lineHeight);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Secondary cursor position: %f,%f\n", cursorInfo.secondaryPosition.x + mModel->mScrollPosition.x, cursorInfo.secondaryPosition.y + mModel->mScrollPosition.y);
}
// Set which cursors are active according the state.
- if( EventData::IsEditingState( mEventData->mState ) || ( EventData::GRAB_HANDLE_PANNING == mEventData->mState ) )
+ if(EventData::IsEditingState(mEventData->mState) || (EventData::GRAB_HANDLE_PANNING == mEventData->mState))
{
- if( cursorInfo.isSecondaryCursor )
+ if(cursorInfo.isSecondaryCursor)
{
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_BOTH );
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_BOTH);
}
else
{
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY );
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY);
}
}
else
{
- mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE );
+ mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE);
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::UpdateCursorPosition\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::UpdateCursorPosition\n");
}
-void Controller::Impl::UpdateSelectionHandle( HandleType handleType,
- const CursorInfo& cursorInfo )
+void Controller::Impl::UpdateSelectionHandle(HandleType handleType,
+ const CursorInfo& cursorInfo)
{
SelectionHandleController::Update(*this, handleType, cursorInfo);
}
-void Controller::Impl::ClampHorizontalScroll( const Vector2& layoutSize )
+void Controller::Impl::ClampHorizontalScroll(const Vector2& layoutSize)
{
// Clamp between -space & -alignment offset.
- if( layoutSize.width > mModel->mVisualModel->mControlSize.width )
+ if(layoutSize.width > mModel->mVisualModel->mControlSize.width)
{
- const float space = ( layoutSize.width - mModel->mVisualModel->mControlSize.width ) + mModel->mAlignmentOffset;
- mModel->mScrollPosition.x = ( mModel->mScrollPosition.x < -space ) ? -space : mModel->mScrollPosition.x;
- mModel->mScrollPosition.x = ( mModel->mScrollPosition.x > -mModel->mAlignmentOffset ) ? -mModel->mAlignmentOffset : mModel->mScrollPosition.x;
+ const float space = (layoutSize.width - mModel->mVisualModel->mControlSize.width) + mModel->mAlignmentOffset;
+ mModel->mScrollPosition.x = (mModel->mScrollPosition.x < -space) ? -space : mModel->mScrollPosition.x;
+ mModel->mScrollPosition.x = (mModel->mScrollPosition.x > -mModel->mAlignmentOffset) ? -mModel->mAlignmentOffset : mModel->mScrollPosition.x;
mEventData->mDecoratorUpdated = true;
}
}
}
-void Controller::Impl::ClampVerticalScroll( const Vector2& layoutSize )
+void Controller::Impl::ClampVerticalScroll(const Vector2& layoutSize)
{
- if( Layout::Engine::SINGLE_LINE_BOX == mLayoutEngine.GetLayout() )
+ if(Layout::Engine::SINGLE_LINE_BOX == mLayoutEngine.GetLayout())
{
// Nothing to do if the text is single line.
return;
}
// Clamp between -space & 0.
- if( layoutSize.height > mModel->mVisualModel->mControlSize.height )
+ if(layoutSize.height > mModel->mVisualModel->mControlSize.height)
{
- const float space = ( layoutSize.height - mModel->mVisualModel->mControlSize.height );
- mModel->mScrollPosition.y = ( mModel->mScrollPosition.y < -space ) ? -space : mModel->mScrollPosition.y;
- mModel->mScrollPosition.y = ( mModel->mScrollPosition.y > 0.f ) ? 0.f : mModel->mScrollPosition.y;
+ const float space = (layoutSize.height - mModel->mVisualModel->mControlSize.height);
+ mModel->mScrollPosition.y = (mModel->mScrollPosition.y < -space) ? -space : mModel->mScrollPosition.y;
+ mModel->mScrollPosition.y = (mModel->mScrollPosition.y > 0.f) ? 0.f : mModel->mScrollPosition.y;
mEventData->mDecoratorUpdated = true;
}
}
}
-void Controller::Impl::ScrollToMakePositionVisible( const Vector2& position, float lineHeight )
+void Controller::Impl::ScrollToMakePositionVisible(const Vector2& position, float lineHeight)
{
- const float cursorWidth = mEventData->mDecorator ? static_cast<float>( mEventData->mDecorator->GetCursorWidth() ) : 0.f;
+ const float cursorWidth = mEventData->mDecorator ? static_cast<float>(mEventData->mDecorator->GetCursorWidth()) : 0.f;
// position is in actor's coords.
const float positionEndX = position.x + cursorWidth;
// Transform the position to decorator coords.
const float decoratorPositionBeginX = position.x + mModel->mScrollPosition.x;
- const float decoratorPositionEndX = positionEndX + mModel->mScrollPosition.x;
+ const float decoratorPositionEndX = positionEndX + mModel->mScrollPosition.x;
const float decoratorPositionBeginY = position.y + mModel->mScrollPosition.y;
- const float decoratorPositionEndY = positionEndY + mModel->mScrollPosition.y;
+ const float decoratorPositionEndY = positionEndY + mModel->mScrollPosition.y;
- if( decoratorPositionBeginX < 0.f )
+ if(decoratorPositionBeginX < 0.f)
{
mModel->mScrollPosition.x = -position.x;
}
- else if( decoratorPositionEndX > mModel->mVisualModel->mControlSize.width )
+ else if(decoratorPositionEndX > mModel->mVisualModel->mControlSize.width)
{
mModel->mScrollPosition.x = mModel->mVisualModel->mControlSize.width - positionEndX;
}
- if( Layout::Engine::MULTI_LINE_BOX == mLayoutEngine.GetLayout() )
+ if(Layout::Engine::MULTI_LINE_BOX == mLayoutEngine.GetLayout())
{
- if( decoratorPositionBeginY < 0.f )
+ if(decoratorPositionBeginY < 0.f)
{
mModel->mScrollPosition.y = -position.y;
}
- else if( decoratorPositionEndY > mModel->mVisualModel->mControlSize.height )
+ else if(decoratorPositionEndY > mModel->mVisualModel->mControlSize.height)
{
mModel->mScrollPosition.y = mModel->mVisualModel->mControlSize.height - positionEndY;
}
}
}
-void Controller::Impl::ScrollTextToMatchCursor( const CursorInfo& cursorInfo )
+void Controller::Impl::ScrollTextToMatchCursor(const CursorInfo& cursorInfo)
{
// Get the current cursor position in decorator coords.
- const Vector2& currentCursorPosition = mEventData->mDecorator->GetPosition( PRIMARY_CURSOR );
-
- const LineIndex lineIndex = mModel->mVisualModel->GetLineOfCharacter( mEventData->mPrimaryCursorPosition );
-
+ const Vector2& currentCursorPosition = mEventData->mDecorator->GetPosition(PRIMARY_CURSOR);
+ const LineIndex lineIndex = mModel->mVisualModel->GetLineOfCharacter(mEventData->mPrimaryCursorPosition);
// Calculate the offset to match the cursor position before the character was deleted.
mModel->mScrollPosition.x = currentCursorPosition.x - cursorInfo.primaryPosition.x;
//If text control has more than two lines and current line index is not last, calculate scrollpositionY
- if( mModel->mVisualModel->mLines.Count() > 1u && lineIndex != mModel->mVisualModel->mLines.Count() -1u )
+ if(mModel->mVisualModel->mLines.Count() > 1u && lineIndex != mModel->mVisualModel->mLines.Count() - 1u)
{
- const float currentCursorGlyphOffset = mEventData->mDecorator->GetGlyphOffset( PRIMARY_CURSOR );
- mModel->mScrollPosition.y = currentCursorPosition.y - cursorInfo.lineOffset - currentCursorGlyphOffset;
+ const float currentCursorGlyphOffset = mEventData->mDecorator->GetGlyphOffset(PRIMARY_CURSOR);
+ mModel->mScrollPosition.y = currentCursorPosition.y - cursorInfo.lineOffset - currentCursorGlyphOffset;
}
-
- ClampHorizontalScroll( mModel->mVisualModel->GetLayoutSize() );
- ClampVerticalScroll( mModel->mVisualModel->GetLayoutSize() );
+ ClampHorizontalScroll(mModel->mVisualModel->GetLayoutSize());
+ ClampVerticalScroll(mModel->mVisualModel->GetLayoutSize());
// Makes the new cursor position visible if needed.
- ScrollToMakePositionVisible( cursorInfo.primaryPosition, cursorInfo.lineHeight );
+ ScrollToMakePositionVisible(cursorInfo.primaryPosition, cursorInfo.lineHeight);
}
void Controller::Impl::ScrollTextToMatchCursor()
{
CursorInfo cursorInfo;
- GetCursorPosition( mEventData->mPrimaryCursorPosition, cursorInfo );
+ GetCursorPosition(mEventData->mPrimaryCursorPosition, cursorInfo);
ScrollTextToMatchCursor(cursorInfo);
}
void Controller::Impl::RequestRelayout()
{
- if( NULL != mControlInterface )
+ if(NULL != mControlInterface)
{
mControlInterface->RequestTextRelayout();
}
Actor actor;
Length numberOfGlyphs = mView.GetNumberOfGlyphs();
- if( numberOfGlyphs > 0u )
+ if(numberOfGlyphs > 0u)
{
Vector<GlyphInfo> glyphs;
- glyphs.Resize( numberOfGlyphs );
+ glyphs.Resize(numberOfGlyphs);
Vector<Vector2> positions;
- positions.Resize( numberOfGlyphs );
+ positions.Resize(numberOfGlyphs);
// Get the line where the glyphs are laid-out.
- const LineRun* lineRun = mModel->mVisualModel->mLines.Begin();
- float alignmentOffset = lineRun->alignmentOffset;
- numberOfGlyphs = mView.GetGlyphs( glyphs.Begin(),
- positions.Begin(),
- alignmentOffset,
- 0u,
- numberOfGlyphs );
+ const LineRun* lineRun = mModel->mVisualModel->mLines.Begin();
+ float alignmentOffset = lineRun->alignmentOffset;
+ numberOfGlyphs = mView.GetGlyphs(glyphs.Begin(),
+ positions.Begin(),
+ alignmentOffset,
+ 0u,
+ numberOfGlyphs);
- glyphs.Resize( numberOfGlyphs );
- positions.Resize( numberOfGlyphs );
+ glyphs.Resize(numberOfGlyphs);
+ positions.Resize(numberOfGlyphs);
- const GlyphInfo* const glyphsBuffer = glyphs.Begin();
- const Vector2* const positionsBuffer = positions.Begin();
+ const GlyphInfo* const glyphsBuffer = glyphs.Begin();
+ const Vector2* const positionsBuffer = positions.Begin();
BackgroundMesh mesh;
- mesh.mVertices.Reserve( 4u * glyphs.Size() );
- mesh.mIndices.Reserve( 6u * glyphs.Size() );
+ mesh.mVertices.Reserve(4u * glyphs.Size());
+ mesh.mIndices.Reserve(6u * glyphs.Size());
const Vector2 textSize = mView.GetLayoutSize();
const float offsetX = textSize.width * 0.5f;
const float offsetY = textSize.height * 0.5f;
- const Vector4* const backgroundColorsBuffer = mView.GetBackgroundColors();
+ const Vector4* const backgroundColorsBuffer = mView.GetBackgroundColors();
const ColorIndex* const backgroundColorIndicesBuffer = mView.GetBackgroundColorIndices();
- const Vector4& defaultBackgroundColor = mModel->mVisualModel->IsBackgroundEnabled() ? mModel->mVisualModel->GetBackgroundColor() : Color::TRANSPARENT;
+ const Vector4& defaultBackgroundColor = mModel->mVisualModel->IsBackgroundEnabled() ? mModel->mVisualModel->GetBackgroundColor() : Color::TRANSPARENT;
- Vector4 quad;
+ Vector4 quad;
uint32_t numberOfQuads = 0u;
- for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
+ for(uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i)
{
- const GlyphInfo& glyph = *( glyphsBuffer + i );
+ const GlyphInfo& glyph = *(glyphsBuffer + i);
// Get the background color of the character.
// The color index zero is reserved for the default background color (i.e. Color::TRANSPARENT)
- const ColorIndex backgroundColorIndex = ( nullptr == backgroundColorsBuffer ) ? 0u : *( backgroundColorIndicesBuffer + i );
- const Vector4& backgroundColor = ( 0u == backgroundColorIndex ) ? defaultBackgroundColor : *( backgroundColorsBuffer + backgroundColorIndex - 1u );
+ const ColorIndex backgroundColorIndex = (nullptr == backgroundColorsBuffer) ? 0u : *(backgroundColorIndicesBuffer + i);
+ const Vector4& backgroundColor = (0u == backgroundColorIndex) ? defaultBackgroundColor : *(backgroundColorsBuffer + backgroundColorIndex - 1u);
// Only create quads for glyphs with a background color
- if ( backgroundColor != Color::TRANSPARENT )
+ if(backgroundColor != Color::TRANSPARENT)
{
- const Vector2 position = *( positionsBuffer + i );
+ const Vector2 position = *(positionsBuffer + i);
- if ( i == 0u && glyphSize == 1u ) // Only one glyph in the whole text
+ if(i == 0u && glyphSize == 1u) // Only one glyph in the whole text
{
quad.x = position.x;
quad.y = 0.0f;
- quad.z = quad.x + std::max( glyph.advance, glyph.xBearing + glyph.width );
+ quad.z = quad.x + std::max(glyph.advance, glyph.xBearing + glyph.width);
quad.w = textSize.height;
}
- else if ( i == 0u ) // The first glyph in the whole text
+ else if(i == 0u) // The first glyph in the whole text
{
quad.x = position.x;
quad.y = 0.0f;
quad.z = quad.x - glyph.xBearing + glyph.advance;
quad.w = textSize.height;
}
- else if ( i == glyphSize - 1u ) // The last glyph in the whole text
+ else if(i == glyphSize - 1u) // The last glyph in the whole text
{
quad.x = position.x - glyph.xBearing;
quad.y = 0.0f;
- quad.z = quad.x + std::max( glyph.advance, glyph.xBearing + glyph.width );
+ quad.z = quad.x + std::max(glyph.advance, glyph.xBearing + glyph.width);
quad.w = textSize.height;
}
else // The glyph in the middle of the text
// Top left
vertex.mPosition.x = quad.x - offsetX;
vertex.mPosition.y = quad.y - offsetY;
- vertex.mColor = backgroundColor;
- mesh.mVertices.PushBack( vertex );
+ vertex.mColor = backgroundColor;
+ mesh.mVertices.PushBack(vertex);
// Top right
vertex.mPosition.x = quad.z - offsetX;
vertex.mPosition.y = quad.y - offsetY;
- vertex.mColor = backgroundColor;
- mesh.mVertices.PushBack( vertex );
+ vertex.mColor = backgroundColor;
+ mesh.mVertices.PushBack(vertex);
// Bottom left
vertex.mPosition.x = quad.x - offsetX;
vertex.mPosition.y = quad.w - offsetY;
- vertex.mColor = backgroundColor;
- mesh.mVertices.PushBack( vertex );
+ vertex.mColor = backgroundColor;
+ mesh.mVertices.PushBack(vertex);
// Bottom right
vertex.mPosition.x = quad.z - offsetX;
vertex.mPosition.y = quad.w - offsetY;
- vertex.mColor = backgroundColor;
- mesh.mVertices.PushBack( vertex );
+ vertex.mColor = backgroundColor;
+ mesh.mVertices.PushBack(vertex);
// Six indices in counter clockwise winding
- mesh.mIndices.PushBack( 1u + 4 * numberOfQuads );
- mesh.mIndices.PushBack( 0u + 4 * numberOfQuads );
- mesh.mIndices.PushBack( 2u + 4 * numberOfQuads );
- mesh.mIndices.PushBack( 2u + 4 * numberOfQuads );
- mesh.mIndices.PushBack( 3u + 4 * numberOfQuads );
- mesh.mIndices.PushBack( 1u + 4 * numberOfQuads );
+ mesh.mIndices.PushBack(1u + 4 * numberOfQuads);
+ mesh.mIndices.PushBack(0u + 4 * numberOfQuads);
+ mesh.mIndices.PushBack(2u + 4 * numberOfQuads);
+ mesh.mIndices.PushBack(2u + 4 * numberOfQuads);
+ mesh.mIndices.PushBack(3u + 4 * numberOfQuads);
+ mesh.mIndices.PushBack(1u + 4 * numberOfQuads);
numberOfQuads++;
}
}
// Only create the background actor if there are glyphs with background color
- if ( mesh.mVertices.Count() > 0u )
+ if(mesh.mVertices.Count() > 0u)
{
Property::Map quadVertexFormat;
- quadVertexFormat[ "aPosition" ] = Property::VECTOR2;
- quadVertexFormat[ "aColor" ] = Property::VECTOR4;
+ quadVertexFormat["aPosition"] = Property::VECTOR2;
+ quadVertexFormat["aColor"] = Property::VECTOR4;
- VertexBuffer quadVertices = VertexBuffer::New( quadVertexFormat );
- quadVertices.SetData( &mesh.mVertices[ 0 ], mesh.mVertices.Size() );
+ VertexBuffer quadVertices = VertexBuffer::New(quadVertexFormat);
+ quadVertices.SetData(&mesh.mVertices[0], mesh.mVertices.Size());
Geometry quadGeometry = Geometry::New();
- quadGeometry.AddVertexBuffer( quadVertices );
- quadGeometry.SetIndexBuffer( &mesh.mIndices[ 0 ], mesh.mIndices.Size() );
+ quadGeometry.AddVertexBuffer(quadVertices);
+ quadGeometry.SetIndexBuffer(&mesh.mIndices[0], mesh.mIndices.Size());
- if( !mShaderBackground )
+ if(!mShaderBackground)
{
- mShaderBackground = Shader::New( SHADER_TEXT_CONTROLLER_BACKGROUND_SHADER_VERT, SHADER_TEXT_CONTROLLER_BACKGROUND_SHADER_FRAG );
+ mShaderBackground = Shader::New(SHADER_TEXT_CONTROLLER_BACKGROUND_SHADER_VERT, SHADER_TEXT_CONTROLLER_BACKGROUND_SHADER_FRAG);
}
- Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, mShaderBackground );
- renderer.SetProperty( Dali::Renderer::Property::BLEND_MODE, BlendMode::ON );
- renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT );
+ Dali::Renderer renderer = Dali::Renderer::New(quadGeometry, mShaderBackground);
+ renderer.SetProperty(Dali::Renderer::Property::BLEND_MODE, BlendMode::ON);
+ renderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT);
actor = Actor::New();
- actor.SetProperty( Dali::Actor::Property::NAME, "TextBackgroundColorActor" );
- actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT );
- actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT );
- actor.SetProperty( Actor::Property::SIZE, textSize );
- actor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR );
- actor.AddRenderer( renderer );
+ actor.SetProperty(Dali::Actor::Property::NAME, "TextBackgroundColorActor");
+ actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT);
+ actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT);
+ actor.SetProperty(Actor::Property::SIZE, textSize);
+ actor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR);
+ actor.AddRenderer(renderer);
}
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
-
/**
* @brief Adds a new font description run for the selected text.
*
* @param[out] startOfSelectedText Index to the first selected character.
* @param[out] lengthOfSelectedText Number of selected characters.
*/
-FontDescriptionRun& UpdateSelectionFontStyleRun( EventData* eventData,
- LogicalModelPtr logicalModel,
- CharacterIndex& startOfSelectedText,
- Length& lengthOfSelectedText )
+FontDescriptionRun& UpdateSelectionFontStyleRun(EventData* eventData,
+ LogicalModelPtr logicalModel,
+ CharacterIndex& startOfSelectedText,
+ Length& lengthOfSelectedText)
{
const bool handlesCrossed = eventData->mLeftSelectionPosition > eventData->mRightSelectionPosition;
// Get start and end position of selection
- startOfSelectedText = handlesCrossed ? eventData->mRightSelectionPosition : eventData->mLeftSelectionPosition;
- lengthOfSelectedText = ( handlesCrossed ? eventData->mLeftSelectionPosition : eventData->mRightSelectionPosition ) - startOfSelectedText;
+ startOfSelectedText = handlesCrossed ? eventData->mRightSelectionPosition : eventData->mLeftSelectionPosition;
+ lengthOfSelectedText = (handlesCrossed ? eventData->mLeftSelectionPosition : eventData->mRightSelectionPosition) - startOfSelectedText;
// Add the font run.
const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count();
- logicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
+ logicalModel->mFontDescriptionRuns.Resize(numberOfRuns + 1u);
- FontDescriptionRun& fontDescriptionRun = *( logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
+ FontDescriptionRun& fontDescriptionRun = *(logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns);
- fontDescriptionRun.characterRun.characterIndex = startOfSelectedText;
+ fontDescriptionRun.characterRun.characterIndex = startOfSelectedText;
fontDescriptionRun.characterRun.numberOfCharacters = lengthOfSelectedText;
// Recalculate the selection highlight as the metrics may have changed.
- eventData->mUpdateLeftSelectionPosition = true;
+ eventData->mUpdateLeftSelectionPosition = true;
eventData->mUpdateRightSelectionPosition = true;
- eventData->mUpdateHighlightBox = true;
+ eventData->mUpdateHighlightBox = true;
return fontDescriptionRun;
}
void Controller::InputFontHandler::SetInputFontFamily(Controller& controller, const std::string& fontFamily)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- controller.mImpl->mEventData->mInputStyle.familyName = fontFamily;
+ controller.mImpl->mEventData->mInputStyle.familyName = fontFamily;
controller.mImpl->mEventData->mInputStyle.isFamilyDefined = true;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState)
{
- CharacterIndex startOfSelectedText = 0u;
- Length lengthOfSelectedText = 0u;
+ CharacterIndex startOfSelectedText = 0u;
+ Length lengthOfSelectedText = 0u;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState)
{
// Update a font description run for the selecting state.
- FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData,
- controller.mImpl->mModel->mLogicalModel,
- startOfSelectedText,
- lengthOfSelectedText );
+ FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData,
+ controller.mImpl->mModel->mLogicalModel,
+ startOfSelectedText,
+ lengthOfSelectedText);
fontDescriptionRun.familyLength = fontFamily.size();
- fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
- memcpy( fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength );
+ fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
+ memcpy(fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength);
fontDescriptionRun.familyDefined = true;
// The memory allocated for the font family name is freed when the font description is removed from the logical model.
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
}
else
{
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
}
// Request to relayout.
- controller.mImpl->mOperationsPending = static_cast<OperationsMask>( controller.mImpl->mOperationsPending |
- VALIDATE_FONTS |
- SHAPE_TEXT |
- GET_GLYPH_METRICS |
- LAYOUT |
- UPDATE_LAYOUT_SIZE |
- REORDER |
- ALIGN );
+ controller.mImpl->mOperationsPending = static_cast<OperationsMask>(controller.mImpl->mOperationsPending |
+ VALIDATE_FONTS |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS |
+ LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ REORDER |
+ ALIGN);
controller.mImpl->mRecalculateNaturalSize = true;
controller.mImpl->RequestRelayout();
// As the font changes, recalculate the handle positions is needed.
- controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
+ controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
controller.mImpl->mEventData->mUpdateRightSelectionPosition = true;
- controller.mImpl->mEventData->mUpdateHighlightBox = true;
- controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
+ controller.mImpl->mEventData->mUpdateHighlightBox = true;
+ controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
}
}
}
const std::string& Controller::InputFontHandler::GetInputFontFamily(const Controller& controller)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
return controller.mImpl->mEventData->mInputStyle.familyName;
}
void Controller::InputFontHandler::SetInputFontWeight(const Controller& controller, FontWeight weight)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- controller.mImpl->mEventData->mInputStyle.weight = weight;
+ controller.mImpl->mEventData->mInputStyle.weight = weight;
controller.mImpl->mEventData->mInputStyle.isWeightDefined = true;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState)
{
- CharacterIndex startOfSelectedText = 0u;
- Length lengthOfSelectedText = 0u;
+ CharacterIndex startOfSelectedText = 0u;
+ Length lengthOfSelectedText = 0u;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState)
{
// Update a font description run for the selecting state.
- FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData,
- controller.mImpl->mModel->mLogicalModel,
- startOfSelectedText,
- lengthOfSelectedText );
+ FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData,
+ controller.mImpl->mModel->mLogicalModel,
+ startOfSelectedText,
+ lengthOfSelectedText);
- fontDescriptionRun.weight = weight;
+ fontDescriptionRun.weight = weight;
fontDescriptionRun.weightDefined = true;
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
}
else
{
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
}
// Request to relayout.
- controller.mImpl->mOperationsPending = static_cast<OperationsMask>( controller.mImpl->mOperationsPending |
- VALIDATE_FONTS |
- SHAPE_TEXT |
- GET_GLYPH_METRICS |
- LAYOUT |
- UPDATE_LAYOUT_SIZE |
- REORDER |
- ALIGN );
+ controller.mImpl->mOperationsPending = static_cast<OperationsMask>(controller.mImpl->mOperationsPending |
+ VALIDATE_FONTS |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS |
+ LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ REORDER |
+ ALIGN);
controller.mImpl->mRecalculateNaturalSize = true;
controller.mImpl->RequestRelayout();
// As the font might change, recalculate the handle positions is needed.
- controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
+ controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
controller.mImpl->mEventData->mUpdateRightSelectionPosition = true;
- controller.mImpl->mEventData->mUpdateHighlightBox = true;
- controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
+ controller.mImpl->mEventData->mUpdateHighlightBox = true;
+ controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
}
}
}
{
bool defined = false;
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
defined = controller.mImpl->mEventData->mInputStyle.isWeightDefined;
}
FontWeight Controller::InputFontHandler::GetInputFontWeight(const Controller& controller)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
return controller.mImpl->mEventData->mInputStyle.weight;
}
void Controller::InputFontHandler::SetInputFontWidth(Controller& controller, FontWidth width)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- controller.mImpl->mEventData->mInputStyle.width = width;
+ controller.mImpl->mEventData->mInputStyle.width = width;
controller.mImpl->mEventData->mInputStyle.isWidthDefined = true;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState)
{
- CharacterIndex startOfSelectedText = 0u;
- Length lengthOfSelectedText = 0u;
+ CharacterIndex startOfSelectedText = 0u;
+ Length lengthOfSelectedText = 0u;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState)
{
// Update a font description run for the selecting state.
- FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData,
- controller.mImpl->mModel->mLogicalModel,
- startOfSelectedText,
- lengthOfSelectedText );
+ FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData,
+ controller.mImpl->mModel->mLogicalModel,
+ startOfSelectedText,
+ lengthOfSelectedText);
- fontDescriptionRun.width = width;
+ fontDescriptionRun.width = width;
fontDescriptionRun.widthDefined = true;
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
}
else
{
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
}
// Request to relayout.
- controller.mImpl->mOperationsPending = static_cast<OperationsMask>( controller.mImpl->mOperationsPending |
- VALIDATE_FONTS |
- SHAPE_TEXT |
- GET_GLYPH_METRICS |
- LAYOUT |
- UPDATE_LAYOUT_SIZE |
- REORDER |
- ALIGN );
+ controller.mImpl->mOperationsPending = static_cast<OperationsMask>(controller.mImpl->mOperationsPending |
+ VALIDATE_FONTS |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS |
+ LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ REORDER |
+ ALIGN);
controller.mImpl->mRecalculateNaturalSize = true;
controller.mImpl->RequestRelayout();
// As the font might change, recalculate the handle positions is needed.
- controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
+ controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
controller.mImpl->mEventData->mUpdateRightSelectionPosition = true;
- controller.mImpl->mEventData->mUpdateHighlightBox = true;
- controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
+ controller.mImpl->mEventData->mUpdateHighlightBox = true;
+ controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
}
}
}
{
bool defined = false;
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
defined = controller.mImpl->mEventData->mInputStyle.isWidthDefined;
}
FontWidth Controller::InputFontHandler::GetInputFontWidth(const Controller& controller)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
return controller.mImpl->mEventData->mInputStyle.width;
}
void Controller::InputFontHandler::SetInputFontSlant(Controller& controller, FontSlant slant)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- controller.mImpl->mEventData->mInputStyle.slant = slant;
+ controller.mImpl->mEventData->mInputStyle.slant = slant;
controller.mImpl->mEventData->mInputStyle.isSlantDefined = true;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState)
{
- CharacterIndex startOfSelectedText = 0u;
- Length lengthOfSelectedText = 0u;
+ CharacterIndex startOfSelectedText = 0u;
+ Length lengthOfSelectedText = 0u;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState)
{
// Update a font description run for the selecting state.
- FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData,
- controller.mImpl->mModel->mLogicalModel,
- startOfSelectedText,
- lengthOfSelectedText );
+ FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData,
+ controller.mImpl->mModel->mLogicalModel,
+ startOfSelectedText,
+ lengthOfSelectedText);
- fontDescriptionRun.slant = slant;
+ fontDescriptionRun.slant = slant;
fontDescriptionRun.slantDefined = true;
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
}
else
{
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
}
// Request to relayout.
- controller.mImpl->mOperationsPending = static_cast<OperationsMask>( controller.mImpl->mOperationsPending |
- VALIDATE_FONTS |
- SHAPE_TEXT |
- GET_GLYPH_METRICS |
- LAYOUT |
- UPDATE_LAYOUT_SIZE |
- REORDER |
- ALIGN );
+ controller.mImpl->mOperationsPending = static_cast<OperationsMask>(controller.mImpl->mOperationsPending |
+ VALIDATE_FONTS |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS |
+ LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ REORDER |
+ ALIGN);
controller.mImpl->mRecalculateNaturalSize = true;
controller.mImpl->RequestRelayout();
// As the font might change, recalculate the handle positions is needed.
- controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
+ controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
controller.mImpl->mEventData->mUpdateRightSelectionPosition = true;
- controller.mImpl->mEventData->mUpdateHighlightBox = true;
- controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
+ controller.mImpl->mEventData->mUpdateHighlightBox = true;
+ controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
}
}
}
{
bool defined = false;
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
defined = controller.mImpl->mEventData->mInputStyle.isSlantDefined;
}
FontSlant Controller::InputFontHandler::GetInputFontSlant(const Controller& controller)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
return controller.mImpl->mEventData->mInputStyle.slant;
}
void Controller::InputFontHandler::SetInputFontPointSize(Controller& controller, float size)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- controller.mImpl->mEventData->mInputStyle.size = size;
+ controller.mImpl->mEventData->mInputStyle.size = size;
controller.mImpl->mEventData->mInputStyle.isSizeDefined = true;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState)
{
- CharacterIndex startOfSelectedText = 0u;
- Length lengthOfSelectedText = 0u;
+ CharacterIndex startOfSelectedText = 0u;
+ Length lengthOfSelectedText = 0u;
- if( EventData::SELECTING == controller.mImpl->mEventData->mState )
+ if(EventData::SELECTING == controller.mImpl->mEventData->mState)
{
// Update a font description run for the selecting state.
- FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData,
- controller.mImpl->mModel->mLogicalModel,
- startOfSelectedText,
- lengthOfSelectedText );
+ FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData,
+ controller.mImpl->mModel->mLogicalModel,
+ startOfSelectedText,
+ lengthOfSelectedText);
- fontDescriptionRun.size = static_cast<PointSize26Dot6>( size * controller.mImpl->mFontSizeScale * 64.f );
+ fontDescriptionRun.size = static_cast<PointSize26Dot6>(size * controller.mImpl->mFontSizeScale * 64.f);
fontDescriptionRun.sizeDefined = true;
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
}
else
{
- controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
+ controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0;
controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
- controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
+ controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count();
}
// Request to relayout.
- controller.mImpl->mOperationsPending = static_cast<OperationsMask>( controller.mImpl->mOperationsPending |
- VALIDATE_FONTS |
- SHAPE_TEXT |
- GET_GLYPH_METRICS |
- LAYOUT |
- UPDATE_LAYOUT_SIZE |
- REORDER |
- ALIGN );
+ controller.mImpl->mOperationsPending = static_cast<OperationsMask>(controller.mImpl->mOperationsPending |
+ VALIDATE_FONTS |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS |
+ LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ REORDER |
+ ALIGN);
controller.mImpl->mRecalculateNaturalSize = true;
controller.mImpl->RequestRelayout();
// As the font might change, recalculate the handle positions is needed.
- controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
+ controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true;
controller.mImpl->mEventData->mUpdateRightSelectionPosition = true;
- controller.mImpl->mEventData->mUpdateHighlightBox = true;
- controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
+ controller.mImpl->mEventData->mUpdateHighlightBox = true;
+ controller.mImpl->mEventData->mScrollAfterUpdatePosition = true;
}
}
}
float Controller::InputFontHandler::GetInputFontPointSize(const Controller& controller)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
return controller.mImpl->mEventData->mInputStyle.size;
}
// Return the default font's point size if there is no EventData.
- return controller.GetDefaultFontSize( Text::Controller::POINT_SIZE );
+ return controller.GetDefaultFontSize(Text::Controller::POINT_SIZE);
}
} // namespace Text
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/controls/text-controls/placeholder-properties.h>
#include <dali-toolkit/internal/text/character-set-conversion.h>
#include <dali-toolkit/internal/text/text-controller-impl.h>
#include <dali-toolkit/internal/text/text-font-style.h>
+#include <dali-toolkit/public-api/controls/text-controls/placeholder-properties.h>
namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
const std::string EMPTY_STRING("");
-const char * const PLACEHOLDER_TEXT = "text";
-const char * const PLACEHOLDER_TEXT_FOCUSED = "textFocused";
-const char * const PLACEHOLDER_COLOR = "color";
-const char * const PLACEHOLDER_FONT_FAMILY = "fontFamily";
-const char * const PLACEHOLDER_FONT_STYLE = "fontStyle";
-const char * const PLACEHOLDER_POINT_SIZE = "pointSize";
-const char * const PLACEHOLDER_PIXEL_SIZE = "pixelSize";
-const char * const PLACEHOLDER_ELLIPSIS = "ellipsis";
+const char* const PLACEHOLDER_TEXT = "text";
+const char* const PLACEHOLDER_TEXT_FOCUSED = "textFocused";
+const char* const PLACEHOLDER_COLOR = "color";
+const char* const PLACEHOLDER_FONT_FAMILY = "fontFamily";
+const char* const PLACEHOLDER_FONT_STYLE = "fontStyle";
+const char* const PLACEHOLDER_POINT_SIZE = "pointSize";
+const char* const PLACEHOLDER_PIXEL_SIZE = "pixelSize";
+const char* const PLACEHOLDER_ELLIPSIS = "ellipsis";
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
void Controller::PlaceholderHandler::SetPlaceholderTextElideEnabled(Controller& controller, bool enabled)
{
controller.mImpl->mEventData->mIsPlaceholderElideEnabled = enabled;
- controller.mImpl->mEventData->mPlaceholderEllipsisFlag = true;
+ controller.mImpl->mEventData->mPlaceholderEllipsisFlag = true;
// Update placeholder if there is no text
- if( controller.mImpl->IsShowingPlaceholderText() ||
- ( 0u == controller.mImpl->mModel->mLogicalModel->mText.Count() ) )
+ if(controller.mImpl->IsShowingPlaceholderText() ||
+ (0u == controller.mImpl->mModel->mLogicalModel->mText.Count()))
{
controller.ShowPlaceholderText();
}
void Controller::PlaceholderHandler::SetPlaceholderText(Controller& controller, PlaceholderType type, const std::string& text)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( PLACEHOLDER_TYPE_INACTIVE == type )
+ if(PLACEHOLDER_TYPE_INACTIVE == type)
{
controller.mImpl->mEventData->mPlaceholderTextInactive = text;
}
}
// Update placeholder if there is no text
- if( controller.mImpl->IsShowingPlaceholderText() ||
- ( 0u == controller.mImpl->mModel->mLogicalModel->mText.Count() ) )
+ if(controller.mImpl->IsShowingPlaceholderText() ||
+ (0u == controller.mImpl->mModel->mLogicalModel->mText.Count()))
{
controller.ShowPlaceholderText();
}
void Controller::PlaceholderHandler::GetPlaceholderText(const Controller& controller, PlaceholderType type, std::string& text)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( PLACEHOLDER_TYPE_INACTIVE == type )
+ if(PLACEHOLDER_TYPE_INACTIVE == type)
{
text = controller.mImpl->mEventData->mPlaceholderTextInactive;
}
void Controller::PlaceholderHandler::SetPlaceholderFontFamily(Controller& controller, const std::string& placeholderTextFontFamily)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( NULL == controller.mImpl->mEventData->mPlaceholderFont )
+ if(NULL == controller.mImpl->mEventData->mPlaceholderFont)
{
controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults();
}
controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.family = placeholderTextFontFamily;
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetPlaceholderFontFamily %s\n", placeholderTextFontFamily.c_str());
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetPlaceholderFontFamily %s\n", placeholderTextFontFamily.c_str());
controller.mImpl->mEventData->mPlaceholderFont->familyDefined = !placeholderTextFontFamily.empty();
controller.mImpl->RequestRelayout();
const std::string& Controller::PlaceholderHandler::GetPlaceholderFontFamily(const Controller& controller)
{
- if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) )
+ if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont))
{
return controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.family;
}
void Controller::PlaceholderHandler::SetPlaceholderTextFontWeight(Controller& controller, FontWeight weight)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( NULL == controller.mImpl->mEventData->mPlaceholderFont )
+ if(NULL == controller.mImpl->mEventData->mPlaceholderFont)
{
controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults();
}
controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.weight = weight;
- controller.mImpl->mEventData->mPlaceholderFont->weightDefined = true;
+ controller.mImpl->mEventData->mPlaceholderFont->weightDefined = true;
controller.mImpl->RequestRelayout();
}
bool Controller::PlaceholderHandler::IsPlaceholderTextFontWeightDefined(const Controller& controller)
{
- if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) )
+ if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont))
{
return controller.mImpl->mEventData->mPlaceholderFont->weightDefined;
}
FontWeight Controller::PlaceholderHandler::GetPlaceholderTextFontWeight(const Controller& controller)
{
- if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) )
+ if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont))
{
return controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.weight;
}
void Controller::PlaceholderHandler::SetPlaceholderTextFontWidth(Controller& controller, FontWidth width)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( NULL == controller.mImpl->mEventData->mPlaceholderFont )
+ if(NULL == controller.mImpl->mEventData->mPlaceholderFont)
{
controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults();
}
controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.width = width;
- controller.mImpl->mEventData->mPlaceholderFont->widthDefined = true;
+ controller.mImpl->mEventData->mPlaceholderFont->widthDefined = true;
controller.mImpl->RequestRelayout();
}
bool Controller::PlaceholderHandler::IsPlaceholderTextFontWidthDefined(const Controller& controller)
{
- if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) )
+ if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont))
{
return controller.mImpl->mEventData->mPlaceholderFont->widthDefined;
}
FontWidth Controller::PlaceholderHandler::GetPlaceholderTextFontWidth(const Controller& controller)
{
- if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) )
+ if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont))
{
return controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.width;
}
void Controller::PlaceholderHandler::SetPlaceholderTextFontSlant(Controller& controller, FontSlant slant)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( NULL == controller.mImpl->mEventData->mPlaceholderFont )
+ if(NULL == controller.mImpl->mEventData->mPlaceholderFont)
{
controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults();
}
controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.slant = slant;
- controller.mImpl->mEventData->mPlaceholderFont->slantDefined = true;
+ controller.mImpl->mEventData->mPlaceholderFont->slantDefined = true;
controller.mImpl->RequestRelayout();
}
bool Controller::PlaceholderHandler::IsPlaceholderTextFontSlantDefined(const Controller& controller)
{
- if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) )
+ if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont))
{
return controller.mImpl->mEventData->mPlaceholderFont->slantDefined;
}
FontSlant Controller::PlaceholderHandler::GetPlaceholderTextFontSlant(const Controller& controller)
{
- if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) )
+ if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont))
{
return controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.slant;
}
void Controller::PlaceholderHandler::SetPlaceholderTextFontSize(Controller& controller, float fontSize, FontSizeType type)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( NULL == controller.mImpl->mEventData->mPlaceholderFont )
+ if(NULL == controller.mImpl->mEventData->mPlaceholderFont)
{
controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults();
}
- switch( type )
+ switch(type)
{
case POINT_SIZE:
{
controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = fontSize;
- controller.mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
- controller.mImpl->mEventData->mIsPlaceholderPixelSize = false; // Font size flag
+ controller.mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
+ controller.mImpl->mEventData->mIsPlaceholderPixelSize = false; // Font size flag
break;
}
case PIXEL_SIZE:
{
// Point size = Pixel size * 72.f / DPI
- unsigned int horizontalDpi = 0u;
- unsigned int verticalDpi = 0u;
- TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
- fontClient.GetDpi( horizontalDpi, verticalDpi );
-
- controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi );
- controller.mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
- controller.mImpl->mEventData->mIsPlaceholderPixelSize = true; // Font size flag
+ unsigned int horizontalDpi = 0u;
+ unsigned int verticalDpi = 0u;
+ TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
+ fontClient.GetDpi(horizontalDpi, verticalDpi);
+
+ controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = (fontSize * 72.f) / static_cast<float>(horizontalDpi);
+ controller.mImpl->mEventData->mPlaceholderFont->sizeDefined = true;
+ controller.mImpl->mEventData->mIsPlaceholderPixelSize = true; // Font size flag
break;
}
}
}
}
-float Controller::PlaceholderHandler::GetPlaceholderTextFontSize(const Controller& controller, FontSizeType type )
+float Controller::PlaceholderHandler::GetPlaceholderTextFontSize(const Controller& controller, FontSizeType type)
{
float value = 0.0f;
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- switch( type )
+ switch(type)
{
case POINT_SIZE:
{
- if( NULL != controller.mImpl->mEventData->mPlaceholderFont )
+ if(NULL != controller.mImpl->mEventData->mPlaceholderFont)
{
value = controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize;
}
else
{
// If the placeholder text font size is not set, then return the default font size.
- value = controller.GetDefaultFontSize( POINT_SIZE );
+ value = controller.GetDefaultFontSize(POINT_SIZE);
}
break;
}
case PIXEL_SIZE:
{
- if( NULL != controller.mImpl->mEventData->mPlaceholderFont )
+ if(NULL != controller.mImpl->mEventData->mPlaceholderFont)
{
// Pixel size = Point size * DPI / 72.f
- unsigned int horizontalDpi = 0u;
- unsigned int verticalDpi = 0u;
- TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
- fontClient.GetDpi( horizontalDpi, verticalDpi );
+ unsigned int horizontalDpi = 0u;
+ unsigned int verticalDpi = 0u;
+ TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
+ fontClient.GetDpi(horizontalDpi, verticalDpi);
- value = controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f;
+ value = controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize * static_cast<float>(horizontalDpi) / 72.f;
}
else
{
// If the placeholder text font size is not set, then return the default font size.
- value = controller.GetDefaultFontSize( PIXEL_SIZE );
+ value = controller.GetDefaultFontSize(PIXEL_SIZE);
}
break;
}
return value;
}
-void Controller::PlaceholderHandler::SetPlaceholderTextColor(Controller& controller, const Vector4& textColor )
+void Controller::PlaceholderHandler::SetPlaceholderTextColor(Controller& controller, const Vector4& textColor)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
controller.mImpl->mEventData->mPlaceholderTextColor = textColor;
}
- if( controller.mImpl->IsShowingPlaceholderText() )
+ if(controller.mImpl->IsShowingPlaceholderText())
{
- controller.mImpl->mModel->mVisualModel->SetTextColor( textColor );
+ controller.mImpl->mModel->mVisualModel->SetTextColor(textColor);
controller.mImpl->RequestRelayout();
}
}
const Vector4& Controller::PlaceholderHandler::GetPlaceholderTextColor(const Controller& controller)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
return controller.mImpl->mEventData->mPlaceholderTextColor;
}
return Color::BLACK;
}
-void Controller::PlaceholderHandler::SetPlaceholderProperty(Controller& controller, const Property::Map& map )
+void Controller::PlaceholderHandler::SetPlaceholderProperty(Controller& controller, const Property::Map& map)
{
const Property::Map::SizeType count = map.Count();
- for( Property::Map::SizeType position = 0; position < count; ++position )
+ for(Property::Map::SizeType position = 0; position < count; ++position)
{
- KeyValuePair keyValue = map.GetKeyValue( position );
- Property::Key& key = keyValue.first;
- Property::Value& value = keyValue.second;
+ KeyValuePair keyValue = map.GetKeyValue(position);
+ Property::Key& key = keyValue.first;
+ Property::Value& value = keyValue.second;
- if( key == Toolkit::Text::PlaceHolder::Property::TEXT || key == PLACEHOLDER_TEXT )
+ if(key == Toolkit::Text::PlaceHolder::Property::TEXT || key == PLACEHOLDER_TEXT)
{
std::string text = "";
- value.Get( text );
+ value.Get(text);
SetPlaceholderText(controller, Controller::PLACEHOLDER_TYPE_INACTIVE, text);
}
- else if( key == Toolkit::Text::PlaceHolder::Property::TEXT_FOCUSED || key == PLACEHOLDER_TEXT_FOCUSED )
+ else if(key == Toolkit::Text::PlaceHolder::Property::TEXT_FOCUSED || key == PLACEHOLDER_TEXT_FOCUSED)
{
std::string text = "";
- value.Get( text );
+ value.Get(text);
SetPlaceholderText(controller, Controller::PLACEHOLDER_TYPE_ACTIVE, text);
}
- else if( key == Toolkit::Text::PlaceHolder::Property::COLOR || key == PLACEHOLDER_COLOR )
+ else if(key == Toolkit::Text::PlaceHolder::Property::COLOR || key == PLACEHOLDER_COLOR)
{
Vector4 textColor;
- value.Get( textColor );
- if( GetPlaceholderTextColor(controller) != textColor )
+ value.Get(textColor);
+ if(GetPlaceholderTextColor(controller) != textColor)
{
SetPlaceholderTextColor(controller, textColor);
}
}
- else if( key == Toolkit::Text::PlaceHolder::Property::FONT_FAMILY || key == PLACEHOLDER_FONT_FAMILY )
+ else if(key == Toolkit::Text::PlaceHolder::Property::FONT_FAMILY || key == PLACEHOLDER_FONT_FAMILY)
{
std::string fontFamily = "";
- value.Get( fontFamily );
+ value.Get(fontFamily);
SetPlaceholderFontFamily(controller, fontFamily);
}
- else if( key == Toolkit::Text::PlaceHolder::Property::FONT_STYLE || key == PLACEHOLDER_FONT_STYLE )
+ else if(key == Toolkit::Text::PlaceHolder::Property::FONT_STYLE || key == PLACEHOLDER_FONT_STYLE)
{
- SetFontStyleProperty( &controller, value, Text::FontStyle::PLACEHOLDER );
+ SetFontStyleProperty(&controller, value, Text::FontStyle::PLACEHOLDER);
}
- else if( key == Toolkit::Text::PlaceHolder::Property::POINT_SIZE || key == PLACEHOLDER_POINT_SIZE )
+ else if(key == Toolkit::Text::PlaceHolder::Property::POINT_SIZE || key == PLACEHOLDER_POINT_SIZE)
{
float pointSize;
- value.Get( pointSize );
- if( !Equals(GetPlaceholderTextFontSize(controller, Text::Controller::POINT_SIZE), pointSize) )
+ value.Get(pointSize);
+ if(!Equals(GetPlaceholderTextFontSize(controller, Text::Controller::POINT_SIZE), pointSize))
{
SetPlaceholderTextFontSize(controller, pointSize, Text::Controller::POINT_SIZE);
}
}
- else if( key == Toolkit::Text::PlaceHolder::Property::PIXEL_SIZE || key == PLACEHOLDER_PIXEL_SIZE )
+ else if(key == Toolkit::Text::PlaceHolder::Property::PIXEL_SIZE || key == PLACEHOLDER_PIXEL_SIZE)
{
float pixelSize;
- value.Get( pixelSize );
- if( !Equals(GetPlaceholderTextFontSize(controller, Text::Controller::PIXEL_SIZE), pixelSize) )
+ value.Get(pixelSize);
+ if(!Equals(GetPlaceholderTextFontSize(controller, Text::Controller::PIXEL_SIZE), pixelSize))
{
SetPlaceholderTextFontSize(controller, pixelSize, Text::Controller::PIXEL_SIZE);
}
}
- else if( key == Toolkit::Text::PlaceHolder::Property::ELLIPSIS || key == PLACEHOLDER_ELLIPSIS )
+ else if(key == Toolkit::Text::PlaceHolder::Property::ELLIPSIS || key == PLACEHOLDER_ELLIPSIS)
{
bool ellipsis;
- value.Get( ellipsis );
+ value.Get(ellipsis);
SetPlaceholderTextElideEnabled(controller, ellipsis);
}
}
void Controller::PlaceholderHandler::GetPlaceholderProperty(Controller& controller, Property::Map& map)
{
- if( NULL != controller.mImpl->mEventData )
+ if(NULL != controller.mImpl->mEventData)
{
- if( !controller.mImpl->mEventData->mPlaceholderTextActive.empty() )
+ if(!controller.mImpl->mEventData->mPlaceholderTextActive.empty())
{
- map[ Text::PlaceHolder::Property::TEXT_FOCUSED ] = controller.mImpl->mEventData->mPlaceholderTextActive;
+ map[Text::PlaceHolder::Property::TEXT_FOCUSED] = controller.mImpl->mEventData->mPlaceholderTextActive;
}
- if( !controller.mImpl->mEventData->mPlaceholderTextInactive.empty() )
+ if(!controller.mImpl->mEventData->mPlaceholderTextInactive.empty())
{
- map[ Text::PlaceHolder::Property::TEXT ] = controller.mImpl->mEventData->mPlaceholderTextInactive;
+ map[Text::PlaceHolder::Property::TEXT] = controller.mImpl->mEventData->mPlaceholderTextInactive;
}
- map[ Text::PlaceHolder::Property::COLOR ] = controller.mImpl->mEventData->mPlaceholderTextColor;
- map[ Text::PlaceHolder::Property::FONT_FAMILY ] = GetPlaceholderFontFamily(controller);
+ map[Text::PlaceHolder::Property::COLOR] = controller.mImpl->mEventData->mPlaceholderTextColor;
+ map[Text::PlaceHolder::Property::FONT_FAMILY] = GetPlaceholderFontFamily(controller);
Property::Value fontStyleMapGet;
- GetFontStyleProperty( &controller, fontStyleMapGet, Text::FontStyle::PLACEHOLDER );
- map[ Text::PlaceHolder::Property::FONT_STYLE ] = fontStyleMapGet;
+ GetFontStyleProperty(&controller, fontStyleMapGet, Text::FontStyle::PLACEHOLDER);
+ map[Text::PlaceHolder::Property::FONT_STYLE] = fontStyleMapGet;
// Choose font size : POINT_SIZE or PIXEL_SIZE
- if( !controller.mImpl->mEventData->mIsPlaceholderPixelSize )
+ if(!controller.mImpl->mEventData->mIsPlaceholderPixelSize)
{
- map[ Text::PlaceHolder::Property::POINT_SIZE ] = GetPlaceholderTextFontSize(controller, Text::Controller::POINT_SIZE);
+ map[Text::PlaceHolder::Property::POINT_SIZE] = GetPlaceholderTextFontSize(controller, Text::Controller::POINT_SIZE);
}
else
{
- map[ Text::PlaceHolder::Property::PIXEL_SIZE ] = GetPlaceholderTextFontSize(controller, Text::Controller::PIXEL_SIZE);
+ map[Text::PlaceHolder::Property::PIXEL_SIZE] = GetPlaceholderTextFontSize(controller, Text::Controller::PIXEL_SIZE);
}
- if( controller.mImpl->mEventData->mPlaceholderEllipsisFlag )
+ if(controller.mImpl->mEventData->mPlaceholderEllipsisFlag)
{
- map[ Text::PlaceHolder::Property::ELLIPSIS ] = IsPlaceholderTextElideEnabled(controller);
+ map[Text::PlaceHolder::Property::ELLIPSIS] = IsPlaceholderTextElideEnabled(controller);
}
}
}
{
Controller::Impl& impl = *controller.mImpl;
- if( impl.IsPlaceholderAvailable() )
+ if(impl.IsPlaceholderAvailable())
{
EventData*& eventData = impl.mEventData;
- DALI_ASSERT_DEBUG( eventData && "No placeholder text available" );
+ DALI_ASSERT_DEBUG(eventData && "No placeholder text available");
- if( NULL == eventData )
+ if(NULL == eventData)
{
return;
}
// Disable handles when showing place-holder text
DecoratorPtr& decorator = eventData->mDecorator;
- decorator->SetHandleActive( GRAB_HANDLE, false );
- decorator->SetHandleActive( LEFT_SELECTION_HANDLE, false );
- decorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false );
+ decorator->SetHandleActive(GRAB_HANDLE, false);
+ decorator->SetHandleActive(LEFT_SELECTION_HANDLE, false);
+ decorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false);
- const char* text( NULL );
- size_t size( 0 );
+ const char* text(NULL);
+ size_t size(0);
// TODO - Switch Placeholder text when changing state
std::string& placeholderTextActive = eventData->mPlaceholderTextActive;
- if( ( EventData::INACTIVE != eventData->mState ) &&
- ( 0u != placeholderTextActive.c_str() ) )
+ if((EventData::INACTIVE != eventData->mState) &&
+ (0u != placeholderTextActive.c_str()))
{
text = placeholderTextActive.c_str();
size = placeholderTextActive.size();
else
{
std::string& placeholderTextInactive = eventData->mPlaceholderTextInactive;
- text = placeholderTextInactive.c_str();
- size = placeholderTextInactive.size();
+ text = placeholderTextInactive.c_str();
+ size = placeholderTextInactive.size();
}
- TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
- textUpdateInfo.mCharacterIndex = 0u;
+ TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
+ textUpdateInfo.mCharacterIndex = 0u;
textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters;
// Reset model for showing placeholder.
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
LogicalModelPtr& logicalModel = model->mLogicalModel;
logicalModel->mText.Clear();
- model->mVisualModel->SetTextColor( eventData->mPlaceholderTextColor );
+ model->mVisualModel->SetTextColor(eventData->mPlaceholderTextColor);
// Convert text into UTF-32
Vector<Character>& utf32Characters = logicalModel->mText;
- utf32Characters.Resize( size );
+ utf32Characters.Resize(size);
// This is a bit horrible but std::string returns a (signed) char*
- const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text );
+ const uint8_t* utf8 = reinterpret_cast<const uint8_t*>(text);
// Transform a text array encoded in utf8 into an array encoded in utf32.
// It returns the actual number of characters.
- const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() );
- utf32Characters.Resize( characterCount );
+ const Length characterCount = Utf8ToUtf32(utf8, size, utf32Characters.Begin());
+ utf32Characters.Resize(characterCount);
// The characters to be added.
textUpdateInfo.mNumberOfCharactersToAdd = characterCount;
impl.mOperationsPending = ALL_OPERATIONS;
// Update the rest of the model during size negotiation
- impl.QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
+ impl.QueueModifyEvent(ModifyEvent::TEXT_REPLACED);
}
}
-
} // namespace Text
} // namespace Toolkit
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/text-controller-relayouter.h>
// EXTERNAL INCLUDES
-#include <limits>
#include <dali/integration-api/debug.h>
+#include <limits>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/layouts/layout-parameters.h>
namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
constexpr float MAX_FLOAT = std::numeric_limits<float>::max();
-float ConvertToEven( float value )
+float ConvertToEven(float value)
{
- int intValue(static_cast<int>( value ));
- return static_cast<float>( intValue + ( intValue & 1 ) );
+ int intValue(static_cast<int>(value));
+ return static_cast<float>(intValue + (intValue & 1));
}
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n");
Vector3 naturalSize;
// Make sure the model is up-to-date before layouting
controller.ProcessModifyEvents();
- Controller::Impl& impl = *controller.mImpl;
- ModelPtr& model = impl.mModel;
- VisualModelPtr& visualModel = model->mVisualModel;
- if( impl.mRecalculateNaturalSize )
+ Controller::Impl& impl = *controller.mImpl;
+ ModelPtr& model = impl.mModel;
+ VisualModelPtr& visualModel = model->mVisualModel;
+ if(impl.mRecalculateNaturalSize)
{
// Operations that can be done only once until the text changes.
- const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
- GET_SCRIPTS |
- VALIDATE_FONTS |
- GET_LINE_BREAKS |
- BIDI_INFO |
- SHAPE_TEXT |
- GET_GLYPH_METRICS );
+ const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
+ GET_SCRIPTS |
+ VALIDATE_FONTS |
+ GET_LINE_BREAKS |
+ BIDI_INFO |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS);
// Set the update info to relayout the whole text.
- TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
- textUpdateInfo.mParagraphCharacterIndex = 0u;
+ TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
+ textUpdateInfo.mParagraphCharacterIndex = 0u;
textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
// Make sure the model is up-to-date before layouting
- impl.UpdateModel( onlyOnceOperations );
+ impl.UpdateModel(onlyOnceOperations);
// Get a reference to the pending operations member
OperationsMask& operationsPending = impl.mOperationsPending;
// Layout the text for the new width.
- operationsPending = static_cast<OperationsMask>( operationsPending | LAYOUT | REORDER );
+ operationsPending = static_cast<OperationsMask>(operationsPending | LAYOUT | REORDER);
// Store the actual control's size to restore later.
const Size actualControlSize = visualModel->mControlSize;
- DoRelayout( controller,
- Size( MAX_FLOAT, MAX_FLOAT ),
- static_cast<OperationsMask>( onlyOnceOperations |
- LAYOUT | REORDER ),
- naturalSize.GetVectorXY() );
+ DoRelayout(controller,
+ Size(MAX_FLOAT, MAX_FLOAT),
+ static_cast<OperationsMask>(onlyOnceOperations |
+ LAYOUT | REORDER),
+ naturalSize.GetVectorXY());
// Do not do again the only once operations.
- operationsPending = static_cast<OperationsMask>( operationsPending & ~onlyOnceOperations );
+ operationsPending = static_cast<OperationsMask>(operationsPending & ~onlyOnceOperations);
// Do the size related operations again.
- const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
- ALIGN |
- REORDER );
- operationsPending = static_cast<OperationsMask>( operationsPending | sizeOperations );
+ const OperationsMask sizeOperations = static_cast<OperationsMask>(LAYOUT |
+ ALIGN |
+ REORDER);
+ operationsPending = static_cast<OperationsMask>(operationsPending | sizeOperations);
// Stores the natural size to avoid recalculate it again
// unless the text/style changes.
- visualModel->SetNaturalSize( naturalSize.GetVectorXY() );
+ visualModel->SetNaturalSize(naturalSize.GetVectorXY());
impl.mRecalculateNaturalSize = false;
// Restore the actual control's size.
visualModel->mControlSize = actualControlSize;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z);
}
else
{
naturalSize = visualModel->GetNaturalSize();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z);
}
- naturalSize.x = ConvertToEven( naturalSize.x );
- naturalSize.y = ConvertToEven( naturalSize.y );
+ naturalSize.x = ConvertToEven(naturalSize.x);
+ naturalSize.y = ConvertToEven(naturalSize.y);
return naturalSize;
}
bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize)
{
- Size textSize;
- Controller::Impl& impl = *controller.mImpl;
- TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
+ Size textSize;
+ Controller::Impl& impl = *controller.mImpl;
+ TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
impl.mFontDefaults->mFitPointSize = pointSize;
- impl.mFontDefaults->sizeDefined = true;
+ impl.mFontDefaults->sizeDefined = true;
controller.ClearFontData();
// Operations that can be done only once until the text changes.
- const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
- GET_SCRIPTS |
- VALIDATE_FONTS |
- GET_LINE_BREAKS |
- BIDI_INFO |
- SHAPE_TEXT|
- GET_GLYPH_METRICS );
-
- textUpdateInfo.mParagraphCharacterIndex = 0u;
+ const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
+ GET_SCRIPTS |
+ VALIDATE_FONTS |
+ GET_LINE_BREAKS |
+ BIDI_INFO |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS);
+
+ textUpdateInfo.mParagraphCharacterIndex = 0u;
textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
// Make sure the model is up-to-date before layouting
- impl.UpdateModel( onlyOnceOperations );
+ impl.UpdateModel(onlyOnceOperations);
- DoRelayout( controller,
- Size( layoutSize.width, MAX_FLOAT ),
- static_cast<OperationsMask>( onlyOnceOperations | LAYOUT),
- textSize);
+ DoRelayout(controller,
+ Size(layoutSize.width, MAX_FLOAT),
+ static_cast<OperationsMask>(onlyOnceOperations | LAYOUT),
+ textSize);
// Clear the update info. This info will be set the next time the text is updated.
textUpdateInfo.Clear();
textUpdateInfo.mClearAll = true;
- if( textSize.width > layoutSize.width || textSize.height > layoutSize.height )
+ if(textSize.width > layoutSize.width || textSize.height > layoutSize.height)
{
return false;
}
{
Controller::Impl& impl = *controller.mImpl;
- const OperationsMask operations = impl.mOperationsPending;
- if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) || impl.mTextFitContentSize != layoutSize )
+ const OperationsMask operations = impl.mOperationsPending;
+ if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize)
{
ModelPtr& model = impl.mModel;
- bool actualellipsis = model->mElideEnabled;
- float minPointSize = impl.mTextFitMinSize;
- float maxPointSize = impl.mTextFitMaxSize;
- float pointInterval = impl.mTextFitStepSize;
+ bool actualellipsis = model->mElideEnabled;
+ float minPointSize = impl.mTextFitMinSize;
+ float maxPointSize = impl.mTextFitMaxSize;
+ float pointInterval = impl.mTextFitStepSize;
model->mElideEnabled = false;
Vector<float> pointSizeArray;
// check zero value
- if( pointInterval < 1.f )
+ if(pointInterval < 1.f)
{
impl.mTextFitStepSize = pointInterval = 1.0f;
}
- pointSizeArray.Reserve( static_cast< unsigned int >( ceil( ( maxPointSize - minPointSize ) / pointInterval ) ) );
+ pointSizeArray.Reserve(static_cast<unsigned int>(ceil((maxPointSize - minPointSize) / pointInterval)));
- for( float i = minPointSize; i < maxPointSize; i += pointInterval )
+ for(float i = minPointSize; i < maxPointSize; i += pointInterval)
{
- pointSizeArray.PushBack( i );
+ pointSizeArray.PushBack(i);
}
- pointSizeArray.PushBack( maxPointSize );
+ pointSizeArray.PushBack(maxPointSize);
int bestSizeIndex = 0;
- int min = bestSizeIndex + 1;
- int max = pointSizeArray.Size() - 1;
- while( min <= max )
+ int min = bestSizeIndex + 1;
+ int max = pointSizeArray.Size() - 1;
+ while(min <= max)
{
- int destI = ( min + max ) / 2;
+ int destI = (min + max) / 2;
- if( CheckForTextFit( controller, pointSizeArray[destI], layoutSize ) )
+ if(CheckForTextFit(controller, pointSizeArray[destI], layoutSize))
{
bestSizeIndex = min;
- min = destI + 1;
+ min = destI + 1;
}
else
{
- max = destI - 1;
+ max = destI - 1;
bestSizeIndex = max;
}
}
- model->mElideEnabled = actualellipsis;
+ model->mElideEnabled = actualellipsis;
impl.mFontDefaults->mFitPointSize = pointSizeArray[bestSizeIndex];
- impl.mFontDefaults->sizeDefined = true;
+ impl.mFontDefaults->sizeDefined = true;
controller.ClearFontData();
}
}
float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width);
// Make sure the model is up-to-date before layouting
controller.ProcessModifyEvents();
- Controller::Impl& impl = *controller.mImpl;
- ModelPtr& model = impl.mModel;
- VisualModelPtr& visualModel = model->mVisualModel;
- TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
+ Controller::Impl& impl = *controller.mImpl;
+ ModelPtr& model = impl.mModel;
+ VisualModelPtr& visualModel = model->mVisualModel;
+ TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
Size layoutSize;
- if( fabsf( width - visualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 ||
- textUpdateInfo.mFullRelayoutNeeded ||
- textUpdateInfo.mClearAll )
+ if(fabsf(width - visualModel->mControlSize.width) > Math::MACHINE_EPSILON_1000 ||
+ textUpdateInfo.mFullRelayoutNeeded ||
+ textUpdateInfo.mClearAll)
{
// Operations that can be done only once until the text changes.
- const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
- GET_SCRIPTS |
- VALIDATE_FONTS |
- GET_LINE_BREAKS |
- BIDI_INFO |
- SHAPE_TEXT |
- GET_GLYPH_METRICS );
+ const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
+ GET_SCRIPTS |
+ VALIDATE_FONTS |
+ GET_LINE_BREAKS |
+ BIDI_INFO |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS);
// Set the update info to relayout the whole text.
- textUpdateInfo.mParagraphCharacterIndex = 0u;
+ textUpdateInfo.mParagraphCharacterIndex = 0u;
textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count();
// Make sure the model is up-to-date before layouting
- impl.UpdateModel( onlyOnceOperations );
+ impl.UpdateModel(onlyOnceOperations);
// Get a reference to the pending operations member
OperationsMask& operationsPending = impl.mOperationsPending;
// Layout the text for the new width.
- operationsPending = static_cast<OperationsMask>( operationsPending | LAYOUT );
+ operationsPending = static_cast<OperationsMask>(operationsPending | LAYOUT);
// Store the actual control's width.
const float actualControlWidth = visualModel->mControlSize.width;
- DoRelayout( controller,
- Size( width, MAX_FLOAT ),
- static_cast<OperationsMask>( onlyOnceOperations |
- LAYOUT ),
- layoutSize );
+ DoRelayout(controller,
+ Size(width, MAX_FLOAT),
+ static_cast<OperationsMask>(onlyOnceOperations |
+ LAYOUT),
+ layoutSize);
// Do not do again the only once operations.
- operationsPending = static_cast<OperationsMask>( operationsPending & ~onlyOnceOperations );
+ operationsPending = static_cast<OperationsMask>(operationsPending & ~onlyOnceOperations);
// Do the size related operations again.
- const OperationsMask sizeOperations = static_cast<OperationsMask>( LAYOUT |
- ALIGN |
- REORDER );
+ const OperationsMask sizeOperations = static_cast<OperationsMask>(LAYOUT |
+ ALIGN |
+ REORDER);
- operationsPending = static_cast<OperationsMask>( operationsPending | sizeOperations );
+ operationsPending = static_cast<OperationsMask>(operationsPending | sizeOperations);
// Clear the update info. This info will be set the next time the text is updated.
textUpdateInfo.Clear();
// Restore the actual control's width.
visualModel->mControlSize.width = actualControlWidth;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height);
}
else
{
layoutSize = visualModel->GetLayoutSize();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height);
}
return layoutSize.height;
Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection)
{
- Controller::Impl& impl = *controller.mImpl;
- ModelPtr& model = impl.mModel;
- VisualModelPtr& visualModel = model->mVisualModel;
- TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
+ Controller::Impl& impl = *controller.mImpl;
+ ModelPtr& model = impl.mModel;
+ VisualModelPtr& visualModel = model->mVisualModel;
+ TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ?"true":"false" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false");
UpdateTextType updateTextType = NONE_UPDATED;
- if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) )
+ if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000))
{
- if( 0u != visualModel->mGlyphPositions.Count() )
+ if(0u != visualModel->mGlyphPositions.Count())
{
visualModel->mGlyphPositions.Clear();
updateTextType = MODEL_UPDATED;
textUpdateInfo.Clear();
// Not worth to relayout if width or height is equal to zero.
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n");
return updateTextType;
}
// Whether a new size has been set.
- const bool newSize = ( size != visualModel->mControlSize );
+ const bool newSize = (size != visualModel->mControlSize);
// Get a reference to the pending operations member
OperationsMask& operationsPending = impl.mOperationsPending;
- if( newSize )
+ if(newSize)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height);
- if( ( 0 == textUpdateInfo.mNumberOfCharactersToAdd ) &&
- ( 0 == textUpdateInfo.mPreviousNumberOfCharacters ) &&
- ( ( visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000 ) || ( visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000 ) ) )
+ if((0 == textUpdateInfo.mNumberOfCharactersToAdd) &&
+ (0 == textUpdateInfo.mPreviousNumberOfCharacters) &&
+ ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000)))
{
textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count();
}
// Layout operations that need to be done if the size changes.
- operationsPending = static_cast<OperationsMask>( operationsPending |
- LAYOUT |
- ALIGN |
- UPDATE_LAYOUT_SIZE |
- REORDER );
+ operationsPending = static_cast<OperationsMask>(operationsPending |
+ LAYOUT |
+ ALIGN |
+ UPDATE_LAYOUT_SIZE |
+ REORDER);
// Set the update info to relayout the whole text.
textUpdateInfo.mFullRelayoutNeeded = true;
- textUpdateInfo.mCharacterIndex = 0u;
+ textUpdateInfo.mCharacterIndex = 0u;
// Store the size used to layout the text.
visualModel->mControlSize = size;
}
// Whether there are modify events.
- if( 0u != impl.mModifyEvents.Count() )
+ if(0u != impl.mModifyEvents.Count())
{
// Style operations that need to be done if the text is modified.
- operationsPending = static_cast<OperationsMask>( operationsPending | COLOR );
+ operationsPending = static_cast<OperationsMask>(operationsPending | COLOR);
}
// Set the update info to elide the text.
- if( model->mElideEnabled ||
- ( ( NULL != impl.mEventData ) && impl.mEventData->mIsPlaceholderElideEnabled ) )
+ if(model->mElideEnabled ||
+ ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled))
{
// Update Text layout for applying elided
- operationsPending = static_cast<OperationsMask>( operationsPending |
- ALIGN |
- LAYOUT |
- UPDATE_LAYOUT_SIZE |
- REORDER );
+ operationsPending = static_cast<OperationsMask>(operationsPending |
+ ALIGN |
+ LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ REORDER);
textUpdateInfo.mFullRelayoutNeeded = true;
- textUpdateInfo.mCharacterIndex = 0u;
+ textUpdateInfo.mCharacterIndex = 0u;
}
- if( model->mMatchSystemLanguageDirection && impl.mLayoutDirection != layoutDirection )
+ if(model->mMatchSystemLanguageDirection && impl.mLayoutDirection != layoutDirection)
{
// Clear the update info. This info will be set the next time the text is updated.
textUpdateInfo.mClearAll = true;
// Apply modifications to the model
// Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again.
- operationsPending = static_cast<OperationsMask>( operationsPending |
- GET_GLYPH_METRICS |
- SHAPE_TEXT |
- UPDATE_DIRECTION |
- LAYOUT |
- BIDI_INFO |
- REORDER );
+ operationsPending = static_cast<OperationsMask>(operationsPending |
+ GET_GLYPH_METRICS |
+ SHAPE_TEXT |
+ UPDATE_DIRECTION |
+ LAYOUT |
+ BIDI_INFO |
+ REORDER);
impl.mLayoutDirection = layoutDirection;
}
// Make sure the model is up-to-date before layouting.
controller.ProcessModifyEvents();
- bool updated = impl.UpdateModel( operationsPending );
+ bool updated = impl.UpdateModel(operationsPending);
// Layout the text.
Size layoutSize;
- updated = DoRelayout( controller, size, operationsPending, layoutSize ) || updated;
+ updated = DoRelayout(controller, size, operationsPending, layoutSize) || updated;
-
- if( updated )
+ if(updated)
{
updateTextType = MODEL_UPDATED;
}
// Do not re-do any operation until something changes.
- operationsPending = NO_OPERATION;
+ operationsPending = NO_OPERATION;
model->mScrollPositionLast = model->mScrollPosition;
// Whether the text control is editable
// Keep the current offset as it will be used to update the decorator's positions (if the size changes).
Vector2 offset;
- if( newSize && isEditable )
+ if(newSize && isEditable)
{
offset = model->mScrollPosition;
}
- if( !isEditable || !controller.IsMultiLineEnabled() )
+ if(!isEditable || !controller.IsMultiLineEnabled())
{
// After doing the text layout, the vertical offset to place the actor in the desired position can be calculated.
- controller.CalculateVerticalOffset( size );
+ controller.CalculateVerticalOffset(size);
}
- if( isEditable )
+ if(isEditable)
{
- if( newSize )
+ if(newSize)
{
// If there is a new size, the scroll position needs to be clamped.
- impl.ClampHorizontalScroll( layoutSize );
+ impl.ClampHorizontalScroll(layoutSize);
// Update the decorator's positions is needed if there is a new size.
- impl.mEventData->mDecorator->UpdatePositions( model->mScrollPosition - offset );
+ impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset);
}
// Move the cursor, grab handle etc.
- if( impl.ProcessInputEvents() )
+ if(impl.ProcessInputEvents())
{
- updateTextType = static_cast<UpdateTextType>( updateTextType | DECORATOR_UPDATED );
+ updateTextType = static_cast<UpdateTextType>(updateTextType | DECORATOR_UPDATED);
}
}
// Clear the update info. This info will be set the next time the text is updated.
textUpdateInfo.Clear();
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n");
return updateTextType;
}
-bool Controller::Relayouter::DoRelayout(Controller& controller, const Size& size, OperationsMask operationsRequired, Size& layoutSize )
+bool Controller::Relayouter::DoRelayout(Controller& controller, const Size& size, OperationsMask operationsRequired, Size& layoutSize)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", &controller, size.width, size.height );
- bool viewUpdated( false );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", &controller, size.width, size.height);
+ bool viewUpdated(false);
Controller::Impl& impl = *controller.mImpl;
// Calculate the operations to be done.
- const OperationsMask operations = static_cast<OperationsMask>( impl.mOperationsPending & operationsRequired );
+ const OperationsMask operations = static_cast<OperationsMask>(impl.mOperationsPending & operationsRequired);
- TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
- const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex;
- const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
+ TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
+ const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex;
+ const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters;
// Get the current layout size.
VisualModelPtr& visualModel = impl.mModel->mVisualModel;
- layoutSize = visualModel->GetLayoutSize();
+ layoutSize = visualModel->GetLayoutSize();
- if( NO_OPERATION != ( LAYOUT & operations ) )
+ if(NO_OPERATION != (LAYOUT & operations))
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n");
// Some vectors with data needed to layout and reorder may be void
// after the first time the text has been laid out.
// Fill the vectors again.
// Calculate the number of glyphs to layout.
- const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
- const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
- const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
- const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
+ const Vector<GlyphIndex>& charactersToGlyph = visualModel->mCharactersToGlyph;
+ const Vector<Length>& glyphsPerCharacter = visualModel->mGlyphsPerCharacter;
+ const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin();
+ const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin();
- const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u );
- const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
+ const CharacterIndex lastIndex = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u);
+ const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex;
// Make sure the index is not out of bound
- if ( charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
- requestedNumberOfCharacters > charactersToGlyph.Count() ||
- ( lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u ) )
+ if(charactersToGlyph.Count() != glyphsPerCharacter.Count() ||
+ requestedNumberOfCharacters > charactersToGlyph.Count() ||
+ (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u))
{
std::string currentText;
- controller.GetText( currentText );
+ controller.GetText(currentText);
- DALI_LOG_ERROR( "Controller::DoRelayout: Attempting to access invalid buffer\n" );
- DALI_LOG_ERROR( "Current text is: %s\n", currentText.c_str() );
- DALI_LOG_ERROR( "startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
+ DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n");
+ DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str());
+ DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count());
return false;
}
- const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u;
+ const Length numberOfGlyphs = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u;
const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count();
- if( 0u == totalNumberOfGlyphs )
+ if(0u == totalNumberOfGlyphs)
{
- if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
+ if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
{
- visualModel->SetLayoutSize( Size::ZERO );
+ visualModel->SetLayoutSize(Size::ZERO);
}
// Nothing else to do if there is no glyphs.
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n");
return true;
}
// Set the layout parameters.
- Layout::Parameters layoutParameters( size, impl.mModel);
+ Layout::Parameters layoutParameters(size, impl.mModel);
// Resize the vector of positions to have the same size than the vector of glyphs.
Vector<Vector2>& glyphPositions = visualModel->mGlyphPositions;
- glyphPositions.Resize( totalNumberOfGlyphs );
+ glyphPositions.Resize(totalNumberOfGlyphs);
// Whether the last character is a new paragraph character.
- const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin();
- textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( impl.mModel->mLogicalModel->mText.Count() - 1u ) ) );
- layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph;
+ const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin();
+ textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u)));
+ layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph;
// The initial glyph and the number of glyphs to layout.
- layoutParameters.startGlyphIndex = startGlyphIndex;
- layoutParameters.numberOfGlyphs = numberOfGlyphs;
- layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex;
+ layoutParameters.startGlyphIndex = startGlyphIndex;
+ layoutParameters.numberOfGlyphs = numberOfGlyphs;
+ layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex;
layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines;
// Update the ellipsis
bool elideTextEnabled = impl.mModel->mElideEnabled;
- if( NULL != impl.mEventData )
+ if(NULL != impl.mEventData)
{
- if( impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText() )
+ if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText())
{
elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled;
}
- else if( EventData::INACTIVE != impl.mEventData->mState )
+ else if(EventData::INACTIVE != impl.mEventData->mState)
{
// Disable ellipsis when editing
elideTextEnabled = false;
}
// Reset the scroll position in inactive state
- if( elideTextEnabled && ( impl.mEventData->mState == EventData::INACTIVE ) )
+ if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE))
{
controller.ResetScrollPosition();
}
// Update the visual model.
bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled;
Size newLayoutSize;
- viewUpdated = impl.mLayoutEngine.LayoutText( layoutParameters,
- newLayoutSize,
- elideTextEnabled,
- isAutoScrollEnabled );
+ viewUpdated = impl.mLayoutEngine.LayoutText(layoutParameters,
+ newLayoutSize,
+ elideTextEnabled,
+ isAutoScrollEnabled);
impl.mIsAutoScrollEnabled = isAutoScrollEnabled;
- viewUpdated = viewUpdated || ( newLayoutSize != layoutSize );
+ viewUpdated = viewUpdated || (newLayoutSize != layoutSize);
- if( viewUpdated )
+ if(viewUpdated)
{
layoutSize = newLayoutSize;
- if( NO_OPERATION != ( UPDATE_DIRECTION & operations ) )
+ if(NO_OPERATION != (UPDATE_DIRECTION & operations))
{
impl.mIsTextDirectionRTL = false;
}
- if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && !visualModel->mLines.Empty() )
+ if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty())
{
impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction;
}
// Sets the layout size.
- if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) )
+ if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations))
{
- visualModel->SetLayoutSize( layoutSize );
+ visualModel->SetLayoutSize(layoutSize);
}
} // view updated
}
- if( NO_OPERATION != ( ALIGN & operations ) )
+ if(NO_OPERATION != (ALIGN & operations))
{
// The laid-out lines.
Vector<LineRun>& lines = visualModel->mLines;
- CharacterIndex alignStartIndex = startIndex;
- Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
+ CharacterIndex alignStartIndex = startIndex;
+ Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters;
// the whole text needs to be full aligned.
// If you do not do a full aligned, only the last line of the multiline input is aligned.
- if( impl.mEventData && impl.mEventData->mUpdateAlignment )
+ if(impl.mEventData && impl.mEventData->mUpdateAlignment)
{
- alignStartIndex = 0u;
- alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
+ alignStartIndex = 0u;
+ alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count();
impl.mEventData->mUpdateAlignment = false;
}
// Need to align with the control's size as the text may contain lines
// starting either with left to right text or right to left.
- impl.mLayoutEngine.Align( size,
- alignStartIndex,
- alignRequestedNumberOfCharacters,
- impl.mModel->mHorizontalAlignment,
- lines,
- impl.mModel->mAlignmentOffset,
- impl.mLayoutDirection,
- impl.mModel->mMatchSystemLanguageDirection );
+ impl.mLayoutEngine.Align(size,
+ alignStartIndex,
+ alignRequestedNumberOfCharacters,
+ impl.mModel->mHorizontalAlignment,
+ lines,
+ impl.mModel->mAlignmentOffset,
+ impl.mLayoutDirection,
+ impl.mModel->mMatchSystemLanguageDirection);
viewUpdated = true;
}
#if defined(DEBUG_ENABLED)
std::string currentText;
- controller.GetText( currentText );
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &controller, (impl.mIsTextDirectionRTL)?"true":"false", currentText.c_str() );
+ controller.GetText(currentText);
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &controller, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str());
#endif
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false"));
return viewUpdated;
}
void Controller::Relayouter::CalculateVerticalOffset(Controller& controller, const Size& controlSize)
{
- Controller::Impl& impl = *controller.mImpl;
- ModelPtr& model = impl.mModel;
- Size layoutSize = model->mVisualModel->GetLayoutSize();
+ Controller::Impl& impl = *controller.mImpl;
+ ModelPtr& model = impl.mModel;
+ Size layoutSize = model->mVisualModel->GetLayoutSize();
- if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 )
+ if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000)
{
// Get the line height of the default font.
layoutSize.height = impl.GetDefaultFontLineHeight();
}
- switch( model->mVerticalAlignment )
+ switch(model->mVerticalAlignment)
{
case VerticalAlignment::TOP:
{
}
case VerticalAlignment::CENTER:
{
- model->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment.
+ model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment.
break;
}
case VerticalAlignment::BOTTOM:
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/text-controller-text-updater.h>
// EXTERNAL INCLUDES
-#include <memory.h>
#include <dali/integration-api/debug.h>
+#include <memory.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/character-set-conversion.h>
namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
void Controller::TextUpdater::SetText(Controller& controller, const std::string& text)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::SetText\n");
Controller::Impl& impl = *controller.mImpl;
EventData*& eventData = impl.mEventData;
- if( nullptr != eventData )
+ if(nullptr != eventData)
{
// If popup shown then hide it by switching to Editing state
- if( ( EventData::SELECTING == eventData->mState ) ||
- ( EventData::EDITING_WITH_POPUP == eventData->mState ) ||
- ( EventData::EDITING_WITH_GRAB_HANDLE == eventData->mState ) ||
- ( EventData::EDITING_WITH_PASTE_POPUP == eventData->mState ) )
+ if((EventData::SELECTING == eventData->mState) ||
+ (EventData::EDITING_WITH_POPUP == eventData->mState) ||
+ (EventData::EDITING_WITH_GRAB_HANDLE == eventData->mState) ||
+ (EventData::EDITING_WITH_PASTE_POPUP == eventData->mState))
{
- impl.ChangeState( EventData::EDITING );
+ impl.ChangeState(EventData::EDITING);
}
}
- if( !text.empty() )
+ if(!text.empty())
{
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
LogicalModelPtr& logicalModel = model->mLogicalModel;
- model->mVisualModel->SetTextColor( impl.mTextColor );
+ model->mVisualModel->SetTextColor(impl.mTextColor);
- MarkupProcessData markupProcessData( logicalModel->mColorRuns,
- logicalModel->mFontDescriptionRuns,
- logicalModel->mEmbeddedItems );
+ MarkupProcessData markupProcessData(logicalModel->mColorRuns,
+ logicalModel->mFontDescriptionRuns,
+ logicalModel->mEmbeddedItems);
- Length textSize = 0u;
- const uint8_t* utf8 = NULL;
- if( impl.mMarkupProcessorEnabled )
+ Length textSize = 0u;
+ const uint8_t* utf8 = NULL;
+ if(impl.mMarkupProcessorEnabled)
{
- ProcessMarkupString( text, markupProcessData );
+ ProcessMarkupString(text, markupProcessData);
textSize = markupProcessData.markupProcessedText.size();
// This is a bit horrible but std::string returns a (signed) char*
- utf8 = reinterpret_cast<const uint8_t*>( markupProcessData.markupProcessedText.c_str() );
+ utf8 = reinterpret_cast<const uint8_t*>(markupProcessData.markupProcessedText.c_str());
}
else
{
textSize = text.size();
// This is a bit horrible but std::string returns a (signed) char*
- utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
+ utf8 = reinterpret_cast<const uint8_t*>(text.c_str());
}
// Convert text into UTF-32
Vector<Character>& utf32Characters = logicalModel->mText;
- utf32Characters.Resize( textSize );
+ utf32Characters.Resize(textSize);
// Transform a text array encoded in utf8 into an array encoded in utf32.
// It returns the actual number of characters.
- Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() );
- utf32Characters.Resize( characterCount );
+ Length characterCount = Utf8ToUtf32(utf8, textSize, utf32Characters.Begin());
+ utf32Characters.Resize(characterCount);
- DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", &controller, textSize, logicalModel->mText.Count() );
+ DALI_ASSERT_DEBUG(textSize >= characterCount && "Invalid UTF32 conversion length");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", &controller, textSize, logicalModel->mText.Count());
// The characters to be added.
impl.mTextUpdateInfo.mNumberOfCharactersToAdd = logicalModel->mText.Count();
lastCursorIndex = characterCount;
// Update the rest of the model during size negotiation
- impl.QueueModifyEvent( ModifyEvent::TEXT_REPLACED );
+ impl.QueueModifyEvent(ModifyEvent::TEXT_REPLACED);
// The natural size needs to be re-calculated.
impl.mRecalculateNaturalSize = true;
}
// Resets the cursor position.
- controller.ResetCursorPosition( lastCursorIndex );
+ controller.ResetCursorPosition(lastCursorIndex);
// Scrolls the text to make the cursor visible.
controller.ResetScrollPosition();
impl.RequestRelayout();
- if( nullptr != eventData )
+ if(nullptr != eventData)
{
// Cancel previously queued events
eventData->mEventQueue.clear();
}
// Do this last since it provides callbacks into application code.
- if( NULL != impl.mEditableControlInterface )
+ if(NULL != impl.mEditableControlInterface)
{
impl.mEditableControlInterface->TextChanged();
}
void Controller::TextUpdater::InsertText(Controller& controller, const std::string& text, Controller::InsertType type)
{
- Controller::Impl& impl = *controller.mImpl;
- EventData*& eventData = impl.mEventData;
+ Controller::Impl& impl = *controller.mImpl;
+ EventData*& eventData = impl.mEventData;
- DALI_ASSERT_DEBUG( nullptr != eventData && "Unexpected InsertText" )
+ DALI_ASSERT_DEBUG(nullptr != eventData && "Unexpected InsertText")
- if( NULL == eventData )
+ if(NULL == eventData)
{
return;
}
- bool removedPrevious = false;
- bool removedSelected = false;
+ bool removedPrevious = false;
+ bool removedSelected = false;
bool maxLengthReached = false;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n",
- &controller, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"),
- eventData->mPrimaryCursorPosition, eventData->mPreEditFlag, eventData->mPreEditStartPosition, eventData->mPreEditLength );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n", &controller, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"), eventData->mPrimaryCursorPosition, eventData->mPreEditFlag, eventData->mPreEditStartPosition, eventData->mPreEditLength);
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
LogicalModelPtr& logicalModel = model->mLogicalModel;
// TODO: At the moment the underline runs are only for pre-edit.
model->mVisualModel->mUnderlineRuns.Clear();
// Remove the previous InputMethodContext pre-edit.
- if( eventData->mPreEditFlag && ( 0u != eventData->mPreEditLength ) )
+ if(eventData->mPreEditFlag && (0u != eventData->mPreEditLength))
{
- removedPrevious = RemoveText( controller,
- -static_cast<int>( eventData->mPrimaryCursorPosition - eventData->mPreEditStartPosition ),
- eventData->mPreEditLength,
- DONT_UPDATE_INPUT_STYLE );
+ removedPrevious = RemoveText(controller,
+ -static_cast<int>(eventData->mPrimaryCursorPosition - eventData->mPreEditStartPosition),
+ eventData->mPreEditLength,
+ DONT_UPDATE_INPUT_STYLE);
eventData->mPrimaryCursorPosition = eventData->mPreEditStartPosition;
- eventData->mPreEditLength = 0u;
+ eventData->mPreEditLength = 0u;
}
else
{
// Remove the previous Selection.
removedSelected = RemoveSelectedText(controller);
-
}
Vector<Character> utf32Characters;
- Length characterCount = 0u;
+ Length characterCount = 0u;
- if( !text.empty() )
+ if(!text.empty())
{
// Convert text into UTF-32
- utf32Characters.Resize( text.size() );
+ utf32Characters.Resize(text.size());
// This is a bit horrible but std::string returns a (signed) char*
- const uint8_t* utf8 = reinterpret_cast<const uint8_t*>( text.c_str() );
+ const uint8_t* utf8 = reinterpret_cast<const uint8_t*>(text.c_str());
// Transform a text array encoded in utf8 into an array encoded in utf32.
// It returns the actual number of characters.
- characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() );
- utf32Characters.Resize( characterCount );
+ characterCount = Utf8ToUtf32(utf8, text.size(), utf32Characters.Begin());
+ utf32Characters.Resize(characterCount);
- DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() );
+ DALI_ASSERT_DEBUG(text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count());
}
- if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded
+ if(0u != utf32Characters.Count()) // Check if Utf8ToUtf32 conversion succeeded
{
// The placeholder text is no longer needed
- if( impl.IsShowingPlaceholderText() )
+ if(impl.IsShowingPlaceholderText())
{
ResetText(controller);
}
- impl.ChangeState( EventData::EDITING );
+ impl.ChangeState(EventData::EDITING);
// Handle the InputMethodContext (predicitive text) state changes
- if( COMMIT == type )
+ if(COMMIT == type)
{
// InputMethodContext is no longer handling key-events
impl.ClearPreEditFlag();
}
else // PRE_EDIT
{
- if( !eventData->mPreEditFlag )
+ if(!eventData->mPreEditFlag)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Entered PreEdit state\n");
// Record the start of the pre-edit text
eventData->mPreEditStartPosition = eventData->mPrimaryCursorPosition;
}
eventData->mPreEditLength = utf32Characters.Count();
- eventData->mPreEditFlag = true;
+ eventData->mPreEditFlag = true;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", eventData->mPreEditStartPosition, eventData->mPreEditLength );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", eventData->mPreEditStartPosition, eventData->mPreEditLength);
}
const Length numberOfCharactersInModel = logicalModel->mText.Count();
// Restrict new text to fit within Maximum characters setting.
- Length maxSizeOfNewText = std::min( ( impl.mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount );
- maxLengthReached = ( characterCount > maxSizeOfNewText );
+ Length maxSizeOfNewText = std::min((impl.mMaximumNumberOfCharacters - numberOfCharactersInModel), characterCount);
+ maxLengthReached = (characterCount > maxSizeOfNewText);
// The cursor position.
CharacterIndex& cursorIndex = eventData->mPrimaryCursorPosition;
// Update the text's style.
// Updates the text style runs by adding characters.
- logicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText );
+ logicalModel->UpdateTextStyleRuns(cursorIndex, maxSizeOfNewText);
// Get the character index from the cursor index.
- const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u;
+ const CharacterIndex styleIndex = (cursorIndex > 0u) ? cursorIndex - 1u : 0u;
// Retrieve the text's style for the given index.
InputStyle style;
- impl.RetrieveDefaultInputStyle( style );
- logicalModel->RetrieveStyle( styleIndex, style );
+ impl.RetrieveDefaultInputStyle(style);
+ logicalModel->RetrieveStyle(styleIndex, style);
InputStyle& inputStyle = eventData->mInputStyle;
// Whether to add a new text color run.
- const bool addColorRun = ( style.textColor != inputStyle.textColor ) && !inputStyle.isDefaultColor;
+ const bool addColorRun = (style.textColor != inputStyle.textColor) && !inputStyle.isDefaultColor;
// Whether to add a new font run.
- const bool addFontNameRun = ( style.familyName != inputStyle.familyName ) && inputStyle.isFamilyDefined;
- const bool addFontWeightRun = ( style.weight != inputStyle.weight ) && inputStyle.isWeightDefined;
- const bool addFontWidthRun = ( style.width != inputStyle.width ) && inputStyle.isWidthDefined;
- const bool addFontSlantRun = ( style.slant != inputStyle.slant ) && inputStyle.isSlantDefined;
- const bool addFontSizeRun = ( style.size != inputStyle.size ) && inputStyle.isSizeDefined ;
+ const bool addFontNameRun = (style.familyName != inputStyle.familyName) && inputStyle.isFamilyDefined;
+ const bool addFontWeightRun = (style.weight != inputStyle.weight) && inputStyle.isWeightDefined;
+ const bool addFontWidthRun = (style.width != inputStyle.width) && inputStyle.isWidthDefined;
+ const bool addFontSlantRun = (style.slant != inputStyle.slant) && inputStyle.isSlantDefined;
+ const bool addFontSizeRun = (style.size != inputStyle.size) && inputStyle.isSizeDefined;
// Add style runs.
- if( addColorRun )
+ if(addColorRun)
{
const VectorBase::SizeType numberOfRuns = logicalModel->mColorRuns.Count();
- logicalModel->mColorRuns.Resize( numberOfRuns + 1u );
+ logicalModel->mColorRuns.Resize(numberOfRuns + 1u);
- ColorRun& colorRun = *( logicalModel->mColorRuns.Begin() + numberOfRuns );
- colorRun.color = inputStyle.textColor;
- colorRun.characterRun.characterIndex = cursorIndex;
+ ColorRun& colorRun = *(logicalModel->mColorRuns.Begin() + numberOfRuns);
+ colorRun.color = inputStyle.textColor;
+ colorRun.characterRun.characterIndex = cursorIndex;
colorRun.characterRun.numberOfCharacters = maxSizeOfNewText;
}
- if( addFontNameRun ||
- addFontWeightRun ||
- addFontWidthRun ||
- addFontSlantRun ||
- addFontSizeRun )
+ if(addFontNameRun ||
+ addFontWeightRun ||
+ addFontWidthRun ||
+ addFontSlantRun ||
+ addFontSizeRun)
{
const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count();
- logicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u );
+ logicalModel->mFontDescriptionRuns.Resize(numberOfRuns + 1u);
- FontDescriptionRun& fontDescriptionRun = *( logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns );
+ FontDescriptionRun& fontDescriptionRun = *(logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns);
- if( addFontNameRun )
+ if(addFontNameRun)
{
fontDescriptionRun.familyLength = inputStyle.familyName.size();
- fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
- memcpy( fontDescriptionRun.familyName, inputStyle.familyName.c_str(), fontDescriptionRun.familyLength );
+ fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength];
+ memcpy(fontDescriptionRun.familyName, inputStyle.familyName.c_str(), fontDescriptionRun.familyLength);
fontDescriptionRun.familyDefined = true;
// The memory allocated for the font family name is freed when the font description is removed from the logical model.
}
- if( addFontWeightRun )
+ if(addFontWeightRun)
{
- fontDescriptionRun.weight = inputStyle.weight;
+ fontDescriptionRun.weight = inputStyle.weight;
fontDescriptionRun.weightDefined = true;
}
- if( addFontWidthRun )
+ if(addFontWidthRun)
{
- fontDescriptionRun.width = inputStyle.width;
+ fontDescriptionRun.width = inputStyle.width;
fontDescriptionRun.widthDefined = true;
}
- if( addFontSlantRun )
+ if(addFontSlantRun)
{
- fontDescriptionRun.slant = inputStyle.slant;
+ fontDescriptionRun.slant = inputStyle.slant;
fontDescriptionRun.slantDefined = true;
}
- if( addFontSizeRun )
+ if(addFontSizeRun)
{
- fontDescriptionRun.size = static_cast<PointSize26Dot6>( inputStyle.size * impl.mFontSizeScale * 64.f );
+ fontDescriptionRun.size = static_cast<PointSize26Dot6>(inputStyle.size * impl.mFontSizeScale * 64.f);
fontDescriptionRun.sizeDefined = true;
}
- fontDescriptionRun.characterRun.characterIndex = cursorIndex;
+ fontDescriptionRun.characterRun.characterIndex = cursorIndex;
fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText;
}
Vector<Character>& modifyText = logicalModel->mText;
auto pos = modifyText.End();
- if( cursorIndex < numberOfCharactersInModel )
+ if(cursorIndex < numberOfCharactersInModel)
{
pos = modifyText.Begin() + cursorIndex;
}
unsigned int realPos = pos - modifyText.Begin();
- modifyText.Insert( pos, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText );
+ modifyText.Insert(pos, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText);
- if( NULL != impl.mEditableControlInterface )
+ if(NULL != impl.mEditableControlInterface)
{
- impl.mEditableControlInterface->TextInserted( realPos, maxSizeOfNewText, text );
+ impl.mEditableControlInterface->TextInserted(realPos, maxSizeOfNewText, text);
}
TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
// Mark the first paragraph to be updated.
- if( Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout() )
+ if(Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout())
{
- textUpdateInfo.mCharacterIndex = 0;
+ textUpdateInfo.mCharacterIndex = 0;
textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters;
- textUpdateInfo.mNumberOfCharactersToAdd = numberOfCharactersInModel + maxSizeOfNewText;
- textUpdateInfo.mClearAll = true;
+ textUpdateInfo.mNumberOfCharactersToAdd = numberOfCharactersInModel + maxSizeOfNewText;
+ textUpdateInfo.mClearAll = true;
}
else
{
- textUpdateInfo.mCharacterIndex = std::min( cursorIndex, textUpdateInfo.mCharacterIndex );
+ textUpdateInfo.mCharacterIndex = std::min(cursorIndex, textUpdateInfo.mCharacterIndex);
textUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText;
}
// Update the cursor index.
cursorIndex += maxSizeOfNewText;
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition);
}
- if( ( 0u == logicalModel->mText.Count() ) &&
- impl.IsPlaceholderAvailable() )
+ if((0u == logicalModel->mText.Count()) &&
+ impl.IsPlaceholderAvailable())
{
// Show place-holder if empty after removing the pre-edit text
controller.ShowPlaceholderText();
eventData->mUpdateCursorPosition = true;
impl.ClearPreEditFlag();
}
- else if( removedPrevious ||
- removedSelected ||
- ( 0 != utf32Characters.Count() ) )
+ else if(removedPrevious ||
+ removedSelected ||
+ (0 != utf32Characters.Count()))
{
// Queue an inserted event
- impl.QueueModifyEvent( ModifyEvent::TEXT_INSERTED );
+ impl.QueueModifyEvent(ModifyEvent::TEXT_INSERTED);
eventData->mUpdateCursorPosition = true;
- if( removedSelected )
+ if(removedSelected)
{
eventData->mScrollAfterDelete = true;
}
}
}
- if( maxLengthReached )
+ if(maxLengthReached)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", logicalModel->mText.Count() );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", logicalModel->mText.Count());
impl.ResetInputMethodContext();
- if( NULL != impl.mEditableControlInterface )
+ if(NULL != impl.mEditableControlInterface)
{
// Do this last since it provides callbacks into application code
impl.mEditableControlInterface->MaxLengthReached();
void Controller::TextUpdater::PasteText(Controller& controller, const std::string& stringToPaste)
{
- InsertText( controller, stringToPaste, Text::Controller::COMMIT );
+ InsertText(controller, stringToPaste, Text::Controller::COMMIT);
Controller::Impl& impl = *controller.mImpl;
- impl.ChangeState( EventData::EDITING );
+ impl.ChangeState(EventData::EDITING);
impl.RequestRelayout();
- if( NULL != impl.mEditableControlInterface )
+ if(NULL != impl.mEditableControlInterface)
{
// Do this last since it provides callbacks into application code
impl.mEditableControlInterface->TextChanged();
}
bool Controller::TextUpdater::RemoveText(
- Controller& controller,
- int cursorOffset,
- int numberOfCharacters,
- UpdateInputStyleType type )
+ Controller& controller,
+ int cursorOffset,
+ int numberOfCharacters,
+ UpdateInputStyleType type)
{
bool removed = false;
- Controller::Impl& impl = *controller.mImpl;
- EventData*& eventData = impl.mEventData;
+ Controller::Impl& impl = *controller.mImpl;
+ EventData*& eventData = impl.mEventData;
- if( nullptr == eventData )
+ if(nullptr == eventData)
{
return removed;
}
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
LogicalModelPtr& logicalModel = model->mLogicalModel;
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n",
- &controller, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n", &controller, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters);
- if( !impl.IsShowingPlaceholderText() )
+ if(!impl.IsShowingPlaceholderText())
{
// Delete at current cursor position
- Vector<Character>& currentText = logicalModel->mText;
- CharacterIndex& oldCursorIndex = eventData->mPrimaryCursorPosition;
+ Vector<Character>& currentText = logicalModel->mText;
+ CharacterIndex& oldCursorIndex = eventData->mPrimaryCursorPosition;
CharacterIndex cursorIndex = 0;
// Validate the cursor position & number of characters
- if( ( static_cast< int >( eventData->mPrimaryCursorPosition ) + cursorOffset ) >= 0 )
+ if((static_cast<int>(eventData->mPrimaryCursorPosition) + cursorOffset) >= 0)
{
cursorIndex = eventData->mPrimaryCursorPosition + cursorOffset;
}
- if( ( cursorIndex + numberOfCharacters ) > currentText.Count() )
+ if((cursorIndex + numberOfCharacters) > currentText.Count())
{
numberOfCharacters = currentText.Count() - cursorIndex;
}
TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo;
- if( eventData->mPreEditFlag || // If the preedit flag is enabled, it means two (or more) of them came together i.e. when two keys have been pressed at the same time.
- ( ( cursorIndex + numberOfCharacters ) <= textUpdateInfo.mPreviousNumberOfCharacters ) )
+ if(eventData->mPreEditFlag || // If the preedit flag is enabled, it means two (or more) of them came together i.e. when two keys have been pressed at the same time.
+ ((cursorIndex + numberOfCharacters) <= textUpdateInfo.mPreviousNumberOfCharacters))
{
// Mark the paragraphs to be updated.
- if( Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout() )
+ if(Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout())
{
- textUpdateInfo.mCharacterIndex = 0;
+ textUpdateInfo.mCharacterIndex = 0;
textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters;
- textUpdateInfo.mNumberOfCharactersToAdd = textUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters;
- textUpdateInfo.mClearAll = true;
+ textUpdateInfo.mNumberOfCharactersToAdd = textUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters;
+ textUpdateInfo.mClearAll = true;
}
else
{
- textUpdateInfo.mCharacterIndex = std::min( cursorIndex, textUpdateInfo.mCharacterIndex );
+ textUpdateInfo.mCharacterIndex = std::min(cursorIndex, textUpdateInfo.mCharacterIndex);
textUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters;
}
// Update the input style and remove the text's style before removing the text.
- if( UPDATE_INPUT_STYLE == type )
+ if(UPDATE_INPUT_STYLE == type)
{
InputStyle& eventDataInputStyle = eventData->mInputStyle;
// Keep a copy of the current input style.
InputStyle currentInputStyle;
- currentInputStyle.Copy( eventDataInputStyle );
+ currentInputStyle.Copy(eventDataInputStyle);
// Set first the default input style.
- impl.RetrieveDefaultInputStyle( eventDataInputStyle );
+ impl.RetrieveDefaultInputStyle(eventDataInputStyle);
// Update the input style.
- logicalModel->RetrieveStyle( cursorIndex, eventDataInputStyle );
+ logicalModel->RetrieveStyle(cursorIndex, eventDataInputStyle);
// Compare if the input style has changed.
- const bool hasInputStyleChanged = !currentInputStyle.Equal( eventDataInputStyle );
+ const bool hasInputStyleChanged = !currentInputStyle.Equal(eventDataInputStyle);
- if( hasInputStyleChanged )
+ if(hasInputStyleChanged)
{
- const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( eventDataInputStyle );
+ const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask(eventDataInputStyle);
// Queue the input style changed signal.
- eventData->mInputStyleChangedQueue.PushBack( styleChangedMask );
+ eventData->mInputStyleChangedQueue.PushBack(styleChangedMask);
}
}
// If the number of current text and the number of characters to be deleted are same,
// it means all texts should be removed and all Preedit variables should be initialized.
- if( ( currentText.Count() - numberOfCharacters == 0 ) && ( cursorIndex == 0 ) )
+ if((currentText.Count() - numberOfCharacters == 0) && (cursorIndex == 0))
{
impl.ClearPreEditFlag();
textUpdateInfo.mNumberOfCharactersToAdd = 0;
}
// Updates the text style runs by removing characters. Runs with no characters are removed.
- logicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters );
+ logicalModel->UpdateTextStyleRuns(cursorIndex, -numberOfCharacters);
// Remove the characters.
Vector<Character>::Iterator first = currentText.Begin() + cursorIndex;
Vector<Character>::Iterator last = first + numberOfCharacters;
- if( NULL != impl.mEditableControlInterface )
+ if(NULL != impl.mEditableControlInterface)
{
std::string utf8;
- Utf32ToUtf8( first, numberOfCharacters, utf8 );
- impl.mEditableControlInterface->TextDeleted( cursorIndex, numberOfCharacters, utf8 );
+ Utf32ToUtf8(first, numberOfCharacters, utf8);
+ impl.mEditableControlInterface->TextDeleted(cursorIndex, numberOfCharacters, utf8);
}
- currentText.Erase( first, last );
+ currentText.Erase(first, last);
// Cursor position retreat
oldCursorIndex = cursorIndex;
eventData->mScrollAfterDelete = true;
- if( EventData::INACTIVE == eventData->mState )
+ if(EventData::INACTIVE == eventData->mState)
{
- impl.ChangeState( EventData::EDITING );
+ impl.ChangeState(EventData::EDITING);
}
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", &controller, numberOfCharacters );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", &controller, numberOfCharacters);
removed = true;
}
}
bool Controller::TextUpdater::RemoveSelectedText(Controller& controller)
{
- bool textRemoved( false );
+ bool textRemoved(false);
Controller::Impl& impl = *controller.mImpl;
- if( EventData::SELECTING == impl.mEventData->mState )
+ if(EventData::SELECTING == impl.mEventData->mState)
{
std::string removedString;
- impl.RetrieveSelection( removedString, true );
+ impl.RetrieveSelection(removedString, true);
- if( !removedString.empty() )
+ if(!removedString.empty())
{
textRemoved = true;
- impl.ChangeState( EventData::EDITING );
+ impl.ChangeState(EventData::EDITING);
}
}
void Controller::TextUpdater::ResetText(Controller& controller)
{
- Controller::Impl& impl = *controller.mImpl;
- LogicalModelPtr& logicalModel = impl.mModel->mLogicalModel;
+ Controller::Impl& impl = *controller.mImpl;
+ LogicalModelPtr& logicalModel = impl.mModel->mLogicalModel;
// Reset buffers.
logicalModel->mText.Clear();
// We have cleared everything including the placeholder-text
impl.PlaceholderCleared();
- impl.mTextUpdateInfo.mCharacterIndex = 0u;
+ impl.mTextUpdateInfo.mCharacterIndex = 0u;
impl.mTextUpdateInfo.mNumberOfCharactersToRemove = impl.mTextUpdateInfo.mPreviousNumberOfCharacters;
- impl.mTextUpdateInfo.mNumberOfCharactersToAdd = 0u;
+ impl.mTextUpdateInfo.mNumberOfCharactersToAdd = 0u;
// Clear any previous text.
impl.mTextUpdateInfo.mClearAll = true;
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/text-controller.h>
// EXTERNAL INCLUDES
-#include <limits>
-#include <cmath>
-#include <memory.h>
#include <dali/integration-api/debug.h>
+#include <memory.h>
+#include <cmath>
+#include <limits>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/text/text-controller-event-handler.h>
namespace
{
-
#if defined(DEBUG_ENABLED)
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
const std::string EMPTY_STRING("");
-int ConvertPixelToPint( float pixel )
+int ConvertPixelToPint(float pixel)
{
- unsigned int horizontalDpi = 0u;
- unsigned int verticalDpi = 0u;
- Dali::TextAbstraction::FontClient fontClient = Dali::TextAbstraction::FontClient::Get();
- fontClient.GetDpi( horizontalDpi, verticalDpi );
+ unsigned int horizontalDpi = 0u;
+ unsigned int verticalDpi = 0u;
+ Dali::TextAbstraction::FontClient fontClient = Dali::TextAbstraction::FontClient::Get();
+ fontClient.GetDpi(horizontalDpi, verticalDpi);
- return ( pixel * 72.f ) / static_cast< float >( horizontalDpi );
+ return (pixel * 72.f) / static_cast<float>(horizontalDpi);
}
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
// public : Constructor.
ControllerPtr Controller::New()
{
- return ControllerPtr( new Controller() );
+ return ControllerPtr(new Controller());
}
-ControllerPtr Controller::New( ControlInterface* controlInterface )
+ControllerPtr Controller::New(ControlInterface* controlInterface)
{
- return ControllerPtr( new Controller( controlInterface ) );
+ return ControllerPtr(new Controller(controlInterface));
}
-ControllerPtr Controller::New( ControlInterface* controlInterface,
- EditableControlInterface* editableControlInterface,
- SelectableControlInterface* selectableControlInterface )
+ControllerPtr Controller::New(ControlInterface* controlInterface,
+ EditableControlInterface* editableControlInterface,
+ SelectableControlInterface* selectableControlInterface)
{
- return ControllerPtr( new Controller( controlInterface,
- editableControlInterface,
- selectableControlInterface ) );
+ return ControllerPtr(new Controller(controlInterface,
+ editableControlInterface,
+ selectableControlInterface));
}
// public : Configure the text controller.
-void Controller::EnableTextInput( DecoratorPtr decorator, InputMethodContext& inputMethodContext )
+void Controller::EnableTextInput(DecoratorPtr decorator, InputMethodContext& inputMethodContext)
{
- if( !decorator )
+ if(!decorator)
{
delete mImpl->mEventData;
mImpl->mEventData = NULL;
return;
}
- if( NULL == mImpl->mEventData )
+ if(NULL == mImpl->mEventData)
{
- mImpl->mEventData = new EventData( decorator, inputMethodContext );
+ mImpl->mEventData = new EventData(decorator, inputMethodContext);
}
}
-void Controller::SetGlyphType( TextAbstraction::GlyphType glyphType )
+void Controller::SetGlyphType(TextAbstraction::GlyphType glyphType)
{
// Metrics for bitmap & vector based glyphs are different
- mImpl->mMetrics->SetGlyphType( glyphType );
+ mImpl->mMetrics->SetGlyphType(glyphType);
// Clear the font-specific data
ClearFontData();
mImpl->RequestRelayout();
}
-void Controller::SetMarkupProcessorEnabled( bool enable )
+void Controller::SetMarkupProcessorEnabled(bool enable)
{
- if( enable != mImpl->mMarkupProcessorEnabled )
+ if(enable != mImpl->mMarkupProcessorEnabled)
{
//If Text was already set, call the SetText again for enabling or disabling markup
mImpl->mMarkupProcessorEnabled = enable;
std::string text;
- GetText( text );
- SetText( text );
+ GetText(text);
+ SetText(text);
}
}
return mImpl->mMarkupProcessorEnabled;
}
-void Controller::SetAutoScrollEnabled( bool enable )
+void Controller::SetAutoScrollEnabled(bool enable)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled[%s] SingleBox[%s]-> [%p]\n", (enable)?"true":"false", ( mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX)?"true":"false", this );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled[%s] SingleBox[%s]-> [%p]\n", (enable) ? "true" : "false", (mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX) ? "true" : "false", this);
- if( mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX )
+ if(mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX)
{
- if( enable )
+ if(enable)
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled for SINGLE_LINE_BOX\n" );
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
- LAYOUT |
- ALIGN |
- UPDATE_LAYOUT_SIZE |
- UPDATE_DIRECTION |
- REORDER );
-
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled for SINGLE_LINE_BOX\n");
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending |
+ LAYOUT |
+ ALIGN |
+ UPDATE_LAYOUT_SIZE |
+ UPDATE_DIRECTION |
+ REORDER);
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled Disabling autoscroll\n");
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
- LAYOUT |
- ALIGN |
- UPDATE_LAYOUT_SIZE |
- REORDER );
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled Disabling autoscroll\n");
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending |
+ LAYOUT |
+ ALIGN |
+ UPDATE_LAYOUT_SIZE |
+ REORDER);
}
mImpl->mIsAutoScrollEnabled = enable;
}
else
{
- DALI_LOG_WARNING( "Attempted AutoScrolling on a non SINGLE_LINE_BOX, request ignored\n" );
+ DALI_LOG_WARNING("Attempted AutoScrolling on a non SINGLE_LINE_BOX, request ignored\n");
mImpl->mIsAutoScrollEnabled = false;
}
}
bool Controller::IsAutoScrollEnabled() const
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", mImpl->mIsAutoScrollEnabled?"true":"false" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", mImpl->mIsAutoScrollEnabled ? "true" : "false");
return mImpl->mIsAutoScrollEnabled;
}
{
float offset = 0.f;
- if( mImpl->mModel->mVisualModel &&
- ( 0u != mImpl->mModel->mVisualModel->mLines.Count() ) )
+ if(mImpl->mModel->mVisualModel &&
+ (0u != mImpl->mModel->mVisualModel->mLines.Count()))
{
- offset = ( *mImpl->mModel->mVisualModel->mLines.Begin() ).alignmentOffset;
+ offset = (*mImpl->mModel->mVisualModel->mLines.Begin()).alignmentOffset;
}
return offset;
}
-void Controller::SetHorizontalScrollEnabled( bool enable )
+void Controller::SetHorizontalScrollEnabled(bool enable)
{
- if( ( NULL != mImpl->mEventData ) &&
- mImpl->mEventData->mDecorator )
+ if((NULL != mImpl->mEventData) &&
+ mImpl->mEventData->mDecorator)
{
- mImpl->mEventData->mDecorator->SetHorizontalScrollEnabled( enable );
+ mImpl->mEventData->mDecorator->SetHorizontalScrollEnabled(enable);
}
}
bool Controller::IsHorizontalScrollEnabled() const
{
- if( ( NULL != mImpl->mEventData ) &&
- mImpl->mEventData->mDecorator )
+ if((NULL != mImpl->mEventData) &&
+ mImpl->mEventData->mDecorator)
{
return mImpl->mEventData->mDecorator->IsHorizontalScrollEnabled();
}
return false;
}
-void Controller::SetVerticalScrollEnabled( bool enable )
+void Controller::SetVerticalScrollEnabled(bool enable)
{
- if( ( NULL != mImpl->mEventData ) &&
- mImpl->mEventData->mDecorator )
+ if((NULL != mImpl->mEventData) &&
+ mImpl->mEventData->mDecorator)
{
- if( mImpl->mEventData->mDecorator )
+ if(mImpl->mEventData->mDecorator)
{
- mImpl->mEventData->mDecorator->SetVerticalScrollEnabled( enable );
+ mImpl->mEventData->mDecorator->SetVerticalScrollEnabled(enable);
}
}
}
bool Controller::IsVerticalScrollEnabled() const
{
- if( ( NULL != mImpl->mEventData ) &&
- mImpl->mEventData->mDecorator )
+ if((NULL != mImpl->mEventData) &&
+ mImpl->mEventData->mDecorator)
{
return mImpl->mEventData->mDecorator->IsVerticalScrollEnabled();
}
return false;
}
-void Controller::SetSmoothHandlePanEnabled( bool enable )
+void Controller::SetSmoothHandlePanEnabled(bool enable)
{
- if( ( NULL != mImpl->mEventData ) &&
- mImpl->mEventData->mDecorator )
+ if((NULL != mImpl->mEventData) &&
+ mImpl->mEventData->mDecorator)
{
- mImpl->mEventData->mDecorator->SetSmoothHandlePanEnabled( enable );
+ mImpl->mEventData->mDecorator->SetSmoothHandlePanEnabled(enable);
}
}
bool Controller::IsSmoothHandlePanEnabled() const
{
- if( ( NULL != mImpl->mEventData ) &&
- mImpl->mEventData->mDecorator )
+ if((NULL != mImpl->mEventData) &&
+ mImpl->mEventData->mDecorator)
{
return mImpl->mEventData->mDecorator->IsSmoothHandlePanEnabled();
}
return false;
}
-void Controller::SetMaximumNumberOfCharacters( Length maxCharacters )
+void Controller::SetMaximumNumberOfCharacters(Length maxCharacters)
{
mImpl->mMaximumNumberOfCharacters = maxCharacters;
}
return mImpl->mMaximumNumberOfCharacters;
}
-void Controller::SetEnableCursorBlink( bool enable )
+void Controller::SetEnableCursorBlink(bool enable)
{
- DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" );
+ DALI_ASSERT_DEBUG(NULL != mImpl->mEventData && "TextInput disabled");
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mCursorBlinkEnabled = enable;
- if( !enable &&
- mImpl->mEventData->mDecorator )
+ if(!enable &&
+ mImpl->mEventData->mDecorator)
{
mImpl->mEventData->mDecorator->StopCursorBlink();
}
bool Controller::GetEnableCursorBlink() const
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
return mImpl->mEventData->mCursorBlinkEnabled;
}
return false;
}
-void Controller::SetMultiLineEnabled( bool enable )
+void Controller::SetMultiLineEnabled(bool enable)
{
const Layout::Engine::Type layout = enable ? Layout::Engine::MULTI_LINE_BOX : Layout::Engine::SINGLE_LINE_BOX;
- if( layout != mImpl->mLayoutEngine.GetLayout() )
+ if(layout != mImpl->mLayoutEngine.GetLayout())
{
// Set the layout type.
- mImpl->mLayoutEngine.SetLayout( layout );
+ mImpl->mLayoutEngine.SetLayout(layout);
// Set the flags to redo the layout operations
- const OperationsMask layoutOperations = static_cast<OperationsMask>( LAYOUT |
- UPDATE_LAYOUT_SIZE |
- ALIGN |
- REORDER );
+ const OperationsMask layoutOperations = static_cast<OperationsMask>(LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ ALIGN |
+ REORDER);
mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | layoutOperations );
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending | layoutOperations);
// Need to recalculate natural size
mImpl->mRecalculateNaturalSize = true;
return Layout::Engine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout();
}
-void Controller::SetHorizontalAlignment( Text::HorizontalAlignment::Type alignment )
+void Controller::SetHorizontalAlignment(Text::HorizontalAlignment::Type alignment)
{
- if( alignment != mImpl->mModel->mHorizontalAlignment )
+ if(alignment != mImpl->mModel->mHorizontalAlignment)
{
// Set the alignment.
mImpl->mModel->mHorizontalAlignment = alignment;
// Set the flag to redo the alignment operation.
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending | ALIGN);
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
mImpl->mEventData->mUpdateAlignment = true;
// Update the cursor if it's in editing mode
- if( EventData::IsEditingState( mImpl->mEventData->mState ) )
+ if(EventData::IsEditingState(mImpl->mEventData->mState))
{
- mImpl->ChangeState( EventData::EDITING );
+ mImpl->ChangeState(EventData::EDITING);
mImpl->mEventData->mUpdateCursorPosition = true;
}
}
return mImpl->mModel->mHorizontalAlignment;
}
-void Controller::SetVerticalAlignment( VerticalAlignment::Type alignment )
+void Controller::SetVerticalAlignment(VerticalAlignment::Type alignment)
{
- if( alignment != mImpl->mModel->mVerticalAlignment )
+ if(alignment != mImpl->mModel->mVerticalAlignment)
{
// Set the alignment.
mImpl->mModel->mVerticalAlignment = alignment;
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | ALIGN );
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending | ALIGN);
mImpl->RequestRelayout();
}
return mImpl->mModel->mIgnoreSpacesAfterText;
}
-void Controller::SetIgnoreSpacesAfterText( bool ignore )
+void Controller::SetIgnoreSpacesAfterText(bool ignore)
{
mImpl->mModel->mIgnoreSpacesAfterText = ignore;
}
return mImpl->mModel->mMatchSystemLanguageDirection;
}
-void Controller::SetMatchSystemLanguageDirection( bool match )
+void Controller::SetMatchSystemLanguageDirection(bool match)
{
mImpl->mModel->mMatchSystemLanguageDirection = match;
}
-void Controller::SetLayoutDirection( Dali::LayoutDirection::Type layoutDirection )
+void Controller::SetLayoutDirection(Dali::LayoutDirection::Type layoutDirection)
{
mImpl->mLayoutDirection = layoutDirection;
}
return mImpl->IsShowingRealText();
}
-
-void Controller::SetLineWrapMode( Text::LineWrap::Mode lineWrapMode )
+void Controller::SetLineWrapMode(Text::LineWrap::Mode lineWrapMode)
{
- if( lineWrapMode != mImpl->mModel->mLineWrapMode )
+ if(lineWrapMode != mImpl->mModel->mLineWrapMode)
{
// Set the text wrap mode.
mImpl->mModel->mLineWrapMode = lineWrapMode;
-
// Update Text layout for applying wrap mode
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
- ALIGN |
- LAYOUT |
- UPDATE_LAYOUT_SIZE |
- REORDER );
- mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending |
+ ALIGN |
+ LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ REORDER);
+ mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
- mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
+ mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
// Request relayout
mImpl->RequestRelayout();
return mImpl->mModel->mLineWrapMode;
}
-void Controller::SetTextElideEnabled( bool enabled )
+void Controller::SetTextElideEnabled(bool enabled)
{
mImpl->mModel->mElideEnabled = enabled;
}
return mImpl->mTextFitEnabled;
}
-void Controller::SetTextFitMinSize( float minSize, FontSizeType type )
+void Controller::SetTextFitMinSize(float minSize, FontSizeType type)
{
- switch( type )
+ switch(type)
{
case POINT_SIZE:
{
}
case PIXEL_SIZE:
{
- mImpl->mTextFitMinSize = ConvertPixelToPint( minSize );
+ mImpl->mTextFitMinSize = ConvertPixelToPint(minSize);
break;
}
}
return mImpl->mTextFitMinSize;
}
-void Controller::SetTextFitMaxSize( float maxSize, FontSizeType type )
+void Controller::SetTextFitMaxSize(float maxSize, FontSizeType type)
{
- switch( type )
+ switch(type)
{
case POINT_SIZE:
{
}
case PIXEL_SIZE:
{
- mImpl->mTextFitMaxSize = ConvertPixelToPint( maxSize );
+ mImpl->mTextFitMaxSize = ConvertPixelToPint(maxSize);
break;
}
}
return mImpl->mTextFitMaxSize;
}
-void Controller::SetTextFitStepSize( float step, FontSizeType type )
+void Controller::SetTextFitStepSize(float step, FontSizeType type)
{
- switch( type )
+ switch(type)
{
case POINT_SIZE:
{
}
case PIXEL_SIZE:
{
- mImpl->mTextFitStepSize = ConvertPixelToPint( step );
+ mImpl->mTextFitStepSize = ConvertPixelToPint(step);
break;
}
}
return mImpl->mTextFitContentSize;
}
-void Controller::SetPlaceholderTextElideEnabled( bool enabled )
+void Controller::SetPlaceholderTextElideEnabled(bool enabled)
{
PlaceholderHandler::SetPlaceholderTextElideEnabled(*this, enabled);
}
return PlaceholderHandler::IsPlaceholderTextElideEnabled(*this);
}
-void Controller::SetSelectionEnabled( bool enabled )
+void Controller::SetSelectionEnabled(bool enabled)
{
mImpl->mEventData->mSelectionEnabled = enabled;
}
return mImpl->mEventData->mSelectionEnabled;
}
-void Controller::SetShiftSelectionEnabled( bool enabled )
+void Controller::SetShiftSelectionEnabled(bool enabled)
{
mImpl->mEventData->mShiftSelectionFlag = enabled;
}
return mImpl->mEventData->mShiftSelectionFlag;
}
-void Controller::SetGrabHandleEnabled( bool enabled )
+void Controller::SetGrabHandleEnabled(bool enabled)
{
mImpl->mEventData->mGrabHandleEnabled = enabled;
}
// public : Update
-void Controller::SetText( const std::string& text )
+void Controller::SetText(const std::string& text)
{
TextUpdater::SetText(*this, text);
}
-void Controller::GetText( std::string& text ) const
+void Controller::GetText(std::string& text) const
{
- if( !mImpl->IsShowingPlaceholderText() )
+ if(!mImpl->IsShowingPlaceholderText())
{
// Retrieves the text string.
- mImpl->GetText( 0u, text );
+ mImpl->GetText(0u, text);
}
else
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this);
}
}
-void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text )
+void Controller::SetPlaceholderText(PlaceholderType type, const std::string& text)
{
PlaceholderHandler::SetPlaceholderText(*this, type, text);
}
-void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const
+void Controller::GetPlaceholderText(PlaceholderType type, std::string& text) const
{
- PlaceholderHandler::GetPlaceholderText(*this, type, text );
+ PlaceholderHandler::GetPlaceholderText(*this, type, text);
}
-void Controller::UpdateAfterFontChange( const std::string& newDefaultFont )
+void Controller::UpdateAfterFontChange(const std::string& newDefaultFont)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange\n");
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange\n");
- if( !mImpl->mFontDefaults->familyDefined ) // If user defined font then should not update when system font changes
+ if(!mImpl->mFontDefaults->familyDefined) // If user defined font then should not update when system font changes
{
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() );
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str());
mImpl->mFontDefaults->mFontDescription.family = newDefaultFont;
ClearFontData();
}
}
-void Controller::RetrieveSelection( std::string& selectedText ) const
+void Controller::RetrieveSelection(std::string& selectedText) const
{
- mImpl->RetrieveSelection( selectedText, false );
+ mImpl->RetrieveSelection(selectedText, false);
}
-void Controller::SetSelection( int start, int end )
+void Controller::SetSelection(int start, int end)
{
- mImpl->SetSelection( start, end );
+ mImpl->SetSelection(start, end);
}
-std::pair< int, int > Controller::GetSelectionIndexes() const
+std::pair<int, int> Controller::GetSelectionIndexes() const
{
return mImpl->GetSelectionIndexes();
}
-void Controller::CopyStringToClipboard( const std::string& source )
+void Controller::CopyStringToClipboard(const std::string& source)
{
- mImpl->CopyStringToClipboard( source );
+ mImpl->CopyStringToClipboard(source);
}
-void Controller::SendSelectionToClipboard( bool deleteAfterSending )
+void Controller::SendSelectionToClipboard(bool deleteAfterSending)
{
- mImpl->SendSelectionToClipboard( deleteAfterSending );
+ mImpl->SendSelectionToClipboard(deleteAfterSending);
}
// public : Default style & Input style
-void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily )
+void Controller::SetDefaultFontFamily(const std::string& defaultFontFamily)
{
- if( NULL == mImpl->mFontDefaults )
+ if(NULL == mImpl->mFontDefaults)
{
mImpl->mFontDefaults = new FontDefaults();
}
mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily;
- DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
+ DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str());
mImpl->mFontDefaults->familyDefined = !defaultFontFamily.empty();
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
// Update the cursor position if it's in editing mode
- if( EventData::IsEditingState( mImpl->mEventData->mState ) )
+ if(EventData::IsEditingState(mImpl->mEventData->mState))
{
- mImpl->mEventData->mDecoratorUpdated = true;
+ mImpl->mEventData->mDecoratorUpdated = true;
mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font family is updated.
}
}
const std::string& Controller::GetDefaultFontFamily() const
{
- if( NULL != mImpl->mFontDefaults )
+ if(NULL != mImpl->mFontDefaults)
{
return mImpl->mFontDefaults->mFontDescription.family;
}
return EMPTY_STRING;
}
-void Controller::SetPlaceholderFontFamily( const std::string& placeholderTextFontFamily )
+void Controller::SetPlaceholderFontFamily(const std::string& placeholderTextFontFamily)
{
PlaceholderHandler::SetPlaceholderFontFamily(*this, placeholderTextFontFamily);
}
return PlaceholderHandler::GetPlaceholderFontFamily(*this);
}
-void Controller::SetDefaultFontWeight( FontWeight weight )
+void Controller::SetDefaultFontWeight(FontWeight weight)
{
- if( NULL == mImpl->mFontDefaults )
+ if(NULL == mImpl->mFontDefaults)
{
mImpl->mFontDefaults = new FontDefaults();
}
mImpl->mFontDefaults->mFontDescription.weight = weight;
- mImpl->mFontDefaults->weightDefined = true;
+ mImpl->mFontDefaults->weightDefined = true;
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
// Update the cursor position if it's in editing mode
- if( EventData::IsEditingState( mImpl->mEventData->mState ) )
+ if(EventData::IsEditingState(mImpl->mEventData->mState))
{
- mImpl->mEventData->mDecoratorUpdated = true;
+ mImpl->mEventData->mDecoratorUpdated = true;
mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font weight is updated.
}
}
bool Controller::IsDefaultFontWeightDefined() const
{
- if( NULL != mImpl->mFontDefaults )
+ if(NULL != mImpl->mFontDefaults)
{
return mImpl->mFontDefaults->weightDefined;
}
FontWeight Controller::GetDefaultFontWeight() const
{
- if( NULL != mImpl->mFontDefaults )
+ if(NULL != mImpl->mFontDefaults)
{
return mImpl->mFontDefaults->mFontDescription.weight;
}
return TextAbstraction::FontWeight::NORMAL;
}
-void Controller::SetPlaceholderTextFontWeight( FontWeight weight )
+void Controller::SetPlaceholderTextFontWeight(FontWeight weight)
{
PlaceholderHandler::SetPlaceholderTextFontWeight(*this, weight);
}
bool Controller::IsPlaceholderTextFontWeightDefined() const
{
- return PlaceholderHandler::IsPlaceholderTextFontWeightDefined(*this);;
+ return PlaceholderHandler::IsPlaceholderTextFontWeightDefined(*this);
+ ;
}
FontWeight Controller::GetPlaceholderTextFontWeight() const
return PlaceholderHandler::GetPlaceholderTextFontWeight(*this);
}
-void Controller::SetDefaultFontWidth( FontWidth width )
+void Controller::SetDefaultFontWidth(FontWidth width)
{
- if( NULL == mImpl->mFontDefaults )
+ if(NULL == mImpl->mFontDefaults)
{
mImpl->mFontDefaults = new FontDefaults();
}
mImpl->mFontDefaults->mFontDescription.width = width;
- mImpl->mFontDefaults->widthDefined = true;
+ mImpl->mFontDefaults->widthDefined = true;
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
// Update the cursor position if it's in editing mode
- if( EventData::IsEditingState( mImpl->mEventData->mState ) )
+ if(EventData::IsEditingState(mImpl->mEventData->mState))
{
- mImpl->mEventData->mDecoratorUpdated = true;
+ mImpl->mEventData->mDecoratorUpdated = true;
mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font width is updated.
}
}
bool Controller::IsDefaultFontWidthDefined() const
{
- if( NULL != mImpl->mFontDefaults )
+ if(NULL != mImpl->mFontDefaults)
{
return mImpl->mFontDefaults->widthDefined;
}
FontWidth Controller::GetDefaultFontWidth() const
{
- if( NULL != mImpl->mFontDefaults )
+ if(NULL != mImpl->mFontDefaults)
{
return mImpl->mFontDefaults->mFontDescription.width;
}
return TextAbstraction::FontWidth::NORMAL;
}
-void Controller::SetPlaceholderTextFontWidth( FontWidth width )
+void Controller::SetPlaceholderTextFontWidth(FontWidth width)
{
PlaceholderHandler::SetPlaceholderTextFontWidth(*this, width);
}
return PlaceholderHandler::GetPlaceholderTextFontWidth(*this);
}
-void Controller::SetDefaultFontSlant( FontSlant slant )
+void Controller::SetDefaultFontSlant(FontSlant slant)
{
- if( NULL == mImpl->mFontDefaults )
+ if(NULL == mImpl->mFontDefaults)
{
mImpl->mFontDefaults = new FontDefaults();
}
mImpl->mFontDefaults->mFontDescription.slant = slant;
- mImpl->mFontDefaults->slantDefined = true;
+ mImpl->mFontDefaults->slantDefined = true;
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
// Update the cursor position if it's in editing mode
- if( EventData::IsEditingState( mImpl->mEventData->mState ) )
+ if(EventData::IsEditingState(mImpl->mEventData->mState))
{
- mImpl->mEventData->mDecoratorUpdated = true;
+ mImpl->mEventData->mDecoratorUpdated = true;
mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font slant is updated.
}
}
bool Controller::IsDefaultFontSlantDefined() const
{
- if( NULL != mImpl->mFontDefaults )
+ if(NULL != mImpl->mFontDefaults)
{
return mImpl->mFontDefaults->slantDefined;
}
FontSlant Controller::GetDefaultFontSlant() const
{
- if( NULL != mImpl->mFontDefaults )
+ if(NULL != mImpl->mFontDefaults)
{
return mImpl->mFontDefaults->mFontDescription.slant;
}
return TextAbstraction::FontSlant::NORMAL;
}
-void Controller::SetPlaceholderTextFontSlant( FontSlant slant )
+void Controller::SetPlaceholderTextFontSlant(FontSlant slant)
{
PlaceholderHandler::SetPlaceholderTextFontSlant(*this, slant);
}
return PlaceholderHandler::GetPlaceholderTextFontSlant(*this);
}
-void Controller::SetFontSizeScale( float scale )
+void Controller::SetFontSizeScale(float scale)
{
mImpl->mFontSizeScale = scale;
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
// Update the cursor position if it's in editing mode
- if( EventData::IsEditingState( mImpl->mEventData->mState ) )
+ if(EventData::IsEditingState(mImpl->mEventData->mState))
{
- mImpl->mEventData->mDecoratorUpdated = true;
+ mImpl->mEventData->mDecoratorUpdated = true;
mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font size is updated.
}
}
float Controller::GetFontSizeScale() const
{
- if( nullptr != mImpl->mFontDefaults )
+ if(nullptr != mImpl->mFontDefaults)
{
return mImpl->mFontSizeScale;
}
return 1.f;
}
-void Controller::SetDefaultFontSize( float fontSize, FontSizeType type )
+void Controller::SetDefaultFontSize(float fontSize, FontSizeType type)
{
- if( NULL == mImpl->mFontDefaults )
+ if(NULL == mImpl->mFontDefaults)
{
mImpl->mFontDefaults = new FontDefaults();
}
- switch( type )
+ switch(type)
{
case POINT_SIZE:
{
mImpl->mFontDefaults->mDefaultPointSize = fontSize;
- mImpl->mFontDefaults->sizeDefined = true;
+ mImpl->mFontDefaults->sizeDefined = true;
break;
}
case PIXEL_SIZE:
{
// Point size = Pixel size * 72.f / DPI
- unsigned int horizontalDpi = 0u;
- unsigned int verticalDpi = 0u;
- TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
- fontClient.GetDpi( horizontalDpi, verticalDpi );
+ unsigned int horizontalDpi = 0u;
+ unsigned int verticalDpi = 0u;
+ TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
+ fontClient.GetDpi(horizontalDpi, verticalDpi);
- mImpl->mFontDefaults->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi );
- mImpl->mFontDefaults->sizeDefined = true;
+ mImpl->mFontDefaults->mDefaultPointSize = (fontSize * 72.f) / static_cast<float>(horizontalDpi);
+ mImpl->mFontDefaults->sizeDefined = true;
break;
}
}
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
// Update the cursor position if it's in editing mode
- if( EventData::IsEditingState( mImpl->mEventData->mState ) )
+ if(EventData::IsEditingState(mImpl->mEventData->mState))
{
- mImpl->mEventData->mDecoratorUpdated = true;
+ mImpl->mEventData->mDecoratorUpdated = true;
mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font size is updated.
}
}
mImpl->RequestRelayout();
}
-float Controller::GetDefaultFontSize( FontSizeType type ) const
+float Controller::GetDefaultFontSize(FontSizeType type) const
{
float value = 0.0f;
- if( NULL != mImpl->mFontDefaults )
+ if(NULL != mImpl->mFontDefaults)
{
- switch( type )
+ switch(type)
{
case POINT_SIZE:
{
case PIXEL_SIZE:
{
// Pixel size = Point size * DPI / 72.f
- unsigned int horizontalDpi = 0u;
- unsigned int verticalDpi = 0u;
- TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
- fontClient.GetDpi( horizontalDpi, verticalDpi );
+ unsigned int horizontalDpi = 0u;
+ unsigned int verticalDpi = 0u;
+ TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
+ fontClient.GetDpi(horizontalDpi, verticalDpi);
- value = mImpl->mFontDefaults->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f;
+ value = mImpl->mFontDefaults->mDefaultPointSize * static_cast<float>(horizontalDpi) / 72.f;
break;
}
}
return value;
}
-void Controller::SetPlaceholderTextFontSize( float fontSize, FontSizeType type )
+void Controller::SetPlaceholderTextFontSize(float fontSize, FontSizeType type)
{
PlaceholderHandler::SetPlaceholderTextFontSize(*this, fontSize, type);
}
-float Controller::GetPlaceholderTextFontSize( FontSizeType type ) const
+float Controller::GetPlaceholderTextFontSize(FontSizeType type) const
{
return PlaceholderHandler::GetPlaceholderTextFontSize(*this, type);
}
-void Controller::SetDefaultColor( const Vector4& color )
+void Controller::SetDefaultColor(const Vector4& color)
{
mImpl->mTextColor = color;
- if( !mImpl->IsShowingPlaceholderText() )
+ if(!mImpl->IsShowingPlaceholderText())
{
- mImpl->mModel->mVisualModel->SetTextColor( color );
+ mImpl->mModel->mVisualModel->SetTextColor(color);
mImpl->mModel->mLogicalModel->mColorRuns.Clear();
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending | COLOR);
mImpl->RequestRelayout();
}
return mImpl->mTextColor;
}
-void Controller::SetPlaceholderTextColor( const Vector4& textColor )
+void Controller::SetPlaceholderTextColor(const Vector4& textColor)
{
PlaceholderHandler::SetPlaceholderTextColor(*this, textColor);
}
return PlaceholderHandler::GetPlaceholderTextColor(*this);
}
-void Controller::SetShadowOffset( const Vector2& shadowOffset )
+void Controller::SetShadowOffset(const Vector2& shadowOffset)
{
- mImpl->mModel->mVisualModel->SetShadowOffset( shadowOffset );
+ mImpl->mModel->mVisualModel->SetShadowOffset(shadowOffset);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->GetShadowOffset();
}
-void Controller::SetShadowColor( const Vector4& shadowColor )
+void Controller::SetShadowColor(const Vector4& shadowColor)
{
- mImpl->mModel->mVisualModel->SetShadowColor( shadowColor );
+ mImpl->mModel->mVisualModel->SetShadowColor(shadowColor);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->GetShadowColor();
}
-void Controller::SetShadowBlurRadius( const float& shadowBlurRadius )
+void Controller::SetShadowBlurRadius(const float& shadowBlurRadius)
{
- if ( fabsf( GetShadowBlurRadius() - shadowBlurRadius ) > Math::MACHINE_EPSILON_1 )
+ if(fabsf(GetShadowBlurRadius() - shadowBlurRadius) > Math::MACHINE_EPSILON_1)
{
- mImpl->mModel->mVisualModel->SetShadowBlurRadius( shadowBlurRadius );
+ mImpl->mModel->mVisualModel->SetShadowBlurRadius(shadowBlurRadius);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->GetShadowBlurRadius();
}
-void Controller::SetUnderlineColor( const Vector4& color )
+void Controller::SetUnderlineColor(const Vector4& color)
{
- mImpl->mModel->mVisualModel->SetUnderlineColor( color );
+ mImpl->mModel->mVisualModel->SetUnderlineColor(color);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->GetUnderlineColor();
}
-void Controller::SetUnderlineEnabled( bool enabled )
+void Controller::SetUnderlineEnabled(bool enabled)
{
- mImpl->mModel->mVisualModel->SetUnderlineEnabled( enabled );
+ mImpl->mModel->mVisualModel->SetUnderlineEnabled(enabled);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->IsUnderlineEnabled();
}
-void Controller::SetUnderlineHeight( float height )
+void Controller::SetUnderlineHeight(float height)
{
- mImpl->mModel->mVisualModel->SetUnderlineHeight( height );
+ mImpl->mModel->mVisualModel->SetUnderlineHeight(height);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->GetUnderlineHeight();
}
-void Controller::SetOutlineColor( const Vector4& color )
+void Controller::SetOutlineColor(const Vector4& color)
{
- mImpl->mModel->mVisualModel->SetOutlineColor( color );
+ mImpl->mModel->mVisualModel->SetOutlineColor(color);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->GetOutlineColor();
}
-void Controller::SetOutlineWidth( uint16_t width )
+void Controller::SetOutlineWidth(uint16_t width)
{
- mImpl->mModel->mVisualModel->SetOutlineWidth( width );
+ mImpl->mModel->mVisualModel->SetOutlineWidth(width);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->GetOutlineWidth();
}
-void Controller::SetBackgroundColor( const Vector4& color )
+void Controller::SetBackgroundColor(const Vector4& color)
{
- mImpl->mModel->mVisualModel->SetBackgroundColor( color );
+ mImpl->mModel->mVisualModel->SetBackgroundColor(color);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->GetBackgroundColor();
}
-void Controller::SetBackgroundEnabled( bool enabled )
+void Controller::SetBackgroundEnabled(bool enabled)
{
- mImpl->mModel->mVisualModel->SetBackgroundEnabled( enabled );
+ mImpl->mModel->mVisualModel->SetBackgroundEnabled(enabled);
mImpl->RequestRelayout();
}
return mImpl->mModel->mVisualModel->IsBackgroundEnabled();
}
-void Controller::SetDefaultEmbossProperties( const std::string& embossProperties )
+void Controller::SetDefaultEmbossProperties(const std::string& embossProperties)
{
- if( NULL == mImpl->mEmbossDefaults )
+ if(NULL == mImpl->mEmbossDefaults)
{
mImpl->mEmbossDefaults = new EmbossDefaults();
}
const std::string& Controller::GetDefaultEmbossProperties() const
{
- if( NULL != mImpl->mEmbossDefaults )
+ if(NULL != mImpl->mEmbossDefaults)
{
return mImpl->mEmbossDefaults->properties;
}
return EMPTY_STRING;
}
-void Controller::SetDefaultOutlineProperties( const std::string& outlineProperties )
+void Controller::SetDefaultOutlineProperties(const std::string& outlineProperties)
{
- if( NULL == mImpl->mOutlineDefaults )
+ if(NULL == mImpl->mOutlineDefaults)
{
mImpl->mOutlineDefaults = new OutlineDefaults();
}
const std::string& Controller::GetDefaultOutlineProperties() const
{
- if( NULL != mImpl->mOutlineDefaults )
+ if(NULL != mImpl->mOutlineDefaults)
{
return mImpl->mOutlineDefaults->properties;
}
return EMPTY_STRING;
}
-bool Controller::SetDefaultLineSpacing( float lineSpacing )
+bool Controller::SetDefaultLineSpacing(float lineSpacing)
{
- if( std::fabs( lineSpacing - mImpl->mLayoutEngine.GetDefaultLineSpacing() ) > Math::MACHINE_EPSILON_1000 )
+ if(std::fabs(lineSpacing - mImpl->mLayoutEngine.GetDefaultLineSpacing()) > Math::MACHINE_EPSILON_1000)
{
mImpl->mLayoutEngine.SetDefaultLineSpacing(lineSpacing);
mImpl->mRecalculateNaturalSize = true;
return mImpl->mLayoutEngine.GetDefaultLineSpacing();
}
-bool Controller::SetDefaultLineSize( float lineSize )
+bool Controller::SetDefaultLineSize(float lineSize)
{
- if( std::fabs( lineSize - mImpl->mLayoutEngine.GetDefaultLineSize() ) > Math::MACHINE_EPSILON_1000 )
+ if(std::fabs(lineSize - mImpl->mLayoutEngine.GetDefaultLineSize()) > Math::MACHINE_EPSILON_1000)
{
mImpl->mLayoutEngine.SetDefaultLineSize(lineSize);
mImpl->mRecalculateNaturalSize = true;
return mImpl->mLayoutEngine.GetDefaultLineSize();
}
-void Controller::SetInputColor( const Vector4& color )
+void Controller::SetInputColor(const Vector4& color)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
- mImpl->mEventData->mInputStyle.textColor = color;
+ mImpl->mEventData->mInputStyle.textColor = color;
mImpl->mEventData->mInputStyle.isDefaultColor = false;
- if( EventData::SELECTING == mImpl->mEventData->mState || EventData::EDITING == mImpl->mEventData->mState || EventData::INACTIVE == mImpl->mEventData->mState )
+ if(EventData::SELECTING == mImpl->mEventData->mState || EventData::EDITING == mImpl->mEventData->mState || EventData::INACTIVE == mImpl->mEventData->mState)
{
const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition;
// Get start and end position of selection
- const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
- const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText;
+ const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition;
+ const Length lengthOfSelectedText = (handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition) - startOfSelectedText;
// Add the color run.
const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count();
- mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u );
+ mImpl->mModel->mLogicalModel->mColorRuns.Resize(numberOfRuns + 1u);
- ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns );
- colorRun.color = color;
- colorRun.characterRun.characterIndex = startOfSelectedText;
+ ColorRun& colorRun = *(mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns);
+ colorRun.color = color;
+ colorRun.characterRun.characterIndex = startOfSelectedText;
colorRun.characterRun.numberOfCharacters = lengthOfSelectedText;
// Request to relayout.
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending | COLOR );
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending | COLOR);
mImpl->RequestRelayout();
- mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
+ mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText;
mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText;
- mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
+ mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText;
}
}
}
const Vector4& Controller::GetInputColor() const
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
return mImpl->mEventData->mInputStyle.textColor;
}
// Return the default text's color if there is no EventData.
return mImpl->mTextColor;
-
}
-void Controller::SetInputFontFamily( const std::string& fontFamily )
+void Controller::SetInputFontFamily(const std::string& fontFamily)
{
InputFontHandler::SetInputFontFamily(*this, fontFamily);
}
return InputFontHandler::GetInputFontFamily(*this);
}
-void Controller::SetInputFontWeight( FontWeight weight )
+void Controller::SetInputFontWeight(FontWeight weight)
{
InputFontHandler::SetInputFontWeight(*this, weight);
}
return InputFontHandler::GetInputFontWeight(*this);
}
-void Controller::SetInputFontWidth( FontWidth width )
+void Controller::SetInputFontWidth(FontWidth width)
{
InputFontHandler::SetInputFontWidth(*this, width);
}
return InputFontHandler::GetInputFontWidth(*this);
}
-void Controller::SetInputFontSlant( FontSlant slant )
+void Controller::SetInputFontSlant(FontSlant slant)
{
InputFontHandler::SetInputFontSlant(*this, slant);
}
return InputFontHandler::GetInputFontSlant(*this);
}
-void Controller::SetInputFontPointSize( float size )
+void Controller::SetInputFontPointSize(float size)
{
InputFontHandler::SetInputFontPointSize(*this, size);
}
return InputFontHandler::GetInputFontPointSize(*this);
}
-void Controller::SetInputLineSpacing( float lineSpacing )
+void Controller::SetInputLineSpacing(float lineSpacing)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
- mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing;
+ mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing;
mImpl->mEventData->mInputStyle.isLineSpacingDefined = true;
}
}
float Controller::GetInputLineSpacing() const
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
return mImpl->mEventData->mInputStyle.lineSpacing;
}
return 0.f;
}
-void Controller::SetInputShadowProperties( const std::string& shadowProperties )
+void Controller::SetInputShadowProperties(const std::string& shadowProperties)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mInputStyle.shadowProperties = shadowProperties;
}
const std::string& Controller::GetInputShadowProperties() const
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
return mImpl->mEventData->mInputStyle.shadowProperties;
}
return EMPTY_STRING;
}
-void Controller::SetInputUnderlineProperties( const std::string& underlineProperties )
+void Controller::SetInputUnderlineProperties(const std::string& underlineProperties)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mInputStyle.underlineProperties = underlineProperties;
}
const std::string& Controller::GetInputUnderlineProperties() const
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
return mImpl->mEventData->mInputStyle.underlineProperties;
}
return EMPTY_STRING;
}
-void Controller::SetInputEmbossProperties( const std::string& embossProperties )
+void Controller::SetInputEmbossProperties(const std::string& embossProperties)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mInputStyle.embossProperties = embossProperties;
}
const std::string& Controller::GetInputEmbossProperties() const
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
return mImpl->mEventData->mInputStyle.embossProperties;
}
return GetDefaultEmbossProperties();
}
-void Controller::SetInputOutlineProperties( const std::string& outlineProperties )
+void Controller::SetInputOutlineProperties(const std::string& outlineProperties)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mInputStyle.outlineProperties = outlineProperties;
}
const std::string& Controller::GetInputOutlineProperties() const
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
return mImpl->mEventData->mInputStyle.outlineProperties;
}
return GetDefaultOutlineProperties();
}
-void Controller::SetInputModePassword( bool passwordInput )
+void Controller::SetInputModePassword(bool passwordInput)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mPasswordInput = passwordInput;
}
bool Controller::IsInputModePassword()
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
return mImpl->mEventData->mPasswordInput;
}
return false;
}
-void Controller::SetNoTextDoubleTapAction( NoTextTap::Action action )
+void Controller::SetNoTextDoubleTapAction(NoTextTap::Action action)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mDoubleTapAction = action;
}
{
NoTextTap::Action action = NoTextTap::NO_ACTION;
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
action = mImpl->mEventData->mDoubleTapAction;
}
return action;
}
-void Controller::SetNoTextLongPressAction( NoTextTap::Action action )
+void Controller::SetNoTextLongPressAction(NoTextTap::Action action)
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mLongPressAction = action;
}
{
NoTextTap::Action action = NoTextTap::NO_ACTION;
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
action = mImpl->mEventData->mLongPressAction;
}
return mImpl->mUnderlineSetByString;
}
-void Controller::UnderlineSetByString( bool setByString )
+void Controller::UnderlineSetByString(bool setByString)
{
mImpl->mUnderlineSetByString = setByString;
}
return mImpl->mShadowSetByString;
}
-void Controller::ShadowSetByString( bool setByString )
+void Controller::ShadowSetByString(bool setByString)
{
mImpl->mShadowSetByString = setByString;
}
return mImpl->mOutlineSetByString;
}
-void Controller::OutlineSetByString( bool setByString )
+void Controller::OutlineSetByString(bool setByString)
{
mImpl->mOutlineSetByString = setByString;
}
return mImpl->mFontStyleSetByString;
}
-void Controller::FontStyleSetByString( bool setByString )
+void Controller::FontStyleSetByString(bool setByString)
{
mImpl->mFontStyleSetByString = setByString;
}
return Relayouter::GetNaturalSize(*this);
}
-bool Controller::CheckForTextFit( float pointSize, Size& layoutSize )
+bool Controller::CheckForTextFit(float pointSize, Size& layoutSize)
{
return Relayouter::CheckForTextFit(*this, pointSize, layoutSize);
}
-void Controller::FitPointSizeforLayout( Size layoutSize )
+void Controller::FitPointSizeforLayout(Size layoutSize)
{
Relayouter::FitPointSizeforLayout(*this, layoutSize);
}
-float Controller::GetHeightForWidth( float width )
+float Controller::GetHeightForWidth(float width)
{
return Relayouter::GetHeightForWidth(*this, width);
}
-int Controller::GetLineCount( float width )
+int Controller::GetLineCount(float width)
{
- GetHeightForWidth( width );
+ GetHeightForWidth(width);
int numberofLines = mImpl->mModel->GetNumberOfLines();
return numberofLines;
}
{
float scrollAmount = 0.0f;
- if (NULL != mImpl->mEventData && mImpl->mEventData->mCheckScrollAmount)
+ if(NULL != mImpl->mEventData && mImpl->mEventData->mCheckScrollAmount)
{
- scrollAmount = mImpl->mModel->mScrollPosition.y - mImpl->mModel->mScrollPositionLast.y;
+ scrollAmount = mImpl->mModel->mScrollPosition.y - mImpl->mModel->mScrollPositionLast.y;
mImpl->mEventData->mCheckScrollAmount = false;
}
return scrollAmount;
}
-bool Controller::GetTextScrollInfo( float& scrollPosition, float& controlHeight, float& layoutHeight )
+bool Controller::GetTextScrollInfo(float& scrollPosition, float& controlHeight, float& layoutHeight)
{
const Vector2& layout = mImpl->mModel->mVisualModel->GetLayoutSize();
- bool isScrolled;
+ bool isScrolled;
- controlHeight = mImpl->mModel->mVisualModel->mControlSize.height;
- layoutHeight = layout.height;
+ controlHeight = mImpl->mModel->mVisualModel->mControlSize.height;
+ layoutHeight = layout.height;
scrollPosition = mImpl->mModel->mScrollPosition.y;
- isScrolled = !Equals( mImpl->mModel->mScrollPosition.y, mImpl->mModel->mScrollPositionLast.y, Math::MACHINE_EPSILON_1 );
+ isScrolled = !Equals(mImpl->mModel->mScrollPosition.y, mImpl->mModel->mScrollPositionLast.y, Math::MACHINE_EPSILON_1);
return isScrolled;
}
void Controller::SetHiddenInputOption(const Property::Map& options)
{
- if( NULL == mImpl->mHiddenInput )
+ if(NULL == mImpl->mHiddenInput)
{
- mImpl->mHiddenInput = new HiddenText( this );
+ mImpl->mHiddenInput = new HiddenText(this);
}
mImpl->mHiddenInput->SetProperties(options);
}
void Controller::GetHiddenInputOption(Property::Map& options)
{
- if( NULL != mImpl->mHiddenInput )
+ if(NULL != mImpl->mHiddenInput)
{
mImpl->mHiddenInput->GetProperties(options);
}
}
-void Controller::SetPlaceholderProperty( const Property::Map& map )
+void Controller::SetPlaceholderProperty(const Property::Map& map)
{
PlaceholderHandler::SetPlaceholderProperty(*this, map);
}
-void Controller::GetPlaceholderProperty( Property::Map& map )
+void Controller::GetPlaceholderProperty(Property::Map& map)
{
PlaceholderHandler::GetPlaceholderProperty(*this, map);
}
// Make sure the model is up-to-date before layouting
ProcessModifyEvents();
- if ( mImpl->mUpdateTextDirection )
+ if(mImpl->mUpdateTextDirection)
{
// Operations that can be done only once until the text changes.
- const OperationsMask onlyOnceOperations = static_cast<OperationsMask>( CONVERT_TO_UTF32 |
- GET_SCRIPTS |
- VALIDATE_FONTS |
- GET_LINE_BREAKS |
- BIDI_INFO |
- SHAPE_TEXT |
- GET_GLYPH_METRICS );
+ const OperationsMask onlyOnceOperations = static_cast<OperationsMask>(CONVERT_TO_UTF32 |
+ GET_SCRIPTS |
+ VALIDATE_FONTS |
+ GET_LINE_BREAKS |
+ BIDI_INFO |
+ SHAPE_TEXT |
+ GET_GLYPH_METRICS);
// Set the update info to relayout the whole text.
- mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
+ mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u;
mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count();
// Make sure the model is up-to-date before layouting
- mImpl->UpdateModel( onlyOnceOperations );
+ mImpl->UpdateModel(onlyOnceOperations);
Vector3 naturalSize;
- DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ),
- static_cast<OperationsMask>( onlyOnceOperations |
- LAYOUT | REORDER | UPDATE_DIRECTION ),
- naturalSize.GetVectorXY() );
+ DoRelayout(Size(MAX_FLOAT, MAX_FLOAT),
+ static_cast<OperationsMask>(onlyOnceOperations |
+ LAYOUT | REORDER | UPDATE_DIRECTION),
+ naturalSize.GetVectorXY());
// Do not do again the only once operations.
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending & ~onlyOnceOperations );
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending & ~onlyOnceOperations);
// Clear the update info. This info will be set the next time the text is updated.
mImpl->mTextUpdateInfo.Clear();
return mImpl->mModel->GetVerticalLineAlignment();
}
-void Controller::SetVerticalLineAlignment( Toolkit::DevelText::VerticalLineAlignment::Type alignment )
+void Controller::SetVerticalLineAlignment(Toolkit::DevelText::VerticalLineAlignment::Type alignment)
{
mImpl->mModel->mVerticalLineAlignment = alignment;
}
// public : Relayout.
-Controller::UpdateTextType Controller::Relayout( const Size& size, Dali::LayoutDirection::Type layoutDirection )
+Controller::UpdateTextType Controller::Relayout(const Size& size, Dali::LayoutDirection::Type layoutDirection)
{
return Relayouter::Relayout(*this, size, layoutDirection);
}
bool Controller::IsInputStyleChangedSignalsQueueEmpty()
{
- return ( NULL == mImpl->mEventData ) || ( 0u == mImpl->mEventData->mInputStyleChangedQueue.Count() );
+ return (NULL == mImpl->mEventData) || (0u == mImpl->mEventData->mInputStyleChangedQueue.Count());
}
void Controller::ProcessInputStyleChangedSignals()
{
- if( NULL == mImpl->mEventData )
+ if(NULL == mImpl->mEventData)
{
// Nothing to do.
return;
}
- for( Vector<InputStyle::Mask>::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(),
- endIt = mImpl->mEventData->mInputStyleChangedQueue.End();
- it != endIt;
- ++it )
+ for(Vector<InputStyle::Mask>::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(),
+ endIt = mImpl->mEventData->mInputStyleChangedQueue.End();
+ it != endIt;
+ ++it)
{
const InputStyle::Mask mask = *it;
- if( NULL != mImpl->mEditableControlInterface )
+ if(NULL != mImpl->mEditableControlInterface)
{
// Emit the input style changed signal.
- mImpl->mEditableControlInterface->InputStyleChanged( mask );
+ mImpl->mEditableControlInterface->InputStyleChanged(mask);
}
}
EventHandler::KeyboardFocusLostEvent(*this);
}
-bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent )
+bool Controller::KeyEvent(const Dali::KeyEvent& keyEvent)
{
return EventHandler::KeyEvent(*this, keyEvent);
}
-void Controller::TapEvent( unsigned int tapCount, float x, float y )
+void Controller::TapEvent(unsigned int tapCount, float x, float y)
{
EventHandler::TapEvent(*this, tapCount, x, y);
}
-void Controller::PanEvent( GestureState state, const Vector2& displacement )
+void Controller::PanEvent(GestureState state, const Vector2& displacement)
{
EventHandler::PanEvent(*this, state, displacement);
}
-void Controller::LongPressEvent( GestureState state, float x, float y )
+void Controller::LongPressEvent(GestureState state, float x, float y)
{
EventHandler::LongPressEvent(*this, state, x, y);
}
-void Controller::SelectEvent( float x, float y, SelectionType selectType )
+void Controller::SelectEvent(float x, float y, SelectionType selectType)
{
EventHandler::SelectEvent(*this, x, y, selectType);
}
-void Controller::SetTextSelectionRange(const uint32_t *start, const uint32_t *end)
+void Controller::SetTextSelectionRange(const uint32_t* start, const uint32_t* end)
{
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
- mImpl->mEventData->mCheckScrollAmount = true;
- mImpl->mEventData->mIsLeftHandleSelected = true;
+ mImpl->mEventData->mCheckScrollAmount = true;
+ mImpl->mEventData->mIsLeftHandleSelected = true;
mImpl->mEventData->mIsRightHandleSelected = true;
mImpl->SetTextSelectionRange(start, end);
mImpl->RequestRelayout();
return mImpl->GetPrimaryCursorPosition();
}
-bool Controller::SetPrimaryCursorPosition( CharacterIndex index )
+bool Controller::SetPrimaryCursorPosition(CharacterIndex index)
{
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
- mImpl->mEventData->mCheckScrollAmount = true;
- mImpl->mEventData->mIsLeftHandleSelected = true;
+ mImpl->mEventData->mCheckScrollAmount = true;
+ mImpl->mEventData->mIsLeftHandleSelected = true;
mImpl->mEventData->mIsRightHandleSelected = true;
- mImpl->mEventData->mCheckScrollAmount = true;
- if( mImpl->SetPrimaryCursorPosition(index) )
+ mImpl->mEventData->mCheckScrollAmount = true;
+ if(mImpl->SetPrimaryCursorPosition(index))
{
KeyboardFocusGainEvent();
return true;
void Controller::SelectWholeText()
{
- SelectEvent( 0.f, 0.f, SelectionType::ALL );
+ SelectEvent(0.f, 0.f, SelectionType::ALL);
}
void Controller::SelectNone()
{
- SelectEvent( 0.f, 0.f, SelectionType::NONE );
+ SelectEvent(0.f, 0.f, SelectionType::NONE);
}
string Controller::GetSelectedText() const
{
string text;
- if( EventData::SELECTING == mImpl->mEventData->mState )
+ if(EventData::SELECTING == mImpl->mEventData->mState)
{
- mImpl->RetrieveSelection( text, false );
+ mImpl->RetrieveSelection(text, false);
}
return text;
}
-InputMethodContext::CallbackData Controller::OnInputMethodContextEvent( InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent )
+InputMethodContext::CallbackData Controller::OnInputMethodContextEvent(InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent)
{
return EventHandler::OnInputMethodContextEvent(*this, inputMethodContext, inputMethodContextEvent);
}
// protected : Inherit from Text::Decorator::ControllerInterface.
-void Controller::GetTargetSize( Vector2& targetSize )
+void Controller::GetTargetSize(Vector2& targetSize)
{
targetSize = mImpl->mModel->mVisualModel->mControlSize;
}
-void Controller::AddDecoration( Actor& actor, bool needsClipping )
+void Controller::AddDecoration(Actor& actor, bool needsClipping)
{
- if( NULL != mImpl->mEditableControlInterface )
+ if(NULL != mImpl->mEditableControlInterface)
{
- mImpl->mEditableControlInterface->AddDecoration( actor, needsClipping );
+ mImpl->mEditableControlInterface->AddDecoration(actor, needsClipping);
}
}
return mImpl->IsEditable();
}
-void Controller::SetEditable( bool editable )
+void Controller::SetEditable(bool editable)
{
- mImpl->SetEditable( editable );
+ mImpl->SetEditable(editable);
if(mImpl->mEventData && mImpl->mEventData->mDecorator)
{
- mImpl->mEventData->mDecorator->SetEditable( editable );
+ mImpl->mEventData->mDecorator->SetEditable(editable);
}
}
-void Controller::ScrollBy( Vector2 scroll )
+void Controller::ScrollBy(Vector2 scroll)
{
- if( mImpl->mEventData && (fabs(scroll.x) > Math::MACHINE_EPSILON_0 || fabs(scroll.y) > Math::MACHINE_EPSILON_0))
+ if(mImpl->mEventData && (fabs(scroll.x) > Math::MACHINE_EPSILON_0 || fabs(scroll.y) > Math::MACHINE_EPSILON_0))
{
- const Vector2& layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
- const Vector2 currentScroll = mImpl->mModel->mScrollPosition;
+ const Vector2& layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize();
+ const Vector2 currentScroll = mImpl->mModel->mScrollPosition;
- scroll.x = -scroll.x;
- scroll.y = -scroll.y;
+ scroll.x = -scroll.x;
+ scroll.y = -scroll.y;
- if( fabs(scroll.x) > Math::MACHINE_EPSILON_0 )
- {
- mImpl->mModel->mScrollPosition.x += scroll.x;
- mImpl->ClampHorizontalScroll( layoutSize );
- }
+ if(fabs(scroll.x) > Math::MACHINE_EPSILON_0)
+ {
+ mImpl->mModel->mScrollPosition.x += scroll.x;
+ mImpl->ClampHorizontalScroll(layoutSize);
+ }
- if( fabs(scroll.y) > Math::MACHINE_EPSILON_0 )
- {
- mImpl->mModel->mScrollPosition.y += scroll.y;
- mImpl->ClampVerticalScroll( layoutSize );
- }
+ if(fabs(scroll.y) > Math::MACHINE_EPSILON_0)
+ {
+ mImpl->mModel->mScrollPosition.y += scroll.y;
+ mImpl->ClampVerticalScroll(layoutSize);
+ }
- if (mImpl->mModel->mScrollPosition != currentScroll)
- {
- mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mModel->mScrollPosition - currentScroll );
- mImpl->RequestRelayout();
- }
+ if(mImpl->mModel->mScrollPosition != currentScroll)
+ {
+ mImpl->mEventData->mDecorator->UpdatePositions(mImpl->mModel->mScrollPosition - currentScroll);
+ mImpl->RequestRelayout();
+ }
}
}
float Controller::GetHorizontalScrollPosition()
{
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
//scroll values are negative internally so we convert them to positive numbers
return -mImpl->mModel->mScrollPosition.x;
float Controller::GetVerticalScrollPosition()
{
- if( mImpl->mEventData )
+ if(mImpl->mEventData)
{
//scroll values are negative internally so we convert them to positive numbers
return -mImpl->mModel->mScrollPosition.y;
return 0;
}
-void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y )
+void Controller::DecorationEvent(HandleType handleType, HandleState state, float x, float y)
{
EventHandler::DecorationEvent(*this, handleType, state, x, y);
}
// protected : Inherit from TextSelectionPopup::TextPopupButtonCallbackInterface.
-void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button )
+void Controller::TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::Buttons button)
{
EventHandler::TextPopupButtonTouched(*this, button);
}
// private : Update.
-void Controller::InsertText( const std::string& text, Controller::InsertType type )
+void Controller::InsertText(const std::string& text, Controller::InsertType type)
{
TextUpdater::InsertText(*this, text, type);
}
-void Controller::PasteText( const std::string& stringToPaste )
+void Controller::PasteText(const std::string& stringToPaste)
{
TextUpdater::PasteText(*this, stringToPaste);
}
-bool Controller::RemoveText( int cursorOffset,
- int numberOfCharacters,
- UpdateInputStyleType type )
+bool Controller::RemoveText(int cursorOffset,
+ int numberOfCharacters,
+ UpdateInputStyleType type)
{
return TextUpdater::RemoveText(*this, cursorOffset, numberOfCharacters, type);
}
// private : Relayout.
-bool Controller::DoRelayout( const Size& size,
- OperationsMask operationsRequired,
- Size& layoutSize )
+bool Controller::DoRelayout(const Size& size,
+ OperationsMask operationsRequired,
+ Size& layoutSize)
{
return Relayouter::DoRelayout(*this, size, operationsRequired, layoutSize);
}
-void Controller::CalculateVerticalOffset( const Size& controlSize )
+void Controller::CalculateVerticalOffset(const Size& controlSize)
{
Relayouter::CalculateVerticalOffset(*this, controlSize);
}
EventHandler::TextDeletedEvent(*this);
}
-bool Controller::DeleteEvent( int keyCode )
+bool Controller::DeleteEvent(int keyCode)
{
return EventHandler::DeleteEvent(*this, keyCode);
}
void Controller::ClearFontData()
{
- if( mImpl->mFontDefaults )
+ if(mImpl->mFontDefaults)
{
mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID
}
// Set flags to update the model.
- mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
+ mImpl->mTextUpdateInfo.mCharacterIndex = 0u;
mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters;
- mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
+ mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count();
- mImpl->mTextUpdateInfo.mClearAll = true;
+ mImpl->mTextUpdateInfo.mClearAll = true;
mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true;
- mImpl->mRecalculateNaturalSize = true;
+ mImpl->mRecalculateNaturalSize = true;
- mImpl->mOperationsPending = static_cast<OperationsMask>( mImpl->mOperationsPending |
- VALIDATE_FONTS |
- SHAPE_TEXT |
- BIDI_INFO |
- GET_GLYPH_METRICS |
- LAYOUT |
- UPDATE_LAYOUT_SIZE |
- REORDER |
- ALIGN );
+ mImpl->mOperationsPending = static_cast<OperationsMask>(mImpl->mOperationsPending |
+ VALIDATE_FONTS |
+ SHAPE_TEXT |
+ BIDI_INFO |
+ GET_GLYPH_METRICS |
+ LAYOUT |
+ UPDATE_LAYOUT_SIZE |
+ REORDER |
+ ALIGN);
}
void Controller::ClearStyleData()
mImpl->mModel->mLogicalModel->ClearFontDescriptionRuns();
}
-void Controller::ResetCursorPosition( CharacterIndex cursorIndex )
+void Controller::ResetCursorPosition(CharacterIndex cursorIndex)
{
// Reset the cursor position
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
mImpl->mEventData->mPrimaryCursorPosition = cursorIndex;
// Update the cursor if it's in editing mode.
- if( EventData::IsEditingState( mImpl->mEventData->mState ) )
+ if(EventData::IsEditingState(mImpl->mEventData->mState))
{
mImpl->mEventData->mUpdateCursorPosition = true;
}
CharacterIndex Controller::GetCursorPosition()
{
- if( !mImpl->mEventData )
+ if(!mImpl->mEventData)
return 0;
return mImpl->mEventData->mPrimaryCursorPosition;
void Controller::ResetScrollPosition()
{
- if( NULL != mImpl->mEventData )
+ if(NULL != mImpl->mEventData)
{
// Reset the scroll position.
- mImpl->mModel->mScrollPosition = Vector2::ZERO;
+ mImpl->mModel->mScrollPosition = Vector2::ZERO;
mImpl->mEventData->mScrollAfterUpdatePosition = true;
}
}
-void Controller::SetControlInterface( ControlInterface* controlInterface )
+void Controller::SetControlInterface(ControlInterface* controlInterface)
{
mImpl->mControlInterface = controlInterface;
}
{
}
-Controller::Controller( ControlInterface* controlInterface )
-:Controller( controlInterface, nullptr, nullptr)
+Controller::Controller(ControlInterface* controlInterface)
+: Controller(controlInterface, nullptr, nullptr)
{
}
-Controller::Controller( ControlInterface* controlInterface,
- EditableControlInterface* editableControlInterface,
- SelectableControlInterface* selectableControlInterface )
+Controller::Controller(ControlInterface* controlInterface,
+ EditableControlInterface* editableControlInterface,
+ SelectableControlInterface* selectableControlInterface)
: mImpl(new Controller::Impl(controlInterface, editableControlInterface, selectableControlInterface))
{
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
-const std::string COLOR_KEY( "color" );
-const std::string OFFSET_KEY( "offset" );
-const std::string BLUR_RADIUS_KEY( "blurRadius" );
-const std::string WIDTH_KEY( "width" );
-const std::string HEIGHT_KEY( "height" );
-const std::string ENABLE_KEY( "enable" );
-const std::string TRUE_TOKEN( "true" );
-const std::string FALSE_TOKEN( "false" );
-}
-
-bool ParseShadowProperties( const Property::Map& shadowPropertiesMap,
- bool& colorDefined,
- Vector4& color,
- bool& offsetDefined,
- Vector2& offset,
- bool& blurRadiusDefined,
- float& blurRadius )
+const std::string COLOR_KEY("color");
+const std::string OFFSET_KEY("offset");
+const std::string BLUR_RADIUS_KEY("blurRadius");
+const std::string WIDTH_KEY("width");
+const std::string HEIGHT_KEY("height");
+const std::string ENABLE_KEY("enable");
+const std::string TRUE_TOKEN("true");
+const std::string FALSE_TOKEN("false");
+} // namespace
+
+bool ParseShadowProperties(const Property::Map& shadowPropertiesMap,
+ bool& colorDefined,
+ Vector4& color,
+ bool& offsetDefined,
+ Vector2& offset,
+ bool& blurRadiusDefined,
+ float& blurRadius)
{
const unsigned int numberOfItems = shadowPropertiesMap.Count();
// Parses and applies the style.
- for( unsigned int index = 0u; index < numberOfItems; ++index )
+ for(unsigned int index = 0u; index < numberOfItems; ++index)
{
- const KeyValuePair& valueGet = shadowPropertiesMap.GetKeyValue( index );
+ const KeyValuePair& valueGet = shadowPropertiesMap.GetKeyValue(index);
- if( ( DevelText::Shadow::Property::COLOR == valueGet.first.indexKey ) || ( COLOR_KEY == valueGet.first.stringKey ) )
+ if((DevelText::Shadow::Property::COLOR == valueGet.first.indexKey) || (COLOR_KEY == valueGet.first.stringKey))
{
/// Color key.
colorDefined = true;
- if( valueGet.second.GetType() == Dali::Property::STRING )
+ if(valueGet.second.GetType() == Dali::Property::STRING)
{
const std::string colorStr = valueGet.second.Get<std::string>();
- Text::ColorStringToVector4( colorStr.c_str(), colorStr.size(), color );
+ Text::ColorStringToVector4(colorStr.c_str(), colorStr.size(), color);
}
else
{
color = valueGet.second.Get<Vector4>();
}
}
- else if( ( DevelText::Shadow::Property::OFFSET == valueGet.first.indexKey ) || ( OFFSET_KEY == valueGet.first.stringKey ) )
+ else if((DevelText::Shadow::Property::OFFSET == valueGet.first.indexKey) || (OFFSET_KEY == valueGet.first.stringKey))
{
/// Offset key.
offsetDefined = true;
- if( valueGet.second.GetType() == Dali::Property::STRING )
+ if(valueGet.second.GetType() == Dali::Property::STRING)
{
const std::string offsetStr = valueGet.second.Get<std::string>();
- StringToVector2( offsetStr.c_str(), offsetStr.size(), offset );
+ StringToVector2(offsetStr.c_str(), offsetStr.size(), offset);
}
else
{
offset = valueGet.second.Get<Vector2>();
}
}
- else if( ( DevelText::Shadow::Property::BLUR_RADIUS == valueGet.first.indexKey ) || ( BLUR_RADIUS_KEY == valueGet.first.stringKey ) )
+ else if((DevelText::Shadow::Property::BLUR_RADIUS == valueGet.first.indexKey) || (BLUR_RADIUS_KEY == valueGet.first.stringKey))
{
/// Blur radius key.
blurRadiusDefined = true;
- if( valueGet.second.GetType() == Dali::Property::STRING )
+ if(valueGet.second.GetType() == Dali::Property::STRING)
{
const std::string blurRadiusStr = valueGet.second.Get<std::string>();
- blurRadius = StringToFloat( blurRadiusStr.c_str() );
+ blurRadius = StringToFloat(blurRadiusStr.c_str());
}
else
{
return 0u == numberOfItems;
}
-bool ParseUnderlineProperties( const Property::Map& underlinePropertiesMap,
- bool& enabled,
- bool& colorDefined,
- Vector4& color,
- bool& heightDefined,
- float& height )
+bool ParseUnderlineProperties(const Property::Map& underlinePropertiesMap,
+ bool& enabled,
+ bool& colorDefined,
+ Vector4& color,
+ bool& heightDefined,
+ float& height)
{
const unsigned int numberOfItems = underlinePropertiesMap.Count();
// Parses and applies the style.
- for( unsigned int index = 0u; index < numberOfItems; ++index )
+ for(unsigned int index = 0u; index < numberOfItems; ++index)
{
- const KeyValuePair& valueGet = underlinePropertiesMap.GetKeyValue( index );
+ const KeyValuePair& valueGet = underlinePropertiesMap.GetKeyValue(index);
- if( ( DevelText::Underline::Property::ENABLE == valueGet.first.indexKey ) || ( ENABLE_KEY == valueGet.first.stringKey ) )
+ if((DevelText::Underline::Property::ENABLE == valueGet.first.indexKey) || (ENABLE_KEY == valueGet.first.stringKey))
{
/// Enable key.
- if( valueGet.second.GetType() == Dali::Property::STRING )
+ if(valueGet.second.GetType() == Dali::Property::STRING)
{
const std::string enableStr = valueGet.second.Get<std::string>();
- enabled = Text::TokenComparison( TRUE_TOKEN, enableStr.c_str(), enableStr.size() );
+ enabled = Text::TokenComparison(TRUE_TOKEN, enableStr.c_str(), enableStr.size());
}
else
{
enabled = valueGet.second.Get<bool>();
}
}
- else if( ( DevelText::Underline::Property::COLOR == valueGet.first.indexKey ) || ( COLOR_KEY == valueGet.first.stringKey ) )
+ else if((DevelText::Underline::Property::COLOR == valueGet.first.indexKey) || (COLOR_KEY == valueGet.first.stringKey))
{
/// Color key.
colorDefined = true;
- if( valueGet.second.GetType() == Dali::Property::STRING )
+ if(valueGet.second.GetType() == Dali::Property::STRING)
{
const std::string colorStr = valueGet.second.Get<std::string>();
- Text::ColorStringToVector4( colorStr.c_str(), colorStr.size(), color );
+ Text::ColorStringToVector4(colorStr.c_str(), colorStr.size(), color);
}
else
{
color = valueGet.second.Get<Vector4>();
}
}
- else if( ( DevelText::Underline::Property::HEIGHT == valueGet.first.indexKey ) || ( HEIGHT_KEY == valueGet.first.stringKey ) )
+ else if((DevelText::Underline::Property::HEIGHT == valueGet.first.indexKey) || (HEIGHT_KEY == valueGet.first.stringKey))
{
/// Height key.
heightDefined = true;
- if( valueGet.second.GetType() == Dali::Property::STRING )
+ if(valueGet.second.GetType() == Dali::Property::STRING)
{
const std::string heightStr = valueGet.second.Get<std::string>();
- height = StringToFloat( heightStr.c_str() );
+ height = StringToFloat(heightStr.c_str());
}
else
{
return 0u == numberOfItems;
}
-bool ParseOutlineProperties( const Property::Map& underlinePropertiesMap,
- bool& colorDefined,
- Vector4& color,
- bool& widthDefined,
- uint16_t& width )
+bool ParseOutlineProperties(const Property::Map& underlinePropertiesMap,
+ bool& colorDefined,
+ Vector4& color,
+ bool& widthDefined,
+ uint16_t& width)
{
const unsigned int numberOfItems = underlinePropertiesMap.Count();
// Parses and applies the style.
- for( unsigned int index = 0u; index < numberOfItems; ++index )
+ for(unsigned int index = 0u; index < numberOfItems; ++index)
{
- const KeyValuePair& valueGet = underlinePropertiesMap.GetKeyValue( index );
+ const KeyValuePair& valueGet = underlinePropertiesMap.GetKeyValue(index);
- if( ( DevelText::Outline::Property::COLOR == valueGet.first.indexKey ) || ( COLOR_KEY == valueGet.first.stringKey ) )
+ if((DevelText::Outline::Property::COLOR == valueGet.first.indexKey) || (COLOR_KEY == valueGet.first.stringKey))
{
/// Color key.
colorDefined = true;
- color = valueGet.second.Get<Vector4>();
+ color = valueGet.second.Get<Vector4>();
}
- else if( ( DevelText::Outline::Property::WIDTH == valueGet.first.indexKey ) || ( WIDTH_KEY == valueGet.first.stringKey ) )
+ else if((DevelText::Outline::Property::WIDTH == valueGet.first.indexKey) || (WIDTH_KEY == valueGet.first.stringKey))
{
/// Width key.
widthDefined = true;
- width = static_cast<uint16_t>( valueGet.second.Get<float>() );
+ width = static_cast<uint16_t>(valueGet.second.Get<float>());
}
}
return 0u == numberOfItems;
}
-bool ParseBackgroundProperties( const Property::Map& backgroundProperties,
- bool& enabled,
- bool& colorDefined,
- Vector4& color )
+bool ParseBackgroundProperties(const Property::Map& backgroundProperties,
+ bool& enabled,
+ bool& colorDefined,
+ Vector4& color)
{
const unsigned int numberOfItems = backgroundProperties.Count();
// Parses and applies the style.
- for( unsigned int index = 0u; index < numberOfItems; ++index )
+ for(unsigned int index = 0u; index < numberOfItems; ++index)
{
- const KeyValuePair& valueGet = backgroundProperties.GetKeyValue( index );
+ const KeyValuePair& valueGet = backgroundProperties.GetKeyValue(index);
- if( ( DevelText::Background::Property::ENABLE == valueGet.first.indexKey ) || ( ENABLE_KEY == valueGet.first.stringKey ) )
+ if((DevelText::Background::Property::ENABLE == valueGet.first.indexKey) || (ENABLE_KEY == valueGet.first.stringKey))
{
/// Enable key.
enabled = valueGet.second.Get<bool>();
}
- else if( ( DevelText::Background::Property::COLOR == valueGet.first.indexKey ) || ( COLOR_KEY == valueGet.first.stringKey ) )
+ else if((DevelText::Background::Property::COLOR == valueGet.first.indexKey) || (COLOR_KEY == valueGet.first.stringKey))
{
/// Color key.
colorDefined = true;
- color = valueGet.second.Get<Vector4>();
+ color = valueGet.second.Get<Vector4>();
}
}
return 0u == numberOfItems;
}
-bool SetUnderlineProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type )
+bool SetUnderlineProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type)
{
bool update = false;
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
const Property::Map& propertiesMap = value.Get<Property::Map>();
- bool enabled = false;
- bool colorDefined = false;
+ bool enabled = false;
+ bool colorDefined = false;
Vector4 color;
- bool heightDefined = false;
- float height = 0.f;
+ bool heightDefined = false;
+ float height = 0.f;
bool empty = true;
- if ( propertiesMap.Empty() )
+ if(propertiesMap.Empty())
{
// Map empty so check if a string provided
const std::string propertyString = value.Get<std::string>();
- if ( !propertyString.empty() )
+ if(!propertyString.empty())
{
Property::Map parsedStringMap;
- Text::ParsePropertyString( propertyString, parsedStringMap );
+ Text::ParsePropertyString(propertyString, parsedStringMap);
- empty = ParseUnderlineProperties( parsedStringMap,
- enabled,
- colorDefined,
- color,
- heightDefined,
- height );
+ empty = ParseUnderlineProperties(parsedStringMap,
+ enabled,
+ colorDefined,
+ color,
+ heightDefined,
+ height);
- controller->UnderlineSetByString( !empty );
+ controller->UnderlineSetByString(!empty);
}
}
else
{
- empty = ParseUnderlineProperties( propertiesMap,
- enabled,
- colorDefined,
- color,
- heightDefined,
- height );
+ empty = ParseUnderlineProperties(propertiesMap,
+ enabled,
+ colorDefined,
+ color,
+ heightDefined,
+ height);
- controller->UnderlineSetByString( false );
+ controller->UnderlineSetByString(false);
}
- if( !empty )
+ if(!empty)
{
- if( enabled != controller->IsUnderlineEnabled() )
+ if(enabled != controller->IsUnderlineEnabled())
{
- controller->SetUnderlineEnabled( enabled );
+ controller->SetUnderlineEnabled(enabled);
update = true;
}
// Sets the default underline values.
- if( colorDefined && ( controller->GetUnderlineColor() != color ) )
+ if(colorDefined && (controller->GetUnderlineColor() != color))
{
- controller->SetUnderlineColor( color );
+ controller->SetUnderlineColor(color);
update = true;
}
- if( heightDefined && ( fabsf( controller->GetUnderlineHeight() - height ) > Math::MACHINE_EPSILON_1000 ) )
+ if(heightDefined && (fabsf(controller->GetUnderlineHeight() - height) > Math::MACHINE_EPSILON_1000))
{
- controller->SetUnderlineHeight( height );
+ controller->SetUnderlineHeight(height);
update = true;
}
}
else
{
// Disable underline.
- if( controller->IsUnderlineEnabled() )
+ if(controller->IsUnderlineEnabled())
{
- controller->SetUnderlineEnabled( false );
+ controller->SetUnderlineEnabled(false);
update = true;
}
}
{
const std::string& underlineProperties = value.Get<std::string>();
- controller->SetInputUnderlineProperties( underlineProperties );
+ controller->SetInputUnderlineProperties(underlineProperties);
break;
}
} // switch
- } // if( controller )
+ } // if( controller )
return update;
}
-void GetUnderlineProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type )
+void GetUnderlineProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type)
{
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
- const bool enabled = controller->IsUnderlineEnabled();
- const Vector4& color = controller->GetUnderlineColor();
- const float height = controller->GetUnderlineHeight();
+ const bool enabled = controller->IsUnderlineEnabled();
+ const Vector4& color = controller->GetUnderlineColor();
+ const float height = controller->GetUnderlineHeight();
- if ( controller->IsUnderlineSetByString() )
+ if(controller->IsUnderlineSetByString())
{
- std::string underlineProperties = "{\"enable\":";
- const std::string enabledStr = enabled ? "true" : "false";
+ std::string underlineProperties = "{\"enable\":";
+ const std::string enabledStr = enabled ? "true" : "false";
underlineProperties += "\"" + enabledStr + "\",";
std::string colorStr;
- Vector4ToColorString( color, colorStr );
+ Vector4ToColorString(color, colorStr);
underlineProperties += "\"color\":\"" + colorStr + "\",";
std::string heightStr;
- FloatToString( height, heightStr );
+ FloatToString(height, heightStr);
underlineProperties += "\"height\":\"" + heightStr + "\"}";
value = underlineProperties;
{
Property::Map map;
- map.Insert( ENABLE_KEY, enabled );
- map.Insert( COLOR_KEY, color );
- map.Insert( HEIGHT_KEY, height );
+ map.Insert(ENABLE_KEY, enabled);
+ map.Insert(COLOR_KEY, color);
+ map.Insert(HEIGHT_KEY, height);
value = map;
}
}
}
-bool SetShadowProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type )
+bool SetShadowProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type)
{
bool update = false;
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
const Property::Map& propertiesMap = value.Get<Property::Map>();
- bool colorDefined = false;
+ bool colorDefined = false;
Vector4 color;
- bool offsetDefined = false;
+ bool offsetDefined = false;
Vector2 offset;
- bool blurRadiusDefined = false;
- float blurRadius;
+ bool blurRadiusDefined = false;
+ float blurRadius;
bool empty = true;
- if ( propertiesMap.Empty() )
+ if(propertiesMap.Empty())
{
- // Map empty so check if a string provided
- const std::string propertyString = value.Get<std::string>();
-
- Property::Map parsedStringMap;
- Text::ParsePropertyString( propertyString, parsedStringMap );
+ // Map empty so check if a string provided
+ const std::string propertyString = value.Get<std::string>();
- empty = ParseShadowProperties( parsedStringMap,
- colorDefined,
- color,
- offsetDefined,
- offset,
- blurRadiusDefined,
- blurRadius );
+ Property::Map parsedStringMap;
+ Text::ParsePropertyString(propertyString, parsedStringMap);
- controller->ShadowSetByString( !empty );
+ empty = ParseShadowProperties(parsedStringMap,
+ colorDefined,
+ color,
+ offsetDefined,
+ offset,
+ blurRadiusDefined,
+ blurRadius);
+ controller->ShadowSetByString(!empty);
}
else
{
- empty = ParseShadowProperties( propertiesMap,
- colorDefined,
- color,
- offsetDefined,
- offset,
- blurRadiusDefined,
- blurRadius );
-
- controller->ShadowSetByString( false );
+ empty = ParseShadowProperties(propertiesMap,
+ colorDefined,
+ color,
+ offsetDefined,
+ offset,
+ blurRadiusDefined,
+ blurRadius);
+
+ controller->ShadowSetByString(false);
}
- if( !empty )
+ if(!empty)
{
// Sets the default shadow values.
- if( colorDefined && ( controller->GetShadowColor() != color ) )
+ if(colorDefined && (controller->GetShadowColor() != color))
{
- controller->SetShadowColor( color );
+ controller->SetShadowColor(color);
update = true;
}
- if( offsetDefined && ( controller->GetShadowOffset() != offset ) )
+ if(offsetDefined && (controller->GetShadowOffset() != offset))
{
- controller->SetShadowOffset( offset );
+ controller->SetShadowOffset(offset);
update = true;
}
- if( blurRadiusDefined && ( controller->GetShadowBlurRadius() != blurRadius ) )
+ if(blurRadiusDefined && (controller->GetShadowBlurRadius() != blurRadius))
{
- controller->SetShadowBlurRadius( blurRadius );
+ controller->SetShadowBlurRadius(blurRadius);
update = true;
}
}
else
{
// Disable shadow.
- if( Vector2::ZERO != controller->GetShadowOffset() )
+ if(Vector2::ZERO != controller->GetShadowOffset())
{
- controller->SetShadowOffset( Vector2::ZERO );
+ controller->SetShadowOffset(Vector2::ZERO);
}
}
break;
{
const std::string& shadowString = value.Get<std::string>();
- controller->SetInputShadowProperties( shadowString );
+ controller->SetInputShadowProperties(shadowString);
break;
}
} // switch
- } // if( controller )
+ } // if( controller )
return update;
}
-void GetShadowProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type )
+void GetShadowProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type)
{
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
- const Vector4& color = controller->GetShadowColor();
- const Vector2& offset = controller->GetShadowOffset();
- const float& blurRadius = controller->GetShadowBlurRadius();
+ const Vector4& color = controller->GetShadowColor();
+ const Vector2& offset = controller->GetShadowOffset();
+ const float& blurRadius = controller->GetShadowBlurRadius();
- if ( controller->IsShadowSetByString() )
+ if(controller->IsShadowSetByString())
{
std::string shadowProperties = "{";
std::string colorStr;
- Vector4ToColorString( color, colorStr );
+ Vector4ToColorString(color, colorStr);
shadowProperties += "\"color\":\"" + colorStr + "\",";
std::string offsetStr;
- Vector2ToString( offset, offsetStr );
+ Vector2ToString(offset, offsetStr);
shadowProperties += "\"offset\":\"" + offsetStr + "\",";
std::string blurRadiusStr;
- FloatToString( blurRadius, blurRadiusStr );
+ FloatToString(blurRadius, blurRadiusStr);
shadowProperties += "\"blurRadius\":\"" + blurRadiusStr + "\"}";
value = shadowProperties;
{
Property::Map map;
- map.Insert( COLOR_KEY, color );
- map.Insert( OFFSET_KEY, offset );
- map.Insert( BLUR_RADIUS_KEY, blurRadius );
+ map.Insert(COLOR_KEY, color);
+ map.Insert(OFFSET_KEY, offset);
+ map.Insert(BLUR_RADIUS_KEY, blurRadius);
value = map;
}
}
}
-bool SetEmbossProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type )
+bool SetEmbossProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type)
{
bool update = false;
- if( controller )
+ if(controller)
{
- const std::string properties = value.Get< std::string >();
+ const std::string properties = value.Get<std::string>();
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
// Stores the default emboss's properties string to be recovered by the GetEmbossProperties() function.
- controller->SetDefaultEmbossProperties( properties );
+ controller->SetDefaultEmbossProperties(properties);
break;
}
case EffectStyle::INPUT:
{
// Stores the input emboss's properties string to be recovered by the GetEmbossProperties() function.
- controller->SetInputEmbossProperties( properties );
+ controller->SetInputEmbossProperties(properties);
break;
}
}
return update;
}
-void GetEmbossProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type )
+void GetEmbossProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type)
{
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
}
}
-bool SetOutlineProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type )
+bool SetOutlineProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type)
{
bool update = false;
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
const Property::Map& propertiesMap = value.Get<Property::Map>();
- bool colorDefined = false;
- Vector4 color;
- bool widthDefined = false;
- uint16_t width = 0u;
+ bool colorDefined = false;
+ Vector4 color;
+ bool widthDefined = false;
+ uint16_t width = 0u;
bool empty = true;
- if ( propertiesMap.Empty() )
+ if(propertiesMap.Empty())
{
- // Map empty so check if a string provided
- // This is purely to maintain backward compatibility, but we don't parse the string to be a property map.
- const std::string propertyString = value.Get<std::string>();
+ // Map empty so check if a string provided
+ // This is purely to maintain backward compatibility, but we don't parse the string to be a property map.
+ const std::string propertyString = value.Get<std::string>();
- // Stores the default outline's properties string to be recovered by the GetOutlineProperties() function.
- controller->SetDefaultOutlineProperties( propertyString );
+ // Stores the default outline's properties string to be recovered by the GetOutlineProperties() function.
+ controller->SetDefaultOutlineProperties(propertyString);
- controller->OutlineSetByString( true );
+ controller->OutlineSetByString(true);
}
else
{
- empty = ParseOutlineProperties( propertiesMap,
- colorDefined,
- color,
- widthDefined,
- width );
+ empty = ParseOutlineProperties(propertiesMap,
+ colorDefined,
+ color,
+ widthDefined,
+ width);
- controller->OutlineSetByString( false );
+ controller->OutlineSetByString(false);
}
- if( !empty )
+ if(!empty)
{
// Sets the default outline values.
- if( colorDefined && ( controller->GetOutlineColor() != color ) )
+ if(colorDefined && (controller->GetOutlineColor() != color))
{
- controller->SetOutlineColor( color );
+ controller->SetOutlineColor(color);
update = true;
}
- if( widthDefined && ( controller->GetOutlineWidth() != width ) )
+ if(widthDefined && (controller->GetOutlineWidth() != width))
{
- controller->SetOutlineWidth( width );
+ controller->SetOutlineWidth(width);
update = true;
}
}
else
{
// Disable outline
- if( 0u != controller->GetOutlineWidth() )
+ if(0u != controller->GetOutlineWidth())
{
- controller->SetOutlineWidth( 0u );
+ controller->SetOutlineWidth(0u);
update = true;
}
}
{
const std::string& outlineProperties = value.Get<std::string>();
- controller->SetInputOutlineProperties( outlineProperties );
+ controller->SetInputOutlineProperties(outlineProperties);
break;
}
} // switch
- } // if( controller )
+ } // if( controller )
return update;
}
-void GetOutlineProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type )
+void GetOutlineProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type)
{
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
- if ( controller->IsOutlineSetByString() )
+ if(controller->IsOutlineSetByString())
{
value = controller->GetDefaultOutlineProperties();
break;
const uint16_t width = controller->GetOutlineWidth();
Property::Map map;
- map.Insert( COLOR_KEY, color );
- map.Insert( WIDTH_KEY, static_cast<int>( width ) );
+ map.Insert(COLOR_KEY, color);
+ map.Insert(WIDTH_KEY, static_cast<int>(width));
value = map;
}
}
-bool SetBackgroundProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type )
+bool SetBackgroundProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type)
{
bool update = false;
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
const Property::Map& propertiesMap = value.Get<Property::Map>();
- bool enabled = false;
- bool colorDefined = false;
+ bool enabled = false;
+ bool colorDefined = false;
Vector4 color;
bool empty = true;
- if ( !propertiesMap.Empty() )
+ if(!propertiesMap.Empty())
{
- empty = ParseBackgroundProperties( propertiesMap,
- enabled,
- colorDefined,
- color );
+ empty = ParseBackgroundProperties(propertiesMap,
+ enabled,
+ colorDefined,
+ color);
}
- if( !empty )
+ if(!empty)
{
- if( enabled != controller->IsBackgroundEnabled() )
+ if(enabled != controller->IsBackgroundEnabled())
{
- controller->SetBackgroundEnabled( enabled );
+ controller->SetBackgroundEnabled(enabled);
update = true;
}
- if( colorDefined && ( controller->GetBackgroundColor() != color ) )
+ if(colorDefined && (controller->GetBackgroundColor() != color))
{
- controller->SetBackgroundColor( color );
+ controller->SetBackgroundColor(color);
update = true;
}
}
else
{
// Disable background.
- if( controller->IsBackgroundEnabled() )
+ if(controller->IsBackgroundEnabled())
{
- controller->SetBackgroundEnabled( false );
+ controller->SetBackgroundEnabled(false);
update = true;
}
}
break;
}
} // switch
- } // if( controller )
+ } // if( controller )
return update;
}
-void GetBackgroundProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type )
+void GetBackgroundProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type)
{
- if( controller )
+ if(controller)
{
- switch( type )
+ switch(type)
{
case EffectStyle::DEFAULT:
{
- const bool enabled = controller->IsBackgroundEnabled();
- const Vector4& color = controller->GetBackgroundColor();
+ const bool enabled = controller->IsBackgroundEnabled();
+ const Vector4& color = controller->GetBackgroundColor();
Property::Map map;
- map.Insert( ENABLE_KEY, enabled );
- map.Insert( COLOR_KEY, color );
+ map.Insert(ENABLE_KEY, enabled);
+ map.Insert(COLOR_KEY, color);
value = map;
break;
-
}
case EffectStyle::INPUT:
{
}
}
-
} // namespace Text
} // namespace Toolkit
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
-DALI_ENUM_TO_STRING_TABLE_BEGIN( HORIZONTAL_ALIGNMENT_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::HorizontalAlignment, BEGIN )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::HorizontalAlignment, CENTER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::HorizontalAlignment, END )
-DALI_ENUM_TO_STRING_TABLE_END( HORIZONTAL_ALIGNMENT_TYPE )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( VERTICAL_ALIGNMENT_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::VerticalAlignment, TOP )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::VerticalAlignment, CENTER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::VerticalAlignment, BOTTOM )
-DALI_ENUM_TO_STRING_TABLE_END( VERTICAL_ALIGNMENT_TYPE )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( LINE_WRAP_MODE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::LineWrap, WORD )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::LineWrap, CHARACTER )
-DALI_ENUM_TO_STRING_TABLE_END( LINE_WRAP_MODE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(HORIZONTAL_ALIGNMENT_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::HorizontalAlignment, BEGIN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::HorizontalAlignment, CENTER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::HorizontalAlignment, END)
+DALI_ENUM_TO_STRING_TABLE_END(HORIZONTAL_ALIGNMENT_TYPE)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(VERTICAL_ALIGNMENT_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::VerticalAlignment, TOP)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::VerticalAlignment, CENTER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::VerticalAlignment, BOTTOM)
+DALI_ENUM_TO_STRING_TABLE_END(VERTICAL_ALIGNMENT_TYPE)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(LINE_WRAP_MODE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::LineWrap, WORD)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::LineWrap, CHARACTER)
+DALI_ENUM_TO_STRING_TABLE_END(LINE_WRAP_MODE)
} // namespace
-bool GetHorizontalAlignmentEnumeration( const Property::Value& propertyValue, Toolkit::Text::HorizontalAlignment::Type& alignment )
+bool GetHorizontalAlignmentEnumeration(const Property::Value& propertyValue, Toolkit::Text::HorizontalAlignment::Type& alignment)
{
- return Scripting::GetEnumerationProperty( propertyValue, HORIZONTAL_ALIGNMENT_TYPE_TABLE, HORIZONTAL_ALIGNMENT_TYPE_TABLE_COUNT, alignment );
+ return Scripting::GetEnumerationProperty(propertyValue, HORIZONTAL_ALIGNMENT_TYPE_TABLE, HORIZONTAL_ALIGNMENT_TYPE_TABLE_COUNT, alignment);
}
-bool GetVerticalAlignmentEnumeration( const Property::Value& propertyValue, Toolkit::Text::VerticalAlignment::Type& alignment )
+bool GetVerticalAlignmentEnumeration(const Property::Value& propertyValue, Toolkit::Text::VerticalAlignment::Type& alignment)
{
- return Scripting::GetEnumerationProperty( propertyValue, VERTICAL_ALIGNMENT_TYPE_TABLE, VERTICAL_ALIGNMENT_TYPE_TABLE_COUNT, alignment );
+ return Scripting::GetEnumerationProperty(propertyValue, VERTICAL_ALIGNMENT_TYPE_TABLE, VERTICAL_ALIGNMENT_TYPE_TABLE_COUNT, alignment);
}
-bool GetLineWrapModeEnumeration( const Property::Value& propertyValue, Toolkit::Text::LineWrap::Mode& lineWrapMode )
+bool GetLineWrapModeEnumeration(const Property::Value& propertyValue, Toolkit::Text::LineWrap::Mode& lineWrapMode)
{
- return Scripting::GetEnumerationProperty( propertyValue, LINE_WRAP_MODE_TABLE, LINE_WRAP_MODE_TABLE_COUNT, lineWrapMode );
+ return Scripting::GetEnumerationProperty(propertyValue, LINE_WRAP_MODE_TABLE, LINE_WRAP_MODE_TABLE_COUNT, lineWrapMode);
}
-const char* GetHorizontalAlignmentString( const Toolkit::Text::HorizontalAlignment::Type& alignment )
+const char* GetHorizontalAlignmentString(const Toolkit::Text::HorizontalAlignment::Type& alignment)
{
- return Scripting::GetLinearEnumerationName< Toolkit::Text::HorizontalAlignment::Type >( alignment,
- HORIZONTAL_ALIGNMENT_TYPE_TABLE,
- HORIZONTAL_ALIGNMENT_TYPE_TABLE_COUNT );
+ return Scripting::GetLinearEnumerationName<Toolkit::Text::HorizontalAlignment::Type>(alignment,
+ HORIZONTAL_ALIGNMENT_TYPE_TABLE,
+ HORIZONTAL_ALIGNMENT_TYPE_TABLE_COUNT);
}
-const char* GetVerticalAlignmentString( const Toolkit::Text::VerticalAlignment::Type& alignment )
+const char* GetVerticalAlignmentString(const Toolkit::Text::VerticalAlignment::Type& alignment)
{
- return Scripting::GetLinearEnumerationName< Toolkit::Text::VerticalAlignment::Type >( alignment,
- VERTICAL_ALIGNMENT_TYPE_TABLE,
- VERTICAL_ALIGNMENT_TYPE_TABLE_COUNT );
+ return Scripting::GetLinearEnumerationName<Toolkit::Text::VerticalAlignment::Type>(alignment,
+ VERTICAL_ALIGNMENT_TYPE_TABLE,
+ VERTICAL_ALIGNMENT_TYPE_TABLE_COUNT);
}
} // namespace Text
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/text/property-string-parser.h>
#include <dali-toolkit/internal/text/markup-processor-helper-functions.h>
+#include <dali-toolkit/internal/text/property-string-parser.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
-const std::string STYLE_KEY( "style" );
-const std::string WEIGHT_KEY( "weight" );
-const std::string WIDTH_KEY( "width" );
-const std::string SLANT_KEY( "slant" );
-const std::string FAMILY_KEY( "family" );
-const std::string TYPE_KEY( "type" );
+const std::string STYLE_KEY("style");
+const std::string WEIGHT_KEY("weight");
+const std::string WIDTH_KEY("width");
+const std::string SLANT_KEY("slant");
+const std::string FAMILY_KEY("family");
+const std::string TYPE_KEY("type");
-const std::string SYSTEM_TOKEN( "system" );
+const std::string SYSTEM_TOKEN("system");
} // namespace
-void SetFontFamilyProperty( ControllerPtr controller, const Property::Value& value )
+void SetFontFamilyProperty(ControllerPtr controller, const Property::Value& value)
{
- if( controller )
+ if(controller)
{
const std::string fontFamilyValue = value.Get<std::string>();
- if( fontFamilyValue.empty() )
+ if(fontFamilyValue.empty())
{
// Resets the default's font family name.
- controller->SetDefaultFontFamily( "" );
+ controller->SetDefaultFontFamily("");
return;
}
Property::Map map;
- ParsePropertyString( fontFamilyValue, map );
+ ParsePropertyString(fontFamilyValue, map);
- if( map.Empty() )
+ if(map.Empty())
{
// There is no map. The font has been passed as a font's family name with no format.
- controller->SetDefaultFontFamily( fontFamilyValue );
+ controller->SetDefaultFontFamily(fontFamilyValue);
}
else
{
/// Family key
- Property::Value* familyValue = map.Find( FAMILY_KEY );
+ Property::Value* familyValue = map.Find(FAMILY_KEY);
std::string fontFamilyName;
- if( NULL != familyValue )
+ if(NULL != familyValue)
{
fontFamilyName = familyValue->Get<std::string>();
}
/// Type key
- Property::Value* typeValue = map.Find( TYPE_KEY );
+ Property::Value* typeValue = map.Find(TYPE_KEY);
std::string typeStr;
- if( NULL != typeValue )
+ if(NULL != typeValue)
{
typeStr = typeValue->Get<std::string>();
}
- if( TokenComparison( SYSTEM_TOKEN, typeStr.c_str(), typeStr.size() ) )
+ if(TokenComparison(SYSTEM_TOKEN, typeStr.c_str(), typeStr.size()))
{
- controller->UpdateAfterFontChange( fontFamilyName );
+ controller->UpdateAfterFontChange(fontFamilyName);
}
else
{
- controller->SetDefaultFontFamily( fontFamilyName );
+ controller->SetDefaultFontFamily(fontFamilyName);
}
}
}
}
-void SetFontStyleProperty( ControllerPtr controller, const Property::Value& value, FontStyle::Type type )
+void SetFontStyleProperty(ControllerPtr controller, const Property::Value& value, FontStyle::Type type)
{
- if( controller )
+ if(controller)
{
Property::Map map;
- if( Property::STRING == value.GetType() )
+ if(Property::STRING == value.GetType())
{
const std::string& fontStyleProperties = value.Get<std::string>();
- ParsePropertyString( fontStyleProperties, map );
- controller->FontStyleSetByString( true );
-
+ ParsePropertyString(fontStyleProperties, map);
+ controller->FontStyleSetByString(true);
}
else
{
map = value.Get<Property::Map>();
- controller->FontStyleSetByString( false );
+ controller->FontStyleSetByString(false);
}
- if( !map.Empty() )
+ if(!map.Empty())
{
/// Weight key
- Property::Value* weightValue = map.Find( WEIGHT_KEY );
+ Property::Value* weightValue = map.Find(WEIGHT_KEY);
- FontWeight weight = TextAbstraction::FontWeight::NONE;
+ FontWeight weight = TextAbstraction::FontWeight::NONE;
const bool weightDefined = weightValue != NULL;
- if( weightDefined )
+ if(weightDefined)
{
const std::string weightStr = weightValue->Get<std::string>();
- Scripting::GetEnumeration< FontWeight >( weightStr.c_str(),
- FONT_WEIGHT_STRING_TABLE,
- FONT_WEIGHT_STRING_TABLE_COUNT,
- weight );
+ Scripting::GetEnumeration<FontWeight>(weightStr.c_str(),
+ FONT_WEIGHT_STRING_TABLE,
+ FONT_WEIGHT_STRING_TABLE_COUNT,
+ weight);
}
/// Width key
- Property::Value* widthValue = map.Find( WIDTH_KEY );
+ Property::Value* widthValue = map.Find(WIDTH_KEY);
- FontWidth width = TextAbstraction::FontWidth::NONE;
+ FontWidth width = TextAbstraction::FontWidth::NONE;
const bool widthDefined = widthValue != NULL;
- if( widthDefined )
+ if(widthDefined)
{
const std::string widthStr = widthValue->Get<std::string>();
- Scripting::GetEnumeration< FontWidth >( widthStr.c_str(),
- FONT_WIDTH_STRING_TABLE,
- FONT_WIDTH_STRING_TABLE_COUNT,
- width );
+ Scripting::GetEnumeration<FontWidth>(widthStr.c_str(),
+ FONT_WIDTH_STRING_TABLE,
+ FONT_WIDTH_STRING_TABLE_COUNT,
+ width);
}
/// Slant key
- Property::Value* slantValue = map.Find( SLANT_KEY );
+ Property::Value* slantValue = map.Find(SLANT_KEY);
- FontSlant slant = TextAbstraction::FontSlant::NONE;
+ FontSlant slant = TextAbstraction::FontSlant::NONE;
const bool slantDefined = slantValue != NULL;
- if( slantDefined )
+ if(slantDefined)
{
const std::string slantStr = slantValue->Get<std::string>();
- Scripting::GetEnumeration< FontSlant >( slantStr.c_str(),
- FONT_SLANT_STRING_TABLE,
- FONT_SLANT_STRING_TABLE_COUNT,
- slant );
+ Scripting::GetEnumeration<FontSlant>(slantStr.c_str(),
+ FONT_SLANT_STRING_TABLE,
+ FONT_SLANT_STRING_TABLE_COUNT,
+ slant);
}
- switch( type )
+ switch(type)
{
case FontStyle::DEFAULT:
{
// Sets the default font's style values.
- if( !weightDefined ||
- ( weightDefined && ( controller->GetDefaultFontWeight() != weight ) ) )
+ if(!weightDefined ||
+ (weightDefined && (controller->GetDefaultFontWeight() != weight)))
{
- controller->SetDefaultFontWeight( weight );
+ controller->SetDefaultFontWeight(weight);
}
- if( !widthDefined ||
- ( widthDefined && ( controller->GetDefaultFontWidth() != width ) ) )
+ if(!widthDefined ||
+ (widthDefined && (controller->GetDefaultFontWidth() != width)))
{
- controller->SetDefaultFontWidth( width );
+ controller->SetDefaultFontWidth(width);
}
- if( !slantDefined ||
- ( slantDefined && ( controller->GetDefaultFontSlant() != slant ) ) )
+ if(!slantDefined ||
+ (slantDefined && (controller->GetDefaultFontSlant() != slant)))
{
- controller->SetDefaultFontSlant( slant );
+ controller->SetDefaultFontSlant(slant);
}
break;
}
case FontStyle::INPUT:
{
// Sets the input font's style values.
- if( !weightDefined ||
- ( weightDefined && ( controller->GetInputFontWeight() != weight ) ) )
+ if(!weightDefined ||
+ (weightDefined && (controller->GetInputFontWeight() != weight)))
{
- controller->SetInputFontWeight( weight );
+ controller->SetInputFontWeight(weight);
}
- if( !widthDefined ||
- ( widthDefined && ( controller->GetInputFontWidth() != width ) ) )
+ if(!widthDefined ||
+ (widthDefined && (controller->GetInputFontWidth() != width)))
{
- controller->SetInputFontWidth( width );
+ controller->SetInputFontWidth(width);
}
- if( !slantDefined ||
- ( slantDefined && ( controller->GetInputFontSlant() != slant ) ) )
+ if(!slantDefined ||
+ (slantDefined && (controller->GetInputFontSlant() != slant)))
{
- controller->SetInputFontSlant( slant );
+ controller->SetInputFontSlant(slant);
}
break;
}
case FontStyle::PLACEHOLDER:
{
// Sets the placeholder text font's style values.
- if( !weightDefined ||
- ( weightDefined && ( controller->GetPlaceholderTextFontWeight() != weight ) ) )
+ if(!weightDefined ||
+ (weightDefined && (controller->GetPlaceholderTextFontWeight() != weight)))
{
- controller->SetPlaceholderTextFontWeight( weight );
+ controller->SetPlaceholderTextFontWeight(weight);
}
- if( !widthDefined ||
- ( widthDefined && ( controller->GetPlaceholderTextFontWidth() != width ) ) )
+ if(!widthDefined ||
+ (widthDefined && (controller->GetPlaceholderTextFontWidth() != width)))
{
- controller->SetPlaceholderTextFontWidth( width );
+ controller->SetPlaceholderTextFontWidth(width);
}
- if( !slantDefined ||
- ( slantDefined && ( controller->GetPlaceholderTextFontSlant() != slant ) ) )
+ if(!slantDefined ||
+ (slantDefined && (controller->GetPlaceholderTextFontSlant() != slant)))
{
- controller->SetPlaceholderTextFontSlant( slant );
+ controller->SetPlaceholderTextFontSlant(slant);
}
break;
}
} // switch
- } // map not empty
+ } // map not empty
else
{
- switch( type )
+ switch(type)
{
case FontStyle::DEFAULT:
{
- controller->SetDefaultFontWeight( TextAbstraction::FontWeight::NONE );
- controller->SetDefaultFontWidth( TextAbstraction::FontWidth::NONE );
- controller->SetDefaultFontSlant( TextAbstraction::FontSlant::NONE );
+ controller->SetDefaultFontWeight(TextAbstraction::FontWeight::NONE);
+ controller->SetDefaultFontWidth(TextAbstraction::FontWidth::NONE);
+ controller->SetDefaultFontSlant(TextAbstraction::FontSlant::NONE);
break;
}
case FontStyle::INPUT:
{
- controller->SetInputFontWeight( TextAbstraction::FontWeight::NONE );
- controller->SetInputFontWidth( TextAbstraction::FontWidth::NONE );
- controller->SetInputFontSlant( TextAbstraction::FontSlant::NONE );
+ controller->SetInputFontWeight(TextAbstraction::FontWeight::NONE);
+ controller->SetInputFontWidth(TextAbstraction::FontWidth::NONE);
+ controller->SetInputFontSlant(TextAbstraction::FontSlant::NONE);
break;
}
case FontStyle::PLACEHOLDER:
{
- controller->SetPlaceholderTextFontWeight( TextAbstraction::FontWeight::NONE );
- controller->SetPlaceholderTextFontWidth( TextAbstraction::FontWidth::NONE );
- controller->SetPlaceholderTextFontSlant( TextAbstraction::FontSlant::NONE );
+ controller->SetPlaceholderTextFontWeight(TextAbstraction::FontWeight::NONE);
+ controller->SetPlaceholderTextFontWidth(TextAbstraction::FontWidth::NONE);
+ controller->SetPlaceholderTextFontSlant(TextAbstraction::FontSlant::NONE);
break;
}
} // switch
- } // map.Empty()
- } // controller
+ } // map.Empty()
+ } // controller
}
-void GetFontStyleProperty( ControllerPtr controller, Property::Value& value, FontStyle::Type type )
+void GetFontStyleProperty(ControllerPtr controller, Property::Value& value, FontStyle::Type type)
{
- if( controller )
+ if(controller)
{
const bool isSetbyString = controller->IsFontStyleSetByString();
- bool weightDefined = false;
- bool widthDefined = false;
- bool slantDefined = false;
- FontWeight weight = TextAbstraction::FontWeight::NONE;
- FontWidth width = TextAbstraction::FontWidth::NONE;
- FontSlant slant = TextAbstraction::FontSlant::NONE;
+ bool weightDefined = false;
+ bool widthDefined = false;
+ bool slantDefined = false;
+ FontWeight weight = TextAbstraction::FontWeight::NONE;
+ FontWidth width = TextAbstraction::FontWidth::NONE;
+ FontSlant slant = TextAbstraction::FontSlant::NONE;
- switch( type )
+ switch(type)
{
case FontStyle::DEFAULT:
{
weightDefined = controller->IsDefaultFontWeightDefined();
- widthDefined = controller->IsDefaultFontWidthDefined();
- slantDefined = controller->IsDefaultFontSlantDefined();
+ widthDefined = controller->IsDefaultFontWidthDefined();
+ slantDefined = controller->IsDefaultFontSlantDefined();
- if( weightDefined )
+ if(weightDefined)
{
weight = controller->GetDefaultFontWeight();
}
- if( widthDefined )
+ if(widthDefined)
{
width = controller->GetDefaultFontWidth();
}
- if( slantDefined )
+ if(slantDefined)
{
slant = controller->GetDefaultFontSlant();
}
case FontStyle::INPUT:
{
weightDefined = controller->IsInputFontWeightDefined();
- widthDefined = controller->IsInputFontWidthDefined();
- slantDefined = controller->IsInputFontSlantDefined();
+ widthDefined = controller->IsInputFontWidthDefined();
+ slantDefined = controller->IsInputFontSlantDefined();
- if( weightDefined )
+ if(weightDefined)
{
weight = controller->GetInputFontWeight();
}
- if( widthDefined )
+ if(widthDefined)
{
width = controller->GetInputFontWidth();
}
- if( slantDefined )
+ if(slantDefined)
{
slant = controller->GetInputFontSlant();
}
{
// The type is FontStyle::PLACEHOLDER
weightDefined = controller->IsPlaceholderTextFontWeightDefined();
- widthDefined = controller->IsPlaceholderTextFontWidthDefined();
- slantDefined = controller->IsPlaceholderTextFontSlantDefined();
+ widthDefined = controller->IsPlaceholderTextFontWidthDefined();
+ slantDefined = controller->IsPlaceholderTextFontSlantDefined();
- if( weightDefined )
+ if(weightDefined)
{
weight = controller->GetPlaceholderTextFontWeight();
}
- if( widthDefined )
+ if(widthDefined)
{
width = controller->GetPlaceholderTextFontWidth();
}
- if( slantDefined )
+ if(slantDefined)
{
slant = controller->GetPlaceholderTextFontSlant();
}
}
}
- if( !isSetbyString )
+ if(!isSetbyString)
{
Property::Map map;
- if( weightDefined )
+ if(weightDefined)
{
- if( TextAbstraction::FontWeight::NONE != weight )
+ if(TextAbstraction::FontWeight::NONE != weight)
{
- const std::string weightStr( GetEnumerationName( weight,
- FONT_WEIGHT_STRING_TABLE,
- FONT_WEIGHT_STRING_TABLE_COUNT ) );
+ const std::string weightStr(GetEnumerationName(weight,
+ FONT_WEIGHT_STRING_TABLE,
+ FONT_WEIGHT_STRING_TABLE_COUNT));
- map.Insert( WEIGHT_KEY, weightStr );
+ map.Insert(WEIGHT_KEY, weightStr);
}
}
- if( widthDefined )
+ if(widthDefined)
{
- if( TextAbstraction::FontWidth::NONE != width )
+ if(TextAbstraction::FontWidth::NONE != width)
{
- const std::string widthStr( GetEnumerationName( width,
- FONT_WIDTH_STRING_TABLE,
- FONT_WIDTH_STRING_TABLE_COUNT ) );
+ const std::string widthStr(GetEnumerationName(width,
+ FONT_WIDTH_STRING_TABLE,
+ FONT_WIDTH_STRING_TABLE_COUNT));
- map.Insert( WIDTH_KEY, widthStr );
+ map.Insert(WIDTH_KEY, widthStr);
}
}
- if( slantDefined )
+ if(slantDefined)
{
- if( TextAbstraction::FontSlant::NONE != slant )
+ if(TextAbstraction::FontSlant::NONE != slant)
{
- const std::string slantStr( GetEnumerationName( slant,
- FONT_SLANT_STRING_TABLE,
- FONT_SLANT_STRING_TABLE_COUNT ) );
+ const std::string slantStr(GetEnumerationName(slant,
+ FONT_SLANT_STRING_TABLE,
+ FONT_SLANT_STRING_TABLE_COUNT));
- map.Insert( SLANT_KEY, slantStr );
+ map.Insert(SLANT_KEY, slantStr);
}
}
{
std::string fontStyleProperties = "{";
- if( weightDefined )
+ if(weightDefined)
{
- if( TextAbstraction::FontWeight::NONE != weight )
+ if(TextAbstraction::FontWeight::NONE != weight)
{
- const std::string weightStr( GetEnumerationName( weight,
- FONT_WEIGHT_STRING_TABLE,
- FONT_WEIGHT_STRING_TABLE_COUNT ) );
+ const std::string weightStr(GetEnumerationName(weight,
+ FONT_WEIGHT_STRING_TABLE,
+ FONT_WEIGHT_STRING_TABLE_COUNT));
fontStyleProperties += "\"weight\":\"" + weightStr + "\",";
}
}
- if( widthDefined )
+ if(widthDefined)
{
- if( TextAbstraction::FontWidth::NONE != width )
+ if(TextAbstraction::FontWidth::NONE != width)
{
- const std::string widthStr( GetEnumerationName( width,
- FONT_WIDTH_STRING_TABLE,
- FONT_WIDTH_STRING_TABLE_COUNT ) );
+ const std::string widthStr(GetEnumerationName(width,
+ FONT_WIDTH_STRING_TABLE,
+ FONT_WIDTH_STRING_TABLE_COUNT));
fontStyleProperties += "\"width\":\"" + widthStr + "\",";
}
}
- if( slantDefined )
+ if(slantDefined)
{
- if( TextAbstraction::FontSlant::NONE != slant )
+ if(TextAbstraction::FontSlant::NONE != slant)
{
- const std::string slantStr( GetEnumerationName( slant,
- FONT_SLANT_STRING_TABLE,
- FONT_SLANT_STRING_TABLE_COUNT ) );
+ const std::string slantStr(GetEnumerationName(slant,
+ FONT_SLANT_STRING_TABLE,
+ FONT_SLANT_STRING_TABLE_COUNT));
fontStyleProperties += "\"slant\":\"" + slantStr + "\"";
}
}
// If last character is comma, it will be removed.
- if((*fontStyleProperties.rbegin()) == ',' )
+ if((*fontStyleProperties.rbegin()) == ',')
{
- fontStyleProperties = fontStyleProperties.substr( 0, fontStyleProperties.size()-1 );
+ fontStyleProperties = fontStyleProperties.substr(0, fontStyleProperties.size() - 1);
}
fontStyleProperties += "}";
value = fontStyleProperties;
} // SetbyString
- }// controller
+ } // controller
}
-FontWeight StringToWeight( const char* const weightStr )
+FontWeight StringToWeight(const char* const weightStr)
{
FontWeight weight = TextAbstraction::FontWeight::NORMAL;
- Scripting::GetEnumeration<FontWeight>( weightStr,
- FONT_WEIGHT_STRING_TABLE,
- FONT_WEIGHT_STRING_TABLE_COUNT,
- weight );
+ Scripting::GetEnumeration<FontWeight>(weightStr,
+ FONT_WEIGHT_STRING_TABLE,
+ FONT_WEIGHT_STRING_TABLE_COUNT,
+ weight);
return weight;
}
-FontWidth StringToWidth( const char* const widthStr )
+FontWidth StringToWidth(const char* const widthStr)
{
FontWidth width = TextAbstraction::FontWidth::NORMAL;
- Scripting::GetEnumeration<FontWidth>( widthStr,
- FONT_WIDTH_STRING_TABLE,
- FONT_WIDTH_STRING_TABLE_COUNT,
- width );
+ Scripting::GetEnumeration<FontWidth>(widthStr,
+ FONT_WIDTH_STRING_TABLE,
+ FONT_WIDTH_STRING_TABLE_COUNT,
+ width);
return width;
}
-FontSlant StringToSlant( const char* const slantStr )
+FontSlant StringToSlant(const char* const slantStr)
{
FontSlant slant = TextAbstraction::FontSlant::NORMAL;
- Scripting::GetEnumeration<FontSlant>( slantStr,
- FONT_SLANT_STRING_TABLE,
- FONT_SLANT_STRING_TABLE_COUNT,
- slant );
+ Scripting::GetEnumeration<FontSlant>(slantStr,
+ FONT_SLANT_STRING_TABLE,
+ FONT_SLANT_STRING_TABLE_COUNT,
+ slant);
return slant;
}
#include <dali-toolkit/internal/text/text-io.h>
// EXTERNAL INCLUDES
-#include <iostream>
#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali/devel-api/text-abstraction/script.h>
+#include <iostream>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
-std::ostream& operator<< (std::ostream& o, const Vector<Character>& text)
+std::ostream& operator<<(std::ostream& o, const Vector<Character>& text)
{
o << std::hex;
- for( unsigned int i=0; i<text.Count(); ++i )
+ for(unsigned int i = 0; i < text.Count(); ++i)
{
o << text[i];
- if( i+1 < text.Count() )
+ if(i + 1 < text.Count())
{
o << " ";
}
return o << std::dec;
}
-std::ostream& operator<< (std::ostream& o, const Vector<ScriptRun>& scriptRun)
+std::ostream& operator<<(std::ostream& o, const Vector<ScriptRun>& scriptRun)
{
- for( unsigned int i=0; i<scriptRun.Count(); ++i )
+ for(unsigned int i = 0; i < scriptRun.Count(); ++i)
{
// e.g. Print "0->9: LATIN" for a ten character run staring from beginning of the model
- o << scriptRun[i].characterRun.characterIndex << "->" << (scriptRun[i].characterRun.characterIndex + scriptRun[i].characterRun.numberOfCharacters ) << ": ";
+ o << scriptRun[i].characterRun.characterIndex << "->" << (scriptRun[i].characterRun.characterIndex + scriptRun[i].characterRun.numberOfCharacters) << ": ";
o << TextAbstraction::ScriptName[scriptRun[i].script];
- if( i+1 < scriptRun.Count() )
+ if(i + 1 < scriptRun.Count())
{
o << ", ";
}
return o << std::dec;
}
-std::ostream& operator<< (std::ostream& o, const Vector<FontRun>& fontRun)
+std::ostream& operator<<(std::ostream& o, const Vector<FontRun>& fontRun)
{
TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
- for( unsigned int i=0; i<fontRun.Count(); ++i )
+ for(unsigned int i = 0; i < fontRun.Count(); ++i)
{
// e.g. Print "0->9: ID:1 TizenSansKorean style:Regular size:10.0" for a ten character run staring from beginning of the model
- o << fontRun[i].characterRun.characterIndex << "->" << (fontRun[i].characterRun.characterIndex + fontRun[i].characterRun.numberOfCharacters ) << ": ";
+ o << fontRun[i].characterRun.characterIndex << "->" << (fontRun[i].characterRun.characterIndex + fontRun[i].characterRun.numberOfCharacters) << ": ";
- FontId id = fontRun[i].fontId;
+ FontId id = fontRun[i].fontId;
TextAbstraction::FontDescription fontDescription;
- fontClient.GetDescription( id, fontDescription );
- o << "ID:" << id << ", " << fontDescription.family << " width: " << fontDescription.width << " weight: " << fontDescription.weight << " slant: " << fontDescription.slant << " size:" << (fontClient.GetPointSize(id) / 64);
+ fontClient.GetDescription(id, fontDescription);
+ o << "ID:" << id << ", " << fontDescription.family << " width: " << fontDescription.width << " weight: " << fontDescription.weight << " slant: " << fontDescription.slant << " size:" << (fontClient.GetPointSize(id) / 64);
- if( i+1 < fontRun.Count() )
+ if(i + 1 < fontRun.Count())
{
o << ", ";
}
return o << std::dec;
}
-std::ostream& operator<< (std::ostream& o, const Vector<LineRun>& lineRuns)
+std::ostream& operator<<(std::ostream& o, const Vector<LineRun>& lineRuns)
{
- for( unsigned int i=0; i<lineRuns.Count(); ++i )
+ for(unsigned int i = 0; i < lineRuns.Count(); ++i)
{
// e.g. Print "Line 0 Glyphs: 0->9 Characters: 0->9 (10)" for a ten character run staring from beginning of the model
- o << "Line " << i << " Glyphs: " << lineRuns[i].glyphRun.glyphIndex << "->" << (lineRuns[i].glyphRun.glyphIndex + lineRuns[i].glyphRun.numberOfGlyphs );
- o << " Characters: " << lineRuns[i].characterRun.characterIndex << "->" << (lineRuns[i].characterRun.characterIndex + lineRuns[i].characterRun.numberOfCharacters );
+ o << "Line " << i << " Glyphs: " << lineRuns[i].glyphRun.glyphIndex << "->" << (lineRuns[i].glyphRun.glyphIndex + lineRuns[i].glyphRun.numberOfGlyphs);
+ o << " Characters: " << lineRuns[i].characterRun.characterIndex << "->" << (lineRuns[i].characterRun.characterIndex + lineRuns[i].characterRun.numberOfCharacters);
o << " Width: " << lineRuns[i].width;
o << " Ascender: " << lineRuns[i].ascender;
o << " Descender: " << lineRuns[i].descender;
- if( i+1 < lineRuns.Count() )
+ if(i + 1 < lineRuns.Count())
{
o << ", ";
}
/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
ModelPtr Model::New()
{
- return ModelPtr( new Model() );
+ return ModelPtr(new Model());
}
const Size& Model::GetControlSize() const
return mVisualModel->GetNumberOfUnderlineRuns();
}
-void Model::GetUnderlineRuns( GlyphRun* underlineRuns, UnderlineRunIndex index, Length numberOfRuns ) const
+void Model::GetUnderlineRuns(GlyphRun* underlineRuns, UnderlineRunIndex index, Length numberOfRuns) const
{
- mVisualModel->GetUnderlineRuns( underlineRuns, index, numberOfRuns );
+ mVisualModel->GetUnderlineRuns(underlineRuns, index, numberOfRuns);
}
const Vector4& Model::GetOutlineColor() const
mVisualModel(),
mScrollPosition(),
mScrollPositionLast(),
- mHorizontalAlignment( Text::HorizontalAlignment::BEGIN ),
- mVerticalAlignment( Text::VerticalAlignment::TOP ),
- mVerticalLineAlignment( DevelText::VerticalLineAlignment::TOP ),
- mLineWrapMode( Text::LineWrap::WORD ),
- mAlignmentOffset( 0.0f ),
- mElideEnabled( false ),
- mIgnoreSpacesAfterText( true ),
- mMatchSystemLanguageDirection( false )
+ mHorizontalAlignment(Text::HorizontalAlignment::BEGIN),
+ mVerticalAlignment(Text::VerticalAlignment::TOP),
+ mVerticalLineAlignment(DevelText::VerticalLineAlignment::TOP),
+ mLineWrapMode(Text::LineWrap::WORD),
+ mAlignmentOffset(0.0f),
+ mElideEnabled(false),
+ mIgnoreSpacesAfterText(true),
+ mMatchSystemLanguageDirection(false)
{
mLogicalModel = LogicalModel::New();
- mVisualModel = VisualModel::New();
+ mVisualModel = VisualModel::New();
}
Model::~Model()
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/text/text-scroller-interface.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/text/text-scroller-interface.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace
{
-
-#if defined ( DEBUG_ENABLED )
- Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_SCROLLING");
+#if defined(DEBUG_ENABLED)
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_SCROLLING");
#endif
const int MINIMUM_SCROLL_SPEED = 1; // Speed should be set by Property system.
* 1) The alignment value of the text label (Use Text::HorizontalAlignment enumerations).
* 2) The text direction, i.e. whether it's LTR or RTL (0 = LTR, 1 = RTL).
*/
-const float HORIZONTAL_ALIGNMENT_TABLE[ Text::HorizontalAlignment::END+1 ][ 2 ] =
-{
- // HorizontalAlignment::BEGIN
+const float HORIZONTAL_ALIGNMENT_TABLE[Text::HorizontalAlignment::END + 1][2] =
{
- -0.5f, // LTR
- 0.5f // RTL
- },
+ // HorizontalAlignment::BEGIN
+ {
+ -0.5f, // LTR
+ 0.5f // RTL
+ },
- // HorizontalAlignment::CENTER
- {
- 0.0f, // LTR
- 0.0f // RTL
- },
+ // HorizontalAlignment::CENTER
+ {
+ 0.0f, // LTR
+ 0.0f // RTL
+ },
- // HorizontalAlignment::END
- {
- 0.5f, // LTR
- -0.5f // RTL
- }
-};
+ // HorizontalAlignment::END
+ {
+ 0.5f, // LTR
+ -0.5f // RTL
+ }};
/**
* @brief How the text should be aligned vertically when scrolling the text.
* -0.5f aligns the text to the top, 0.0f aligns the text to the center, 0.5f aligns the text to the bottom.
* The alignment depends on the alignment value of the text label (Use Text::VerticalAlignment enumerations).
*/
-const float VERTICAL_ALIGNMENT_TABLE[ Text::VerticalAlignment::BOTTOM+1 ] =
-{
- -0.5f, // VerticalAlignment::TOP
- 0.0f, // VerticalAlignment::CENTER
- 0.5f // VerticalAlignment::BOTTOM
+const float VERTICAL_ALIGNMENT_TABLE[Text::VerticalAlignment::BOTTOM + 1] =
+ {
+ -0.5f, // VerticalAlignment::TOP
+ 0.0f, // VerticalAlignment::CENTER
+ 0.5f // VerticalAlignment::BOTTOM
};
} // namespace
namespace Text
{
-
-TextScrollerPtr TextScroller::New( ScrollerInterface& scrollerInterface )
+TextScrollerPtr TextScroller::New(ScrollerInterface& scrollerInterface)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::New\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::New\n");
- TextScrollerPtr textScroller( new TextScroller( scrollerInterface) );
+ TextScrollerPtr textScroller(new TextScroller(scrollerInterface));
return textScroller;
}
-void TextScroller::SetGap( int gap )
+void TextScroller::SetGap(int gap)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetGap gap[%d]\n", gap );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetGap gap[%d]\n", gap);
mWrapGap = static_cast<float>(gap);
}
return static_cast<int>(mWrapGap);
}
-void TextScroller::SetSpeed( int scrollSpeed )
+void TextScroller::SetSpeed(int scrollSpeed)
{
- mScrollSpeed = std::max( MINIMUM_SCROLL_SPEED, scrollSpeed );
+ mScrollSpeed = std::max(MINIMUM_SCROLL_SPEED, scrollSpeed);
}
int TextScroller::GetSpeed() const
return mScrollSpeed;
}
-void TextScroller::SetLoopCount( int loopCount )
+void TextScroller::SetLoopCount(int loopCount)
{
- if ( loopCount >= 0 )
+ if(loopCount >= 0)
{
mLoopCount = loopCount;
}
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetLoopCount [%d] Status[%s]\n", mLoopCount, (loopCount)?"looping":"stop" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetLoopCount [%d] Status[%s]\n", mLoopCount, (loopCount) ? "looping" : "stop");
}
int TextScroller::GetLoopCount() const
return mLoopCount;
}
-void TextScroller::SetLoopDelay( float delay )
+void TextScroller::SetLoopDelay(float delay)
{
mLoopDelay = delay;
}
return mLoopDelay;
}
-void TextScroller::SetStopMode( TextLabel::AutoScrollStopMode::Type stopMode )
+void TextScroller::SetStopMode(TextLabel::AutoScrollStopMode::Type stopMode)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetAutoScrollStopMode [%s]\n",(stopMode == TextLabel::AutoScrollStopMode::IMMEDIATE)?"IMMEDIATE":"FINISH_LOOP" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetAutoScrollStopMode [%s]\n", (stopMode == TextLabel::AutoScrollStopMode::IMMEDIATE) ? "IMMEDIATE" : "FINISH_LOOP");
mStopMode = stopMode;
}
void TextScroller::StopScrolling()
{
- if ( mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING )
+ if(mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING)
{
- switch( mStopMode )
+ switch(mStopMode)
{
case TextLabel::AutoScrollStopMode::IMMEDIATE:
{
}
case TextLabel::AutoScrollStopMode::FINISH_LOOP:
{
- mScrollAnimation.SetLoopCount( 1 ); // As animation already playing this allows the current animation to finish instead of trying to stop mid-way
+ mScrollAnimation.SetLoopCount(1); // As animation already playing this allows the current animation to finish instead of trying to stop mid-way
break;
}
default:
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Undifined AutoScrollStopMode\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Undifined AutoScrollStopMode\n");
}
}
}
return mStopMode;
}
-TextScroller::TextScroller( ScrollerInterface& scrollerInterface )
-: mScrollerInterface( scrollerInterface ),
- mScrollDeltaIndex( Property::INVALID_INDEX ),
- mScrollSpeed( MINIMUM_SCROLL_SPEED ),
- mLoopCount( 1 ),
- mLoopDelay( 0.0f ),
- mWrapGap( 0.0f ),
- mStopMode( TextLabel::AutoScrollStopMode::FINISH_LOOP )
+TextScroller::TextScroller(ScrollerInterface& scrollerInterface)
+: mScrollerInterface(scrollerInterface),
+ mScrollDeltaIndex(Property::INVALID_INDEX),
+ mScrollSpeed(MINIMUM_SCROLL_SPEED),
+ mLoopCount(1),
+ mLoopDelay(0.0f),
+ mWrapGap(0.0f),
+ mStopMode(TextLabel::AutoScrollStopMode::FINISH_LOOP)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller Default Constructor\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller Default Constructor\n");
}
TextScroller::~TextScroller()
{
}
-void TextScroller::SetParameters( Actor scrollingTextActor, Renderer renderer, TextureSet textureSet, const Size& controlSize, const Size& textureSize, const float wrapGap, CharacterDirection direction, HorizontalAlignment::Type horizontalAlignment, VerticalAlignment::Type verticalAlignment )
+void TextScroller::SetParameters(Actor scrollingTextActor, Renderer renderer, TextureSet textureSet, const Size& controlSize, const Size& textureSize, const float wrapGap, CharacterDirection direction, HorizontalAlignment::Type horizontalAlignment, VerticalAlignment::Type verticalAlignment)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters controlSize[%f,%f] textureSize[%f,%f] direction[%d]\n",
- controlSize.x, controlSize.y, textureSize.x, textureSize.y, direction );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetParameters controlSize[%f,%f] textureSize[%f,%f] direction[%d]\n", controlSize.x, controlSize.y, textureSize.x, textureSize.y, direction);
mRenderer = renderer;
float animationProgress = 0.0f;
- int remainedLoop = mLoopCount;
- if ( mScrollAnimation )
+ int remainedLoop = mLoopCount;
+ if(mScrollAnimation)
{
- if( mScrollAnimation.GetState() == Animation::PLAYING )
+ if(mScrollAnimation.GetState() == Animation::PLAYING)
{
animationProgress = mScrollAnimation.GetCurrentProgress();
- if( mLoopCount > 0 ) // If not a ininity loop, then calculate remained loop
+ if(mLoopCount > 0) // If not a ininity loop, then calculate remained loop
{
- remainedLoop = mLoopCount - ( mScrollAnimation.GetCurrentLoop() );
- remainedLoop = ( remainedLoop <= 0 ? 1 : remainedLoop );
+ remainedLoop = mLoopCount - (mScrollAnimation.GetCurrentLoop());
+ remainedLoop = (remainedLoop <= 0 ? 1 : remainedLoop);
}
}
mScrollAnimation.Clear();
// Reset to the original shader and texture before scrolling
mRenderer.SetShader(mShader);
- if( mTextureSet )
+ if(mTextureSet)
{
- mRenderer.SetTextures( mTextureSet );
+ mRenderer.SetTextures(mTextureSet);
}
}
- mShader = mRenderer.GetShader();
+ mShader = mRenderer.GetShader();
mTextureSet = mRenderer.GetTextures();
// Set the shader and texture for scrolling
- Shader shader = Shader::New( SHADER_TEXT_SCROLLER_SHADER_VERT, SHADER_TEXT_SCROLLER_SHADER_FRAG, Shader::Hint::NONE );
- mRenderer.SetShader( shader );
- mRenderer.SetTextures( textureSet );
+ Shader shader = Shader::New(SHADER_TEXT_SCROLLER_SHADER_VERT, SHADER_TEXT_SCROLLER_SHADER_FRAG, Shader::Hint::NONE);
+ mRenderer.SetShader(shader);
+ mRenderer.SetTextures(textureSet);
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters wrapGap[%f]\n", wrapGap );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetParameters wrapGap[%f]\n", wrapGap);
float horizontalAlign;
- if( textureSize.x > controlSize.x )
+ if(textureSize.x > controlSize.x)
{
// if Text is elided, scroll should start at the begin of text.
- horizontalAlign = HORIZONTAL_ALIGNMENT_TABLE[HorizontalAlignment::BEGIN][ direction ];
+ horizontalAlign = HORIZONTAL_ALIGNMENT_TABLE[HorizontalAlignment::BEGIN][direction];
}
else
{
- horizontalAlign = HORIZONTAL_ALIGNMENT_TABLE[ horizontalAlignment ][ direction ];
+ horizontalAlign = HORIZONTAL_ALIGNMENT_TABLE[horizontalAlignment][direction];
}
- const float verticalAlign = VERTICAL_ALIGNMENT_TABLE[ verticalAlignment ];
+ const float verticalAlign = VERTICAL_ALIGNMENT_TABLE[verticalAlignment];
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters horizontalAlign[%f], verticalAlign[%f]\n", horizontalAlign, verticalAlign );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetParameters horizontalAlign[%f], verticalAlign[%f]\n", horizontalAlign, verticalAlign);
- shader.RegisterProperty( "uTextureSize", textureSize );
- shader.RegisterProperty( "uHorizontalAlign", horizontalAlign );
- shader.RegisterProperty( "uVerticalAlign", verticalAlign );
- shader.RegisterProperty( "uGap", wrapGap );
- mScrollDeltaIndex = shader.RegisterProperty( "uDelta", 0.0f );
+ shader.RegisterProperty("uTextureSize", textureSize);
+ shader.RegisterProperty("uHorizontalAlign", horizontalAlign);
+ shader.RegisterProperty("uVerticalAlign", verticalAlign);
+ shader.RegisterProperty("uGap", wrapGap);
+ mScrollDeltaIndex = shader.RegisterProperty("uDelta", 0.0f);
- float scrollAmount = std::max( textureSize.width, controlSize.width );
- float scrollDuration = scrollAmount / mScrollSpeed;
+ float scrollAmount = std::max(textureSize.width, controlSize.width);
+ float scrollDuration = scrollAmount / mScrollSpeed;
- if ( direction )
+ if(direction)
{
- scrollAmount = -scrollAmount; // reverse direction of scrolling
+ scrollAmount = -scrollAmount; // reverse direction of scrolling
}
- StartScrolling( scrollingTextActor, scrollAmount, scrollDuration, remainedLoop );
+ StartScrolling(scrollingTextActor, scrollAmount, scrollDuration, remainedLoop);
mScrollAnimation.SetCurrentProgress(animationProgress);
}
-void TextScroller::AutoScrollAnimationFinished( Dali::Animation& animation )
+void TextScroller::AutoScrollAnimationFinished(Dali::Animation& animation)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::AutoScrollAnimationFinished\n" );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::AutoScrollAnimationFinished\n");
mScrollerInterface.ScrollingFinished();
// Revert to the original shader and texture after scrolling
mRenderer.SetShader(mShader);
- if ( mTextureSet )
+ if(mTextureSet)
{
- mRenderer.SetTextures( mTextureSet );
+ mRenderer.SetTextures(mTextureSet);
}
}
-void TextScroller::StartScrolling( Actor scrollingTextActor, float scrollAmount, float scrollDuration, int loopCount )
+void TextScroller::StartScrolling(Actor scrollingTextActor, float scrollAmount, float scrollDuration, int loopCount)
{
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::StartScrolling scrollAmount[%f] scrollDuration[%f], loop[%d] speed[%d]\n", scrollAmount, scrollDuration, loopCount, mScrollSpeed );
-
- Shader shader = mRenderer.GetShader();
- mScrollAnimation = Animation::New( scrollDuration );
- mScrollAnimation.AnimateTo( Property( shader, mScrollDeltaIndex ), scrollAmount, TimePeriod( mLoopDelay, scrollDuration ) );
- mScrollAnimation.SetEndAction( Animation::DISCARD );
- mScrollAnimation.SetLoopCount( loopCount );
- mScrollAnimation.FinishedSignal().Connect( this, &TextScroller::AutoScrollAnimationFinished );
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::StartScrolling scrollAmount[%f] scrollDuration[%f], loop[%d] speed[%d]\n", scrollAmount, scrollDuration, loopCount, mScrollSpeed);
+
+ Shader shader = mRenderer.GetShader();
+ mScrollAnimation = Animation::New(scrollDuration);
+ mScrollAnimation.AnimateTo(Property(shader, mScrollDeltaIndex), scrollAmount, TimePeriod(mLoopDelay, scrollDuration));
+ mScrollAnimation.SetEndAction(Animation::DISCARD);
+ mScrollAnimation.SetLoopCount(loopCount);
+ mScrollAnimation.FinishedSignal().Connect(this, &TextScroller::AutoScrollAnimationFinished);
mScrollAnimation.Play();
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace
{
-
/**
* @brief Struct used to calculate the selection box.
*/
Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS");
#endif
-const float MAX_FLOAT = std::numeric_limits<float>::max();
-const float MIN_FLOAT = std::numeric_limits<float>::min();
-const Dali::Toolkit::Text::CharacterDirection LTR = false; ///< Left To Right direction
+const float MAX_FLOAT = std::numeric_limits<float>::max();
+const float MIN_FLOAT = std::numeric_limits<float>::min();
+const Dali::Toolkit::Text::CharacterDirection LTR = false; ///< Left To Right direction
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
void SelectionHandleController::Reposition(Controller::Impl& impl)
{
EventData*& eventData = impl.mEventData;
CharacterIndex selectionStart = eventData->mLeftSelectionPosition;
- CharacterIndex selectionEnd = eventData->mRightSelectionPosition;
+ CharacterIndex selectionEnd = eventData->mRightSelectionPosition;
DecoratorPtr& decorator = eventData->mDecorator;
- if( selectionStart == selectionEnd )
+ if(selectionStart == selectionEnd)
{
// Nothing to select if handles are in the same place.
// So, deactive Highlight box.
- decorator->SetHighlightActive( false );
+ decorator->SetHighlightActive(false);
return;
}
decorator->ClearHighlights();
- ModelPtr& model = impl.mModel;
- VisualModelPtr& visualModel = model->mVisualModel;
+ ModelPtr& model = impl.mModel;
+ VisualModelPtr& visualModel = model->mVisualModel;
LogicalModelPtr& logicalModel = model->mLogicalModel;
- const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin();
- const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin();
- const GlyphInfo* const glyphsBuffer = visualModel->mGlyphs.Begin();
- const Vector2* const positionsBuffer = visualModel->mGlyphPositions.Begin();
- const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin();
- const CharacterIndex* const glyphToCharacterBuffer = visualModel->mGlyphsToCharacters.Begin();
- const CharacterDirection* const modelCharacterDirectionsBuffer = ( 0u != logicalModel->mCharacterDirections.Count() ) ? logicalModel->mCharacterDirections.Begin() : NULL;
+ const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin();
+ const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin();
+ const GlyphInfo* const glyphsBuffer = visualModel->mGlyphs.Begin();
+ const Vector2* const positionsBuffer = visualModel->mGlyphPositions.Begin();
+ const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin();
+ const CharacterIndex* const glyphToCharacterBuffer = visualModel->mGlyphsToCharacters.Begin();
+ const CharacterDirection* const modelCharacterDirectionsBuffer = (0u != logicalModel->mCharacterDirections.Count()) ? logicalModel->mCharacterDirections.Begin() : NULL;
- const bool isLastCharacter = selectionEnd >= logicalModel->mText.Count();
- const CharacterDirection startDirection = ( ( NULL == modelCharacterDirectionsBuffer ) ? false : *( modelCharacterDirectionsBuffer + selectionStart ) );
- const CharacterDirection endDirection = ( ( NULL == modelCharacterDirectionsBuffer ) ? false : *( modelCharacterDirectionsBuffer + ( selectionEnd - ( isLastCharacter ? 1u : 0u ) ) ) );
+ const bool isLastCharacter = selectionEnd >= logicalModel->mText.Count();
+ const CharacterDirection startDirection = ((NULL == modelCharacterDirectionsBuffer) ? false : *(modelCharacterDirectionsBuffer + selectionStart));
+ const CharacterDirection endDirection = ((NULL == modelCharacterDirectionsBuffer) ? false : *(modelCharacterDirectionsBuffer + (selectionEnd - (isLastCharacter ? 1u : 0u))));
// Swap the indices if the start is greater than the end.
const bool indicesSwapped = selectionStart > selectionEnd;
// Tell the decorator to flip the selection handles if needed.
- decorator->SetSelectionHandleFlipState( indicesSwapped, startDirection, endDirection );
+ decorator->SetSelectionHandleFlipState(indicesSwapped, startDirection, endDirection);
- if( indicesSwapped )
+ if(indicesSwapped)
{
- std::swap( selectionStart, selectionEnd );
+ std::swap(selectionStart, selectionEnd);
}
// Get the indices to the first and last selected glyphs.
const CharacterIndex selectionEndMinusOne = selectionEnd - 1u;
- const GlyphIndex glyphStart = *( charactersToGlyphBuffer + selectionStart );
- const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + selectionEndMinusOne );
- const GlyphIndex glyphEnd = *( charactersToGlyphBuffer + selectionEndMinusOne ) + ( ( numberOfGlyphs > 0 ) ? numberOfGlyphs - 1u : 0u );
+ const GlyphIndex glyphStart = *(charactersToGlyphBuffer + selectionStart);
+ const Length numberOfGlyphs = *(glyphsPerCharacterBuffer + selectionEndMinusOne);
+ const GlyphIndex glyphEnd = *(charactersToGlyphBuffer + selectionEndMinusOne) + ((numberOfGlyphs > 0) ? numberOfGlyphs - 1u : 0u);
// Get the lines where the glyphs are laid-out.
const LineRun* lineRun = visualModel->mLines.Begin();
- LineIndex lineIndex = 0u;
- Length numberOfLines = 0u;
- visualModel->GetNumberOfLines( glyphStart,
- 1u + glyphEnd - glyphStart,
- lineIndex,
- numberOfLines );
+ LineIndex lineIndex = 0u;
+ Length numberOfLines = 0u;
+ visualModel->GetNumberOfLines(glyphStart,
+ 1u + glyphEnd - glyphStart,
+ lineIndex,
+ numberOfLines);
const LineIndex firstLineIndex = lineIndex;
// Create the structure to store some selection box info.
Vector<SelectionBoxInfo> selectionBoxLinesInfo;
- selectionBoxLinesInfo.Resize( numberOfLines );
+ selectionBoxLinesInfo.Resize(numberOfLines);
SelectionBoxInfo* selectionBoxInfo = selectionBoxLinesInfo.Begin();
- selectionBoxInfo->minX = MAX_FLOAT;
- selectionBoxInfo->maxX = MIN_FLOAT;
+ selectionBoxInfo->minX = MAX_FLOAT;
+ selectionBoxInfo->maxX = MIN_FLOAT;
// Keep the min and max 'x' position to calculate the size and position of the highlighed text.
- float minHighlightX = std::numeric_limits<float>::max();
- float maxHighlightX = std::numeric_limits<float>::min();
- Size highLightSize;
+ float minHighlightX = std::numeric_limits<float>::max();
+ float maxHighlightX = std::numeric_limits<float>::min();
+ Size highLightSize;
Vector2 highLightPosition; // The highlight position in decorator's coords.
// Retrieve the first line and get the line's vertical offset, the line's height and the index to the last glyph.
// The line's vertical offset of all the lines before the line where the first glyph is laid-out.
- selectionBoxInfo->lineOffset = CalculateLineOffset( visualModel->mLines,
- firstLineIndex );
+ selectionBoxInfo->lineOffset = CalculateLineOffset(visualModel->mLines,
+ firstLineIndex);
// Transform to decorator's (control) coords.
selectionBoxInfo->lineOffset += model->mScrollPosition.y;
GlyphIndex lastGlyphOfLine = lineRun->glyphRun.glyphIndex + lineRun->glyphRun.numberOfGlyphs - 1u;
// Check if the first glyph is a ligature that must be broken like Latin ff, fi, or Arabic ﻻ, etc which needs special code.
- const Length numberOfCharactersStart = *( charactersPerGlyphBuffer + glyphStart );
- bool splitStartGlyph = ( numberOfCharactersStart > 1u ) && HasLigatureMustBreak( logicalModel->GetScript( selectionStart ) );
+ const Length numberOfCharactersStart = *(charactersPerGlyphBuffer + glyphStart);
+ bool splitStartGlyph = (numberOfCharactersStart > 1u) && HasLigatureMustBreak(logicalModel->GetScript(selectionStart));
// Check if the last glyph is a ligature that must be broken like Latin ff, fi, or Arabic ﻻ, etc which needs special code.
- const Length numberOfCharactersEnd = *( charactersPerGlyphBuffer + glyphEnd );
- bool splitEndGlyph = ( glyphStart != glyphEnd ) && ( numberOfCharactersEnd > 1u ) && HasLigatureMustBreak( logicalModel->GetScript( selectionEndMinusOne ) );
+ const Length numberOfCharactersEnd = *(charactersPerGlyphBuffer + glyphEnd);
+ bool splitEndGlyph = (glyphStart != glyphEnd) && (numberOfCharactersEnd > 1u) && HasLigatureMustBreak(logicalModel->GetScript(selectionEndMinusOne));
// The number of quads of the selection box.
- const unsigned int numberOfQuads = 1u + ( glyphEnd - glyphStart ) + ( ( numberOfLines > 1u ) ? 2u * numberOfLines : 0u );
- decorator->ResizeHighlightQuads( numberOfQuads );
+ const unsigned int numberOfQuads = 1u + (glyphEnd - glyphStart) + ((numberOfLines > 1u) ? 2u * numberOfLines : 0u);
+ decorator->ResizeHighlightQuads(numberOfQuads);
// Count the actual number of quads.
unsigned int actualNumberOfQuads = 0u;
- Vector4 quad;
+ Vector4 quad;
// Traverse the glyphs.
- for( GlyphIndex index = glyphStart; index <= glyphEnd; ++index )
+ for(GlyphIndex index = glyphStart; index <= glyphEnd; ++index)
{
- const GlyphInfo& glyph = *( glyphsBuffer + index );
- const Vector2& position = *( positionsBuffer + index );
+ const GlyphInfo& glyph = *(glyphsBuffer + index);
+ const Vector2& position = *(positionsBuffer + index);
- if( splitStartGlyph )
+ if(splitStartGlyph)
{
// If the first glyph is a ligature that must be broken it may be needed to add only part of the glyph to the highlight box.
- const float glyphAdvance = glyph.advance / static_cast<float>( numberOfCharactersStart );
- const CharacterIndex interGlyphIndex = selectionStart - *( glyphToCharacterBuffer + glyphStart );
+ const float glyphAdvance = glyph.advance / static_cast<float>(numberOfCharactersStart);
+ const CharacterIndex interGlyphIndex = selectionStart - *(glyphToCharacterBuffer + glyphStart);
// Get the direction of the character.
CharacterDirection isCurrentRightToLeft = false;
- if( nullptr != modelCharacterDirectionsBuffer ) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right.
+ if(nullptr != modelCharacterDirectionsBuffer) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right.
{
- isCurrentRightToLeft = *( modelCharacterDirectionsBuffer + selectionStart );
+ isCurrentRightToLeft = *(modelCharacterDirectionsBuffer + selectionStart);
}
// The end point could be in the middle of the ligature.
// Calculate the number of characters selected.
- const Length numberOfCharacters = ( glyphStart == glyphEnd ) ? ( selectionEnd - selectionStart ) : ( numberOfCharactersStart - interGlyphIndex );
+ const Length numberOfCharacters = (glyphStart == glyphEnd) ? (selectionEnd - selectionStart) : (numberOfCharactersStart - interGlyphIndex);
- quad.x = lineRun->alignmentOffset + position.x - glyph.xBearing + model->mScrollPosition.x + glyphAdvance * static_cast<float>( isCurrentRightToLeft ? ( numberOfCharactersStart - interGlyphIndex - numberOfCharacters ) : interGlyphIndex );
+ quad.x = lineRun->alignmentOffset + position.x - glyph.xBearing + model->mScrollPosition.x + glyphAdvance * static_cast<float>(isCurrentRightToLeft ? (numberOfCharactersStart - interGlyphIndex - numberOfCharacters) : interGlyphIndex);
quad.y = selectionBoxInfo->lineOffset;
- quad.z = quad.x + static_cast<float>( numberOfCharacters ) * glyphAdvance;
+ quad.z = quad.x + static_cast<float>(numberOfCharacters) * glyphAdvance;
quad.w = selectionBoxInfo->lineOffset + selectionBoxInfo->lineHeight;
// Store the min and max 'x' for each line.
- selectionBoxInfo->minX = std::min( selectionBoxInfo->minX, quad.x );
- selectionBoxInfo->maxX = std::max( selectionBoxInfo->maxX, quad.z );
+ selectionBoxInfo->minX = std::min(selectionBoxInfo->minX, quad.x);
+ selectionBoxInfo->maxX = std::max(selectionBoxInfo->maxX, quad.z);
- decorator->AddHighlight( actualNumberOfQuads, quad );
+ decorator->AddHighlight(actualNumberOfQuads, quad);
++actualNumberOfQuads;
splitStartGlyph = false;
continue;
}
- if( splitEndGlyph && ( index == glyphEnd ) )
+ if(splitEndGlyph && (index == glyphEnd))
{
// Equally, if the last glyph is a ligature that must be broken it may be needed to add only part of the glyph to the highlight box.
- const float glyphAdvance = glyph.advance / static_cast<float>( numberOfCharactersEnd );
- const CharacterIndex interGlyphIndex = selectionEnd - *( glyphToCharacterBuffer + glyphEnd );
+ const float glyphAdvance = glyph.advance / static_cast<float>(numberOfCharactersEnd);
+ const CharacterIndex interGlyphIndex = selectionEnd - *(glyphToCharacterBuffer + glyphEnd);
// Get the direction of the character.
CharacterDirection isCurrentRightToLeft = false;
- if( nullptr != modelCharacterDirectionsBuffer ) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right.
+ if(nullptr != modelCharacterDirectionsBuffer) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right.
{
- isCurrentRightToLeft = *( modelCharacterDirectionsBuffer + selectionEnd );
+ isCurrentRightToLeft = *(modelCharacterDirectionsBuffer + selectionEnd);
}
const Length numberOfCharacters = numberOfCharactersEnd - interGlyphIndex;
- quad.x = lineRun->alignmentOffset + position.x - glyph.xBearing + model->mScrollPosition.x + ( isCurrentRightToLeft ? ( glyphAdvance * static_cast<float>( numberOfCharacters ) ) : 0.f );
+ quad.x = lineRun->alignmentOffset + position.x - glyph.xBearing + model->mScrollPosition.x + (isCurrentRightToLeft ? (glyphAdvance * static_cast<float>(numberOfCharacters)) : 0.f);
quad.y = selectionBoxInfo->lineOffset;
- quad.z = quad.x + static_cast<float>( interGlyphIndex ) * glyphAdvance;
+ quad.z = quad.x + static_cast<float>(interGlyphIndex) * glyphAdvance;
quad.w = quad.y + selectionBoxInfo->lineHeight;
// Store the min and max 'x' for each line.
- selectionBoxInfo->minX = std::min( selectionBoxInfo->minX, quad.x );
- selectionBoxInfo->maxX = std::max( selectionBoxInfo->maxX, quad.z );
+ selectionBoxInfo->minX = std::min(selectionBoxInfo->minX, quad.x);
+ selectionBoxInfo->maxX = std::max(selectionBoxInfo->maxX, quad.z);
- decorator->AddHighlight( actualNumberOfQuads,
- quad );
+ decorator->AddHighlight(actualNumberOfQuads,
+ quad);
++actualNumberOfQuads;
splitEndGlyph = false;
quad.w = quad.y + selectionBoxInfo->lineHeight;
// Store the min and max 'x' for each line.
- selectionBoxInfo->minX = std::min( selectionBoxInfo->minX, quad.x );
- selectionBoxInfo->maxX = std::max( selectionBoxInfo->maxX, quad.z );
+ selectionBoxInfo->minX = std::min(selectionBoxInfo->minX, quad.x);
+ selectionBoxInfo->maxX = std::max(selectionBoxInfo->maxX, quad.z);
- decorator->AddHighlight( actualNumberOfQuads,
- quad );
+ decorator->AddHighlight(actualNumberOfQuads,
+ quad);
++actualNumberOfQuads;
// Whether to retrieve the next line.
- if( index == lastGlyphOfLine )
+ if(index == lastGlyphOfLine)
{
++lineIndex;
- if( lineIndex < firstLineIndex + numberOfLines )
+ if(lineIndex < firstLineIndex + numberOfLines)
{
// Retrieve the next line.
++lineRun;
// Traverses all the lines and updates the min and max 'x' positions and the total height.
// The final width is calculated after 'boxifying' the selection.
- for( Vector<SelectionBoxInfo>::ConstIterator it = selectionBoxLinesInfo.Begin(),
- endIt = selectionBoxLinesInfo.End();
- it != endIt;
- ++it )
+ for(Vector<SelectionBoxInfo>::ConstIterator it = selectionBoxLinesInfo.Begin(),
+ endIt = selectionBoxLinesInfo.End();
+ it != endIt;
+ ++it)
{
const SelectionBoxInfo& info = *it;
// Update the size of the highlighted text.
highLightSize.height += info.lineHeight;
- minHighlightX = std::min( minHighlightX, info.minX );
- maxHighlightX = std::max( maxHighlightX, info.maxX );
+ minHighlightX = std::min(minHighlightX, info.minX);
+ maxHighlightX = std::max(maxHighlightX, info.maxX);
}
// Add extra geometry to 'boxify' the selection.
- if( 1u < numberOfLines )
+ if(1u < numberOfLines)
{
// Boxify the first line.
- lineRun = visualModel->mLines.Begin() + firstLineIndex;
- const SelectionBoxInfo& firstSelectionBoxLineInfo = *( selectionBoxLinesInfo.Begin() );
+ lineRun = visualModel->mLines.Begin() + firstLineIndex;
+ const SelectionBoxInfo& firstSelectionBoxLineInfo = *(selectionBoxLinesInfo.Begin());
- bool boxifyBegin = ( LTR != lineRun->direction ) && ( LTR != startDirection );
- bool boxifyEnd = ( LTR == lineRun->direction ) && ( LTR == startDirection );
+ bool boxifyBegin = (LTR != lineRun->direction) && (LTR != startDirection);
+ bool boxifyEnd = (LTR == lineRun->direction) && (LTR == startDirection);
- if( boxifyBegin )
+ if(boxifyBegin)
{
quad.x = 0.f;
quad.y = firstSelectionBoxLineInfo.lineOffset;
quad.w = firstSelectionBoxLineInfo.lineOffset + firstSelectionBoxLineInfo.lineHeight;
// Boxify at the beginning of the line.
- decorator->AddHighlight( actualNumberOfQuads,
- quad );
+ decorator->AddHighlight(actualNumberOfQuads,
+ quad);
++actualNumberOfQuads;
// Update the size of the highlighted text.
minHighlightX = 0.f;
}
- if( boxifyEnd )
+ if(boxifyEnd)
{
quad.x = firstSelectionBoxLineInfo.maxX;
quad.y = firstSelectionBoxLineInfo.lineOffset;
quad.w = firstSelectionBoxLineInfo.lineOffset + firstSelectionBoxLineInfo.lineHeight;
// Boxify at the end of the line.
- decorator->AddHighlight( actualNumberOfQuads,
- quad );
+ decorator->AddHighlight(actualNumberOfQuads,
+ quad);
++actualNumberOfQuads;
// Update the size of the highlighted text.
}
// Boxify the central lines.
- if( 2u < numberOfLines )
+ if(2u < numberOfLines)
{
- for( Vector<SelectionBoxInfo>::ConstIterator it = selectionBoxLinesInfo.Begin() + 1u,
- endIt = selectionBoxLinesInfo.End() - 1u;
- it != endIt;
- ++it )
+ for(Vector<SelectionBoxInfo>::ConstIterator it = selectionBoxLinesInfo.Begin() + 1u,
+ endIt = selectionBoxLinesInfo.End() - 1u;
+ it != endIt;
+ ++it)
{
const SelectionBoxInfo& info = *it;
quad.z = info.minX;
quad.w = info.lineOffset + info.lineHeight;
- decorator->AddHighlight( actualNumberOfQuads,
- quad );
+ decorator->AddHighlight(actualNumberOfQuads,
+ quad);
++actualNumberOfQuads;
quad.x = info.maxX;
quad.z = visualModel->mControlSize.width;
quad.w = info.lineOffset + info.lineHeight;
- decorator->AddHighlight( actualNumberOfQuads,
- quad );
+ decorator->AddHighlight(actualNumberOfQuads,
+ quad);
++actualNumberOfQuads;
}
}
// Boxify the last line.
- lineRun = visualModel->mLines.Begin() + firstLineIndex + numberOfLines - 1u;
- const SelectionBoxInfo& lastSelectionBoxLineInfo = *( selectionBoxLinesInfo.End() - 1u );
+ lineRun = visualModel->mLines.Begin() + firstLineIndex + numberOfLines - 1u;
+ const SelectionBoxInfo& lastSelectionBoxLineInfo = *(selectionBoxLinesInfo.End() - 1u);
- boxifyBegin = ( LTR == lineRun->direction ) && ( LTR == endDirection );
- boxifyEnd = ( LTR != lineRun->direction ) && ( LTR != endDirection );
+ boxifyBegin = (LTR == lineRun->direction) && (LTR == endDirection);
+ boxifyEnd = (LTR != lineRun->direction) && (LTR != endDirection);
- if( boxifyBegin )
+ if(boxifyBegin)
{
quad.x = 0.f;
quad.y = lastSelectionBoxLineInfo.lineOffset;
quad.w = lastSelectionBoxLineInfo.lineOffset + lastSelectionBoxLineInfo.lineHeight;
// Boxify at the beginning of the line.
- decorator->AddHighlight( actualNumberOfQuads,
- quad );
+ decorator->AddHighlight(actualNumberOfQuads,
+ quad);
++actualNumberOfQuads;
// Update the size of the highlighted text.
minHighlightX = 0.f;
}
- if( boxifyEnd )
+ if(boxifyEnd)
{
quad.x = lastSelectionBoxLineInfo.maxX;
quad.y = lastSelectionBoxLineInfo.lineOffset;
}
// Set the actual number of quads.
- decorator->ResizeHighlightQuads( actualNumberOfQuads );
+ decorator->ResizeHighlightQuads(actualNumberOfQuads);
// Sets the highlight's size and position. In decorator's coords.
// The highlight's height has been calculated above (before 'boxifying' the highlight).
highLightSize.width = maxHighlightX - minHighlightX;
- highLightPosition.x = minHighlightX;
- const SelectionBoxInfo& firstSelectionBoxLineInfo = *( selectionBoxLinesInfo.Begin() );
- highLightPosition.y = firstSelectionBoxLineInfo.lineOffset;
+ highLightPosition.x = minHighlightX;
+ const SelectionBoxInfo& firstSelectionBoxLineInfo = *(selectionBoxLinesInfo.Begin());
+ highLightPosition.y = firstSelectionBoxLineInfo.lineOffset;
- decorator->SetHighLightBox( highLightPosition, highLightSize, static_cast<float>( model->GetOutlineWidth() ) );
+ decorator->SetHighLightBox(highLightPosition, highLightSize, static_cast<float>(model->GetOutlineWidth()));
- if( !decorator->IsSmoothHandlePanEnabled() )
+ if(!decorator->IsSmoothHandlePanEnabled())
{
CursorInfo primaryCursorInfo;
impl.GetCursorPosition(eventData->mLeftSelectionPosition, primaryCursorInfo);
decorator->SetPosition(LEFT_SELECTION_HANDLE,
primaryPosition.x,
primaryCursorInfo.lineOffset + model->mScrollPosition.y,
- primaryCursorInfo.lineHeight );
+ primaryCursorInfo.lineHeight);
CursorInfo secondaryCursorInfo;
impl.GetCursorPosition(eventData->mRightSelectionPosition, secondaryCursorInfo);
decorator->SetPosition(RIGHT_SELECTION_HANDLE,
secondaryPosition.x,
secondaryCursorInfo.lineOffset + model->mScrollPosition.y,
- secondaryCursorInfo.lineHeight );
+ secondaryCursorInfo.lineHeight);
}
// Set the flag to update the decorator.
return;
}
- ModelPtr& model = impl.mModel;
- VisualModelPtr& visualModel = model->mVisualModel;
- const Length numberOfGlyphs = visualModel->mGlyphs.Count();
- const Length numberOfLines = visualModel->mLines.Count();
- if( ( 0 == numberOfGlyphs ) ||
- ( 0 == numberOfLines ) )
+ ModelPtr& model = impl.mModel;
+ VisualModelPtr& visualModel = model->mVisualModel;
+ const Length numberOfGlyphs = visualModel->mGlyphs.Count();
+ const Length numberOfLines = visualModel->mLines.Count();
+ if((0 == numberOfGlyphs) ||
+ (0 == numberOfLines))
{
// Nothing to do if there is no text.
return;
}
// Find which word was selected
- CharacterIndex selectionStart( 0 );
- CharacterIndex selectionEnd( 0 );
- CharacterIndex noTextHitIndex( 0 );
- const bool characterHit = FindSelectionIndices( visualModel,
- model->mLogicalModel,
- impl.mMetrics,
- visualX,
- visualY,
- selectionStart,
- selectionEnd,
- noTextHitIndex );
- DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%p selectionStart %d selectionEnd %d\n", &impl, selectionStart, selectionEnd );
-
- if( characterHit || ( Controller::NoTextTap::HIGHLIGHT == action ) )
+ CharacterIndex selectionStart(0);
+ CharacterIndex selectionEnd(0);
+ CharacterIndex noTextHitIndex(0);
+ const bool characterHit = FindSelectionIndices(visualModel,
+ model->mLogicalModel,
+ impl.mMetrics,
+ visualX,
+ visualY,
+ selectionStart,
+ selectionEnd,
+ noTextHitIndex);
+ DALI_LOG_INFO(gLogFilter, Debug::Verbose, "%p selectionStart %d selectionEnd %d\n", &impl, selectionStart, selectionEnd);
+
+ if(characterHit || (Controller::NoTextTap::HIGHLIGHT == action))
{
- impl.ChangeState( EventData::SELECTING );
+ impl.ChangeState(EventData::SELECTING);
- eventData->mLeftSelectionPosition = selectionStart;
+ eventData->mLeftSelectionPosition = selectionStart;
eventData->mRightSelectionPosition = selectionEnd;
- eventData->mUpdateLeftSelectionPosition = true;
+ eventData->mUpdateLeftSelectionPosition = true;
eventData->mUpdateRightSelectionPosition = true;
- eventData->mUpdateHighlightBox = true;
+ eventData->mUpdateHighlightBox = true;
// It may happen an InputMethodContext commit event arrives before the selection event
// if the InputMethodContext is in pre-edit state. The commit event will set the
// to false, the highlight box won't be updated.
eventData->mUpdateCursorPosition = false;
- eventData->mScrollAfterUpdatePosition = ( eventData->mLeftSelectionPosition != eventData->mRightSelectionPosition );
+ eventData->mScrollAfterUpdatePosition = (eventData->mLeftSelectionPosition != eventData->mRightSelectionPosition);
// Cursor to be positioned at end of selection so if selection interrupted and edit mode restarted the cursor will be at end of selection
- eventData->mPrimaryCursorPosition = std::max( eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition );
+ eventData->mPrimaryCursorPosition = std::max(eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition);
}
- else if( Controller::NoTextTap::SHOW_SELECTION_POPUP == action )
+ else if(Controller::NoTextTap::SHOW_SELECTION_POPUP == action)
{
// Nothing to select. i.e. a white space, out of bounds
- impl.ChangeState( EventData::EDITING_WITH_POPUP );
+ impl.ChangeState(EventData::EDITING_WITH_POPUP);
eventData->mPrimaryCursorPosition = noTextHitIndex;
- eventData->mUpdateCursorPosition = true;
- eventData->mUpdateGrabHandlePosition = true;
+ eventData->mUpdateCursorPosition = true;
+ eventData->mUpdateGrabHandlePosition = true;
eventData->mScrollAfterUpdatePosition = true;
- eventData->mUpdateInputStyle = true;
+ eventData->mUpdateInputStyle = true;
}
- else if( Controller::NoTextTap::NO_ACTION == action )
+ else if(Controller::NoTextTap::NO_ACTION == action)
{
// Nothing to select. i.e. a white space, out of bounds
eventData->mPrimaryCursorPosition = noTextHitIndex;
- eventData->mUpdateCursorPosition = true;
- eventData->mUpdateGrabHandlePosition = true;
+ eventData->mUpdateCursorPosition = true;
+ eventData->mUpdateGrabHandlePosition = true;
eventData->mScrollAfterUpdatePosition = true;
- eventData->mUpdateInputStyle = true;
+ eventData->mUpdateInputStyle = true;
}
}
void SelectionHandleController::Update(Controller::Impl& impl, HandleType handleType, const CursorInfo& cursorInfo)
{
- if( ( LEFT_SELECTION_HANDLE != handleType ) &&
- ( RIGHT_SELECTION_HANDLE != handleType ) )
+ if((LEFT_SELECTION_HANDLE != handleType) &&
+ (RIGHT_SELECTION_HANDLE != handleType))
{
return;
}
- ModelPtr& model = impl.mModel;
+ ModelPtr& model = impl.mModel;
const Vector2 cursorPosition = cursorInfo.primaryPosition + model->mScrollPosition;
// Sets the handle's position.
eventData->mDecorator->SetPosition(handleType,
cursorPosition.x,
cursorInfo.lineOffset + model->mScrollPosition.y,
- cursorInfo.lineHeight );
+ cursorInfo.lineHeight);
// If selection handle at start of the text and other at end of the text then all text is selected.
- const CharacterIndex startOfSelection = std::min( eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition );
- const CharacterIndex endOfSelection = std::max ( eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition );
- eventData->mAllTextSelected = ( startOfSelection == 0 ) && ( endOfSelection == model->mLogicalModel->mText.Count() );
+ const CharacterIndex startOfSelection = std::min(eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition);
+ const CharacterIndex endOfSelection = std::max(eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition);
+ eventData->mAllTextSelected = (startOfSelection == 0) && (endOfSelection == model->mLogicalModel->mText.Count());
}
} // namespace Text
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace
{
-
-const float DEFAULT_VERTICAL_SCROLL_DURATION(0.15f); ///< Duration to complete scroll animation
+const float DEFAULT_VERTICAL_SCROLL_DURATION(0.15f); ///< Duration to complete scroll animation
} // namespace
namespace Text
{
-
TextVerticalScrollerPtr TextVerticalScroller::New()
{
- TextVerticalScrollerPtr textScroller( new TextVerticalScroller() );
+ TextVerticalScrollerPtr textScroller(new TextVerticalScroller());
return textScroller;
}
TextVerticalScroller::TextVerticalScroller()
-: mDuration( DEFAULT_VERTICAL_SCROLL_DURATION ),
- mScrollTo( 0.0f )
+: mDuration(DEFAULT_VERTICAL_SCROLL_DURATION),
+ mScrollTo(0.0f)
{
}
{
}
-void TextVerticalScroller::CheckStartAnimation( Actor& sourceActor, float x, float y, float scrollAmount )
+void TextVerticalScroller::CheckStartAnimation(Actor& sourceActor, float x, float y, float scrollAmount)
{
- if ( Equals( scrollAmount, 0.0f, Math::MACHINE_EPSILON_1 ) )
+ if(Equals(scrollAmount, 0.0f, Math::MACHINE_EPSILON_1))
{
// scroll animation isn't required, set position only
- if( mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING )
+ if(mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING)
{
mScrollAnimation.Clear();
}
- sourceActor.SetProperty( Actor::Property::POSITION, Vector2( x, y ));
+ sourceActor.SetProperty(Actor::Property::POSITION, Vector2(x, y));
return;
}
float toY = y + scrollAmount;
// Either actor or scroll area is changed, so restart animation
- if( mScrollAnimation )
+ if(mScrollAnimation)
{
mScrollAnimation.Clear();
}
else
{
// Create animation at first
- mScrollAnimation = Animation::New( mDuration );
+ mScrollAnimation = Animation::New(mDuration);
}
mScrollingActor = sourceActor;
- mScrollTo = toY;
+ mScrollTo = toY;
// Set animation attribute
- sourceActor.SetProperty( Actor::Property::POSITION, Vector2( x, y ));
- mScrollAnimation.AnimateTo( Property(sourceActor, Actor::Property::POSITION_Y), mScrollTo, AlphaFunction::EASE_OUT_SINE );
+ sourceActor.SetProperty(Actor::Property::POSITION, Vector2(x, y));
+ mScrollAnimation.AnimateTo(Property(sourceActor, Actor::Property::POSITION_Y), mScrollTo, AlphaFunction::EASE_OUT_SINE);
mScrollAnimation.Play();
}
-void TextVerticalScroller::SetDuration( float duration )
+void TextVerticalScroller::SetDuration(float duration)
{
mDuration = duration;
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
ViewInterface::ViewInterface()
{
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/text/text-view.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/math/vector2.h>
#include <dali/devel-api/text-abstraction/font-client.h>
+#include <dali/public-api/math/vector2.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
struct View::Impl
{
- VisualModelPtr mVisualModel;
+ VisualModelPtr mVisualModel;
TextAbstraction::FontClient mFontClient; ///< Handle to the font client.
};
View::View()
-: mImpl( NULL )
+: mImpl(NULL)
{
mImpl = new View::Impl();
delete mImpl;
}
-void View::SetVisualModel( VisualModelPtr visualModel )
+void View::SetVisualModel(VisualModelPtr visualModel)
{
mImpl->mVisualModel = visualModel;
}
const Vector2& View::GetControlSize() const
{
- if ( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->mControlSize;
}
const Vector2& View::GetLayoutSize() const
{
- if ( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetLayoutSize();
}
Length View::GetNumberOfGlyphs() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
const VisualModel& model = *mImpl->mVisualModel;
- const Length glyphCount = model.mGlyphs.Count();
+ const Length glyphCount = model.mGlyphs.Count();
const Length positionCount = model.mGlyphPositions.Count();
- DALI_ASSERT_DEBUG( positionCount <= glyphCount && "Invalid glyph positions in Model" );
+ DALI_ASSERT_DEBUG(positionCount <= glyphCount && "Invalid glyph positions in Model");
return (positionCount < glyphCount) ? positionCount : glyphCount;
}
return 0;
}
-Length View::GetGlyphs( GlyphInfo* glyphs,
- Vector2* glyphPositions,
- float& minLineOffset,
- GlyphIndex glyphIndex,
- Length numberOfGlyphs ) const
+Length View::GetGlyphs(GlyphInfo* glyphs,
+ Vector2* glyphPositions,
+ float& minLineOffset,
+ GlyphIndex glyphIndex,
+ Length numberOfGlyphs) const
{
Length numberOfLaidOutGlyphs = 0u;
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
// If ellipsis is enabled, the number of glyphs the layout engine has laid out may be less than 'numberOfGlyphs'.
// Check the last laid out line to know if the layout engine elided some text.
const Length numberOfLines = mImpl->mVisualModel->mLines.Count();
- if( numberOfLines > 0u )
+ if(numberOfLines > 0u)
{
- const LineRun& lastLine = *( mImpl->mVisualModel->mLines.Begin() + ( numberOfLines - 1u ) );
+ const LineRun& lastLine = *(mImpl->mVisualModel->mLines.Begin() + (numberOfLines - 1u));
// If ellipsis is enabled, calculate the number of laid out glyphs.
// Otherwise use the given number of glyphs.
- if( lastLine.ellipsis )
+ if(lastLine.ellipsis)
{
numberOfLaidOutGlyphs = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs;
}
numberOfLaidOutGlyphs = numberOfGlyphs;
}
- if( 0u < numberOfLaidOutGlyphs )
+ if(0u < numberOfLaidOutGlyphs)
{
// Retrieve from the visual model the glyphs and positions.
- mImpl->mVisualModel->GetGlyphs( glyphs,
- glyphIndex,
- numberOfLaidOutGlyphs );
+ mImpl->mVisualModel->GetGlyphs(glyphs,
+ glyphIndex,
+ numberOfLaidOutGlyphs);
- mImpl->mVisualModel->GetGlyphPositions( glyphPositions,
- glyphIndex,
- numberOfLaidOutGlyphs );
+ mImpl->mVisualModel->GetGlyphPositions(glyphPositions,
+ glyphIndex,
+ numberOfLaidOutGlyphs);
// Get the lines for the given range of glyphs.
// The lines contain the alignment offset which needs to be added to the glyph's position.
- LineIndex firstLine = 0u;
- Length numberOfLines = 0u;
- mImpl->mVisualModel->GetNumberOfLines( glyphIndex,
- numberOfLaidOutGlyphs,
- firstLine,
- numberOfLines );
+ LineIndex firstLine = 0u;
+ Length numberOfLines = 0u;
+ mImpl->mVisualModel->GetNumberOfLines(glyphIndex,
+ numberOfLaidOutGlyphs,
+ firstLine,
+ numberOfLines);
Vector<LineRun> lines;
- lines.Resize( numberOfLines );
+ lines.Resize(numberOfLines);
LineRun* lineBuffer = lines.Begin();
- mImpl->mVisualModel->GetLinesOfGlyphRange( lineBuffer,
- glyphIndex,
- numberOfLaidOutGlyphs );
+ mImpl->mVisualModel->GetLinesOfGlyphRange(lineBuffer,
+ glyphIndex,
+ numberOfLaidOutGlyphs);
// Get the first line for the given glyph range.
LineIndex lineIndex = firstLine;
- LineRun* line = lineBuffer + lineIndex;
+ LineRun* line = lineBuffer + lineIndex;
// Index of the last glyph of the line.
GlyphIndex lastGlyphIndexOfLine = line->glyphRun.glyphIndex + line->glyphRun.numberOfGlyphs - 1u;
// Add the alignment offset to the glyph's position.
minLineOffset = line->alignmentOffset;
- float penY = line->ascender;
- for( Length index = 0u; index < numberOfLaidOutGlyphs; ++index )
+ float penY = line->ascender;
+ for(Length index = 0u; index < numberOfLaidOutGlyphs; ++index)
{
- Vector2& position = *( glyphPositions + index );
+ Vector2& position = *(glyphPositions + index);
position.x += line->alignmentOffset;
position.y += penY;
- if( lastGlyphIndexOfLine == index )
+ if(lastGlyphIndexOfLine == index)
{
penY += -line->descender;
// Get the next line.
++lineIndex;
- if( lineIndex < numberOfLines )
+ if(lineIndex < numberOfLines)
{
- line = lineBuffer + lineIndex;
- minLineOffset = std::min( minLineOffset, line->alignmentOffset );
+ line = lineBuffer + lineIndex;
+ minLineOffset = std::min(minLineOffset, line->alignmentOffset);
lastGlyphIndexOfLine = line->glyphRun.glyphIndex + line->glyphRun.numberOfGlyphs - 1u;
}
}
- if( 1u == numberOfLaidOutGlyphs )
+ if(1u == numberOfLaidOutGlyphs)
{
// not a point try to do ellipsis with only one laid out character.
return numberOfLaidOutGlyphs;
}
- if( lastLine.ellipsis )
+ if(lastLine.ellipsis)
{
- if( ( 1u == numberOfLines ) &&
- ( lastLine.ascender - lastLine.descender > mImpl->mVisualModel->mControlSize.height ) )
+ if((1u == numberOfLines) &&
+ (lastLine.ascender - lastLine.descender > mImpl->mVisualModel->mControlSize.height))
{
// Get the first glyph which is going to be replaced and the ellipsis glyph.
- GlyphInfo& glyphInfo = *glyphs;
- const GlyphInfo& ellipsisGlyph = mImpl->mFontClient.GetEllipsisGlyph( mImpl->mFontClient.GetPointSize( glyphInfo.fontId ) );
+ GlyphInfo& glyphInfo = *glyphs;
+ const GlyphInfo& ellipsisGlyph = mImpl->mFontClient.GetEllipsisGlyph(mImpl->mFontClient.GetPointSize(glyphInfo.fontId));
// Change the 'x' and 'y' position of the ellipsis glyph.
Vector2& position = *glyphPositions;
- position.x = ellipsisGlyph.xBearing;
- position.y = mImpl->mVisualModel->mControlSize.height - ellipsisGlyph.yBearing;
+ position.x = ellipsisGlyph.xBearing;
+ position.y = mImpl->mVisualModel->mControlSize.height - ellipsisGlyph.yBearing;
// Replace the glyph by the ellipsis glyph.
glyphInfo = ellipsisGlyph;
- return 1u;
+ return 1u;
}
// firstPenX, penY and firstPenSet are used to position the ellipsis glyph if needed.
- float firstPenX = 0.f; // Used if rtl text is elided.
- float penY = 0.f;
- bool firstPenSet = false;
+ float firstPenX = 0.f; // Used if rtl text is elided.
+ float penY = 0.f;
+ bool firstPenSet = false;
// Add the ellipsis glyph.
- bool inserted = false;
- float removedGlypsWidth = 0.f;
- Length numberOfRemovedGlyphs = 0u;
- GlyphIndex index = numberOfLaidOutGlyphs - 1u;
+ bool inserted = false;
+ float removedGlypsWidth = 0.f;
+ Length numberOfRemovedGlyphs = 0u;
+ GlyphIndex index = numberOfLaidOutGlyphs - 1u;
// The ellipsis glyph has to fit in the place where the last glyph(s) is(are) removed.
- while( !inserted )
+ while(!inserted)
{
- const GlyphInfo& glyphToRemove = *( glyphs + index );
+ const GlyphInfo& glyphToRemove = *(glyphs + index);
- if( 0u != glyphToRemove.fontId )
+ if(0u != glyphToRemove.fontId)
{
// i.e. The font id of the glyph shaped from the '\n' character is zero.
// Need to reshape the glyph as the font may be different in size.
- const GlyphInfo& ellipsisGlyph = mImpl->mFontClient.GetEllipsisGlyph( mImpl->mFontClient.GetPointSize( glyphToRemove.fontId ) );
+ const GlyphInfo& ellipsisGlyph = mImpl->mFontClient.GetEllipsisGlyph(mImpl->mFontClient.GetPointSize(glyphToRemove.fontId));
- if( !firstPenSet )
+ if(!firstPenSet)
{
- const Vector2& position = *( glyphPositions + index );
+ const Vector2& position = *(glyphPositions + index);
// Calculates the penY of the current line. It will be used to position the ellipsis glyph.
penY = position.y + glyphToRemove.yBearing;
// Calculates the first penX which will be used if rtl text is elided.
firstPenX = position.x - glyphToRemove.xBearing;
- if( firstPenX < -ellipsisGlyph.xBearing )
+ if(firstPenX < -ellipsisGlyph.xBearing)
{
// Avoids to exceed the bounding box when rtl text is elided.
firstPenX = -ellipsisGlyph.xBearing;
firstPenSet = true;
}
- removedGlypsWidth += std::min( glyphToRemove.advance, ( glyphToRemove.xBearing + glyphToRemove.width ) );
+ removedGlypsWidth += std::min(glyphToRemove.advance, (glyphToRemove.xBearing + glyphToRemove.width));
// Calculate the width of the ellipsis glyph and check if it fits.
const float ellipsisGlyphWidth = ellipsisGlyph.width + ellipsisGlyph.xBearing;
- if( ellipsisGlyphWidth < removedGlypsWidth )
+ if(ellipsisGlyphWidth < removedGlypsWidth)
{
- GlyphInfo& glyphInfo = *( glyphs + index );
- Vector2& position = *( glyphPositions + index );
- position.x -= ( 0.f > glyphInfo.xBearing ) ? glyphInfo.xBearing : 0.f;
+ GlyphInfo& glyphInfo = *(glyphs + index);
+ Vector2& position = *(glyphPositions + index);
+ position.x -= (0.f > glyphInfo.xBearing) ? glyphInfo.xBearing : 0.f;
// Replace the glyph by the ellipsis glyph.
glyphInfo = ellipsisGlyph;
// Change the 'x' and 'y' position of the ellipsis glyph.
- if( position.x > firstPenX )
+ if(position.x > firstPenX)
{
position.x = firstPenX + removedGlypsWidth - ellipsisGlyphWidth;
}
}
}
- if( !inserted )
+ if(!inserted)
{
- if( index > 0u )
+ if(index > 0u)
{
--index;
}
const Vector4* const View::GetColors() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->mColors.Begin();
}
const ColorIndex* const View::GetColorIndices() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->mColorIndices.Begin();
}
const Vector4* const View::GetBackgroundColors() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->mBackgroundColors.Begin();
}
const ColorIndex* const View::GetBackgroundColorIndices() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->mBackgroundColorIndices.Begin();
}
const Vector4& View::GetTextColor() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetTextColor();
}
const Vector2& View::GetShadowOffset() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetShadowOffset();
}
const Vector4& View::GetShadowColor() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetShadowColor();
}
const Vector4& View::GetUnderlineColor() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetUnderlineColor();
}
bool View::IsUnderlineEnabled() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->IsUnderlineEnabled();
}
float View::GetUnderlineHeight() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetUnderlineHeight();
}
Length View::GetNumberOfUnderlineRuns() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetNumberOfUnderlineRuns();
}
return 0u;
}
-void View::GetUnderlineRuns( GlyphRun* underlineRuns,
- UnderlineRunIndex index,
- Length numberOfRuns ) const
+void View::GetUnderlineRuns(GlyphRun* underlineRuns,
+ UnderlineRunIndex index,
+ Length numberOfRuns) const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
- mImpl->mVisualModel->GetUnderlineRuns( underlineRuns,
- index,
- numberOfRuns );
+ mImpl->mVisualModel->GetUnderlineRuns(underlineRuns,
+ index,
+ numberOfRuns);
}
}
const Vector4& View::GetOutlineColor() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetOutlineColor();
}
uint16_t View::GetOutlineWidth() const
{
- if( mImpl->mVisualModel )
+ if(mImpl->mVisualModel)
{
return mImpl->mVisualModel->GetOutlineWidth();
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
VisualModelPtr VisualModel::New()
{
- return VisualModelPtr( new VisualModel() );
+ return VisualModelPtr(new VisualModel());
}
-void VisualModel::CreateCharacterToGlyphTable( CharacterIndex startIndex,
- GlyphIndex startGlyphIndex,
- Length numberOfCharacters )
+void VisualModel::CreateCharacterToGlyphTable(CharacterIndex startIndex,
+ GlyphIndex startGlyphIndex,
+ Length numberOfCharacters)
{
- if( 0u == numberOfCharacters )
+ if(0u == numberOfCharacters)
{
// Nothing to do.
return;
}
- DALI_ASSERT_DEBUG( mGlyphsPerCharacter.Count() != 0u );
+ DALI_ASSERT_DEBUG(mGlyphsPerCharacter.Count() != 0u);
// Get the total number of characters.
- const Length totalNumberOfCharacters = ( 0u == mGlyphsToCharacters.Count() ) ? 0u : *( mGlyphsToCharacters.End() - 1u ) + *( mCharactersPerGlyph.End() - 1u ); // Index to the first character + the number of characters that form the last glyph.
+ const Length totalNumberOfCharacters = (0u == mGlyphsToCharacters.Count()) ? 0u : *(mGlyphsToCharacters.End() - 1u) + *(mCharactersPerGlyph.End() - 1u); // Index to the first character + the number of characters that form the last glyph.
// Whether the current buffer is being updated or is set from scratch.
const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters;
Vector<GlyphIndex> newCharactersToGlyph;
- GlyphIndex* charactersToGlyphBuffer = NULL;
+ GlyphIndex* charactersToGlyphBuffer = NULL;
// 1) Reserve some space for the glyph indices to avoid reallocations.
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- newCharactersToGlyph.Resize( numberOfCharacters );
+ newCharactersToGlyph.Resize(numberOfCharacters);
charactersToGlyphBuffer = newCharactersToGlyph.Begin();
}
else
{
- mCharactersToGlyph.Resize( numberOfCharacters );
+ mCharactersToGlyph.Resize(numberOfCharacters);
charactersToGlyphBuffer = mCharactersToGlyph.Begin() + startIndex;
}
// 2) Traverse the glyphs and set the glyph indices per character.
// Index to the glyph.
- GlyphIndex glyphIndex = startGlyphIndex;
- CharacterIndex characterIndex = startIndex;
+ GlyphIndex glyphIndex = startGlyphIndex;
+ CharacterIndex characterIndex = startIndex;
const CharacterIndex lastCharacterIndexPlusOne = startIndex + numberOfCharacters;
- for( Vector<Length>::ConstIterator it = mCharactersPerGlyph.Begin() + glyphIndex,
- endIt = mCharactersPerGlyph.End();
- ( it != endIt ) && ( characterIndex < lastCharacterIndexPlusOne );
- ++it )
+ for(Vector<Length>::ConstIterator it = mCharactersPerGlyph.Begin() + glyphIndex,
+ endIt = mCharactersPerGlyph.End();
+ (it != endIt) && (characterIndex < lastCharacterIndexPlusOne);
+ ++it)
{
const Length numberOfCharactersPerGlyph = *it;
Length numberOfGlyphs = 0u;
// Set the glyph indices.
- for( Length index = 0u; index < numberOfCharactersPerGlyph; ++index, ++characterIndex )
+ for(Length index = 0u; index < numberOfCharactersPerGlyph; ++index, ++characterIndex)
{
*charactersToGlyphBuffer = glyphIndex;
- numberOfGlyphs += *( glyphsPerCharacterBuffer + characterIndex );
+ numberOfGlyphs += *(glyphsPerCharacterBuffer + characterIndex);
++charactersToGlyphBuffer;
}
glyphIndex += numberOfGlyphs;
}
// If the character to glyph buffer is updated, it needs to be inserted in the model.
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
// Update the indices.
const Length numberOfGlyphs = glyphIndex - startGlyphIndex;
- for( Vector<Length>::Iterator it = mCharactersToGlyph.Begin() + startIndex,
- endIt = mCharactersToGlyph.End();
- it != endIt;
- ++it )
+ for(Vector<Length>::Iterator it = mCharactersToGlyph.Begin() + startIndex,
+ endIt = mCharactersToGlyph.End();
+ it != endIt;
+ ++it)
{
*it += numberOfGlyphs;
}
- mCharactersToGlyph.Insert( mCharactersToGlyph.Begin() + startIndex,
- newCharactersToGlyph.Begin(),
- newCharactersToGlyph.End() );
-
+ mCharactersToGlyph.Insert(mCharactersToGlyph.Begin() + startIndex,
+ newCharactersToGlyph.Begin(),
+ newCharactersToGlyph.End());
}
}
-void VisualModel::CreateGlyphsPerCharacterTable( CharacterIndex startIndex,
- GlyphIndex startGlyphIndex,
- Length numberOfCharacters )
+void VisualModel::CreateGlyphsPerCharacterTable(CharacterIndex startIndex,
+ GlyphIndex startGlyphIndex,
+ Length numberOfCharacters)
{
- if( 0u == numberOfCharacters )
+ if(0u == numberOfCharacters)
{
// Nothing to do.
return;
}
// Get the total number of characters.
- const Length totalNumberOfCharacters = ( 0u == mGlyphsToCharacters.Count() ) ? 0u : *( mGlyphsToCharacters.End() - 1u ) + *( mCharactersPerGlyph.End() - 1u ); // Index to the first character + the number of characters that form the last glyph.
+ const Length totalNumberOfCharacters = (0u == mGlyphsToCharacters.Count()) ? 0u : *(mGlyphsToCharacters.End() - 1u) + *(mCharactersPerGlyph.End() - 1u); // Index to the first character + the number of characters that form the last glyph.
// Whether the current buffer is being updated or is set from scratch.
const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters;
Vector<Length> newGlyphsPerCharacter;
- Length* glyphsPerCharacterBuffer = NULL;
+ Length* glyphsPerCharacterBuffer = NULL;
// 1) Reserve some space for the glyphs per character to avoid reallocations.
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- newGlyphsPerCharacter.Resize( numberOfCharacters );
+ newGlyphsPerCharacter.Resize(numberOfCharacters);
glyphsPerCharacterBuffer = newGlyphsPerCharacter.Begin();
}
else
{
- mGlyphsPerCharacter.Resize( numberOfCharacters );
+ mGlyphsPerCharacter.Resize(numberOfCharacters);
glyphsPerCharacterBuffer = mGlyphsPerCharacter.Begin() + startIndex;
}
// The number of 'characters per glyph' equal to zero.
Length zeroCharactersPerGlyph = 0u;
- for( Vector<Length>::ConstIterator it = mCharactersPerGlyph.Begin() + startGlyphIndex,
- endIt = mCharactersPerGlyph.End();
- ( it != endIt ) && ( traversedCharacters < numberOfCharacters );
- ++it )
+ for(Vector<Length>::ConstIterator it = mCharactersPerGlyph.Begin() + startGlyphIndex,
+ endIt = mCharactersPerGlyph.End();
+ (it != endIt) && (traversedCharacters < numberOfCharacters);
+ ++it)
{
const Length numberOfCharactersPerGlyph = *it;
traversedCharacters += numberOfCharactersPerGlyph;
// Set the glyphs per character.
- if( 0u == numberOfCharactersPerGlyph )
+ if(0u == numberOfCharactersPerGlyph)
{
++zeroCharactersPerGlyph;
}
else
{
- const Length numberOfZeroGlyphsPerCharacter = ( numberOfCharactersPerGlyph - 1u );
- for( Length zeroIndex = 0u; zeroIndex < numberOfZeroGlyphsPerCharacter; ++zeroIndex )
+ const Length numberOfZeroGlyphsPerCharacter = (numberOfCharactersPerGlyph - 1u);
+ for(Length zeroIndex = 0u; zeroIndex < numberOfZeroGlyphsPerCharacter; ++zeroIndex)
{
*glyphsPerCharacterBuffer = 0u;
}
// If the glyphs per character buffer is updated, it needs to be inserted in the model.
- if( updateCurrentBuffer )
+ if(updateCurrentBuffer)
{
- mGlyphsPerCharacter.Insert( mGlyphsPerCharacter.Begin() + startIndex,
- newGlyphsPerCharacter.Begin(),
- newGlyphsPerCharacter.End() );
+ mGlyphsPerCharacter.Insert(mGlyphsPerCharacter.Begin() + startIndex,
+ newGlyphsPerCharacter.Begin(),
+ newGlyphsPerCharacter.End());
}
}
-void VisualModel::GetGlyphs( GlyphInfo* glyphs,
- GlyphIndex glyphIndex,
- Length numberOfGlyphs ) const
+void VisualModel::GetGlyphs(GlyphInfo* glyphs,
+ GlyphIndex glyphIndex,
+ Length numberOfGlyphs) const
{
- memcpy( glyphs, mGlyphs.Begin() + glyphIndex, numberOfGlyphs * sizeof( GlyphInfo ) );
+ memcpy(glyphs, mGlyphs.Begin() + glyphIndex, numberOfGlyphs * sizeof(GlyphInfo));
}
-void VisualModel::GetGlyphPositions( Vector2* glyphPositions,
- GlyphIndex glyphIndex,
- Length numberOfGlyphs ) const
+void VisualModel::GetGlyphPositions(Vector2* glyphPositions,
+ GlyphIndex glyphIndex,
+ Length numberOfGlyphs) const
{
- memcpy( glyphPositions, mGlyphPositions.Begin() + glyphIndex, numberOfGlyphs * sizeof( Vector2 ) );
+ memcpy(glyphPositions, mGlyphPositions.Begin() + glyphIndex, numberOfGlyphs * sizeof(Vector2));
}
-void VisualModel::GetNumberOfLines( GlyphIndex glyphIndex,
- Length numberOfGlyphs,
- LineIndex& firstLine,
- Length& numberOfLines ) const
+void VisualModel::GetNumberOfLines(GlyphIndex glyphIndex,
+ Length numberOfGlyphs,
+ LineIndex& firstLine,
+ Length& numberOfLines) const
{
// Initialize the number of lines and the first line.
- firstLine = 0u;
- numberOfLines = 0u;
+ firstLine = 0u;
+ numberOfLines = 0u;
bool firstLineFound = false;
const GlyphIndex lastGlyphIndex = glyphIndex + numberOfGlyphs;
// Traverse the lines and count those lines within the range of glyphs.
- for( Vector<LineRun>::ConstIterator it = mLines.Begin(),
- endIt = mLines.End();
- it != endIt;
- ++it )
+ for(Vector<LineRun>::ConstIterator it = mLines.Begin(),
+ endIt = mLines.End();
+ it != endIt;
+ ++it)
{
const LineRun& line = *it;
- if( ( line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs > glyphIndex ) &&
- ( lastGlyphIndex > line.glyphRun.glyphIndex ) )
+ if((line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs > glyphIndex) &&
+ (lastGlyphIndex > line.glyphRun.glyphIndex))
{
firstLineFound = true;
++numberOfLines;
}
- else if( lastGlyphIndex <= line.glyphRun.glyphIndex )
+ else if(lastGlyphIndex <= line.glyphRun.glyphIndex)
{
// nothing else to do.
break;
}
- if( !firstLineFound )
+ if(!firstLineFound)
{
++firstLine;
}
}
}
-void VisualModel::GetLinesOfGlyphRange( LineRun* lines,
- GlyphIndex glyphIndex,
- Length numberOfGlyphs ) const
+void VisualModel::GetLinesOfGlyphRange(LineRun* lines,
+ GlyphIndex glyphIndex,
+ Length numberOfGlyphs) const
{
- LineIndex firstLine = 0u;
- Length numberOfLines = 0u;
+ LineIndex firstLine = 0u;
+ Length numberOfLines = 0u;
- GetNumberOfLines( glyphIndex,
- numberOfGlyphs,
- firstLine,
- numberOfLines );
+ GetNumberOfLines(glyphIndex,
+ numberOfGlyphs,
+ firstLine,
+ numberOfLines);
- memcpy( lines, mLines.Begin() + firstLine, numberOfLines * sizeof( LineRun ) );
+ memcpy(lines, mLines.Begin() + firstLine, numberOfLines * sizeof(LineRun));
}
-LineIndex VisualModel::GetLineOfCharacter( CharacterIndex characterIndex )
+LineIndex VisualModel::GetLineOfCharacter(CharacterIndex characterIndex)
{
// 1) Check line is empty or not.
- if( mLines.Empty() )
+ if(mLines.Empty())
{
return 0u;
}
// 2) Check in the cached line.
- const LineRun& lineRun = *( mLines.Begin() + mCachedLineIndex );
- if( ( lineRun.characterRun.characterIndex <= characterIndex ) &&
- ( characterIndex < lineRun.characterRun.characterIndex + lineRun.characterRun.numberOfCharacters ) )
+ const LineRun& lineRun = *(mLines.Begin() + mCachedLineIndex);
+ if((lineRun.characterRun.characterIndex <= characterIndex) &&
+ (characterIndex < lineRun.characterRun.characterIndex + lineRun.characterRun.numberOfCharacters))
{
return mCachedLineIndex;
}
// 3) Is not in the cached line. Check in the other lines.
LineIndex index = characterIndex < lineRun.characterRun.characterIndex ? 0u : mCachedLineIndex + 1u;
- for( Vector<LineRun>::ConstIterator it = mLines.Begin() + index,
- endIt = mLines.End();
- it != endIt;
- ++it, ++index )
+ for(Vector<LineRun>::ConstIterator it = mLines.Begin() + index,
+ endIt = mLines.End();
+ it != endIt;
+ ++it, ++index)
{
const LineRun& lineRun = *it;
- if( characterIndex < lineRun.characterRun.characterIndex + lineRun.characterRun.numberOfCharacters )
+ if(characterIndex < lineRun.characterRun.characterIndex + lineRun.characterRun.numberOfCharacters)
{
mCachedLineIndex = index;
break;
return index;
}
-void VisualModel::GetUnderlineRuns( GlyphRun* underlineRuns,
- UnderlineRunIndex index,
- Length numberOfRuns ) const
+void VisualModel::GetUnderlineRuns(GlyphRun* underlineRuns,
+ UnderlineRunIndex index,
+ Length numberOfRuns) const
{
- memcpy( underlineRuns,
- mUnderlineRuns.Begin() + index,
- numberOfRuns * sizeof( GlyphRun ) );
+ memcpy(underlineRuns,
+ mUnderlineRuns.Begin() + index,
+ numberOfRuns * sizeof(GlyphRun));
}
-void VisualModel::SetNaturalSize( const Vector2& size )
+void VisualModel::SetNaturalSize(const Vector2& size)
{
mNaturalSize = size;
}
return mNaturalSize;
}
-void VisualModel::SetLayoutSize( const Vector2& size )
+void VisualModel::SetLayoutSize(const Vector2& size)
{
mLayoutSize = size;
}
return mLayoutSize;
}
-void VisualModel::SetTextColor( const Vector4& textColor )
+void VisualModel::SetTextColor(const Vector4& textColor)
{
mTextColor = textColor;
- if ( !mUnderlineColorSet )
+ if(!mUnderlineColorSet)
{
mUnderlineColor = textColor;
}
}
-void VisualModel::SetShadowOffset( const Vector2& shadowOffset )
+void VisualModel::SetShadowOffset(const Vector2& shadowOffset)
{
mShadowOffset = shadowOffset;
}
-void VisualModel::SetShadowColor( const Vector4& shadowColor )
+void VisualModel::SetShadowColor(const Vector4& shadowColor)
{
mShadowColor = shadowColor;
}
-void VisualModel::SetShadowBlurRadius( const float& shadowBlurRadius )
+void VisualModel::SetShadowBlurRadius(const float& shadowBlurRadius)
{
mShadowBlurRadius = shadowBlurRadius;
}
-void VisualModel::SetUnderlineColor( const Vector4& color )
+void VisualModel::SetUnderlineColor(const Vector4& color)
{
- mUnderlineColor = color;
+ mUnderlineColor = color;
mUnderlineColorSet = true;
}
-void VisualModel::SetOutlineColor( const Vector4& color )
+void VisualModel::SetOutlineColor(const Vector4& color)
{
mOutlineColor = color;
}
-void VisualModel::SetUnderlineEnabled( bool enabled )
+void VisualModel::SetUnderlineEnabled(bool enabled)
{
mUnderlineEnabled = enabled;
}
-void VisualModel::SetUnderlineHeight( float height )
+void VisualModel::SetUnderlineHeight(float height)
{
mUnderlineHeight = height;
}
-void VisualModel::SetOutlineWidth( uint16_t width )
+void VisualModel::SetOutlineWidth(uint16_t width)
{
mOutlineWidth = width;
}
-void VisualModel::SetBackgroundColor( const Vector4& color )
+void VisualModel::SetBackgroundColor(const Vector4& color)
{
mBackgroundColor = color;
}
-void VisualModel::SetBackgroundEnabled( bool enabled )
+void VisualModel::SetBackgroundEnabled(bool enabled)
{
mBackgroundEnabled = enabled;
}
mGlyphsPerCharacter(),
mGlyphPositions(),
mLines(),
- mTextColor( Color::BLACK ),
- mShadowColor( Color::BLACK ),
- mUnderlineColor( Color::BLACK ),
- mOutlineColor( Color::WHITE ),
- mBackgroundColor( Color::TRANSPARENT ),
+ mTextColor(Color::BLACK),
+ mShadowColor(Color::BLACK),
+ mUnderlineColor(Color::BLACK),
+ mOutlineColor(Color::WHITE),
+ mBackgroundColor(Color::TRANSPARENT),
mControlSize(),
mShadowOffset(),
- mUnderlineHeight( 0.0f ),
- mShadowBlurRadius( 0.0f ),
- mOutlineWidth( 0u ),
+ mUnderlineHeight(0.0f),
+ mShadowBlurRadius(0.0f),
+ mOutlineWidth(0u),
mNaturalSize(),
mLayoutSize(),
- mCachedLineIndex( 0u ),
- mUnderlineEnabled( false ),
- mUnderlineColorSet( false ),
- mBackgroundEnabled( false )
+ mCachedLineIndex(0u),
+ mUnderlineEnabled(false),
+ mUnderlineColorSet(false),
+ mBackgroundEnabled(false)
{
}
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Text
{
-
namespace
{
/**
*/
struct XHTMLEntityLookup
{
- const char* const entityName; // XHTML Named Entity string
- const char* const entityCode; // Corresponding UTF-8
+ const char* const entityName; // XHTML Named Entity string
+ const char* const entityCode; // Corresponding UTF-8
};
/* table of html name entities supported in DALi
* these are stored as pair with Named entity as Key and
* its utf 8 as value
*/
+// clang-format off
const XHTMLEntityLookup XHTMLEntityLookupTable[] =
- {
- { ""\0" ,"\x22\0" },
- { "&\0" ,"\x26\0" },
- { "'\0" ,"\x27\0" },
- { "<\0" ,"\x3c\0" },
- { ">\0" ,"\x3e\0" },
- { " \0" ,"\xc2\xa0\0" },
- { "¡\0" ,"\xc2\xa1\0" },
- { "¢\0" ,"\xc2\xa2\0" },
- { "£\0" ,"\xc2\xa3\0" },
- { "¤\0" ,"\xc2\xa4\0" },
- { "¥\0" ,"\xc2\xa5\0" },
- { "¦\0" ,"\xc2\xa6\0" },
- { "§\0" ,"\xc2\xa7\0" },
- { "¨\0" ,"\xc2\xa8\0" },
- { "©\0" ,"\xc2\xa9\0" },
- { "ª\0" ,"\xc2\xaa\0" },
- { "«\0" ,"\xc2\xab\0" },
- { "¬\0" ,"\xc2\xac\0" },
- { "­\0" ,"\xc2\xad\0" },
- { "®\0" ,"\xc2\xae\0" },
- { "¯\0" ,"\xc2\xaf\0" },
- { "°\0" ,"\xc2\xb0\0" },
- { "±\0" ,"\xc2\xb1\0" },
- { "²\0" ,"\xc2\xb2\0" },
- { "³\0" ,"\xc2\xb3\0" },
- { "´\0" ,"\xc2\xb4\0" },
- { "µ\0" ,"\xc2\xb5\0" },
- { "¶\0" ,"\xc2\xb6\0" },
- { "·\0" ,"\xc2\xb7\0" },
- { "¸\0" ,"\xc2\xb8\0" },
- { "¹\0" ,"\xc2\xb9\0" },
- { "º\0" ,"\xc2\xba\0" },
- { "»\0" ,"\xc2\xbb\0" },
- { "¼\0" ,"\xc2\xbc\0" },
- { "½\0" ,"\xc2\xbd\0" },
- { "¾\0" ,"\xc2\xbe\0" },
- { "¿\0" ,"\xc2\xbf\0" },
- { "À\0" ,"\xc3\x80\0" },
- { "Á\0" ,"\xc3\x81\0" },
- { "Â\0" ,"\xc3\x82\0" },
- { "Ã\0" ,"\xc3\x83\0" },
- { "Ä\0" ,"\xc3\x84\0" },
- { "Å\0" ,"\xc3\x85\0" },
- { "Æ\0" ,"\xc3\x86\0" },
- { "Ç\0" ,"\xc3\x87\0" },
- { "È\0" ,"\xc3\x88\0" },
- { "É\0" ,"\xc3\x89\0" },
- { "Ê\0" ,"\xc3\x8a\0" },
- { "Ë\0" ,"\xc3\x8b\0" },
- { "Ì\0" ,"\xc3\x8c\0" },
- { "Í\0" ,"\xc3\x8d\0" },
- { "Î\0" ,"\xc3\x8e\0" },
- { "Ï\0" ,"\xc3\x8f\0" },
- { "Ð\0" ,"\xc3\x90\0" },
- { "Ñ\0" ,"\xc3\x91\0" },
- { "Ò\0" ,"\xc3\x92\0" },
- { "Ó\0" ,"\xc3\x93\0" },
- { "Ô\0" ,"\xc3\x94\0" },
- { "Õ\0" ,"\xc3\x95\0" },
- { "Ö\0" ,"\xc3\x96\0" },
- { "×\0" ,"\xc3\x97\0" },
- { "Ø\0" ,"\xc3\x98\0" },
- { "Ù\0" ,"\xc3\x99\0" },
- { "Ú\0" ,"\xc3\x9a\0" },
- { "Û\0" ,"\xc3\x9b\0" },
- { "Ü\0" ,"\xc3\x9c\0" },
- { "Ý\0" ,"\xc3\x9d\0" },
- { "Þ\0" ,"\xc3\x9e\0" },
- { "ß\0" ,"\xc3\x9f\0" },
- { "à\0" ,"\xc3\xa0\0" },
- { "á\0" ,"\xc3\xa1\0" },
- { "â\0" ,"\xc3\xa2\0" },
- { "ã\0" ,"\xc3\xa3\0" },
- { "ä\0" ,"\xc3\xa4\0" },
- { "å\0" ,"\xc3\xa5\0" },
- { "æ\0" ,"\xc3\xa6\0" },
- { "ç\0" ,"\xc3\xa7\0" },
- { "è\0" ,"\xc3\xa8\0" },
- { "é\0" ,"\xc3\xa9\0" },
- { "ê\0" ,"\xc3\xaa\0" },
- { "ë\0" ,"\xc3\xab\0" },
- { "ì\0" ,"\xc3\xac\0" },
- { "í\0" ,"\xc3\xad\0" },
- { "î\0" ,"\xc3\xae\0" },
- { "ï\0" ,"\xc3\xaf\0" },
- { "ð\0" ,"\xc3\xb0\0" },
- { "ñ\0" ,"\xc3\xb1\0" },
- { "ò\0" ,"\xc3\xb2\0" },
- { "ó\0" ,"\xc3\xb3\0" },
- { "ô\0" ,"\xc3\xb4\0" },
- { "õ\0" ,"\xc3\xb5\0" },
- { "ö\0" ,"\xc3\xb6\0" },
- { "÷\0" ,"\xc3\xb7\0" },
- { "ø\0" ,"\xc3\xb8\0" },
- { "ù\0" ,"\xc3\xb9\0" },
- { "ú\0" ,"\xc3\xba\0" },
- { "û\0" ,"\xc3\xbb\0" },
- { "ü\0" ,"\xc3\xbc\0" },
- { "ý\0" ,"\xc3\xbd\0" },
- { "þ\0" ,"\xc3\xbe\0" },
- { "ÿ\0" ,"\xc3\xbf\0" },
- { "Œ\0" ,"\xc5\x92\0" },
- { "œ\0" ,"\xc5\x93\0" },
- { "Š\0" ,"\xc5\xa0\0" },
- { "š\0" ,"\xc5\xa1\0" },
- { "Ÿ\0" ,"\xc5\xb8\0" },
- { "ƒ\0" ,"\xc6\x92\0" },
- { "ˆ\0" ,"\xcb\x86\0" },
- { "˜\0" ,"\xcb\x9c\0" },
- { "Α\0" ,"\xce\x91\0" },
- { "Β\0" ,"\xce\x92\0" },
- { "Γ\0" ,"\xce\x93\0" },
- { "Δ\0" ,"\xce\x94\0" },
- { "Ε\0" ,"\xce\x95\0" },
- { "Ζ\0" ,"\xce\x96\0" },
- { "Η\0" ,"\xce\x97\0" },
- { "Θ\0" ,"\xce\x98\0" },
- { "Ι\0" ,"\xce\x99\0" },
- { "Κ\0" ,"\xce\x9a\0" },
- { "Λ\0" ,"\xce\x9b\0" },
- { "Μ\0" ,"\xce\x9c\0" },
- { "Ν\0" ,"\xce\x9d\0" },
- { "Ξ\0" ,"\xce\x9e\0" },
- { "Ο\0" ,"\xce\x9f\0" },
- { "Π\0" ,"\xce\xa0\0" },
- { "Ρ\0" ,"\xce\xa1\0" },
- { "Σ\0" ,"\xce\xa3\0" },
- { "Τ\0" ,"\xce\xa4\0" },
- { "Υ\0" ,"\xce\xa5\0" },
- { "Φ\0" ,"\xce\xa6\0" },
- { "Χ\0" ,"\xce\xa7\0" },
- { "Ψ\0" ,"\xce\xa8\0" },
- { "Ω\0" ,"\xce\xa9\0" },
- { "α\0" ,"\xce\xb1\0" },
- { "β\0" ,"\xce\xb2\0" },
- { "γ\0" ,"\xce\xb3\0" },
- { "δ\0" ,"\xce\xb4\0" },
- { "ε\0" ,"\xce\xb5\0" },
- { "ζ\0" ,"\xce\xb6\0" },
- { "η\0" ,"\xce\xb7\0" },
- { "θ\0" ,"\xce\xb8\0" },
- { "ι\0" ,"\xce\xb9\0" },
- { "κ\0" ,"\xce\xba\0" },
- { "λ\0" ,"\xce\xbb\0" },
- { "μ\0" ,"\xce\xbc\0" },
- { "ν\0" ,"\xce\xbd\0" },
- { "ξ\0" ,"\xce\xbe\0" },
- { "ο\0" ,"\xce\xbf\0" },
- { "π\0" ,"\xcf\x80\0" },
- { "ρ\0" ,"\xcf\x81\0" },
- { "ς\0" ,"\xcf\x82\0" },
- { "σ\0" ,"\xcf\x83\0" },
- { "τ\0" ,"\xcf\x84\0" },
- { "υ\0" ,"\xcf\x85\0" },
- { "φ\0" ,"\xcf\x86\0" },
- { "χ\0" ,"\xcf\x87\0" },
- { "ψ\0" ,"\xcf\x88\0" },
- { "ω\0" ,"\xcf\x89\0" },
- { "ϑ\0","\xcf\x91\0" },
- { "ϒ\0" ,"\xcf\x92\0" },
- { "ϖ\0" ,"\xcf\x96\0" },
- { " \0" ,"\xe2\x80\x82\0" },
- { " \0" ,"\xe2\x80\x83\0" },
- { " \0" ,"\xe2\x80\x89\0" },
- { "‌\0" ,"\xe2\x80\x8c\0" },
- { "‍\0" ,"\xe2\x80\x8d\0" },
- { "‎\0" ,"\xe2\x80\x8e\0" },
- { "‏\0" ,"\xe2\x80\x8f\0" },
- { "–\0" ,"\xe2\x80\x93\0" },
- { "—\0" ,"\xe2\x80\x94\0" },
- { "‘\0" ,"\xe2\x80\x98\0" },
- { "’\0" ,"\xe2\x80\x99\0" },
- { "‚\0" ,"\xe2\x80\x9a\0" },
- { "“\0" ,"\xe2\x80\x9c\0" },
- { "”\0" ,"\xe2\x80\x9d\0" },
- { "„\0" ,"\xe2\x80\x9e\0" },
- { "†\0" ,"\xe2\x80\xa0\0" },
- { "‡\0" ,"\xe2\x80\xa1\0" },
- { "•\0" ,"\xe2\x80\xa2\0" },
- { "…\0" ,"\xe2\x80\xa6\0" },
- { "‰\0" ,"\xe2\x80\xb0\0" },
- { "′\0" ,"\xe2\x80\xb2\0" },
- { "″\0" ,"\xe2\x80\xb3\0" },
- { "‹\0" ,"\xe2\x80\xb9\0" },
- { "›\0" ,"\xe2\x80\xba\0" },
- { "‾\0" ,"\xe2\x80\xbe\0" },
- { "⁄\0" ,"\xe2\x81\x84\0" },
- { "€\0" ,"\xe2\x82\xac\0" },
- { "ℑ\0" ,"\xe2\x84\x91\0" },
- { "℘\0" ,"\xe2\x84\x98\0" },
- { "ℜ\0" ,"\xe2\x84\x9c\0" },
- { "™\0" ,"\xe2\x84\xa2\0" },
- { "ℵ\0" ,"\xe2\x84\xb5\0" },
- { "←\0" ,"\xe2\x86\x90\0" },
- { "↑\0" ,"\xe2\x86\x91\0" },
- { "→\0" ,"\xe2\x86\x92\0" },
- { "↓\0" ,"\xe2\x86\x93\0" },
- { "↔\0" ,"\xe2\x86\x94\0" },
- { "↵\0" ,"\xe2\x86\xb5\0" },
- { "⇐\0" ,"\xe2\x87\x90\0" },
- { "⇑\0" ,"\xe2\x87\x91\0" },
- { "⇒\0" ,"\xe2\x87\x92\0" },
- { "⇓\0" ,"\xe2\x87\x93\0" },
- { "⇔\0" ,"\xe2\x87\x94\0" },
- { "∀\0" ,"\xe2\x88\x80\0" },
- { "∂\0" ,"\xe2\x88\x82\0" },
- { "∃\0" ,"\xe2\x88\x83\0" },
- { "∅\0" ,"\xe2\x88\x85\0" },
- { "∇\0" ,"\xe2\x88\x87\0" },
- { "∈\0" ,"\xe2\x88\x88\0" },
- { "∉\0" ,"\xe2\x88\x89\0" },
- { "∋\0" ,"\xe2\x88\x8b\0" },
- { "∏\0" ,"\xe2\x88\x8f\0" },
- { "∑\0" ,"\xe2\x88\x91\0" },
- { "−\0" ,"\xe2\x88\x92\0" },
- { "∗\0" ,"\xe2\x88\x97\0" },
- { "√\0" ,"\xe2\x88\x9a\0" },
- { "∝\0" ,"\xe2\x88\x9d\0" },
- { "∞\0" ,"\xe2\x88\x9e\0" },
- { "∠\0" ,"\xe2\x88\xa0\0" },
- { "∧\0" ,"\xe2\x88\xa7\0" },
- { "∨\0" ,"\xe2\x88\xa8\0" },
- { "∩\0" ,"\xe2\x88\xa9\0" },
- { "∪\0" ,"\xe2\x88\xaa\0" },
- { "∫\0" ,"\xe2\x88\xab\0" },
- { "∴\0" ,"\xe2\x88\xb4\0" },
- { "∼\0" ,"\xe2\x88\xbc\0" },
- { "≅\0" ,"\xe2\x89\x85\0" },
- { "≈\0" ,"\xe2\x89\x88\0" },
- { "≠\0" ,"\xe2\x89\xa0\0" },
- { "≡\0" ,"\xe2\x89\xa1\0" },
- { "≤\0" ,"\xe2\x89\xa4\0" },
- { "≥\0" ,"\xe2\x89\xa5\0" },
- { "⊂\0" ,"\xe2\x8a\x82\0" },
- { "⊃\0" ,"\xe2\x8a\x83\0" },
- { "⊄\0" ,"\xe2\x8a\x84\0" },
- { "⊆\0" ,"\xe2\x8a\x86\0" },
- { "⊇\0" ,"\xe2\x8a\x87\0" },
- { "⊕\0" ,"\xe2\x8a\x95\0" },
- { "⊗\0" ,"\xe2\x8a\x97\0" },
- { "⊥\0" ,"\xe2\x8a\xa5\0" },
- { "⋅\0" ,"\xe2\x8b\x85\0" },
- { "⌈\0" ,"\xe2\x8c\x88\0" },
- { "⌉\0" ,"\xe2\x8c\x89\0" },
- { "⌊\0" ,"\xe2\x8c\x8a\0" },
- { "⌋\0" ,"\xe2\x8c\x8b\0" },
- { "◊\0" ,"\xe2\x97\x8a\0" },
- { "♠\0" ,"\xe2\x99\xa0\0" },
- { "♣\0" ,"\xe2\x99\xa3\0" },
- { "♥\0" ,"\xe2\x99\xa5\0" },
- { "♦\0" ,"\xe2\x99\xa6\0" },
- { "⟨\0" ,"\xe2\x9f\xa8\0" },
- { "⟩\0" ,"\xe2\x9f\xa9\0" }
+{
+ {""\0" ,"\x22\0" },
+ {"&\0" ,"\x26\0" },
+ {"'\0" ,"\x27\0" },
+ {"<\0" ,"\x3c\0" },
+ {">\0" ,"\x3e\0" },
+ {" \0" ,"\xc2\xa0\0" },
+ {"¡\0" ,"\xc2\xa1\0" },
+ {"¢\0" ,"\xc2\xa2\0" },
+ {"£\0" ,"\xc2\xa3\0" },
+ {"¤\0" ,"\xc2\xa4\0" },
+ {"¥\0" ,"\xc2\xa5\0" },
+ {"¦\0" ,"\xc2\xa6\0" },
+ {"§\0" ,"\xc2\xa7\0" },
+ {"¨\0" ,"\xc2\xa8\0" },
+ {"©\0" ,"\xc2\xa9\0" },
+ {"ª\0" ,"\xc2\xaa\0" },
+ {"«\0" ,"\xc2\xab\0" },
+ {"¬\0" ,"\xc2\xac\0" },
+ {"­\0" ,"\xc2\xad\0" },
+ {"®\0" ,"\xc2\xae\0" },
+ {"¯\0" ,"\xc2\xaf\0" },
+ {"°\0" ,"\xc2\xb0\0" },
+ {"±\0" ,"\xc2\xb1\0" },
+ {"²\0" ,"\xc2\xb2\0" },
+ {"³\0" ,"\xc2\xb3\0" },
+ {"´\0" ,"\xc2\xb4\0" },
+ {"µ\0" ,"\xc2\xb5\0" },
+ {"¶\0" ,"\xc2\xb6\0" },
+ {"·\0" ,"\xc2\xb7\0" },
+ {"¸\0" ,"\xc2\xb8\0" },
+ {"¹\0" ,"\xc2\xb9\0" },
+ {"º\0" ,"\xc2\xba\0" },
+ {"»\0" ,"\xc2\xbb\0" },
+ {"¼\0" ,"\xc2\xbc\0" },
+ {"½\0" ,"\xc2\xbd\0" },
+ {"¾\0" ,"\xc2\xbe\0" },
+ {"¿\0" ,"\xc2\xbf\0" },
+ {"À\0" ,"\xc3\x80\0" },
+ {"Á\0" ,"\xc3\x81\0" },
+ {"Â\0" ,"\xc3\x82\0" },
+ {"Ã\0" ,"\xc3\x83\0" },
+ {"Ä\0" ,"\xc3\x84\0" },
+ {"Å\0" ,"\xc3\x85\0" },
+ {"Æ\0" ,"\xc3\x86\0" },
+ {"Ç\0" ,"\xc3\x87\0" },
+ {"È\0" ,"\xc3\x88\0" },
+ {"É\0" ,"\xc3\x89\0" },
+ {"Ê\0" ,"\xc3\x8a\0" },
+ {"Ë\0" ,"\xc3\x8b\0" },
+ {"Ì\0" ,"\xc3\x8c\0" },
+ {"Í\0" ,"\xc3\x8d\0" },
+ {"Î\0" ,"\xc3\x8e\0" },
+ {"Ï\0" ,"\xc3\x8f\0" },
+ {"Ð\0" ,"\xc3\x90\0" },
+ {"Ñ\0" ,"\xc3\x91\0" },
+ {"Ò\0" ,"\xc3\x92\0" },
+ {"Ó\0" ,"\xc3\x93\0" },
+ {"Ô\0" ,"\xc3\x94\0" },
+ {"Õ\0" ,"\xc3\x95\0" },
+ {"Ö\0" ,"\xc3\x96\0" },
+ {"×\0" ,"\xc3\x97\0" },
+ {"Ø\0" ,"\xc3\x98\0" },
+ {"Ù\0" ,"\xc3\x99\0" },
+ {"Ú\0" ,"\xc3\x9a\0" },
+ {"Û\0" ,"\xc3\x9b\0" },
+ {"Ü\0" ,"\xc3\x9c\0" },
+ {"Ý\0" ,"\xc3\x9d\0" },
+ {"Þ\0" ,"\xc3\x9e\0" },
+ {"ß\0" ,"\xc3\x9f\0" },
+ {"à\0" ,"\xc3\xa0\0" },
+ {"á\0" ,"\xc3\xa1\0" },
+ {"â\0" ,"\xc3\xa2\0" },
+ {"ã\0" ,"\xc3\xa3\0" },
+ {"ä\0" ,"\xc3\xa4\0" },
+ {"å\0" ,"\xc3\xa5\0" },
+ {"æ\0" ,"\xc3\xa6\0" },
+ {"ç\0" ,"\xc3\xa7\0" },
+ {"è\0" ,"\xc3\xa8\0" },
+ {"é\0" ,"\xc3\xa9\0" },
+ {"ê\0" ,"\xc3\xaa\0" },
+ {"ë\0" ,"\xc3\xab\0" },
+ {"ì\0" ,"\xc3\xac\0" },
+ {"í\0" ,"\xc3\xad\0" },
+ {"î\0" ,"\xc3\xae\0" },
+ {"ï\0" ,"\xc3\xaf\0" },
+ {"ð\0" ,"\xc3\xb0\0" },
+ {"ñ\0" ,"\xc3\xb1\0" },
+ {"ò\0" ,"\xc3\xb2\0" },
+ {"ó\0" ,"\xc3\xb3\0" },
+ {"ô\0" ,"\xc3\xb4\0" },
+ {"õ\0" ,"\xc3\xb5\0" },
+ {"ö\0" ,"\xc3\xb6\0" },
+ {"÷\0" ,"\xc3\xb7\0" },
+ {"ø\0" ,"\xc3\xb8\0" },
+ {"ù\0" ,"\xc3\xb9\0" },
+ {"ú\0" ,"\xc3\xba\0" },
+ {"û\0" ,"\xc3\xbb\0" },
+ {"ü\0" ,"\xc3\xbc\0" },
+ {"ý\0" ,"\xc3\xbd\0" },
+ {"þ\0" ,"\xc3\xbe\0" },
+ {"ÿ\0" ,"\xc3\xbf\0" },
+ {"Œ\0" ,"\xc5\x92\0" },
+ {"œ\0" ,"\xc5\x93\0" },
+ {"Š\0" ,"\xc5\xa0\0" },
+ {"š\0" ,"\xc5\xa1\0" },
+ {"Ÿ\0" ,"\xc5\xb8\0" },
+ {"ƒ\0" ,"\xc6\x92\0" },
+ {"ˆ\0" ,"\xcb\x86\0" },
+ {"˜\0" ,"\xcb\x9c\0" },
+ {"Α\0" ,"\xce\x91\0" },
+ {"Β\0" ,"\xce\x92\0" },
+ {"Γ\0" ,"\xce\x93\0" },
+ {"Δ\0" ,"\xce\x94\0" },
+ {"Ε\0" ,"\xce\x95\0" },
+ {"Ζ\0" ,"\xce\x96\0" },
+ {"Η\0" ,"\xce\x97\0" },
+ {"Θ\0" ,"\xce\x98\0" },
+ {"Ι\0" ,"\xce\x99\0" },
+ {"Κ\0" ,"\xce\x9a\0" },
+ {"Λ\0" ,"\xce\x9b\0" },
+ {"Μ\0" ,"\xce\x9c\0" },
+ {"Ν\0" ,"\xce\x9d\0" },
+ {"Ξ\0" ,"\xce\x9e\0" },
+ {"Ο\0" ,"\xce\x9f\0" },
+ {"Π\0" ,"\xce\xa0\0" },
+ {"Ρ\0" ,"\xce\xa1\0" },
+ {"Σ\0" ,"\xce\xa3\0" },
+ {"Τ\0" ,"\xce\xa4\0" },
+ {"Υ\0" ,"\xce\xa5\0" },
+ {"Φ\0" ,"\xce\xa6\0" },
+ {"Χ\0" ,"\xce\xa7\0" },
+ {"Ψ\0" ,"\xce\xa8\0" },
+ {"Ω\0" ,"\xce\xa9\0" },
+ {"α\0" ,"\xce\xb1\0" },
+ {"β\0" ,"\xce\xb2\0" },
+ {"γ\0" ,"\xce\xb3\0" },
+ {"δ\0" ,"\xce\xb4\0" },
+ {"ε\0" ,"\xce\xb5\0" },
+ {"ζ\0" ,"\xce\xb6\0" },
+ {"η\0" ,"\xce\xb7\0" },
+ {"θ\0" ,"\xce\xb8\0" },
+ {"ι\0" ,"\xce\xb9\0" },
+ {"κ\0" ,"\xce\xba\0" },
+ {"λ\0" ,"\xce\xbb\0" },
+ {"μ\0" ,"\xce\xbc\0" },
+ {"ν\0" ,"\xce\xbd\0" },
+ {"ξ\0" ,"\xce\xbe\0" },
+ {"ο\0" ,"\xce\xbf\0" },
+ {"π\0" ,"\xcf\x80\0" },
+ {"ρ\0" ,"\xcf\x81\0" },
+ {"ς\0" ,"\xcf\x82\0" },
+ {"σ\0" ,"\xcf\x83\0" },
+ {"τ\0" ,"\xcf\x84\0" },
+ {"υ\0" ,"\xcf\x85\0" },
+ {"φ\0" ,"\xcf\x86\0" },
+ {"χ\0" ,"\xcf\x87\0" },
+ {"ψ\0" ,"\xcf\x88\0" },
+ {"ω\0" ,"\xcf\x89\0" },
+ {"ϑ\0","\xcf\x91\0" },
+ {"ϒ\0" ,"\xcf\x92\0" },
+ {"ϖ\0" ,"\xcf\x96\0" },
+ {" \0" ,"\xe2\x80\x82\0" },
+ {" \0" ,"\xe2\x80\x83\0" },
+ {" \0" ,"\xe2\x80\x89\0" },
+ {"‌\0" ,"\xe2\x80\x8c\0" },
+ {"‍\0" ,"\xe2\x80\x8d\0" },
+ {"‎\0" ,"\xe2\x80\x8e\0" },
+ {"‏\0" ,"\xe2\x80\x8f\0" },
+ {"–\0" ,"\xe2\x80\x93\0" },
+ {"—\0" ,"\xe2\x80\x94\0" },
+ {"‘\0" ,"\xe2\x80\x98\0" },
+ {"’\0" ,"\xe2\x80\x99\0" },
+ {"‚\0" ,"\xe2\x80\x9a\0" },
+ {"“\0" ,"\xe2\x80\x9c\0" },
+ {"”\0" ,"\xe2\x80\x9d\0" },
+ {"„\0" ,"\xe2\x80\x9e\0" },
+ {"†\0" ,"\xe2\x80\xa0\0" },
+ {"‡\0" ,"\xe2\x80\xa1\0" },
+ {"•\0" ,"\xe2\x80\xa2\0" },
+ {"…\0" ,"\xe2\x80\xa6\0" },
+ {"‰\0" ,"\xe2\x80\xb0\0" },
+ {"′\0" ,"\xe2\x80\xb2\0" },
+ {"″\0" ,"\xe2\x80\xb3\0" },
+ {"‹\0" ,"\xe2\x80\xb9\0" },
+ {"›\0" ,"\xe2\x80\xba\0" },
+ {"‾\0" ,"\xe2\x80\xbe\0" },
+ {"⁄\0" ,"\xe2\x81\x84\0" },
+ {"€\0" ,"\xe2\x82\xac\0" },
+ {"ℑ\0" ,"\xe2\x84\x91\0" },
+ {"℘\0" ,"\xe2\x84\x98\0" },
+ {"ℜ\0" ,"\xe2\x84\x9c\0" },
+ {"™\0" ,"\xe2\x84\xa2\0" },
+ {"ℵ\0" ,"\xe2\x84\xb5\0" },
+ {"←\0" ,"\xe2\x86\x90\0" },
+ {"↑\0" ,"\xe2\x86\x91\0" },
+ {"→\0" ,"\xe2\x86\x92\0" },
+ {"↓\0" ,"\xe2\x86\x93\0" },
+ {"↔\0" ,"\xe2\x86\x94\0" },
+ {"↵\0" ,"\xe2\x86\xb5\0" },
+ {"⇐\0" ,"\xe2\x87\x90\0" },
+ {"⇑\0" ,"\xe2\x87\x91\0" },
+ {"⇒\0" ,"\xe2\x87\x92\0" },
+ {"⇓\0" ,"\xe2\x87\x93\0" },
+ {"⇔\0" ,"\xe2\x87\x94\0" },
+ {"∀\0" ,"\xe2\x88\x80\0" },
+ {"∂\0" ,"\xe2\x88\x82\0" },
+ {"∃\0" ,"\xe2\x88\x83\0" },
+ {"∅\0" ,"\xe2\x88\x85\0" },
+ {"∇\0" ,"\xe2\x88\x87\0" },
+ {"∈\0" ,"\xe2\x88\x88\0" },
+ {"∉\0" ,"\xe2\x88\x89\0" },
+ {"∋\0" ,"\xe2\x88\x8b\0" },
+ {"∏\0" ,"\xe2\x88\x8f\0" },
+ {"∑\0" ,"\xe2\x88\x91\0" },
+ {"−\0" ,"\xe2\x88\x92\0" },
+ {"∗\0" ,"\xe2\x88\x97\0" },
+ {"√\0" ,"\xe2\x88\x9a\0" },
+ {"∝\0" ,"\xe2\x88\x9d\0" },
+ {"∞\0" ,"\xe2\x88\x9e\0" },
+ {"∠\0" ,"\xe2\x88\xa0\0" },
+ {"∧\0" ,"\xe2\x88\xa7\0" },
+ {"∨\0" ,"\xe2\x88\xa8\0" },
+ {"∩\0" ,"\xe2\x88\xa9\0" },
+ {"∪\0" ,"\xe2\x88\xaa\0" },
+ {"∫\0" ,"\xe2\x88\xab\0" },
+ {"∴\0" ,"\xe2\x88\xb4\0" },
+ {"∼\0" ,"\xe2\x88\xbc\0" },
+ {"≅\0" ,"\xe2\x89\x85\0" },
+ {"≈\0" ,"\xe2\x89\x88\0" },
+ {"≠\0" ,"\xe2\x89\xa0\0" },
+ {"≡\0" ,"\xe2\x89\xa1\0" },
+ {"≤\0" ,"\xe2\x89\xa4\0" },
+ {"≥\0" ,"\xe2\x89\xa5\0" },
+ {"⊂\0" ,"\xe2\x8a\x82\0" },
+ {"⊃\0" ,"\xe2\x8a\x83\0" },
+ {"⊄\0" ,"\xe2\x8a\x84\0" },
+ {"⊆\0" ,"\xe2\x8a\x86\0" },
+ {"⊇\0" ,"\xe2\x8a\x87\0" },
+ {"⊕\0" ,"\xe2\x8a\x95\0" },
+ {"⊗\0" ,"\xe2\x8a\x97\0" },
+ {"⊥\0" ,"\xe2\x8a\xa5\0" },
+ {"⋅\0" ,"\xe2\x8b\x85\0" },
+ {"⌈\0" ,"\xe2\x8c\x88\0" },
+ {"⌉\0" ,"\xe2\x8c\x89\0" },
+ {"⌊\0" ,"\xe2\x8c\x8a\0" },
+ {"⌋\0" ,"\xe2\x8c\x8b\0" },
+ {"◊\0" ,"\xe2\x97\x8a\0" },
+ {"♠\0" ,"\xe2\x99\xa0\0" },
+ {"♣\0" ,"\xe2\x99\xa3\0" },
+ {"♥\0" ,"\xe2\x99\xa5\0" },
+ {"♦\0" ,"\xe2\x99\xa6\0" },
+ {"⟨\0" ,"\xe2\x9f\xa8\0" },
+ {"⟩\0" ,"\xe2\x9f\xa9\0" }
};
+// clang-format on
-const std::size_t XHTMLENTITY_LOOKUP_COUNT = (sizeof( XHTMLEntityLookupTable))/ (sizeof(XHTMLEntityLookup));
+const std::size_t XHTMLENTITY_LOOKUP_COUNT = (sizeof(XHTMLEntityLookupTable)) / (sizeof(XHTMLEntityLookup));
} // unnamed namespace
-const char* const NamedEntityToUtf8( const char* const markupText, unsigned int len )
+const char* const NamedEntityToUtf8(const char* const markupText, unsigned int len)
{
// finding if given XHTML named entity is supported or not
- for( size_t i = 0; i < XHTMLENTITY_LOOKUP_COUNT ; ++i )
+ for(size_t i = 0; i < XHTMLENTITY_LOOKUP_COUNT; ++i)
{
unsigned int entityLen = strlen(XHTMLEntityLookupTable[i].entityName);
- if( len == entityLen )
+ if(len == entityLen)
{
- if( strncmp( markupText, XHTMLEntityLookupTable[i].entityName, len ) == 0 ) // if named Entity found in table
- {
- return XHTMLEntityLookupTable[i].entityCode;
- }
+ if(strncmp(markupText, XHTMLEntityLookupTable[i].entityName, len) == 0) // if named Entity found in table
+ {
+ return XHTMLEntityLookupTable[i].entityCode;
+ }
}
}
return NULL;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-CubeTransitionCrossEffect::CubeTransitionCrossEffect( unsigned int numRows, unsigned int numColumns )
-: CubeTransitionEffect( numRows, numColumns ),
- mDisplacementSpreadFactor( 0.008f )
+CubeTransitionCrossEffect::CubeTransitionCrossEffect(unsigned int numRows, unsigned int numColumns)
+: CubeTransitionEffect(numRows, numColumns),
+ mDisplacementSpreadFactor(0.008f)
{
}
-Toolkit::CubeTransitionCrossEffect CubeTransitionCrossEffect::New(unsigned int numRows, unsigned int numColumns )
+Toolkit::CubeTransitionCrossEffect CubeTransitionCrossEffect::New(unsigned int numRows, unsigned int numColumns)
{
// Create the implementation
- IntrusivePtr< CubeTransitionCrossEffect > internalCubeTransEffect = new CubeTransitionCrossEffect( numRows, numColumns );
+ IntrusivePtr<CubeTransitionCrossEffect> internalCubeTransEffect = new CubeTransitionCrossEffect(numRows, numColumns);
// Pass ownership to CustomActor handle
- Toolkit::CubeTransitionCrossEffect cubeTransEffect( *internalCubeTransEffect );
+ Toolkit::CubeTransitionCrossEffect cubeTransEffect(*internalCubeTransEffect);
//Initialization
internalCubeTransEffect->Initialize();
void CubeTransitionCrossEffect::OnInitialize()
{
unsigned int idx;
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
- for( unsigned int x = y % 2; x < mColumns; x += 2 )
+ for(unsigned int x = y % 2; x < mColumns; x += 2)
{
idx = y * mColumns + x;
- SetTargetTop( idx );
+ SetTargetTop(idx);
}
- for( unsigned int x = ( y + 1 ) % 2; x < mColumns; x += 2 )
+ for(unsigned int x = (y + 1) % 2; x < mColumns; x += 2)
{
idx = y * mColumns + x;
- SetTargetRight( idx );
+ SetTargetRight(idx);
}
}
}
-void CubeTransitionCrossEffect::OnStartTransition( Vector2 panPosition, Vector2 panDisplacement )
+void CubeTransitionCrossEffect::OnStartTransition(Vector2 panPosition, Vector2 panDisplacement)
{
- float angle = Math::PI_2;
+ float angle = Math::PI_2;
unsigned int idx;
- if( panDisplacement.x < 0 )
+ if(panDisplacement.x < 0)
{
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
- for( unsigned int x = y % 2; x < mColumns; x += 2 )
+ for(unsigned int x = y % 2; x < mColumns; x += 2)
{
idx = y * mColumns + x;
- SetTargetTop( idx );
+ SetTargetTop(idx);
}
- for( unsigned int x = ( y + 1 ) % 2; x < mColumns; x += 2 )
+ for(unsigned int x = (y + 1) % 2; x < mColumns; x += 2)
{
idx = y * mColumns + x;
- SetTargetRight( idx );
+ SetTargetRight(idx);
}
}
}
{
angle = -angle;
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
- for( unsigned int x = y % 2; x < mColumns; x += 2 )
+ for(unsigned int x = y % 2; x < mColumns; x += 2)
{
idx = y * mColumns + x;
- SetTargetBottom( idx );
+ SetTargetBottom(idx);
}
- for( unsigned int x = ( y + 1 ) % 2; x < mColumns; x += 2 )
+ for(unsigned int x = (y + 1) % 2; x < mColumns; x += 2)
{
idx = y * mColumns + x;
- SetTargetLeft( idx );
+ SetTargetLeft(idx);
}
}
}
- const Vector2 halfSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).GetVectorXY() * 0.5f;
+ const Vector2 halfSize = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE).GetVectorXY() * 0.5f;
//the centre to "explode" the tiles outwards from
- Vector3 centre( halfSize.x, halfSize.y, -1.0f / mDisplacementSpreadFactor );
+ Vector3 centre(halfSize.x, halfSize.y, -1.0f / mDisplacementSpreadFactor);
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
- for( unsigned int x = y%2; x < mColumns; x=x+2) // rotate vertically
+ for(unsigned int x = y % 2; x < mColumns; x = x + 2) // rotate vertically
{
- idx = y*mColumns + x;
- SetupAnimation( idx, x, y, -angle, Vector3::XAXIS, centre );
+ idx = y * mColumns + x;
+ SetupAnimation(idx, x, y, -angle, Vector3::XAXIS, centre);
}
- for( unsigned int x = (y+1)%2; x < mColumns; x=x+2) // rotate horizontally
+ for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2) // rotate horizontally
{
- idx = y*mColumns + x;
- SetupAnimation( idx, x, y, angle, Vector3::YAXIS, centre );
+ idx = y * mColumns + x;
+ SetupAnimation(idx, x, y, angle, Vector3::YAXIS, centre);
}
}
mIsAnimating = true;
}
-void CubeTransitionCrossEffect::SetupAnimation( unsigned int actorIndex, unsigned int x, unsigned int y, float angle, const Vector3 axis, const Vector3& displacementCentre )
+void CubeTransitionCrossEffect::SetupAnimation(unsigned int actorIndex, unsigned int x, unsigned int y, float angle, const Vector3 axis, const Vector3& displacementCentre)
{
- const Vector2 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).GetVectorXY();
- Vector2 halfSize = size * 0.5f;
+ const Vector2 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE).GetVectorXY();
+ Vector2 halfSize = size * 0.5f;
//the position of the centre of the front face tile
- Vector3 position( halfSize.x * (2.0f * x + 1.0f) / mColumns, halfSize.y * (2.0f * y + 1.0f ) / mRows, 0.0f );
+ Vector3 position(halfSize.x * (2.0f * x + 1.0f) / mColumns, halfSize.y * (2.0f * y + 1.0f) / mRows, 0.0f);
Vector3 direction = position - displacementCentre;
- float length = direction.Length();
+ float length = direction.Length();
direction.Normalize();
float deltaLength = mCubeDisplacement / direction.z; //the length along the direction vector such that the projected direction onto the z axis is equal to mCubeDisplacement
- Vector3 newPosition = ( direction * (length + deltaLength ) ) + displacementCentre;
+ Vector3 newPosition = (direction * (length + deltaLength)) + displacementCentre;
Vector3 newLocalPosition = newPosition - position;
- mAnimation.AnimateTo( Property( mBoxes[ actorIndex ], Actor::Property::ORIENTATION ), Quaternion( Radian( -angle ), axis ), AlphaFunction::EASE_IN_OUT_SINE );
- mAnimation.AnimateTo( Property( mBoxes[ actorIndex ], Actor::Property::POSITION ), newLocalPosition, AlphaFunction::BOUNCE );
+ mAnimation.AnimateTo(Property(mBoxes[actorIndex], Actor::Property::ORIENTATION), Quaternion(Radian(-angle), axis), AlphaFunction::EASE_IN_OUT_SINE);
+ mAnimation.AnimateTo(Property(mBoxes[actorIndex], Actor::Property::POSITION), newLocalPosition, AlphaFunction::BOUNCE);
- mAnimation.AnimateTo( Property( mCurrentTiles[ actorIndex ], Actor::Property::COLOR ), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT );
- mAnimation.AnimateTo( Property( mTargetTiles[ actorIndex ], Actor::Property::COLOR ), FULL_BRIGHTNESS, AlphaFunction::EASE_IN );
+ mAnimation.AnimateTo(Property(mCurrentTiles[actorIndex], Actor::Property::COLOR), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT);
+ mAnimation.AnimateTo(Property(mTargetTiles[actorIndex], Actor::Property::COLOR), FULL_BRIGHTNESS, AlphaFunction::EASE_IN);
}
} // namespace Internal
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "cube-transition-effect-impl.h"
// EXTERNAL INCLUDES
-#include <cstring> // for strcmp
-#include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/type-registry-helper.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/object/type-registry-helper.h>
+#include <dali/public-api/object/type-registry.h>
+#include <cstring> // for strcmp
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// Setup properties, signals and actions using the type-registry.
-DALI_TYPE_REGISTRATION_BEGIN( Toolkit::CubeTransitionEffect, Dali::BaseHandle, NULL );
+DALI_TYPE_REGISTRATION_BEGIN(Toolkit::CubeTransitionEffect, Dali::BaseHandle, NULL);
-DALI_SIGNAL_REGISTRATION( Toolkit, CubeTransitionEffect, "transitionCompleted", SIGNAL_TRANSITION_COMPLETED )
+DALI_SIGNAL_REGISTRATION(Toolkit, CubeTransitionEffect, "transitionCompleted", SIGNAL_TRANSITION_COMPLETED)
DALI_TYPE_REGISTRATION_END()
-Actor CreateTile( const Vector4& samplerRect )
+Actor CreateTile(const Vector4& samplerRect)
{
- Actor tile = Actor::New();
- tile.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
- tile.RegisterProperty( "uTextureRect", samplerRect );
+ Actor tile = Actor::New();
+ tile.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
+ tile.RegisterProperty("uTextureRect", samplerRect);
return tile;
}
-}
+} // namespace
+
+const Vector4 CubeTransitionEffect::FULL_BRIGHTNESS(1.0f, 1.0f, 1.0f, 1.0f);
+const Vector4 CubeTransitionEffect::HALF_BRIGHTNESS(0.5f, 0.5f, 0.5f, 1.0f);
-const Vector4 CubeTransitionEffect::FULL_BRIGHTNESS( 1.0f, 1.0f, 1.0f, 1.0f );
-const Vector4 CubeTransitionEffect::HALF_BRIGHTNESS( 0.5f, 0.5f, 0.5f, 1.0f );
-
-CubeTransitionEffect::CubeTransitionEffect( unsigned int rows, unsigned int columns )
-: Control( ControlBehaviour( DISABLE_STYLE_CHANGE_SIGNALS ) ),
- mRows( rows ),
- mColumns( columns ),
- mIsAnimating( false ),
- mIsPaused( false ),
- mAnimationDuration( 1.f ),
- mCubeDisplacement( 0.f )
+CubeTransitionEffect::CubeTransitionEffect(unsigned int rows, unsigned int columns)
+: Control(ControlBehaviour(DISABLE_STYLE_CHANGE_SIGNALS)),
+ mRows(rows),
+ mColumns(columns),
+ mIsAnimating(false),
+ mIsPaused(false),
+ mAnimationDuration(1.f),
+ mCubeDisplacement(0.f)
{
}
{
}
-void CubeTransitionEffect::SetTargetRight( unsigned int idx )
+void CubeTransitionEffect::SetTargetRight(unsigned int idx)
{
- mBoxType[ idx ] = RIGHT;
+ mBoxType[idx] = RIGHT;
- mBoxes[ idx ].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f );
+ mBoxes[idx].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f);
- mTargetTiles[ idx ].SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 1.f, 0.5f, 0.5f) );
- mTargetTiles[ idx ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( 90.f ), Vector3::YAXIS ) );
+ mTargetTiles[idx].SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(1.f, 0.5f, 0.5f));
+ mTargetTiles[idx].SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(90.f), Vector3::YAXIS));
}
-void CubeTransitionEffect::SetTargetLeft( unsigned int idx )
+void CubeTransitionEffect::SetTargetLeft(unsigned int idx)
{
- mBoxType[ idx ] = LEFT;
+ mBoxType[idx] = LEFT;
- mBoxes[ idx ].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f );
+ mBoxes[idx].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f);
- mTargetTiles[ idx ].SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.f, 0.5f, 0.5f) );
- mTargetTiles[ idx ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( -90.f ), Vector3::YAXIS ) );
+ mTargetTiles[idx].SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.f, 0.5f, 0.5f));
+ mTargetTiles[idx].SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(-90.f), Vector3::YAXIS));
}
-void CubeTransitionEffect::SetTargetBottom( unsigned int idx )
+void CubeTransitionEffect::SetTargetBottom(unsigned int idx)
{
- mBoxType[ idx ] = BOTTOM;
+ mBoxType[idx] = BOTTOM;
- mBoxes[ idx ].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f );
+ mBoxes[idx].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f);
- mTargetTiles[ idx ].SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 0.f, 0.5f) );
- mTargetTiles[ idx ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( 90.f ), Vector3::XAXIS ) );
+ mTargetTiles[idx].SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.5f, 0.f, 0.5f));
+ mTargetTiles[idx].SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(90.f), Vector3::XAXIS));
}
-void CubeTransitionEffect::SetTargetTop( unsigned int idx )
+void CubeTransitionEffect::SetTargetTop(unsigned int idx)
{
- mBoxType[ idx ] = TOP;
+ mBoxType[idx] = TOP;
- mBoxes[ idx ].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f );
+ mBoxes[idx].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f);
- mTargetTiles[ idx ].SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 1.f, 0.5f) );
- mTargetTiles[ idx ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( -90.f ), Vector3::XAXIS ) );
+ mTargetTiles[idx].SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.5f, 1.f, 0.5f));
+ mTargetTiles[idx].SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(-90.f), Vector3::XAXIS));
}
-void CubeTransitionEffect::OnRelayout( const Vector2& size, RelayoutContainer& container )
+void CubeTransitionEffect::OnRelayout(const Vector2& size, RelayoutContainer& container)
{
- mTileSize = Vector2( size.x / mColumns, size.y / mRows );
+ mTileSize = Vector2(size.x / mColumns, size.y / mRows);
- mBoxRoot.SetProperty( Actor::Property::SIZE_WIDTH, size.x );
- mBoxRoot.SetProperty( Actor::Property::SIZE_HEIGHT, size.y );
- mBoxRoot.SetProperty( Actor::Property::SIZE_DEPTH, 1.0f );
+ mBoxRoot.SetProperty(Actor::Property::SIZE_WIDTH, size.x);
+ mBoxRoot.SetProperty(Actor::Property::SIZE_HEIGHT, size.y);
+ mBoxRoot.SetProperty(Actor::Property::SIZE_DEPTH, 1.0f);
- for( size_t i = 0; i < mBoxes.size(); ++i )
+ for(size_t i = 0; i < mBoxes.size(); ++i)
{
- mBoxes[ i ].SetProperty( Actor::Property::SIZE_WIDTH, mTileSize.x );
- mBoxes[ i ].SetProperty( Actor::Property::SIZE_HEIGHT, mTileSize.y );
+ mBoxes[i].SetProperty(Actor::Property::SIZE_WIDTH, mTileSize.x);
+ mBoxes[i].SetProperty(Actor::Property::SIZE_HEIGHT, mTileSize.y);
- switch( mBoxType[i] )
+ switch(mBoxType[i])
{
case LEFT:
case RIGHT:
{
- mBoxes[ i ].SetProperty( Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f );
- mBoxes[ i ].SetProperty( Actor::Property::SIZE_DEPTH, mTileSize.x );
+ mBoxes[i].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f);
+ mBoxes[i].SetProperty(Actor::Property::SIZE_DEPTH, mTileSize.x);
break;
}
case BOTTOM:
case TOP:
{
- mBoxes[ i ].SetProperty( Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f );
- mBoxes[ i ].SetProperty( Actor::Property::SIZE_DEPTH, mTileSize.y );
+ mBoxes[i].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f);
+ mBoxes[i].SetProperty(Actor::Property::SIZE_DEPTH, mTileSize.y);
break;
}
}
}
- for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it )
+ for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it)
{
- it->SetProperty( Actor::Property::SIZE_WIDTH, mTileSize.x );
- it->SetProperty( Actor::Property::SIZE_HEIGHT, mTileSize.y );
+ it->SetProperty(Actor::Property::SIZE_WIDTH, mTileSize.x);
+ it->SetProperty(Actor::Property::SIZE_HEIGHT, mTileSize.y);
}
- for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it )
+ for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it)
{
- it->SetProperty( Actor::Property::SIZE_WIDTH, mTileSize.x );
- it->SetProperty( Actor::Property::SIZE_HEIGHT, mTileSize.y );
+ it->SetProperty(Actor::Property::SIZE_WIDTH, mTileSize.x);
+ it->SetProperty(Actor::Property::SIZE_HEIGHT, mTileSize.y);
}
}
void CubeTransitionEffect::Initialize()
{
- Self().RegisterProperty( "uTextureRect", Vector4( 0.0f, 0.0f, 1.0f, 1.0f ) );
+ Self().RegisterProperty("uTextureRect", Vector4(0.0f, 0.0f, 1.0f, 1.0f));
mBoxType.Resize(mColumns * mRows);
//create the box parents
mBoxRoot = Actor::New();
- mBoxRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mBoxRoot.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ mBoxRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mBoxRoot.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
mCurrentTiles.clear();
mTargetTiles.clear();
- mCurrentTiles.reserve( mColumns * mRows );
- mTargetTiles.reserve( mColumns * mRows );
+ mCurrentTiles.reserve(mColumns * mRows);
+ mTargetTiles.reserve(mColumns * mRows);
- Vector2 gridSizeInv( 1.0f / mColumns, 1.0f / mRows );
- Vector3 offset( 0.5f * gridSizeInv.x, 0.5f * gridSizeInv.y, 0.0f );
+ Vector2 gridSizeInv(1.0f / mColumns, 1.0f / mRows);
+ Vector3 offset(0.5f * gridSizeInv.x, 0.5f * gridSizeInv.y, 0.0f);
Vector3 anchor;
- for( unsigned int y = 0; y < mRows; ++y, anchor.y += 1.0f / mRows )
+ for(unsigned int y = 0; y < mRows; ++y, anchor.y += 1.0f / mRows)
{
anchor.x = 0.0f;
- for( unsigned int x = 0; x <mColumns; ++x, anchor.x += 1.0f / mColumns )
+ for(unsigned int x = 0; x < mColumns; ++x, anchor.x += 1.0f / mColumns)
{
- Vector4 textureRect( anchor.x, anchor.y, anchor.x + gridSizeInv.x, anchor.y + gridSizeInv.y );
+ Vector4 textureRect(anchor.x, anchor.y, anchor.x + gridSizeInv.x, anchor.y + gridSizeInv.y);
- Actor currentTile = CreateTile( textureRect );
- currentTile.SetProperty( Actor::Property::COLOR, FULL_BRIGHTNESS );
- currentTile.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
- mCurrentTiles.push_back( currentTile );
+ Actor currentTile = CreateTile(textureRect);
+ currentTile.SetProperty(Actor::Property::COLOR, FULL_BRIGHTNESS);
+ currentTile.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
+ mCurrentTiles.push_back(currentTile);
- Actor targetTile = CreateTile( textureRect );
- targetTile.SetProperty( Actor::Property::COLOR, HALF_BRIGHTNESS );
- mTargetTiles.push_back( targetTile );
+ Actor targetTile = CreateTile(textureRect);
+ targetTile.SetProperty(Actor::Property::COLOR, HALF_BRIGHTNESS);
+ mTargetTiles.push_back(targetTile);
Actor box = Actor::New();
- box.SetProperty( Actor::Property::PARENT_ORIGIN, anchor + offset );
- box.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
+ box.SetProperty(Actor::Property::PARENT_ORIGIN, anchor + offset);
+ box.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
- box.Add( currentTile );
- box.Add( targetTile );
+ box.Add(currentTile);
+ box.Add(targetTile);
- mBoxRoot.Add( box );
+ mBoxRoot.Add(box);
- mBoxes.push_back( box );
+ mBoxes.push_back(box);
}
}
OnInitialize();
}
-void CubeTransitionEffect::OnSceneConnection( int depth )
+void CubeTransitionEffect::OnSceneConnection(int depth)
{
Geometry geometry = VisualFactoryCache::CreateQuadGeometry();
- Shader shader = Shader::New( SHADER_CUBE_TRANSITION_EFFECT_VERT, SHADER_CUBE_TRANSITION_EFFECT_FRAG );
+ Shader shader = Shader::New(SHADER_CUBE_TRANSITION_EFFECT_VERT, SHADER_CUBE_TRANSITION_EFFECT_FRAG);
TextureSet textureSet = TextureSet::New();
- if( mCurrentTexture )
+ if(mCurrentTexture)
{
- textureSet.SetTexture( 0u, mCurrentTexture );
+ textureSet.SetTexture(0u, mCurrentTexture);
}
- mCurrentRenderer = Renderer::New( geometry, shader );
- mCurrentRenderer.SetTextures( textureSet );
+ mCurrentRenderer = Renderer::New(geometry, shader);
+ mCurrentRenderer.SetTextures(textureSet);
- mCurrentRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, depth );
- Self().AddRenderer( mCurrentRenderer );
+ mCurrentRenderer.SetProperty(Renderer::Property::DEPTH_INDEX, depth);
+ Self().AddRenderer(mCurrentRenderer);
- Control::OnSceneConnection( depth );
+ Control::OnSceneConnection(depth);
}
void CubeTransitionEffect::OnSceneDisconnection()
{
- if( mCurrentRenderer )
+ if(mCurrentRenderer)
{
- Self().RemoveRenderer( mCurrentRenderer );
+ Self().RemoveRenderer(mCurrentRenderer);
- for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it )
+ for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it)
{
- it->RemoveRenderer( mCurrentRenderer );
+ it->RemoveRenderer(mCurrentRenderer);
}
mCurrentRenderer.Reset();
}
- if( mTargetRenderer )
+ if(mTargetRenderer)
{
- for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it )
+ for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it)
{
- it->RemoveRenderer( mTargetRenderer );
+ it->RemoveRenderer(mTargetRenderer);
}
mTargetRenderer.Reset();
}
Control::OnSceneDisconnection();
}
-void CubeTransitionEffect::SetTransitionDuration( float duration )
+void CubeTransitionEffect::SetTransitionDuration(float duration)
{
mAnimationDuration = duration;
}
-float CubeTransitionEffect::GetTransitionDuration( ) const
+float CubeTransitionEffect::GetTransitionDuration() const
{
return mAnimationDuration;
}
-void CubeTransitionEffect::SetCubeDisplacement( float displacement )
+void CubeTransitionEffect::SetCubeDisplacement(float displacement)
{
mCubeDisplacement = displacement;
}
return mIsAnimating;
}
-void CubeTransitionEffect::SetCurrentTexture( Texture texture )
+void CubeTransitionEffect::SetCurrentTexture(Texture texture)
{
mCurrentTexture = texture;
- if( mCurrentRenderer )
+ if(mCurrentRenderer)
{
TextureSet textureSet = mCurrentRenderer.GetTextures();
- textureSet.SetTexture( 0u, mCurrentTexture);
+ textureSet.SetTexture(0u, mCurrentTexture);
}
}
-void CubeTransitionEffect::SetTargetTexture( Texture texture )
+void CubeTransitionEffect::SetTargetTexture(Texture texture)
{
mTargetTexture = texture;
- if( mTargetRenderer )
+ if(mTargetRenderer)
{
TextureSet textureSet = mTargetRenderer.GetTextures();
- textureSet.SetTexture( 0u, mTargetTexture );
+ textureSet.SetTexture(0u, mTargetTexture);
}
}
-void CubeTransitionEffect::StartTransition( bool toNextImage )
+void CubeTransitionEffect::StartTransition(bool toNextImage)
{
- Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
- if( toNextImage )
+ Vector3 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
+ if(toNextImage)
{
- StartTransition( Vector2(size.x* 0.5f, size.y*0.5f), Vector2( -10.f, 0.f ) );
+ StartTransition(Vector2(size.x * 0.5f, size.y * 0.5f), Vector2(-10.f, 0.f));
}
else
{
- StartTransition( Vector2(size.x* 0.5f, size.y*0.5f), Vector2( 10.f, 0.f ));
+ StartTransition(Vector2(size.x * 0.5f, size.y * 0.5f), Vector2(10.f, 0.f));
}
}
-void CubeTransitionEffect::StartTransition( Vector2 panPosition, Vector2 panDisplacement )
+void CubeTransitionEffect::StartTransition(Vector2 panPosition, Vector2 panDisplacement)
{
- if( !mCurrentRenderer )
+ if(!mCurrentRenderer)
{
- DALI_LOG_ERROR( "Trying to transition a cube transition without an image set\n" );
+ DALI_LOG_ERROR("Trying to transition a cube transition without an image set\n");
return;
}
//create the target renderer
TextureSet textureSet = TextureSet::New();
- if( mTargetTexture )
+ if(mTargetTexture)
{
- textureSet.SetTexture( 0u, mTargetTexture );
+ textureSet.SetTexture(0u, mTargetTexture);
}
Geometry geometry = mCurrentRenderer.GetGeometry();
- Shader shader( mCurrentRenderer.GetShader() );
- mTargetRenderer = Renderer::New( geometry, shader );
- mTargetRenderer.SetTextures( textureSet );
+ Shader shader(mCurrentRenderer.GetShader());
+ mTargetRenderer = Renderer::New(geometry, shader);
+ mTargetRenderer.SetTextures(textureSet);
int depthIndex = mCurrentRenderer.GetProperty<int>(Renderer::Property::DEPTH_INDEX);
- mTargetRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex );
+ mTargetRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, depthIndex);
- for( size_t i = 0; i < mBoxes.size(); ++i )
+ for(size_t i = 0; i < mBoxes.size(); ++i)
{
- mBoxes[ i ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Radian( 0.0f ), Vector3::XAXIS ) );
+ mBoxes[i].SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(0.0f), Vector3::XAXIS));
}
- for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it )
+ for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it)
{
- it->SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 0.5f, 1.0f) );
- it->SetProperty( Actor::Property::ORIENTATION, Quaternion( Radian( 0.0f ), Vector3::XAXIS ) );
- it->AddRenderer( mCurrentRenderer );
+ it->SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.5f, 0.5f, 1.0f));
+ it->SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(0.0f), Vector3::XAXIS));
+ it->AddRenderer(mCurrentRenderer);
}
- for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it )
+ for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it)
{
- it->AddRenderer( mTargetRenderer );
+ it->AddRenderer(mTargetRenderer);
}
- Self().RemoveRenderer( mCurrentRenderer );
- Self().Add( mBoxRoot );
+ Self().RemoveRenderer(mCurrentRenderer);
+ Self().Add(mBoxRoot);
if(mAnimation)
{
mAnimation.Reset();
}
- mAnimation = Animation::New( mAnimationDuration );
- mAnimation.FinishedSignal().Connect( this, &CubeTransitionEffect::OnTransitionFinished );
+ mAnimation = Animation::New(mAnimationDuration);
+ mAnimation.FinishedSignal().Connect(this, &CubeTransitionEffect::OnTransitionFinished);
- OnStartTransition( panPosition, panDisplacement );
+ OnStartTransition(panPosition, panDisplacement);
}
void CubeTransitionEffect::PauseTransition()
{
- if( mIsAnimating && !mIsPaused )
+ if(mIsAnimating && !mIsPaused)
{
mAnimation.Pause();
mIsPaused = true;
void CubeTransitionEffect::ResumeTransition()
{
- if( mIsAnimating && mIsPaused)
+ if(mIsAnimating && mIsPaused)
{
mAnimation.Play();
mIsPaused = false;
mAnimation.Reset();
mIsAnimating = false;
- Self().Remove( mBoxRoot );
+ Self().Remove(mBoxRoot);
- for( size_t i = 0; i < mBoxes.size(); ++i )
+ for(size_t i = 0; i < mBoxes.size(); ++i)
{
- mBoxes[ i ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Radian( 0.0f ), Vector3::XAXIS ) );
+ mBoxes[i].SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(0.0f), Vector3::XAXIS));
}
- for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it )
+ for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it)
{
- it->SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 0.5f, 1.0f) );
- it->SetProperty( Actor::Property::ORIENTATION, Quaternion( Radian( 0.0f ), Vector3::XAXIS ) );
- it->SetProperty( Actor::Property::COLOR, FULL_BRIGHTNESS );
+ it->SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.5f, 0.5f, 1.0f));
+ it->SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(0.0f), Vector3::XAXIS));
+ it->SetProperty(Actor::Property::COLOR, FULL_BRIGHTNESS);
}
- if( mCurrentRenderer )
+ if(mCurrentRenderer)
{
- for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it )
+ for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it)
{
- it->RemoveRenderer( mCurrentRenderer );
+ it->RemoveRenderer(mCurrentRenderer);
}
- Self().AddRenderer( mCurrentRenderer );
+ Self().AddRenderer(mCurrentRenderer);
}
- for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it )
+ for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it)
{
- it->SetProperty( Actor::Property::COLOR, HALF_BRIGHTNESS );
+ it->SetProperty(Actor::Property::COLOR, HALF_BRIGHTNESS);
}
- if( mTargetRenderer )
+ if(mTargetRenderer)
{
- for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it )
+ for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it)
{
- it->RemoveRenderer( mTargetRenderer );
+ it->RemoveRenderer(mTargetRenderer);
}
}
}
void CubeTransitionEffect::OnTransitionFinished(Animation& source)
{
-
- std::swap( mCurrentTiles, mTargetTiles );
- std::swap( mCurrentRenderer, mTargetRenderer );
- std::swap( mCurrentTexture, mTargetTexture );
+ std::swap(mCurrentTiles, mTargetTiles);
+ std::swap(mCurrentRenderer, mTargetRenderer);
+ std::swap(mCurrentTexture, mTargetTexture);
ResetToInitialState();
//Emit signal
- Toolkit::CubeTransitionEffect handle( GetOwner() );
- mTransitionCompletedSignal.Emit( handle, mCurrentTexture );
+ Toolkit::CubeTransitionEffect handle(GetOwner());
+ mTransitionCompletedSignal.Emit(handle, mCurrentTexture);
}
Toolkit::CubeTransitionEffect::TransitionCompletedSignalType& CubeTransitionEffect::TransitionCompletedSignal()
return mTransitionCompletedSignal;
}
-bool CubeTransitionEffect::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
+bool CubeTransitionEffect::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
{
- Dali::BaseHandle handle( object );
+ Dali::BaseHandle handle(object);
- bool connected( true );
- Toolkit::CubeTransitionEffect cubeTransitionEffect = Toolkit::CubeTransitionEffect::DownCast( handle );
+ bool connected(true);
+ Toolkit::CubeTransitionEffect cubeTransitionEffect = Toolkit::CubeTransitionEffect::DownCast(handle);
- if( 0 == strcmp( signalName.c_str(), SIGNAL_TRANSITION_COMPLETED ) )
+ if(0 == strcmp(signalName.c_str(), SIGNAL_TRANSITION_COMPLETED))
{
- cubeTransitionEffect.TransitionCompletedSignal().Connect( tracker, functor );
+ cubeTransitionEffect.TransitionCompletedSignal().Connect(tracker, functor);
}
else
{
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-CubeTransitionFoldEffect::CubeTransitionFoldEffect( unsigned int numRows, unsigned int numColumns )
-: CubeTransitionEffect( numRows, numColumns )
+CubeTransitionFoldEffect::CubeTransitionFoldEffect(unsigned int numRows, unsigned int numColumns)
+: CubeTransitionEffect(numRows, numColumns)
{
}
-Toolkit::CubeTransitionFoldEffect CubeTransitionFoldEffect::New(unsigned int numRows, unsigned int numColumns )
+Toolkit::CubeTransitionFoldEffect CubeTransitionFoldEffect::New(unsigned int numRows, unsigned int numColumns)
{
// Create the implementation
- IntrusivePtr< CubeTransitionFoldEffect > internalCubeTransEffect = new CubeTransitionFoldEffect( numRows, numColumns );
+ IntrusivePtr<CubeTransitionFoldEffect> internalCubeTransEffect = new CubeTransitionFoldEffect(numRows, numColumns);
// Pass ownership to CustomActor handle
- Toolkit::CubeTransitionFoldEffect cubeTransEffect( *internalCubeTransEffect );
+ Toolkit::CubeTransitionFoldEffect cubeTransEffect(*internalCubeTransEffect);
//Initialization
internalCubeTransEffect->Initialize();
void CubeTransitionFoldEffect::OnInitialize()
{
unsigned int idx;
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
- idx = y*mColumns;
- for( unsigned int x = y%2; x < mColumns; x=x+2)
+ idx = y * mColumns;
+ for(unsigned int x = y % 2; x < mColumns; x = x + 2)
{
- SetTargetLeft( idx + x );
+ SetTargetLeft(idx + x);
}
- for( unsigned int x = (y+1)%2; x < mColumns; x=x+2)
+ for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2)
{
- SetTargetRight( idx + x );
+ SetTargetRight(idx + x);
}
}
}
-void CubeTransitionFoldEffect::OnStartTransition( Vector2 panPosition, Vector2 panDisplacement )
+void CubeTransitionFoldEffect::OnStartTransition(Vector2 panPosition, Vector2 panDisplacement)
{
float angle = Math::PI_2;
unsigned int idx;
- if( panDisplacement.x < 0 )
+ if(panDisplacement.x < 0)
{
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
- idx = y*mColumns;
- for( unsigned int x = y%2; x < mColumns; x=x+2)
+ idx = y * mColumns;
+ for(unsigned int x = y % 2; x < mColumns; x = x + 2)
{
- SetTargetLeft( idx + x );
+ SetTargetLeft(idx + x);
}
- for( unsigned int x = (y+1)%2; x < mColumns; x=x+2)
+ for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2)
{
- SetTargetRight( idx + x );
+ SetTargetRight(idx + x);
}
}
}
{
angle = -angle;
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
- idx = y*mColumns;
- for( unsigned int x = y%2; x < mColumns; x=x+2)
+ idx = y * mColumns;
+ for(unsigned int x = y % 2; x < mColumns; x = x + 2)
{
- SetTargetRight( idx + x );
+ SetTargetRight(idx + x);
}
- for( unsigned int x = (y+1)%2; x < mColumns; x=x+2)
+ for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2)
{
- SetTargetLeft( idx + x );
+ SetTargetLeft(idx + x);
}
}
}
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
- idx = y*mColumns;
- for( unsigned int x = y%2; x < mColumns; x=x+2)
+ idx = y * mColumns;
+ for(unsigned int x = y % 2; x < mColumns; x = x + 2)
{
- SetupAnimation( idx + x, x, angle );
+ SetupAnimation(idx + x, x, angle);
}
- for( unsigned int x = (y+1)%2; x < mColumns; x=x+2)
+ for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2)
{
- SetupAnimation( idx + x, x, -angle );
+ SetupAnimation(idx + x, x, -angle);
}
}
mIsAnimating = true;
}
-void CubeTransitionFoldEffect::SetupAnimation( unsigned int actorIndex, unsigned int x, float angle )
+void CubeTransitionFoldEffect::SetupAnimation(unsigned int actorIndex, unsigned int x, float angle)
{
//rotate and translate the cube such that the edges remain in constant contact
//calculate the maximum distance the cube has to move when it the box has rotated 45 degrees
//accumulating over the length of the row we get:
// delta_distance_at_x = x * delta_distance;
- float delta = (float)x * mTileSize.x * ( 1.4142f - 1.0f );
+ float delta = (float)x * mTileSize.x * (1.4142f - 1.0f);
- Vector3 position( mBoxes[ actorIndex ].GetCurrentProperty< Vector3 >( Actor::Property::POSITION ) );
- mAnimation.AnimateTo( Property( mBoxes[ actorIndex ], Actor::Property::ORIENTATION ), Quaternion( Radian( angle ), Vector3::YAXIS ), AlphaFunction::LINEAR );
- mAnimation.AnimateTo( Property( mBoxes[ actorIndex ], Actor::Property::POSITION_X ), position.x + delta, AlphaFunction::BOUNCE );
+ Vector3 position(mBoxes[actorIndex].GetCurrentProperty<Vector3>(Actor::Property::POSITION));
+ mAnimation.AnimateTo(Property(mBoxes[actorIndex], Actor::Property::ORIENTATION), Quaternion(Radian(angle), Vector3::YAXIS), AlphaFunction::LINEAR);
+ mAnimation.AnimateTo(Property(mBoxes[actorIndex], Actor::Property::POSITION_X), position.x + delta, AlphaFunction::BOUNCE);
- mAnimation.AnimateTo( Property( mCurrentTiles[ actorIndex ], Actor::Property::COLOR ), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT );
- mAnimation.AnimateTo( Property( mTargetTiles[ actorIndex ], Actor::Property::COLOR ), FULL_BRIGHTNESS, AlphaFunction::EASE_IN );
+ mAnimation.AnimateTo(Property(mCurrentTiles[actorIndex], Actor::Property::COLOR), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT);
+ mAnimation.AnimateTo(Property(mTargetTiles[actorIndex], Actor::Property::COLOR), FULL_BRIGHTNESS, AlphaFunction::EASE_IN);
}
} // namespace Internal
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-CubeTransitionWaveEffect::CubeTransitionWaveEffect( unsigned int numRows, unsigned int numColumns )
-: CubeTransitionEffect( numRows, numColumns ),
- mSaddleAA( 1.f ),
- mSaddleBB( 1.f ),
- mSaddleB( 1.f )
+CubeTransitionWaveEffect::CubeTransitionWaveEffect(unsigned int numRows, unsigned int numColumns)
+: CubeTransitionEffect(numRows, numColumns),
+ mSaddleAA(1.f),
+ mSaddleBB(1.f),
+ mSaddleB(1.f)
{
}
-Toolkit::CubeTransitionWaveEffect CubeTransitionWaveEffect::New(unsigned int numRows, unsigned int numColumns )
+Toolkit::CubeTransitionWaveEffect CubeTransitionWaveEffect::New(unsigned int numRows, unsigned int numColumns)
{
// Create the implementation
- IntrusivePtr< CubeTransitionWaveEffect > internalCubeTransEffect = new CubeTransitionWaveEffect( numRows, numColumns );
+ IntrusivePtr<CubeTransitionWaveEffect> internalCubeTransEffect = new CubeTransitionWaveEffect(numRows, numColumns);
// Pass ownership to CustomActor handle
- Toolkit::CubeTransitionWaveEffect cubeTransEffect( *internalCubeTransEffect );
+ Toolkit::CubeTransitionWaveEffect cubeTransEffect(*internalCubeTransEffect);
//Initialization
internalCubeTransEffect->Initialize();
void CubeTransitionWaveEffect::OnInitialize()
{
- for( unsigned int idx = 0; idx < mTargetTiles.size(); idx++ )
+ for(unsigned int idx = 0; idx < mTargetTiles.size(); idx++)
{
- SetTargetRight( idx );
+ SetTargetRight(idx);
}
}
-void CubeTransitionWaveEffect::OnStartTransition( Vector2 panPosition, Vector2 panDisplacement )
+void CubeTransitionWaveEffect::OnStartTransition(Vector2 panPosition, Vector2 panDisplacement)
{
bool forward = panDisplacement.x < 0.0;
- CalculateSaddleSurfaceParameters( panPosition, forward ? panDisplacement : -panDisplacement );
+ CalculateSaddleSurfaceParameters(panPosition, forward ? panDisplacement : -panDisplacement);
float angle = Math::PI_2;
unsigned int idx;
- if( forward )
+ if(forward)
{
- for( idx = 0; idx < mTargetTiles.size(); idx++ )
+ for(idx = 0; idx < mTargetTiles.size(); idx++)
{
- SetTargetRight( idx );
+ SetTargetRight(idx);
}
}
else
{
angle = -angle;
- for( idx = 0; idx < mTargetTiles.size(); idx++ )
+ for(idx = 0; idx < mTargetTiles.size(); idx++)
{
- SetTargetLeft( idx );
+ SetTargetLeft(idx);
}
}
float thirdAnimationDuration = mAnimationDuration / 3.f;
- for( unsigned int y = 0; y < mRows; y++ )
+ for(unsigned int y = 0; y < mRows; y++)
{
idx = y * mColumns;
- for( unsigned int x = 0; x < mColumns; x++, idx++)
+ for(unsigned int x = 0; x < mColumns; x++, idx++)
{
// the delay value is within 0.f ~ 2.f*thirdAnimationDuration
- float delay = thirdAnimationDuration * CalculateDelay( x * mTileSize.width, y * mTileSize.height, forward );
+ float delay = thirdAnimationDuration * CalculateDelay(x * mTileSize.width, y * mTileSize.height, forward);
- mAnimation.AnimateTo( Property( mBoxes[ idx ], Actor::Property::ORIENTATION ), Quaternion( Radian( -angle ), Vector3::YAXIS ),
- AlphaFunction::EASE_OUT_SINE, TimePeriod( delay, thirdAnimationDuration ) );
- mAnimation.AnimateBy( Property( mBoxes[idx], Actor::Property::POSITION ), Vector3( 0.f, 0.f, -mCubeDisplacement ),
- AlphaFunction::BOUNCE, TimePeriod( delay, thirdAnimationDuration ) );
+ mAnimation.AnimateTo(Property(mBoxes[idx], Actor::Property::ORIENTATION), Quaternion(Radian(-angle), Vector3::YAXIS), AlphaFunction::EASE_OUT_SINE, TimePeriod(delay, thirdAnimationDuration));
+ mAnimation.AnimateBy(Property(mBoxes[idx], Actor::Property::POSITION), Vector3(0.f, 0.f, -mCubeDisplacement), AlphaFunction::BOUNCE, TimePeriod(delay, thirdAnimationDuration));
- mAnimation.AnimateTo( Property( mCurrentTiles[ idx ], Actor::Property::COLOR ), HALF_BRIGHTNESS,
- AlphaFunction::EASE_OUT, TimePeriod( delay, thirdAnimationDuration ) );
- mAnimation.AnimateTo( Property( mTargetTiles[ idx ], Actor::Property::COLOR ), FULL_BRIGHTNESS,
- AlphaFunction::EASE_IN, TimePeriod( delay, thirdAnimationDuration ) );
+ mAnimation.AnimateTo(Property(mCurrentTiles[idx], Actor::Property::COLOR), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT, TimePeriod(delay, thirdAnimationDuration));
+ mAnimation.AnimateTo(Property(mTargetTiles[idx], Actor::Property::COLOR), FULL_BRIGHTNESS, AlphaFunction::EASE_IN, TimePeriod(delay, thirdAnimationDuration));
}
}
mIsAnimating = true;
}
-void CubeTransitionWaveEffect::CalculateSaddleSurfaceParameters( Vector2 position, Vector2 displacement )
+void CubeTransitionWaveEffect::CalculateSaddleSurfaceParameters(Vector2 position, Vector2 displacement)
{
- const Vector2 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).GetVectorXY();
+ const Vector2 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE).GetVectorXY();
// the line passes through 'position' and has the direction of 'displacement'
float coefA, coefB, coefC; //line equation: Ax+By+C=0;
coefA = displacement.y;
coefB = -displacement.x;
- coefC = -displacement.y*position.x + displacement.x*position.y;
+ coefC = -displacement.y * position.x + displacement.x * position.y;
- float inversedAABB = 1.f / (coefA*coefA+coefB*coefB);
+ float inversedAABB = 1.f / (coefA * coefA + coefB * coefB);
float inversedSqrtAABB = sqrtf(inversedAABB);
float saddleA;
if(displacement.y > 0)
{
//distance from (0,0) to the line
- float distanceTopLeft = fabsf(coefC) * inversedSqrtAABB;
+ float distanceTopLeft = fabsf(coefC) * inversedSqrtAABB;
//distance from (viewAreaSize.x, viewAreaSize.y) to the line
- float distanceBottomRight = fabsf(coefA*size.x+coefB*size.y+coefC) * inversedSqrtAABB;
- saddleA = std::max( distanceTopLeft, distanceBottomRight );
+ float distanceBottomRight = fabsf(coefA * size.x + coefB * size.y + coefC) * inversedSqrtAABB;
+ saddleA = std::max(distanceTopLeft, distanceBottomRight);
//foot of a perpendicular: (viewAreaSize.x,0) to the line
- float footX1 = ( coefB*coefB*size.x - coefA*coefC) * inversedAABB;
- float footY1 = (-coefA*coefB*size.x - coefB*coefC) * inversedAABB;
+ float footX1 = (coefB * coefB * size.x - coefA * coefC) * inversedAABB;
+ float footY1 = (-coefA * coefB * size.x - coefB * coefC) * inversedAABB;
//foot of a perpendicular: (0,viewAreaSize.y) to the line
- float footX2 = (-coefA*coefB*size.y - coefA*coefC) * inversedAABB;
- float footY2 = ( coefA*coefA*size.y - coefB*coefC) * inversedAABB;
- mSaddleBB = (footX1-footX2)*(footX1-footX2) + (footY1-footY2)*(footY1-footY2);
- mTranslation = Vector2(-footX2,-footY2);
+ float footX2 = (-coefA * coefB * size.y - coefA * coefC) * inversedAABB;
+ float footY2 = (coefA * coefA * size.y - coefB * coefC) * inversedAABB;
+ mSaddleBB = (footX1 - footX2) * (footX1 - footX2) + (footY1 - footY2) * (footY1 - footY2);
+ mTranslation = Vector2(-footX2, -footY2);
}
else
{
//distance from(viewAreaSize.x,0) to the line
- float distanceTopRight = fabsf(coefA*size.x+coefC) * inversedSqrtAABB;
+ float distanceTopRight = fabsf(coefA * size.x + coefC) * inversedSqrtAABB;
//distance from(0,viewAreaSize.y) to the line
- float distanceBottomLeft = fabsf(coefB*size.y+coefC) * inversedSqrtAABB;
- saddleA = std::max( distanceTopRight, distanceBottomLeft );
+ float distanceBottomLeft = fabsf(coefB * size.y + coefC) * inversedSqrtAABB;
+ saddleA = std::max(distanceTopRight, distanceBottomLeft);
//foot of a perpendicular: (0,0) to the line
- float footX3 = (-coefA*coefC) * inversedAABB;
- float footY3 = (-coefB*coefC) * inversedAABB;
+ float footX3 = (-coefA * coefC) * inversedAABB;
+ float footY3 = (-coefB * coefC) * inversedAABB;
//foot of a perpendicular: (viewAreaSize.x,viewAreaSize.y) to the line
- float footX4 = ( coefB*coefB*size.x - coefA*coefB*size.y - coefA*coefC) * inversedAABB;
- float footY4 = (-coefA*coefB*size.x + coefA*coefA*size.y - coefB*coefC) * inversedAABB;
- mSaddleBB = (footX3-footX4)*(footX3-footX4) + (footY3-footY4)*(footY3-footY4);
+ float footX4 = (coefB * coefB * size.x - coefA * coefB * size.y - coefA * coefC) * inversedAABB;
+ float footY4 = (-coefA * coefB * size.x + coefA * coefA * size.y - coefB * coefC) * inversedAABB;
+ mSaddleBB = (footX3 - footX4) * (footX3 - footX4) + (footY3 - footY4) * (footY3 - footY4);
mTranslation = Vector2(-footX3, -footY3);
}
}
else if(mSaddleB < saddleA)
{
- mSaddleB = saddleA;
- mSaddleBB = mSaddleB*mSaddleB;
+ mSaddleB = saddleA;
+ mSaddleBB = mSaddleB * mSaddleB;
}
- mSaddleAA = saddleA*saddleA;
+ mSaddleAA = saddleA * saddleA;
mRotation = Vector2(-displacement.x, displacement.y);
mRotation.Normalize();
}
-float CubeTransitionWaveEffect::CalculateDelay( float x, float y, bool forward )
+float CubeTransitionWaveEffect::CalculateDelay(float x, float y, bool forward)
{
- float tx = x + mTranslation.x;
- float ty = y + mTranslation.y;
+ float tx = x + mTranslation.x;
+ float ty = y + mTranslation.y;
float valueX = mRotation.x * tx - mRotation.y * ty;
float valueY = mRotation.y * tx + mRotation.x * ty;
- if( !forward ) // to previous image
+ if(!forward) // to previous image
{
valueX = mSaddleB - valueX;
}
//the return value is a float number between 0.f and 2.f
- return (1.f + valueY*valueY / mSaddleAA - valueX*valueX / mSaddleBB);
+ return (1.f + valueY * valueY / mSaddleAA - valueX * valueX / mSaddleBB);
}
} // namespace Internal
//INTERNAL INCLUDES
#include <dali-toolkit/devel-api/visuals/animated-gradient-visual-properties-devel.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
-#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-DALI_ENUM_TO_STRING_TABLE_BEGIN( GRADIENT_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::GradientType, LINEAR )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::GradientType, RADIAL )
-DALI_ENUM_TO_STRING_TABLE_END( GRADIENT_TYPE )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( UNIT_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::UnitType, OBJECT_BOUNDING_BOX )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::UnitType, USER_SPACE )
-DALI_ENUM_TO_STRING_TABLE_END( UNIT_TYPE )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( SPREAD_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::SpreadType, REFLECT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::SpreadType, REPEAT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::SpreadType, CLAMP )
-DALI_ENUM_TO_STRING_TABLE_END( SPREAD_TYPE )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( DIRECTION_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType, FORWARD )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType, BACKWARD )
-DALI_ENUM_TO_STRING_TABLE_END( DIRECTION_TYPE )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( MOTION_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType, LOOP )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType, MIRROR )
-DALI_ENUM_TO_STRING_TABLE_END( MOTION_TYPE )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( EASING_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, LINEAR )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, IN )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, OUT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, IN_OUT )
-DALI_ENUM_TO_STRING_TABLE_END( EASING_TYPE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(GRADIENT_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::GradientType, LINEAR)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::GradientType, RADIAL)
+DALI_ENUM_TO_STRING_TABLE_END(GRADIENT_TYPE)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(UNIT_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::UnitType, OBJECT_BOUNDING_BOX)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::UnitType, USER_SPACE)
+DALI_ENUM_TO_STRING_TABLE_END(UNIT_TYPE)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(SPREAD_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::SpreadType, REFLECT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::SpreadType, REPEAT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::SpreadType, CLAMP)
+DALI_ENUM_TO_STRING_TABLE_END(SPREAD_TYPE)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(DIRECTION_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType, FORWARD)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType, BACKWARD)
+DALI_ENUM_TO_STRING_TABLE_END(DIRECTION_TYPE)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(MOTION_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType, LOOP)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType, MIRROR)
+DALI_ENUM_TO_STRING_TABLE_END(MOTION_TYPE)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(EASING_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, LINEAR)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, IN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, OUT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, IN_OUT)
+DALI_ENUM_TO_STRING_TABLE_END(EASING_TYPE)
// Default values of each properties
const Toolkit::DevelAnimatedGradientVisual::GradientType::Type DEFAULT_GRADIENT_TYPE = Toolkit::DevelAnimatedGradientVisual::GradientType::LINEAR;
const Toolkit::DevelAnimatedGradientVisual::UnitType::Type DEFAULT_UNIT_TYPE = Toolkit::DevelAnimatedGradientVisual::UnitType::OBJECT_BOUNDING_BOX;
const Toolkit::DevelAnimatedGradientVisual::SpreadType::Type DEFAULT_SPREAD_TYPE = Toolkit::DevelAnimatedGradientVisual::SpreadType::REFLECT;
-const float DEFAULT_START_POSITION[] = { -0.5f, 0.0f };
-const float DEFAULT_START_COLOR[] = { 143.0f/255.0f, 170.0f/255.0f, 220.0f/255.0f, 255.0f/255.0f };
-const float DEFAULT_END_POSITION[] = { 0.5f, 0.0f };
-const float DEFAULT_END_COLOR[] = { 255.0f/255.0f, 163.0f/255.0f, 163.0f/255.0f, 255.0f/255.0f };
-const float DEFAULT_ROTATE_CENTER[] = { 0.0f, 0.0f };
+const float DEFAULT_START_POSITION[] = {-0.5f, 0.0f};
+const float DEFAULT_START_COLOR[] = {143.0f / 255.0f, 170.0f / 255.0f, 220.0f / 255.0f, 255.0f / 255.0f};
+const float DEFAULT_END_POSITION[] = {0.5f, 0.0f};
+const float DEFAULT_END_COLOR[] = {255.0f / 255.0f, 163.0f / 255.0f, 163.0f / 255.0f, 255.0f / 255.0f};
+const float DEFAULT_ROTATE_CENTER[] = {0.0f, 0.0f};
const float DEFAULT_ROTATE_AMOUNT = 0.0f;
const float DEFAULT_ANIMATION_START_VALUE = 0.0f;
const Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::Type DEFAULT_ANIMATION_MOTION_TYPE = Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::LOOP;
const Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::Type DEFAULT_ANIMATION_EASING_TYPE = Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR;
-Property::Value GetStartValue( const Property::Map& map, Property::Index index, const char* const name )
+Property::Value GetStartValue(const Property::Map& map, Property::Index index, const char* const name)
{
// Get start value of animation parameter
- Property::Value* res = map.Find( index, name );
- if( res )
+ Property::Value* res = map.Find(index, name);
+ if(res)
{
Property::Map* s_map = res->GetMap();
- if( s_map )
+ if(s_map)
{
- res = s_map->Find( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, START_VALUE_NAME );
- DALI_ASSERT_ALWAYS( res && "Start value is not setup in Property::Map" );
+ res = s_map->Find(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, START_VALUE_NAME);
+ DALI_ASSERT_ALWAYS(res && "Start value is not setup in Property::Map");
}
}
else
{
- DALI_ASSERT_ALWAYS( !"Start value is not setup even default" );
+ DALI_ASSERT_ALWAYS(!"Start value is not setup even default");
}
return *res;
}
-VisualFactoryCache::ShaderType GetShaderType( Toolkit::DevelAnimatedGradientVisual::GradientType::Type grad, Toolkit::DevelAnimatedGradientVisual::UnitType::Type unit, Toolkit::DevelAnimatedGradientVisual::SpreadType::Type spread )
+VisualFactoryCache::ShaderType GetShaderType(Toolkit::DevelAnimatedGradientVisual::GradientType::Type grad, Toolkit::DevelAnimatedGradientVisual::UnitType::Type unit, Toolkit::DevelAnimatedGradientVisual::SpreadType::Type spread)
{
return static_cast<VisualFactoryCache::ShaderType>(
VisualFactoryCache::ANIMATED_GRADIENT_SHADER_LINEAR_BOUNDING_REFLECT +
- static_cast<unsigned int>( grad ) * 6 + // 6 is the number of UnitType * SpreadType
- static_cast<unsigned int>( unit ) * 3 + // 3 is the number of SpreadType.
- static_cast<unsigned int>( spread )
- );
+ static_cast<unsigned int>(grad) * 6 + // 6 is the number of UnitType * SpreadType
+ static_cast<unsigned int>(unit) * 3 + // 3 is the number of SpreadType.
+ static_cast<unsigned int>(spread));
}
} // unnamed namespace
-AnimatedGradientVisualPtr AnimatedGradientVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+AnimatedGradientVisualPtr AnimatedGradientVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
- AnimatedGradientVisualPtr animatedGradientVisualPtr( new AnimatedGradientVisual( factoryCache ) );
- animatedGradientVisualPtr->SetProperties( properties );
+ AnimatedGradientVisualPtr animatedGradientVisualPtr(new AnimatedGradientVisual(factoryCache));
+ animatedGradientVisualPtr->SetProperties(properties);
animatedGradientVisualPtr->Initialize();
return animatedGradientVisualPtr;
}
-AnimatedGradientVisual::AnimatedGradientVisual( VisualFactoryCache& factoryCache )
-: Visual::Base( factoryCache, Visual::FittingMode::FILL, static_cast<Toolkit::Visual::Type>( Toolkit::DevelVisual::ANIMATED_GRADIENT ) )
+AnimatedGradientVisual::AnimatedGradientVisual(VisualFactoryCache& factoryCache)
+: Visual::Base(factoryCache, Visual::FittingMode::FILL, static_cast<Toolkit::Visual::Type>(Toolkit::DevelVisual::ANIMATED_GRADIENT))
{
SetupDefaultValue();
}
AnimatedGradientVisual::~AnimatedGradientVisual()
{
-
}
void AnimatedGradientVisual::SetupDefaultValue()
mUnitType = DEFAULT_UNIT_TYPE;
mSpreadType = DEFAULT_SPREAD_TYPE;
- mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION] = Vector2( DEFAULT_START_POSITION );
- mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR] = Vector4( DEFAULT_START_COLOR );
- mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION] = Vector2( DEFAULT_END_POSITION );
- mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR] = Vector4( DEFAULT_END_COLOR );
- mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER] = Vector2( DEFAULT_ROTATE_CENTER );
+ mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION] = Vector2(DEFAULT_START_POSITION);
+ mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR] = Vector4(DEFAULT_START_COLOR);
+ mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION] = Vector2(DEFAULT_END_POSITION);
+ mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR] = Vector4(DEFAULT_END_COLOR);
+ mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER] = Vector2(DEFAULT_ROTATE_CENTER);
mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT] = DEFAULT_ROTATE_AMOUNT;
// Default Offset value is very special. unlimited animation from 0.0f to 2.0f
{
Property::Map map;
- map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, 0.0f );
- map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET, 2.0f );
- map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT, -1 );
+ map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, 0.0f);
+ map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET, 2.0f);
+ map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT, -1);
mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET] = map;
}
}
-void AnimatedGradientVisual::DoSetProperties( const Property::Map& propertyMap )
+void AnimatedGradientVisual::DoSetProperties(const Property::Map& propertyMap)
{
//GRADIENT_TYPE
- Property::Value* gradientTypeValue = propertyMap.Find( Toolkit::DevelAnimatedGradientVisual::Property::GRADIENT_TYPE, GRADIENT_TYPE_NAME );
- Toolkit::DevelAnimatedGradientVisual::GradientType::Type gradientType = mGradientType;
- if( gradientTypeValue )
+ Property::Value* gradientTypeValue = propertyMap.Find(Toolkit::DevelAnimatedGradientVisual::Property::GRADIENT_TYPE, GRADIENT_TYPE_NAME);
+ Toolkit::DevelAnimatedGradientVisual::GradientType::Type gradientType = mGradientType;
+ if(gradientTypeValue)
{
- Scripting::GetEnumerationProperty( *gradientTypeValue, GRADIENT_TYPE_TABLE, GRADIENT_TYPE_TABLE_COUNT, gradientType );
+ Scripting::GetEnumerationProperty(*gradientTypeValue, GRADIENT_TYPE_TABLE, GRADIENT_TYPE_TABLE_COUNT, gradientType);
}
//UNIT_TYPE
- Property::Value* unitTypeValue = propertyMap.Find( Toolkit::DevelAnimatedGradientVisual::Property::UNIT_TYPE, UNIT_TYPE_NAME );
- Toolkit::DevelAnimatedGradientVisual::UnitType::Type unitType = mUnitType;
- if( unitTypeValue )
+ Property::Value* unitTypeValue = propertyMap.Find(Toolkit::DevelAnimatedGradientVisual::Property::UNIT_TYPE, UNIT_TYPE_NAME);
+ Toolkit::DevelAnimatedGradientVisual::UnitType::Type unitType = mUnitType;
+ if(unitTypeValue)
{
- Scripting::GetEnumerationProperty( *unitTypeValue, UNIT_TYPE_TABLE, UNIT_TYPE_TABLE_COUNT, unitType );
+ Scripting::GetEnumerationProperty(*unitTypeValue, UNIT_TYPE_TABLE, UNIT_TYPE_TABLE_COUNT, unitType);
}
//SPREAD_TYPE
- Property::Value* spreadTypeValue = propertyMap.Find( Toolkit::DevelAnimatedGradientVisual::Property::SPREAD_TYPE, SPREAD_TYPE_NAME );
- Toolkit::DevelAnimatedGradientVisual::SpreadType::Type spreadType = mSpreadType;
- if( spreadTypeValue )
+ Property::Value* spreadTypeValue = propertyMap.Find(Toolkit::DevelAnimatedGradientVisual::Property::SPREAD_TYPE, SPREAD_TYPE_NAME);
+ Toolkit::DevelAnimatedGradientVisual::SpreadType::Type spreadType = mSpreadType;
+ if(spreadTypeValue)
{
- Scripting::GetEnumerationProperty( *spreadTypeValue, SPREAD_TYPE_TABLE, SPREAD_TYPE_TABLE_COUNT, spreadType );
+ Scripting::GetEnumerationProperty(*spreadTypeValue, SPREAD_TYPE_TABLE, SPREAD_TYPE_TABLE_COUNT, spreadType);
}
mGradientType = gradientType;
- mUnitType = unitType;
- mSpreadType = spreadType;
+ mUnitType = unitType;
+ mSpreadType = spreadType;
SetupGradientAnimationData(propertyMap);
}
-void AnimatedGradientVisual::SetupGradientAnimationData( const Property::Map& propertyMap )
+void AnimatedGradientVisual::SetupGradientAnimationData(const Property::Map& propertyMap)
{
mGradientAnimationDataList.Clear(); // Clear Transition Information. All animation will deleted safely
static Property::Map propertyNameMap;
static Property::Map propertyUniformNameMap;
- if( propertyNameMap.Empty() )
+ if(propertyNameMap.Empty())
{
propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION] = START_POSITION_NAME;
- propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR ] = START_COLOR_NAME;
- propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION ] = END_POSITION_NAME;
- propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR ] = END_COLOR_NAME;
- propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER ] = ROTATE_CENTER_NAME;
- propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT ] = ROTATE_AMOUNT_NAME;
- propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET ] = OFFSET_NAME;
+ propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR] = START_COLOR_NAME;
+ propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION] = END_POSITION_NAME;
+ propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR] = END_COLOR_NAME;
+ propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER] = ROTATE_CENTER_NAME;
+ propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT] = ROTATE_AMOUNT_NAME;
+ propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET] = OFFSET_NAME;
}
- if( propertyUniformNameMap.Empty() )
+ if(propertyUniformNameMap.Empty())
{
propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION] = UNIFORM_START_POINT_NAME;
- propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR ] = UNIFORM_START_COLOR_NAME;
- propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION ] = UNIFORM_END_POINT_NAME;
- propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR ] = UNIFORM_END_COLOR_NAME;
- propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER ] = UNIFORM_ROTATE_CENTER_NAME;
- propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT ] = UNIFORM_ROTATE_ANGLE_NAME;
- propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET ] = UNIFORM_OFFSET_NAME;
+ propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR] = UNIFORM_START_COLOR_NAME;
+ propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION] = UNIFORM_END_POINT_NAME;
+ propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR] = UNIFORM_END_COLOR_NAME;
+ propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER] = UNIFORM_ROTATE_CENTER_NAME;
+ propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT] = UNIFORM_ROTATE_ANGLE_NAME;
+ propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET] = UNIFORM_OFFSET_NAME;
}
Property::Map::SizeType map_index_end = propertyNameMap.Count();
- for( Property::Map::SizeType map_index = 0; map_index < map_index_end; map_index++ )
+ for(Property::Map::SizeType map_index = 0; map_index < map_index_end; map_index++)
{
- KeyValuePair property_pair = propertyNameMap.GetKeyValue( map_index );
- KeyValuePair uniform_pair = propertyUniformNameMap.GetKeyValue( map_index );
- Property::Index index = property_pair.first.indexKey;
- const std::string property_name = property_pair.second.Get< std::string >();
- const std::string uniform_name = uniform_pair.second.Get< std::string >();
+ KeyValuePair property_pair = propertyNameMap.GetKeyValue(map_index);
+ KeyValuePair uniform_pair = propertyUniformNameMap.GetKeyValue(map_index);
+ Property::Index index = property_pair.first.indexKey;
+ const std::string property_name = property_pair.second.Get<std::string>();
+ const std::string uniform_name = uniform_pair.second.Get<std::string>();
- Property::Map map;
+ Property::Map map;
Property::Value default_value = mValueMap[index];
- map["target"] = "background";
+ map["target"] = "background";
map["property"] = uniform_name;
- Property::Value *value = propertyMap.Find( index, property_name );
- if( !value )
+ Property::Value* value = propertyMap.Find(index, property_name);
+ if(!value)
{
value = &default_value;
}
mValueMap[index] = (*value);
}
- int loop_count = 0;
- float delay = 0.0f;
- bool forward = true;
- bool auto_mirror = false;
- std::string ease_str = "LINEAR";
- Property::Map *map_value = value->GetMap();
- if( map_value )
+ int loop_count = 0;
+ float delay = 0.0f;
+ bool forward = true;
+ bool auto_mirror = false;
+ std::string ease_str = "LINEAR";
+ Property::Map* map_value = value->GetMap();
+ if(map_value)
{
- auto getValueFromMap = [ &map_value ]( const Property::Index& index, const std::string& name, Property::Value& res ) -> void
- {
- Property::Value *sub_value = map_value->Find( index, name );
- if( sub_value )
+ auto getValueFromMap = [&map_value](const Property::Index& index, const std::string& name, Property::Value& res) -> void {
+ Property::Value* sub_value = map_value->Find(index, name);
+ if(sub_value)
{
res = *sub_value;
}
Property::Value value_repeat = DEFAULT_ANIMATION_REPEAT;
Property::Value value_repeat_delay = DEFAULT_ANIMATION_REPEAT_DELAY;
- getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START , START_VALUE_NAME , value_start );
- getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET , TARGET_VALUE_NAME , value_target );
- getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DURATION , DURATION_NAME , value_duration );
- getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DELAY , DELAY_NAME , value_delay );
- getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT , REPEAT_NAME , value_repeat );
- getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT_DELAY, REPEAT_DELAY_NAME , value_repeat_delay );
+ getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, START_VALUE_NAME, value_start);
+ getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET, TARGET_VALUE_NAME, value_target);
+ getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DURATION, DURATION_NAME, value_duration);
+ getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DELAY, DELAY_NAME, value_delay);
+ getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT, REPEAT_NAME, value_repeat);
+ getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT_DELAY, REPEAT_DELAY_NAME, value_repeat_delay);
Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::Type direction_type = DEFAULT_ANIMATION_DIRECTION_TYPE;
Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::Type motion_type = DEFAULT_ANIMATION_MOTION_TYPE;
Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::Type easing_type = DEFAULT_ANIMATION_EASING_TYPE;
- Property::Value *direction_sub_value = map_value->Find( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DIRECTION, DIRECTION_TYPE_NAME );
- if( direction_sub_value )
+ Property::Value* direction_sub_value = map_value->Find(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DIRECTION, DIRECTION_TYPE_NAME);
+ if(direction_sub_value)
{
- Scripting::GetEnumerationProperty( *direction_sub_value, DIRECTION_TYPE_TABLE, DIRECTION_TYPE_TABLE_COUNT, direction_type );
+ Scripting::GetEnumerationProperty(*direction_sub_value, DIRECTION_TYPE_TABLE, DIRECTION_TYPE_TABLE_COUNT, direction_type);
}
- Property::Value *motion_sub_value = map_value->Find( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::MOTION_TYPE, MOTION_TYPE_NAME );
- if( motion_sub_value )
+ Property::Value* motion_sub_value = map_value->Find(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::MOTION_TYPE, MOTION_TYPE_NAME);
+ if(motion_sub_value)
{
- Scripting::GetEnumerationProperty( *motion_sub_value , MOTION_TYPE_TABLE , MOTION_TYPE_TABLE_COUNT , motion_type );
+ Scripting::GetEnumerationProperty(*motion_sub_value, MOTION_TYPE_TABLE, MOTION_TYPE_TABLE_COUNT, motion_type);
}
- Property::Value *easing_sub_value = map_value->Find( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::EASING_TYPE, EASING_TYPE_NAME );
- if( easing_sub_value )
+ Property::Value* easing_sub_value = map_value->Find(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::EASING_TYPE, EASING_TYPE_NAME);
+ if(easing_sub_value)
{
- Scripting::GetEnumerationProperty( *easing_sub_value , EASING_TYPE_TABLE , EASING_TYPE_TABLE_COUNT , easing_type );
+ Scripting::GetEnumerationProperty(*easing_sub_value, EASING_TYPE_TABLE, EASING_TYPE_TABLE_COUNT, easing_type);
}
- forward = ( direction_type == Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::FORWARD );
- delay = value_delay.Get< float >();
- loop_count = value_repeat.Get< int >();
- auto_mirror = ( motion_type == Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::MIRROR );
+ forward = (direction_type == Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::FORWARD);
+ delay = value_delay.Get<float>();
+ loop_count = value_repeat.Get<int>();
+ auto_mirror = (motion_type == Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::MIRROR);
- switch( easing_type )
+ switch(easing_type)
{
case Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR:
{
}
map["initialValue"] = forward ? value_start : value_target;
- map["targetValue"] = forward ? value_target : value_start;
- if( loop_count != 0 )
+ map["targetValue"] = forward ? value_target : value_start;
+ if(loop_count != 0)
{
map["animator"] = Property::Map()
- .Add( "alphaFunction", ease_str )
- .Add( "timePeriod", Property::Map()
- .Add( "delay", value_repeat_delay.Get< float >() )
- .Add( "duration", value_duration.Get< float >() ) );
+ .Add("alphaFunction", ease_str)
+ .Add("timePeriod", Property::Map().Add("delay", value_repeat_delay.Get<float>()).Add("duration", value_duration.Get<float>()));
}
}
else
{
map["initialValue"] = *value;
- map["targetValue"] = *value;
+ map["targetValue"] = *value;
}
- AnimatedGradientVisual::GradientAnimationData *animData = new AnimatedGradientVisual::GradientAnimationData();
- animData->transition = Toolkit::TransitionData::New( map );
- animData->index = index;
- animData->loop_count = loop_count;
- animData->delay = delay;
- animData->forward = forward;
- animData->auto_mirror = auto_mirror;
- mGradientAnimationDataList.PushBack( animData );
+ AnimatedGradientVisual::GradientAnimationData* animData = new AnimatedGradientVisual::GradientAnimationData();
+ animData->transition = Toolkit::TransitionData::New(map);
+ animData->index = index;
+ animData->loop_count = loop_count;
+ animData->delay = delay;
+ animData->forward = forward;
+ animData->auto_mirror = auto_mirror;
+ mGradientAnimationDataList.PushBack(animData);
}
}
void AnimatedGradientVisual::SetupAnimation()
{
- for( auto&& elem : mGradientAnimationDataList )
+ for(auto&& elem : mGradientAnimationDataList)
{
- Toolkit::TransitionData& transition = elem->transition;
- Animation& animation = elem->animation;
- int loop_count = elem->loop_count;
- bool auto_mirror = elem->auto_mirror;
- bool without_animation = ( loop_count == 0 );
-
- const Internal::TransitionData& transitionData = Toolkit::GetImplementation( transition );
- for( auto iter = transitionData.Begin(); iter != transitionData.End(); iter++ )
+ Toolkit::TransitionData& transition = elem->transition;
+ Animation& animation = elem->animation;
+ int loop_count = elem->loop_count;
+ bool auto_mirror = elem->auto_mirror;
+ bool without_animation = (loop_count == 0);
+
+ const Internal::TransitionData& transitionData = Toolkit::GetImplementation(transition);
+ for(auto iter = transitionData.Begin(); iter != transitionData.End(); iter++)
{
- TransitionData::Animator *animator = (*iter);
- AnimateProperty( animation, *animator );
+ TransitionData::Animator* animator = (*iter);
+ AnimateProperty(animation, *animator);
}
- if( animation && !without_animation )
+ if(animation && !without_animation)
{
- if( loop_count < 0 )
+ if(loop_count < 0)
{
- animation.SetLooping( true );
+ animation.SetLooping(true);
}
- else if( loop_count > 0 )
+ else if(loop_count > 0)
{
- animation.SetLoopCount( loop_count );
+ animation.SetLoopCount(loop_count);
}
- if( auto_mirror )
+ if(auto_mirror)
{
- animation.SetLoopingMode( Animation::LoopingMode::AUTO_REVERSE );
+ animation.SetLoopingMode(Animation::LoopingMode::AUTO_REVERSE);
}
}
}
void AnimatedGradientVisual::PlayAnimation()
{
- for( auto&& elem : mGradientAnimationDataList )
+ for(auto&& elem : mGradientAnimationDataList)
{
Animation& animation = elem->animation;
- if( animation )
+ if(animation)
{
float delay = elem->delay;
- if( delay > 0.0f )
+ if(delay > 0.0f)
{
- animation.PlayAfter( delay );
+ animation.PlayAfter(delay);
}
- else if( delay < 0.0f )
+ else if(delay < 0.0f)
{
float progress = -delay / animation.GetDuration(); // (duration + repeat_duration)
if(progress >= 1.0f)
{
- int cur_loop = animation.GetLoopCount();
- int decrease_loop = floor( progress ) + 1;
- while( decrease_loop > progress )
+ int cur_loop = animation.GetLoopCount();
+ int decrease_loop = floor(progress) + 1;
+ while(decrease_loop > progress)
{
decrease_loop--;
}
progress -= decrease_loop;
- if( cur_loop == 0 )
+ if(cur_loop == 0)
{
- animation.PlayFrom( progress );
+ animation.PlayFrom(progress);
}
else
{
cur_loop -= decrease_loop;
- if( cur_loop > 0 )
+ if(cur_loop > 0)
{
- animation.SetLoopCount( cur_loop );
- animation.PlayFrom( progress );
+ animation.SetLoopCount(cur_loop);
+ animation.PlayFrom(progress);
}
else
{
// animation done. make this animation finished safely.
- animation.SetLoopCount( 1 );
- animation.PlayFrom( 1.0f );
+ animation.SetLoopCount(1);
+ animation.PlayFrom(1.0f);
}
}
}
else
{
- animation.PlayFrom( progress );
+ animation.PlayFrom(progress);
}
}
else
void AnimatedGradientVisual::StopAnimation()
{
- for( auto&& elem : mGradientAnimationDataList )
+ for(auto&& elem : mGradientAnimationDataList)
{
Animation& animation = elem->animation;
- if( animation )
+ if(animation)
{
animation.Stop();
}
void AnimatedGradientVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
-void AnimatedGradientVisual::DoSetOnScene( Actor& actor )
+void AnimatedGradientVisual::DoSetOnScene(Actor& actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
SetupAnimation();
PlayAnimation();
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
-void AnimatedGradientVisual::DoSetOffScene( Actor& actor )
+void AnimatedGradientVisual::DoSetOffScene(Actor& actor)
{
- DALI_ASSERT_DEBUG( (bool)mImpl->mRenderer && "There should always be a renderer whilst on stage");
+ DALI_ASSERT_DEBUG((bool)mImpl->mRenderer && "There should always be a renderer whilst on stage");
StopAnimation();
- actor.RemoveRenderer( mImpl->mRenderer );
+ actor.RemoveRenderer(mImpl->mRenderer);
}
-void AnimatedGradientVisual::DoCreatePropertyMap( Property::Map& map ) const
+void AnimatedGradientVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_GRADIENT );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_GRADIENT);
//Create non-animated properties
- map.Insert( Toolkit::DevelAnimatedGradientVisual::Property::GRADIENT_TYPE, static_cast<int>(mGradientType) );
- map.Insert( Toolkit::DevelAnimatedGradientVisual::Property::UNIT_TYPE , static_cast<int>(mUnitType) );
- map.Insert( Toolkit::DevelAnimatedGradientVisual::Property::SPREAD_TYPE , static_cast<int>(mSpreadType) );
+ map.Insert(Toolkit::DevelAnimatedGradientVisual::Property::GRADIENT_TYPE, static_cast<int>(mGradientType));
+ map.Insert(Toolkit::DevelAnimatedGradientVisual::Property::UNIT_TYPE, static_cast<int>(mUnitType));
+ map.Insert(Toolkit::DevelAnimatedGradientVisual::Property::SPREAD_TYPE, static_cast<int>(mSpreadType));
//Create animated properties. Get from transition for more realistic test. Not from animation cause Animation may not setuped
- for( auto&& elem : mGradientAnimationDataList )
+ for(auto&& elem : mGradientAnimationDataList)
{
- Toolkit::TransitionData& transition = elem->transition;
- Property::Index index = elem->index;
- int loop_count = elem->loop_count;
- float delay = elem->delay;
- bool forward = elem->forward;
- bool auto_mirror = elem->auto_mirror;
-
- const Internal::TransitionData& transitionData = Toolkit::GetImplementation( transition );
- for( auto iter = transitionData.Begin(); iter != transitionData.End(); iter++ )
+ Toolkit::TransitionData& transition = elem->transition;
+ Property::Index index = elem->index;
+ int loop_count = elem->loop_count;
+ float delay = elem->delay;
+ bool forward = elem->forward;
+ bool auto_mirror = elem->auto_mirror;
+
+ const Internal::TransitionData& transitionData = Toolkit::GetImplementation(transition);
+ for(auto iter = transitionData.Begin(); iter != transitionData.End(); iter++)
{
- TransitionData::Animator *animator = (*iter);
- if( animator->animate )
+ TransitionData::Animator* animator = (*iter);
+ if(animator->animate)
{
//with animation
- Property::Map animation_map;
- Property::Value value_start = forward ? animator->initialValue : animator->targetValue;
+ Property::Map animation_map;
+ Property::Value value_start = forward ? animator->initialValue : animator->targetValue;
Property::Value value_target = forward ? animator->targetValue : animator->initialValue;
Property::Value value_direction;
- Property::Value value_duration = Property::Value( animator->timePeriodDuration );
- Property::Value value_delay = Property::Value( delay );
- Property::Value value_repeat = Property::Value( loop_count );
- Property::Value value_repeat_delay = Property::Value( animator->timePeriodDelay );
+ Property::Value value_duration = Property::Value(animator->timePeriodDuration);
+ Property::Value value_delay = Property::Value(delay);
+ Property::Value value_repeat = Property::Value(loop_count);
+ Property::Value value_repeat_delay = Property::Value(animator->timePeriodDelay);
Property::Value value_motion_type;
Property::Value value_easing_type;
- if( forward )
+ if(forward)
{
- value_direction = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::FORWARD );
+ value_direction = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::FORWARD);
}
else
{
- value_direction = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::BACKWARD );
+ value_direction = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::BACKWARD);
}
- if( auto_mirror )
+ if(auto_mirror)
{
- value_motion_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::MIRROR );
+ value_motion_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::MIRROR);
}
else
{
- value_motion_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::LOOP );
+ value_motion_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::LOOP);
}
- switch( animator->alphaFunction.GetBuiltinFunction() )
+ switch(animator->alphaFunction.GetBuiltinFunction())
{
case Dali::AlphaFunction::LINEAR:
{
- value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR );
+ value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR);
break;
}
case Dali::AlphaFunction::EASE_IN_SQUARE:
{
- value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::IN );
+ value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::IN);
break;
}
case Dali::AlphaFunction::EASE_OUT_SQUARE:
{
- value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::OUT );
+ value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::OUT);
break;
}
case Dali::AlphaFunction::EASE_IN_OUT:
{
- value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::IN_OUT );
+ value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::IN_OUT);
break;
}
default:
{
- value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR );
+ value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR);
}
}
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START , value_start );
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET , value_target );
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DIRECTION , value_direction );
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DURATION , value_duration );
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DELAY , value_delay );
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT , value_repeat );
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT_DELAY, value_repeat_delay );
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::MOTION_TYPE , value_motion_type );
- animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::EASING_TYPE , value_easing_type );
-
- map.Insert( index, animation_map );
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, value_start);
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET, value_target);
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DIRECTION, value_direction);
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DURATION, value_duration);
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DELAY, value_delay);
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT, value_repeat);
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT_DELAY, value_repeat_delay);
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::MOTION_TYPE, value_motion_type);
+ animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::EASING_TYPE, value_easing_type);
+
+ map.Insert(index, animation_map);
}
else
{
//without animation
- map.Insert( index, animator->targetValue );
+ map.Insert(index, animator->targetValue);
}
}
}
}
-void AnimatedGradientVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void AnimatedGradientVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
-
}
Shader AnimatedGradientVisual::CreateShader()
std::string tagUnit;
std::string tagGrad;
std::string tagSpread;
- switch( mUnitType )
+ switch(mUnitType)
{
case Toolkit::DevelAnimatedGradientVisual::UnitType::OBJECT_BOUNDING_BOX:
{
break;
}
}
- switch( mGradientType )
+ switch(mGradientType)
{
case Toolkit::DevelAnimatedGradientVisual::GradientType::LINEAR:
{
break;
}
}
- switch( mSpreadType )
+ switch(mSpreadType)
{
case Toolkit::DevelAnimatedGradientVisual::SpreadType::REFLECT:
{
std::string vert;
std::string frag;
- vert = "#define " + tagUnit + "\n"
- + SHADER_ANIMATED_GRADIENT_VISUAL_SHADER_VERT.data();
- frag = "#define " + tagGrad + "\n"
- + "#define " + tagSpread + "\n"
- + SHADER_ANIMATED_GRADIENT_VISUAL_SHADER_FRAG.data();
+ vert = "#define " + tagUnit + "\n" + SHADER_ANIMATED_GRADIENT_VISUAL_SHADER_VERT.data();
+ frag = "#define " + tagGrad + "\n" + "#define " + tagSpread + "\n" + SHADER_ANIMATED_GRADIENT_VISUAL_SHADER_FRAG.data();
- shader = Shader::New( vert, frag );
+ shader = Shader::New(vert, frag);
return shader;
}
void AnimatedGradientVisual::OnInitialize()
{
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
- VisualFactoryCache::ShaderType shaderType = GetShaderType( mGradientType, mUnitType, mSpreadType );
- Shader shader = mFactoryCache.GetShader( shaderType );
- if( !shader )
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
+ VisualFactoryCache::ShaderType shaderType = GetShaderType(mGradientType, mUnitType, mSpreadType);
+ Shader shader = mFactoryCache.GetShader(shaderType);
+ if(!shader)
{
shader = CreateShader();
- mFactoryCache.SaveShader( shaderType, shader );
+ mFactoryCache.SaveShader(shaderType, shader);
}
- mImpl->mRenderer = Renderer::New( geometry, shader );
+ mImpl->mRenderer = Renderer::New(geometry, shader);
- mImpl->mRenderer.RegisterProperty( UNIFORM_START_POINT_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION, START_POSITION_NAME ) );
- mImpl->mRenderer.RegisterProperty( UNIFORM_START_COLOR_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR , START_COLOR_NAME ) );
- mImpl->mRenderer.RegisterProperty( UNIFORM_END_POINT_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION , END_POSITION_NAME ) );
- mImpl->mRenderer.RegisterProperty( UNIFORM_END_COLOR_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR , END_COLOR_NAME ) );
- mImpl->mRenderer.RegisterProperty( UNIFORM_ROTATE_CENTER_NAME, GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER , ROTATE_CENTER_NAME ) );
- mImpl->mRenderer.RegisterProperty( UNIFORM_ROTATE_ANGLE_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT , ROTATE_AMOUNT_NAME ) );
- mImpl->mRenderer.RegisterProperty( UNIFORM_OFFSET_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::OFFSET , OFFSET_NAME ) );
+ mImpl->mRenderer.RegisterProperty(UNIFORM_START_POINT_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION, START_POSITION_NAME));
+ mImpl->mRenderer.RegisterProperty(UNIFORM_START_COLOR_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR, START_COLOR_NAME));
+ mImpl->mRenderer.RegisterProperty(UNIFORM_END_POINT_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION, END_POSITION_NAME));
+ mImpl->mRenderer.RegisterProperty(UNIFORM_END_COLOR_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR, END_COLOR_NAME));
+ mImpl->mRenderer.RegisterProperty(UNIFORM_ROTATE_CENTER_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER, ROTATE_CENTER_NAME));
+ mImpl->mRenderer.RegisterProperty(UNIFORM_ROTATE_ANGLE_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT, ROTATE_AMOUNT_NAME));
+ mImpl->mRenderer.RegisterProperty(UNIFORM_OFFSET_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::OFFSET, OFFSET_NAME));
//Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
-}//namespace Internal
+} //namespace Internal
-}//namespace Toolkit
+} //namespace Toolkit
-}//namespace Dali
+} //namespace Dali
#include <memory>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
-#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
-#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
-#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
-#include <dali-toolkit/internal/visuals/animated-image/fixed-image-cache.h>
-#include <dali-toolkit/internal/visuals/animated-image/rolling-image-cache.h>
-#include <dali-toolkit/internal/visuals/animated-image/rolling-animated-image-cache.h>
#include <dali-toolkit/devel-api/image-loader/image-atlas.h>
#include <dali-toolkit/devel-api/image-loader/texture-manager.h>
#include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
+#include <dali-toolkit/internal/visuals/animated-image/fixed-image-cache.h>
+#include <dali-toolkit/internal/visuals/animated-image/rolling-animated-image-cache.h>
+#include <dali-toolkit/internal/visuals/animated-image/rolling-image-cache.h>
+#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
+#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/internal/visuals/visual-string-constants.h>
+#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
// stop behavior
-DALI_ENUM_TO_STRING_TABLE_BEGIN( STOP_BEHAVIOR )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME )
-DALI_ENUM_TO_STRING_TABLE_END( STOP_BEHAVIOR )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(STOP_BEHAVIOR)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME)
+DALI_ENUM_TO_STRING_TABLE_END(STOP_BEHAVIOR)
// wrap modes
-DALI_ENUM_TO_STRING_TABLE_BEGIN( WRAP_MODE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, DEFAULT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, CLAMP_TO_EDGE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, REPEAT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, MIRRORED_REPEAT )
-DALI_ENUM_TO_STRING_TABLE_END( WRAP_MODE )
-
-const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
+DALI_ENUM_TO_STRING_TABLE_BEGIN(WRAP_MODE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, DEFAULT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, CLAMP_TO_EDGE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, REPEAT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, MIRRORED_REPEAT)
+DALI_ENUM_TO_STRING_TABLE_END(WRAP_MODE)
+
+const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
constexpr auto LOOP_FOREVER = -1;
#if defined(DEBUG_ENABLED)
Debug::Filter* gAnimImgLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ANIMATED_IMAGE");
#endif
-}
-
+} // namespace
/**
* Multi-image Flow of execution
* Time
*/
-AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties )
+AnimatedImageVisualPtr AnimatedImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
{
- AnimatedImageVisualPtr visual( new AnimatedImageVisual( factoryCache, shaderFactory ) );
- visual->InitializeAnimatedImage( imageUrl );
- visual->SetProperties( properties );
+ AnimatedImageVisualPtr visual(new AnimatedImageVisual(factoryCache, shaderFactory));
+ visual->InitializeAnimatedImage(imageUrl);
+ visual->SetProperties(properties);
- if( visual->mFrameCount > 0 )
+ if(visual->mFrameCount > 0)
{
visual->LoadFirstBatch();
}
return visual;
}
-AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Property::Array& imageUrls, const Property::Map& properties )
+AnimatedImageVisualPtr AnimatedImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Property::Array& imageUrls, const Property::Map& properties)
{
- AnimatedImageVisualPtr visual( new AnimatedImageVisual( factoryCache, shaderFactory ) );
+ AnimatedImageVisualPtr visual(new AnimatedImageVisual(factoryCache, shaderFactory));
visual->mImageUrls = new ImageCache::UrlList();
- visual->mImageUrls->reserve( imageUrls.Count() );
+ visual->mImageUrls->reserve(imageUrls.Count());
- for( unsigned int i=0; i < imageUrls.Count(); ++i)
+ for(unsigned int i = 0; i < imageUrls.Count(); ++i)
{
ImageCache::UrlStore urlStore;
urlStore.mTextureId = TextureManager::INVALID_TEXTURE_ID;
- urlStore.mUrl = imageUrls[i].Get<std::string>();
- visual->mImageUrls->push_back( urlStore );
+ urlStore.mUrl = imageUrls[i].Get<std::string>();
+ visual->mImageUrls->push_back(urlStore);
}
visual->mFrameCount = imageUrls.Count();
- visual->SetProperties( properties );
+ visual->SetProperties(properties);
- if( visual->mFrameCount > 0 )
+ if(visual->mFrameCount > 0)
{
visual->LoadFirstBatch();
}
return visual;
}
-AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl )
+AnimatedImageVisualPtr AnimatedImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
{
- AnimatedImageVisualPtr visual( new AnimatedImageVisual( factoryCache, shaderFactory ) );
- visual->InitializeAnimatedImage( imageUrl );
+ AnimatedImageVisualPtr visual(new AnimatedImageVisual(factoryCache, shaderFactory));
+ visual->InitializeAnimatedImage(imageUrl);
- if( visual->mFrameCount > 0 )
+ if(visual->mFrameCount > 0)
{
visual->LoadFirstBatch();
}
return visual;
}
-void AnimatedImageVisual::InitializeAnimatedImage( const VisualUrl& imageUrl )
+void AnimatedImageVisual::InitializeAnimatedImage(const VisualUrl& imageUrl)
{
- mImageUrl = imageUrl;
- mAnimatedImageLoading = AnimatedImageLoading::New( imageUrl.GetUrl(), imageUrl.IsLocalResource() );
- mFrameCount = mAnimatedImageLoading.GetImageCount();
+ mImageUrl = imageUrl;
+ mAnimatedImageLoading = AnimatedImageLoading::New(imageUrl.GetUrl(), imageUrl.IsLocalResource());
+ mFrameCount = mAnimatedImageLoading.GetImageCount();
}
-AnimatedImageVisual::AnimatedImageVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory )
-: Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::ANIMATED_IMAGE ),
+AnimatedImageVisual::AnimatedImageVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory)
+: Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::ANIMATED_IMAGE),
mFrameDelayTimer(),
mPlacementActor(),
- mImageVisualShaderFactory( shaderFactory ),
- mPixelArea( FULL_TEXTURE_RECT ),
+ mImageVisualShaderFactory(shaderFactory),
+ mPixelArea(FULL_TEXTURE_RECT),
mImageUrl(),
mAnimatedImageLoading(),
- mFrameIndexForJumpTo( 0 ),
- mImageUrls( NULL ),
- mImageCache( NULL ),
- mCacheSize( 2 ),
- mBatchSize( 2 ),
- mFrameDelay( 100 ),
- mLoopCount( LOOP_FOREVER ),
- mCurrentLoopIndex( 0 ),
- mUrlIndex( 0 ),
- mFrameCount( 0 ),
+ mFrameIndexForJumpTo(0),
+ mImageUrls(NULL),
+ mImageCache(NULL),
+ mCacheSize(2),
+ mBatchSize(2),
+ mFrameDelay(100),
+ mLoopCount(LOOP_FOREVER),
+ mCurrentLoopIndex(0),
+ mUrlIndex(0),
+ mFrameCount(0),
mImageSize(),
- mWrapModeU( WrapMode::DEFAULT ),
- mWrapModeV( WrapMode::DEFAULT ),
- mActionStatus( DevelAnimatedImageVisual::Action::PLAY ),
- mStopBehavior( DevelImageVisual::StopBehavior::CURRENT_FRAME ),
+ mWrapModeU(WrapMode::DEFAULT),
+ mWrapModeV(WrapMode::DEFAULT),
+ mActionStatus(DevelAnimatedImageVisual::Action::PLAY),
+ mStopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME),
mStartFirstFrame(false),
- mIsJumpTo( false )
-{}
+ mIsJumpTo(false)
+{
+}
AnimatedImageVisual::~AnimatedImageVisual()
{
delete mImageUrls;
}
-void AnimatedImageVisual::GetNaturalSize( Vector2& naturalSize )
+void AnimatedImageVisual::GetNaturalSize(Vector2& naturalSize)
{
- if( mImageSize.GetWidth() == 0 && mImageSize.GetHeight() == 0)
+ if(mImageSize.GetWidth() == 0 && mImageSize.GetHeight() == 0)
{
- if( mImageUrl.IsValid() )
+ if(mImageUrl.IsValid())
{
mImageSize = mAnimatedImageLoading.GetImageSize();
}
- else if( mImageUrls && mImageUrls->size() > 0 )
+ else if(mImageUrls && mImageUrls->size() > 0)
{
- mImageSize = Dali::GetClosestImageSize( (*mImageUrls)[0].mUrl );
+ mImageSize = Dali::GetClosestImageSize((*mImageUrls)[0].mUrl);
}
}
- naturalSize.width = mImageSize.GetWidth();
+ naturalSize.width = mImageSize.GetWidth();
naturalSize.height = mImageSize.GetHeight();
}
-void AnimatedImageVisual::DoCreatePropertyMap( Property::Map& map ) const
+void AnimatedImageVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
bool sync = IsSynchronousLoadingRequired();
- map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync );
+ map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync);
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::ANIMATED_IMAGE );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::ANIMATED_IMAGE);
- if( mImageUrl.IsValid() )
+ if(mImageUrl.IsValid())
{
- map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
+ map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
}
- if( mImageUrls != NULL && ! mImageUrls->empty() )
+ if(mImageUrls != NULL && !mImageUrls->empty())
{
Property::Array urls;
- for( unsigned int i=0; i<mImageUrls->size(); ++i)
+ for(unsigned int i = 0; i < mImageUrls->size(); ++i)
{
- urls.Add( (*mImageUrls)[i].mUrl );
+ urls.Add((*mImageUrls)[i].mUrl);
}
- Property::Value value( const_cast<Property::Array&>(urls) );
- map.Insert( Toolkit::ImageVisual::Property::URL, value );
+ Property::Value value(const_cast<Property::Array&>(urls));
+ map.Insert(Toolkit::ImageVisual::Property::URL, value);
}
- map.Insert( Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea );
- map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU );
- map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV );
+ map.Insert(Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea);
+ map.Insert(Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU);
+ map.Insert(Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV);
- map.Insert( Toolkit::ImageVisual::Property::BATCH_SIZE, static_cast<int>(mBatchSize) );
- map.Insert( Toolkit::ImageVisual::Property::CACHE_SIZE, static_cast<int>(mCacheSize) );
- map.Insert( Toolkit::ImageVisual::Property::FRAME_DELAY, static_cast<int>(mFrameDelay) );
- map.Insert( Toolkit::DevelImageVisual::Property::LOOP_COUNT, static_cast<int>(mLoopCount) );
- map.Insert( Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, (mImageCache) ? static_cast<int32_t>(mImageCache->GetCurrentFrameIndex()) : -1 );
- map.Insert( Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, (mImageCache) ? static_cast<int32_t>(mImageCache->GetTotalFrameCount()) : -1 );
+ map.Insert(Toolkit::ImageVisual::Property::BATCH_SIZE, static_cast<int>(mBatchSize));
+ map.Insert(Toolkit::ImageVisual::Property::CACHE_SIZE, static_cast<int>(mCacheSize));
+ map.Insert(Toolkit::ImageVisual::Property::FRAME_DELAY, static_cast<int>(mFrameDelay));
+ map.Insert(Toolkit::DevelImageVisual::Property::LOOP_COUNT, static_cast<int>(mLoopCount));
+ map.Insert(Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, (mImageCache) ? static_cast<int32_t>(mImageCache->GetCurrentFrameIndex()) : -1);
+ map.Insert(Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, (mImageCache) ? static_cast<int32_t>(mImageCache->GetTotalFrameCount()) : -1);
- map.Insert( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mStopBehavior );
+ map.Insert(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mStopBehavior);
}
-void AnimatedImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void AnimatedImageVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
-void AnimatedImageVisual::OnDoAction( const Dali::Property::Index actionId, const Dali::Property::Value& attributes )
+void AnimatedImageVisual::OnDoAction(const Dali::Property::Index actionId, const Dali::Property::Value& attributes)
{
// Check if action is valid for this visual type and perform action if possible
- switch ( actionId )
+ switch(actionId)
{
case DevelAnimatedImageVisual::Action::PAUSE:
{
}
case DevelAnimatedImageVisual::Action::PLAY:
{
- if( mFrameDelayTimer && IsOnScene() && mActionStatus != DevelAnimatedImageVisual::Action::PLAY )
+ if(mFrameDelayTimer && IsOnScene() && mActionStatus != DevelAnimatedImageVisual::Action::PLAY)
{
mFrameDelayTimer.Start();
}
// STOP reset functionality will actually be done in a future change
// Stop will be executed on next timer tick
mActionStatus = DevelAnimatedImageVisual::Action::STOP;
- if( IsOnScene() )
+ if(IsOnScene())
{
DisplayNextFrame();
}
case DevelAnimatedImageVisual::Action::JUMP_TO:
{
int32_t frameNumber;
- if( attributes.Get( frameNumber ) )
+ if(attributes.Get(frameNumber))
{
- if( frameNumber < 0 || frameNumber >= static_cast<int32_t>( mFrameCount ) )
+ if(frameNumber < 0 || frameNumber >= static_cast<int32_t>(mFrameCount))
{
- DALI_LOG_ERROR( "Invalid frame index used.\n" );
+ DALI_LOG_ERROR("Invalid frame index used.\n");
}
else
{
- mIsJumpTo = true;
+ mIsJumpTo = true;
mFrameIndexForJumpTo = frameNumber;
- if( IsOnScene() )
+ if(IsOnScene())
{
DisplayNextFrame();
}
}
}
-void AnimatedImageVisual::DoSetProperties( const Property::Map& propertyMap )
+void AnimatedImageVisual::DoSetProperties(const Property::Map& propertyMap)
{
// url[s] already passed in from constructor
- for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
+ for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
{
- KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
- if( keyValue.first.type == Property::Key::INDEX )
+ KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
+ if(keyValue.first.type == Property::Key::INDEX)
{
- DoSetProperty( keyValue.first.indexKey, keyValue.second );
+ DoSetProperty(keyValue.first.indexKey, keyValue.second);
}
else
{
- if( keyValue.first == PIXEL_AREA_UNIFORM_NAME )
+ if(keyValue.first == PIXEL_AREA_UNIFORM_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second);
}
- else if( keyValue.first == IMAGE_WRAP_MODE_U )
+ else if(keyValue.first == IMAGE_WRAP_MODE_U)
{
- DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second);
}
- else if( keyValue.first == IMAGE_WRAP_MODE_V )
+ else if(keyValue.first == IMAGE_WRAP_MODE_V)
{
- DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second);
}
- else if( keyValue.first == BATCH_SIZE_NAME )
+ else if(keyValue.first == BATCH_SIZE_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::BATCH_SIZE, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::BATCH_SIZE, keyValue.second);
}
- else if( keyValue.first == CACHE_SIZE_NAME )
+ else if(keyValue.first == CACHE_SIZE_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::CACHE_SIZE, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::CACHE_SIZE, keyValue.second);
}
- else if( keyValue.first == FRAME_DELAY_NAME )
+ else if(keyValue.first == FRAME_DELAY_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::FRAME_DELAY, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::FRAME_DELAY, keyValue.second);
}
- else if( keyValue.first == LOOP_COUNT_NAME )
+ else if(keyValue.first == LOOP_COUNT_NAME)
{
- DoSetProperty( Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second );
+ DoSetProperty(Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second);
}
- else if( keyValue.first == STOP_BEHAVIOR_NAME )
+ else if(keyValue.first == STOP_BEHAVIOR_NAME)
{
- DoSetProperty( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second );
+ DoSetProperty(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second);
}
}
}
}
-void AnimatedImageVisual::DoSetProperty( Property::Index index,
- const Property::Value& value )
+void AnimatedImageVisual::DoSetProperty(Property::Index index,
+ const Property::Value& value)
{
switch(index)
{
case Toolkit::ImageVisual::Property::PIXEL_AREA:
{
- value.Get( mPixelArea );
+ value.Get(mPixelArea);
break;
}
case Toolkit::ImageVisual::Property::WRAP_MODE_U:
{
int wrapMode = 0;
- if(Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode ))
+ if(Scripting::GetEnumerationProperty(value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode))
{
mWrapModeU = Dali::WrapMode::Type(wrapMode);
}
case Toolkit::ImageVisual::Property::WRAP_MODE_V:
{
int wrapMode = 0;
- if(Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode ))
+ if(Scripting::GetEnumerationProperty(value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode))
{
mWrapModeV = Dali::WrapMode::Type(wrapMode);
}
case Toolkit::ImageVisual::Property::BATCH_SIZE:
{
int batchSize;
- if( value.Get( batchSize ) )
+ if(value.Get(batchSize))
{
- if( batchSize < 2 )
+ if(batchSize < 2)
{
- DALI_LOG_ERROR( "The minimum value of batch size is 2." );
+ DALI_LOG_ERROR("The minimum value of batch size is 2.");
}
else
{
case Toolkit::ImageVisual::Property::CACHE_SIZE:
{
int cacheSize;
- if( value.Get( cacheSize ) )
+ if(value.Get(cacheSize))
{
- if( cacheSize < 2 )
+ if(cacheSize < 2)
{
- DALI_LOG_ERROR( "The minimum value of cache size is 2." );
+ DALI_LOG_ERROR("The minimum value of cache size is 2.");
}
else
{
case Toolkit::ImageVisual::Property::FRAME_DELAY:
{
int frameDelay;
- if( value.Get( frameDelay ) )
+ if(value.Get(frameDelay))
{
mFrameDelay = frameDelay;
}
case Toolkit::DevelImageVisual::Property::LOOP_COUNT:
{
int loopCount;
- if( value.Get( loopCount ) )
+ if(value.Get(loopCount))
{
mLoopCount = loopCount;
}
case Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR:
{
int32_t stopBehavior = mStopBehavior;
- if( Scripting::GetEnumerationProperty( value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior ) )
+ if(Scripting::GetEnumerationProperty(value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior))
{
- mStopBehavior = DevelImageVisual::StopBehavior::Type( stopBehavior );
+ mStopBehavior = DevelImageVisual::StopBehavior::Type(stopBehavior);
}
break;
}
case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
{
bool sync = false;
- value.Get( sync );
- if( sync )
+ value.Get(sync);
+ if(sync)
{
mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
}
}
}
-void AnimatedImageVisual::DoSetOnScene( Actor& actor )
+void AnimatedImageVisual::DoSetOnScene(Actor& actor)
{
- mPlacementActor = actor;
+ mPlacementActor = actor;
TextureSet textureSet = PrepareTextureSet();
- if( textureSet ) // if the image loading is successful
+ if(textureSet) // if the image loading is successful
{
- StartFirstFrame( textureSet );
+ StartFirstFrame(textureSet);
}
else
{
}
}
-void AnimatedImageVisual::DoSetOffScene( Actor& actor )
+void AnimatedImageVisual::DoSetOffScene(Actor& actor)
{
- DALI_ASSERT_DEBUG( (bool)mImpl->mRenderer && "There should always be a renderer whilst on stage");
+ DALI_ASSERT_DEBUG((bool)mImpl->mRenderer && "There should always be a renderer whilst on stage");
- if( mFrameDelayTimer )
+ if(mFrameDelayTimer)
{
mFrameDelayTimer.Stop();
mFrameDelayTimer.Reset();
}
- actor.RemoveRenderer( mImpl->mRenderer );
+ actor.RemoveRenderer(mImpl->mRenderer);
mPlacementActor.Reset();
mStartFirstFrame = false;
}
void AnimatedImageVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
void AnimatedImageVisual::OnInitialize()
{
- bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE;
- bool atlasing = false;
- Shader shader = mImageVisualShaderFactory.GetShader( mFactoryCache, atlasing, defaultWrapMode, IsRoundedCornerRequired() );
+ bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE;
+ bool atlasing = false;
+ Shader shader = mImageVisualShaderFactory.GetShader(mFactoryCache, atlasing, defaultWrapMode, IsRoundedCornerRequired());
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
- mImpl->mRenderer = Renderer::New( geometry, shader );
+ mImpl->mRenderer = Renderer::New(geometry, shader);
// Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
- if( !defaultWrapMode ) // custom wrap mode
+ if(!defaultWrapMode) // custom wrap mode
{
- Vector2 wrapMode(mWrapModeU-WrapMode::CLAMP_TO_EDGE, mWrapModeV-WrapMode::CLAMP_TO_EDGE);
- wrapMode.Clamp( Vector2::ZERO, Vector2( 2.f, 2.f ) );
- mImpl->mRenderer.RegisterProperty( WRAP_MODE_UNIFORM_NAME, wrapMode );
+ Vector2 wrapMode(mWrapModeU - WrapMode::CLAMP_TO_EDGE, mWrapModeV - WrapMode::CLAMP_TO_EDGE);
+ wrapMode.Clamp(Vector2::ZERO, Vector2(2.f, 2.f));
+ mImpl->mRenderer.RegisterProperty(WRAP_MODE_UNIFORM_NAME, wrapMode);
}
- if( mPixelArea != FULL_TEXTURE_RECT )
+ if(mPixelArea != FULL_TEXTURE_RECT)
{
- mImpl->mRenderer.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, mPixelArea );
+ mImpl->mRenderer.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, mPixelArea);
}
}
{
// Ensure the batch size and cache size are no bigger than the number of URLs,
// and that the cache is at least as big as the batch size.
- uint16_t numUrls = 0;
+ uint16_t numUrls = 0;
uint16_t batchSize = 1;
uint16_t cacheSize = 1;
- if( mImageUrls )
+ if(mImageUrls)
{
numUrls = mImageUrls->size();
}
numUrls = mFrameCount;
}
- batchSize = std::min( mBatchSize, numUrls );
- cacheSize = std::min( std::max( batchSize, mCacheSize ), numUrls );
+ batchSize = std::min(mBatchSize, numUrls);
+ cacheSize = std::min(std::max(batchSize, mCacheSize), numUrls);
- DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::LoadFirstBatch() batchSize:%d cacheSize:%d\n", batchSize, cacheSize);
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::LoadFirstBatch() batchSize:%d cacheSize:%d\n", batchSize, cacheSize);
- mUrlIndex = 0;
+ mUrlIndex = 0;
TextureManager& textureManager = mFactoryCache.GetTextureManager();
- if( mAnimatedImageLoading )
+ if(mAnimatedImageLoading)
{
- mImageCache = new RollingAnimatedImageCache( textureManager, mAnimatedImageLoading, mFrameCount, *this, cacheSize, batchSize, IsSynchronousLoadingRequired() );
+ mImageCache = new RollingAnimatedImageCache(textureManager, mAnimatedImageLoading, mFrameCount, *this, cacheSize, batchSize, IsSynchronousLoadingRequired());
}
- else if( mImageUrls )
+ else if(mImageUrls)
{
- if( batchSize > 0 && cacheSize > 0 )
+ if(batchSize > 0 && cacheSize > 0)
{
- if( cacheSize < numUrls )
+ if(cacheSize < numUrls)
{
- mImageCache = new RollingImageCache( textureManager, *mImageUrls, *this, cacheSize, batchSize );
+ mImageCache = new RollingImageCache(textureManager, *mImageUrls, *this, cacheSize, batchSize);
}
else
{
- mImageCache = new FixedImageCache( textureManager, *mImageUrls, *this, batchSize );
+ mImageCache = new FixedImageCache(textureManager, *mImageUrls, *this, batchSize);
}
}
else
{
- mImageCache = new RollingImageCache( textureManager, *mImageUrls, *this, 1, 1 );
+ mImageCache = new RollingImageCache(textureManager, *mImageUrls, *this, 1, 1);
}
}
- if (!mImageCache)
+ if(!mImageCache)
{
DALI_LOG_ERROR("mImageCache is null\n");
}
}
-void AnimatedImageVisual::StartFirstFrame( TextureSet& textureSet )
+void AnimatedImageVisual::StartFirstFrame(TextureSet& textureSet)
{
- DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::StartFirstFrame()\n");
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::StartFirstFrame()\n");
mStartFirstFrame = false;
if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
Actor actor = mPlacementActor.GetHandle();
- if( actor )
+ if(actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
mPlacementActor.Reset();
}
}
- if( mFrameCount > 1 )
+ if(mFrameCount > 1)
{
- int frameDelay = mImageCache->GetFrameInterval( 0 );
- if( frameDelay == 0u )
+ int frameDelay = mImageCache->GetFrameInterval(0);
+ if(frameDelay == 0u)
{
frameDelay = mFrameDelay; // from URL array
}
- mFrameDelayTimer = Timer::New( frameDelay );
- mFrameDelayTimer.TickSignal().Connect( this, &AnimatedImageVisual::DisplayNextFrame );
+ mFrameDelayTimer = Timer::New(frameDelay);
+ mFrameDelayTimer.TickSignal().Connect(this, &AnimatedImageVisual::DisplayNextFrame);
mFrameDelayTimer.Start();
}
- DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"ResourceReady(ResourceStatus::READY)\n");
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "ResourceReady(ResourceStatus::READY)\n");
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
TextureSet AnimatedImageVisual::PrepareTextureSet()
{
TextureSet textureSet;
- if (mImageCache)
+ if(mImageCache)
{
textureSet = mImageCache->FirstFrame();
}
- if( textureSet )
+ if(textureSet)
{
- SetImageSize( textureSet );
+ SetImageSize(textureSet);
}
return textureSet;
}
-void AnimatedImageVisual::SetImageSize( TextureSet& textureSet )
+void AnimatedImageVisual::SetImageSize(TextureSet& textureSet)
{
- if( textureSet )
+ if(textureSet)
{
- Texture texture = textureSet.GetTexture( 0 );
- if( texture )
+ Texture texture = textureSet.GetTexture(0);
+ if(texture)
{
- mImageSize.SetWidth( texture.GetWidth() );
- mImageSize.SetHeight( texture.GetHeight() );
+ mImageSize.SetWidth(texture.GetWidth());
+ mImageSize.SetHeight(texture.GetHeight());
}
}
}
-void AnimatedImageVisual::FrameReady( TextureSet textureSet )
+void AnimatedImageVisual::FrameReady(TextureSet textureSet)
{
if(textureSet)
{
}
else
{
- DALI_LOG_INFO( gAnimImgLogFilter, Debug::Concise, "ResourceReady(ResourceStatus::FAILED)\n" );
- ResourceReady( Toolkit::Visual::ResourceStatus::FAILED );
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "ResourceReady(ResourceStatus::FAILED)\n");
+ ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
}
}
if(mImageCache)
{
- bool nextFrame = false;
+ bool nextFrame = false;
uint32_t frameIndex = mImageCache->GetCurrentFrameIndex();
- if( mIsJumpTo )
+ if(mIsJumpTo)
{
- mIsJumpTo = false;
+ mIsJumpTo = false;
frameIndex = mFrameIndexForJumpTo;
}
- else if( mActionStatus == DevelAnimatedImageVisual::Action::PAUSE )
+ else if(mActionStatus == DevelAnimatedImageVisual::Action::PAUSE)
{
return false;
}
- else if( mActionStatus == DevelAnimatedImageVisual::Action::STOP )
+ else if(mActionStatus == DevelAnimatedImageVisual::Action::STOP)
{
frameIndex = 0;
- if( mStopBehavior == DevelImageVisual::StopBehavior::FIRST_FRAME )
+ if(mStopBehavior == DevelImageVisual::StopBehavior::FIRST_FRAME)
{
frameIndex = 0;
}
- else if( mStopBehavior == DevelImageVisual::StopBehavior::LAST_FRAME )
+ else if(mStopBehavior == DevelImageVisual::StopBehavior::LAST_FRAME)
{
frameIndex = mFrameCount - 1;
}
}
else
{
- if( mFrameCount > 1 )
+ if(mFrameCount > 1)
{
nextFrame = true;
frameIndex++;
- if( frameIndex >= mFrameCount )
+ if(frameIndex >= mFrameCount)
{
frameIndex %= mFrameCount;
++mCurrentLoopIndex;
}
}
- unsigned int delay = mImageCache->GetFrameInterval( frameIndex );
- if( delay > 0u )
+ unsigned int delay = mImageCache->GetFrameInterval(frameIndex);
+ if(delay > 0u)
{
- if( mFrameDelayTimer.GetInterval() != delay )
+ if(mFrameDelayTimer.GetInterval() != delay)
{
- mFrameDelayTimer.SetInterval( delay );
+ mFrameDelayTimer.SetInterval(delay);
}
}
}
- DALI_LOG_INFO( gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::DisplayNextFrame(this:%p) CurrentFrameIndex:%d\n", this, frameIndex);
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::DisplayNextFrame(this:%p) CurrentFrameIndex:%d\n", this, frameIndex);
TextureSet textureSet;
if(nextFrame)
}
else
{
- textureSet = mImageCache->Frame( frameIndex );
+ textureSet = mImageCache->Frame(frameIndex);
}
- if( textureSet )
+ if(textureSet)
{
- SetImageSize( textureSet );
- if( mImpl->mRenderer )
+ SetImageSize(textureSet);
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
}
}
- continueTimer = ( mActionStatus == DevelAnimatedImageVisual::Action::PLAY ) ? true : false;
+ continueTimer = (mActionStatus == DevelAnimatedImageVisual::Action::PLAY) ? true : false;
}
return continueTimer;
}
-
} // namespace Internal
} // namespace Toolkit
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Internal
{
-
namespace
{
-const bool ENABLE_ORIENTATION_CORRECTION( true );
+const bool ENABLE_ORIENTATION_CORRECTION(true);
} // namespace
FixedImageCache::FixedImageCache(
- TextureManager& textureManager, UrlList& urlList, ImageCache::FrameReadyObserver& observer,
- unsigned int batchSize )
-: ImageCache( textureManager, observer, batchSize ),
- mImageUrls( urlList ),
+ TextureManager& textureManager, UrlList& urlList, ImageCache::FrameReadyObserver& observer, unsigned int batchSize)
+: ImageCache(textureManager, observer, batchSize),
+ mImageUrls(urlList),
mFront(0u)
{
- mReadyFlags.reserve( mImageUrls.size() );
+ mReadyFlags.reserve(mImageUrls.size());
LoadBatch();
}
FixedImageCache::~FixedImageCache()
{
- if( mTextureManagerAlive )
+ if(mTextureManagerAlive)
{
- for( std::size_t i = 0; i < mImageUrls.size() ; ++i )
+ for(std::size_t i = 0; i < mImageUrls.size(); ++i)
{
- mTextureManager.Remove( mImageUrls[i].mTextureId, this );
+ mTextureManager.Remove(mImageUrls[i].mTextureId, this);
}
}
}
-TextureSet FixedImageCache::Frame( uint32_t frameIndex )
+TextureSet FixedImageCache::Frame(uint32_t frameIndex)
{
- while( frameIndex > mFront )
+ while(frameIndex > mFront)
{
++mFront;
- if( mFront >= mImageUrls.size() )
+ if(mFront >= mImageUrls.size())
{
mFront = 0;
}
mFront = frameIndex;
TextureSet textureSet;
- if( IsFrontReady() == true )
+ if(IsFrontReady() == true)
{
textureSet = GetFrontTextureSet();
}
{
TextureSet textureSet = GetFrontTextureSet();
- if( ! textureSet )
+ if(!textureSet)
{
mWaitingForReadyFrame = true;
}
return textureSet;
}
-uint32_t FixedImageCache::GetFrameInterval( uint32_t frameIndex ) const
+uint32_t FixedImageCache::GetFrameInterval(uint32_t frameIndex) const
{
return 0u;
}
bool FixedImageCache::IsFrontReady() const
{
- return ( mReadyFlags.size() > 0 && mReadyFlags[mFront] == true );
+ return (mReadyFlags.size() > 0 && mReadyFlags[mFront] == true);
}
void FixedImageCache::LoadBatch()
// no more images are loaded.
bool frontFrameReady = IsFrontReady();
- for( unsigned int i=0; i< mBatchSize && mUrlIndex < mImageUrls.size(); ++i )
+ for(unsigned int i = 0; i < mBatchSize && mUrlIndex < mImageUrls.size(); ++i)
{
- std::string& url = mImageUrls[ mUrlIndex ].mUrl;
+ std::string& url = mImageUrls[mUrlIndex].mUrl;
mReadyFlags.push_back(false);
// need to account for this inside the UploadComplete method using mRequestingLoad.
mRequestingLoad = true;
- bool synchronousLoading = false;
- bool atlasingStatus = false;
- bool loadingStatus = false;
- TextureManager::MaskingDataPointer maskInfo = nullptr;
- AtlasUploadObserver* atlasObserver = nullptr;
- ImageAtlasManagerPtr imageAtlasManager = nullptr;
- Vector4 textureRect;
- Dali::ImageDimensions textureRectSize;
- auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
+ bool synchronousLoading = false;
+ bool atlasingStatus = false;
+ bool loadingStatus = false;
+ TextureManager::MaskingDataPointer maskInfo = nullptr;
+ AtlasUploadObserver* atlasObserver = nullptr;
+ ImageAtlasManagerPtr imageAtlasManager = nullptr;
+ Vector4 textureRect;
+ Dali::ImageDimensions textureRectSize;
+ auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
mTextureManager.LoadTexture(
- url, ImageDimensions(), FittingMode::SCALE_TO_FILL,
- SamplingMode::BOX_THEN_LINEAR, maskInfo,
- synchronousLoading, mImageUrls[ mUrlIndex ].mTextureId, textureRect, textureRectSize,
- atlasingStatus, loadingStatus, Dali::WrapMode::Type::DEFAULT,
- Dali::WrapMode::Type::DEFAULT, this,
- atlasObserver, imageAtlasManager, ENABLE_ORIENTATION_CORRECTION, TextureManager::ReloadPolicy::CACHED,
- preMultiply );
-
- if( loadingStatus == false ) // not loading, means it's already ready.
+ url, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, maskInfo, synchronousLoading, mImageUrls[mUrlIndex].mTextureId, textureRect, textureRectSize, atlasingStatus, loadingStatus, Dali::WrapMode::Type::DEFAULT, Dali::WrapMode::Type::DEFAULT, this, atlasObserver, imageAtlasManager, ENABLE_ORIENTATION_CORRECTION, TextureManager::ReloadPolicy::CACHED, preMultiply);
+
+ if(loadingStatus == false) // not loading, means it's already ready.
{
- SetImageFrameReady( mImageUrls[ mUrlIndex ].mTextureId );
+ SetImageFrameReady(mImageUrls[mUrlIndex].mTextureId);
}
mRequestingLoad = false;
++mUrlIndex;
}
- CheckFrontFrame( frontFrameReady );
+ CheckFrontFrame(frontFrameReady);
}
-void FixedImageCache::SetImageFrameReady( TextureManager::TextureId textureId )
+void FixedImageCache::SetImageFrameReady(TextureManager::TextureId textureId)
{
- for( std::size_t i = 0; i < mImageUrls.size() ; ++i )
+ for(std::size_t i = 0; i < mImageUrls.size(); ++i)
{
- if( mImageUrls[i].mTextureId == textureId )
+ if(mImageUrls[i].mTextureId == textureId)
{
mReadyFlags[i] = true;
break;
TextureSet FixedImageCache::GetFrontTextureSet() const
{
- return mTextureManager.GetTextureSet( mImageUrls[mFront].mTextureId );
+ return mTextureManager.GetTextureSet(mImageUrls[mFront].mTextureId);
}
-void FixedImageCache::CheckFrontFrame( bool wasReady )
+void FixedImageCache::CheckFrontFrame(bool wasReady)
{
- if( mWaitingForReadyFrame && wasReady == false && IsFrontReady() )
+ if(mWaitingForReadyFrame && wasReady == false && IsFrontReady())
{
mWaitingForReadyFrame = false;
- mObserver.FrameReady( GetFrontTextureSet() );
+ mObserver.FrameReady(GetFrontTextureSet());
}
}
{
bool frontFrameReady = IsFrontReady();
- if( ! mRequestingLoad )
+ if(!mRequestingLoad)
{
- SetImageFrameReady( textureId );
+ SetImageFrameReady(textureId);
- CheckFrontFrame( frontFrameReady );
+ CheckFrontFrame(frontFrameReady);
}
else
{
}
void FixedImageCache::LoadComplete(
- bool loadSuccess,
+ bool loadSuccess,
Devel::PixelBuffer pixelBuffer,
- const VisualUrl& url,
- bool preMultiplied )
+ const VisualUrl& url,
+ bool preMultiplied)
{
// LoadComplete is called if this TextureUploadObserver requested to load
// an image that will be returned as a type of PixelBuffer by using a method
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Internal
{
-
-ImageCache::ImageCache( TextureManager& textureManager,
- ImageCache::FrameReadyObserver& observer,
- unsigned int batchSize )
-: mTextureManager( textureManager ),
- mObserver( observer ),
- mBatchSize( batchSize ),
+ImageCache::ImageCache(TextureManager& textureManager,
+ ImageCache::FrameReadyObserver& observer,
+ unsigned int batchSize)
+: mTextureManager(textureManager),
+ mObserver(observer),
+ mBatchSize(batchSize),
mUrlIndex(0u),
mWaitingForReadyFrame(false),
mRequestingLoad(false),
mTextureManagerAlive(true)
{
- mTextureManager.AddObserver( *this );
+ mTextureManager.AddObserver(*this);
}
ImageCache::~ImageCache()
{
- if( mTextureManagerAlive )
+ if(mTextureManagerAlive)
{
- mTextureManager.RemoveObserver( *this );
+ mTextureManager.RemoveObserver(*this);
}
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#if defined(DEBUG_ENABLED)
Debug::Filter* gAnimImgLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ANIMATED_IMAGE");
-#define LOG_CACHE \
- { \
- std::ostringstream oss; \
- oss<<"Size:"<<mQueue.Count()<<" [ "; \
- for(std::size_t _i=0; _i<mQueue.Count(); ++_i) \
- { \
- oss<<_i<< \
- "={ frm#: " << mQueue[_i].mFrameNumber << \
- " tex: " << mImageUrls[mQueue[_i].mFrameNumber].mTextureId<<"}, "; \
- } \
- oss<<" ]"<<std::endl; \
- DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"%s",oss.str().c_str()); \
+#define LOG_CACHE \
+ { \
+ std::ostringstream oss; \
+ oss << "Size:" << mQueue.Count() << " [ "; \
+ for(std::size_t _i = 0; _i < mQueue.Count(); ++_i) \
+ { \
+ oss << _i << "={ frm#: " << mQueue[_i].mFrameNumber << " tex: " << mImageUrls[mQueue[_i].mFrameNumber].mTextureId << "}, "; \
+ } \
+ oss << " ]" << std::endl; \
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "%s", oss.str().c_str()); \
}
#else
- #define LOG_CACHE
+#define LOG_CACHE
#endif
-const bool ENABLE_ORIENTATION_CORRECTION( true );
+const bool ENABLE_ORIENTATION_CORRECTION(true);
-}
+} // namespace
namespace Dali
{
{
namespace Internal
{
-
RollingAnimatedImageCache::RollingAnimatedImageCache(
- TextureManager& textureManager, AnimatedImageLoading& animatedImageLoading, uint32_t frameCount, ImageCache::FrameReadyObserver& observer,
- uint16_t cacheSize, uint16_t batchSize, bool isSynchronousLoading )
-: ImageCache( textureManager, observer, batchSize ),
- mAnimatedImageLoading( animatedImageLoading ),
- mFrameCount( frameCount ),
- mFrameIndex( 0 ),
- mCacheSize( cacheSize ),
- mQueue( cacheSize ),
- mIsSynchronousLoading( isSynchronousLoading ),
- mOnLoading( false )
+ TextureManager& textureManager, AnimatedImageLoading& animatedImageLoading, uint32_t frameCount, ImageCache::FrameReadyObserver& observer, uint16_t cacheSize, uint16_t batchSize, bool isSynchronousLoading)
+: ImageCache(textureManager, observer, batchSize),
+ mAnimatedImageLoading(animatedImageLoading),
+ mFrameCount(frameCount),
+ mFrameIndex(0),
+ mCacheSize(cacheSize),
+ mQueue(cacheSize),
+ mIsSynchronousLoading(isSynchronousLoading),
+ mOnLoading(false)
{
- mImageUrls.resize( mFrameCount );
- mIntervals.assign( mFrameCount, 0 );
+ mImageUrls.resize(mFrameCount);
+ mIntervals.assign(mFrameCount, 0);
LoadBatch();
}
RollingAnimatedImageCache::~RollingAnimatedImageCache()
{
- if( mTextureManagerAlive )
+ if(mTextureManagerAlive)
{
- while( !mQueue.IsEmpty() )
+ while(!mQueue.IsEmpty())
{
ImageFrame imageFrame = mQueue.PopFront();
- mTextureManager.Remove( mImageUrls[ imageFrame.mFrameNumber ].mTextureId, this );
+ mTextureManager.Remove(mImageUrls[imageFrame.mFrameNumber].mTextureId, this);
}
}
}
-TextureSet RollingAnimatedImageCache::Frame( uint32_t frameIndex )
+TextureSet RollingAnimatedImageCache::Frame(uint32_t frameIndex)
{
bool popExist = false;
- while( !mQueue.IsEmpty() && mQueue.Front().mFrameNumber != frameIndex )
+ while(!mQueue.IsEmpty() && mQueue.Front().mFrameNumber != frameIndex)
{
ImageFrame imageFrame = mQueue.PopFront();
- mTextureManager.Remove( mImageUrls[ imageFrame.mFrameNumber ].mTextureId, this );
- mImageUrls[ imageFrame.mFrameNumber ].mTextureId = TextureManager::INVALID_TEXTURE_ID;
- popExist = true;
+ mTextureManager.Remove(mImageUrls[imageFrame.mFrameNumber].mTextureId, this);
+ mImageUrls[imageFrame.mFrameNumber].mTextureId = TextureManager::INVALID_TEXTURE_ID;
+ popExist = true;
}
TextureSet textureSet;
// If we need to load new frame that are not stored in queue.
// Load the frame synchronously.
- if( mIsSynchronousLoading && mQueue.IsEmpty() )
+ if(mIsSynchronousLoading && mQueue.IsEmpty())
{
bool synchronousLoading = true;
- textureSet = mTextureManager.LoadAnimatedImageTexture( mAnimatedImageLoading, frameIndex, SamplingMode::BOX_THEN_LINEAR,
- synchronousLoading, mImageUrls[ frameIndex ].mTextureId, Dali::WrapMode::Type::DEFAULT,
- Dali::WrapMode::Type::DEFAULT, this );
- mFrameIndex = ( frameIndex + 1 ) % mFrameCount;
+ textureSet = mTextureManager.LoadAnimatedImageTexture(mAnimatedImageLoading, frameIndex, SamplingMode::BOX_THEN_LINEAR, synchronousLoading, mImageUrls[frameIndex].mTextureId, Dali::WrapMode::Type::DEFAULT, Dali::WrapMode::Type::DEFAULT, this);
+ mFrameIndex = (frameIndex + 1) % mFrameCount;
}
- if( popExist || mQueue.IsEmpty() )
+ if(popExist || mQueue.IsEmpty())
{
// If the frame of frameIndex was already loaded, load batch from the last frame of queue
- if( !mQueue.IsEmpty() )
+ if(!mQueue.IsEmpty())
{
if(!mLoadWaitingQueue.empty())
{
- mFrameIndex = ( mLoadWaitingQueue.back() + 1 ) % mFrameCount;
+ mFrameIndex = (mLoadWaitingQueue.back() + 1) % mFrameCount;
}
else
{
- mFrameIndex = ( mQueue.Back().mFrameNumber + 1 ) % mFrameCount;
+ mFrameIndex = (mQueue.Back().mFrameNumber + 1) % mFrameCount;
}
}
else
// If the request is for the first frame or a jumped frame(JUMP_TO) remove current waiting queue.
mLoadWaitingQueue.clear();
// If the queue is empty, and the frame of frameIndex is not loaded synchronously. load batch from the frame of frameIndex
- if( !textureSet )
+ if(!textureSet)
{
mFrameIndex = frameIndex;
}
LoadBatch();
}
- if( !textureSet )
+ if(!textureSet)
{
- if( IsFrontReady() == true )
+ if(IsFrontReady() == true)
{
textureSet = GetFrontTextureSet();
}
TextureSet RollingAnimatedImageCache::FirstFrame()
{
- return Frame( 0u );
+ return Frame(0u);
}
TextureSet RollingAnimatedImageCache::NextFrame()
return textureSet;
}
-uint32_t RollingAnimatedImageCache::GetFrameInterval( uint32_t frameIndex ) const
+uint32_t RollingAnimatedImageCache::GetFrameInterval(uint32_t frameIndex) const
{
- return mAnimatedImageLoading.GetFrameInterval( frameIndex );
+ return mAnimatedImageLoading.GetFrameInterval(frameIndex);
}
int32_t RollingAnimatedImageCache::GetCurrentFrameIndex() const
bool RollingAnimatedImageCache::IsFrontReady() const
{
- return ( !mQueue.IsEmpty() && mQueue.Front().mReady );
+ return (!mQueue.IsEmpty() && mQueue.Front().mReady);
}
-void RollingAnimatedImageCache::RequestFrameLoading( uint32_t frameIndex )
+void RollingAnimatedImageCache::RequestFrameLoading(uint32_t frameIndex)
{
ImageFrame imageFrame;
imageFrame.mFrameNumber = frameIndex;
mRequestingLoad = true;
bool synchronousLoading = false;
- mTextureManager.LoadAnimatedImageTexture( mAnimatedImageLoading, frameIndex, SamplingMode::BOX_THEN_LINEAR,
- synchronousLoading, mImageUrls[ frameIndex ].mTextureId, Dali::WrapMode::Type::DEFAULT,
- Dali::WrapMode::Type::DEFAULT, this );
+ mTextureManager.LoadAnimatedImageTexture(mAnimatedImageLoading, frameIndex, SamplingMode::BOX_THEN_LINEAR, synchronousLoading, mImageUrls[frameIndex].mTextureId, Dali::WrapMode::Type::DEFAULT, Dali::WrapMode::Type::DEFAULT, this);
mRequestingLoad = false;
}
// removed, and another frame is loaded
bool frontFrameReady = IsFrontReady();
- for( unsigned int i=0; i< mBatchSize && mQueue.Count() + mLoadWaitingQueue.size() < static_cast<uint32_t>(mCacheSize) && !mQueue.IsFull(); ++i )
+ for(unsigned int i = 0; i < mBatchSize && mQueue.Count() + mLoadWaitingQueue.size() < static_cast<uint32_t>(mCacheSize) && !mQueue.IsFull(); ++i)
{
- if( !mOnLoading )
+ if(!mOnLoading)
{
mOnLoading = true;
- RequestFrameLoading( mFrameIndex );
+ RequestFrameLoading(mFrameIndex);
}
else
{
- mLoadWaitingQueue.push_back( mFrameIndex );
+ mLoadWaitingQueue.push_back(mFrameIndex);
}
mFrameIndex++;
mFrameIndex %= mFrameCount;
}
- CheckFrontFrame( frontFrameReady );
+ CheckFrontFrame(frontFrameReady);
LOG_CACHE;
}
-void RollingAnimatedImageCache::SetImageFrameReady( TextureManager::TextureId textureId )
+void RollingAnimatedImageCache::SetImageFrameReady(TextureManager::TextureId textureId)
{
- for( std::size_t i = 0; i < mQueue.Count() ; ++i )
+ for(std::size_t i = 0; i < mQueue.Count(); ++i)
{
- if( GetCachedTextureId( i ) == textureId )
+ if(GetCachedTextureId(i) == textureId)
{
mQueue[i].mReady = true;
break;
TextureSet RollingAnimatedImageCache::GetFrontTextureSet() const
{
- DALI_LOG_INFO( gAnimImgLogFilter, Debug::Concise, "RollingAnimatedImageCache::GetFrontTextureSet() FrameNumber:%d\n", mQueue[ 0 ].mFrameNumber );
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "RollingAnimatedImageCache::GetFrontTextureSet() FrameNumber:%d\n", mQueue[0].mFrameNumber);
- TextureManager::TextureId textureId = GetCachedTextureId( 0 );
- return mTextureManager.GetTextureSet( textureId );
+ TextureManager::TextureId textureId = GetCachedTextureId(0);
+ return mTextureManager.GetTextureSet(textureId);
}
-TextureManager::TextureId RollingAnimatedImageCache::GetCachedTextureId( int index ) const
+TextureManager::TextureId RollingAnimatedImageCache::GetCachedTextureId(int index) const
{
- return mImageUrls[ mQueue[ index ].mFrameNumber ].mTextureId;
+ return mImageUrls[mQueue[index].mFrameNumber].mTextureId;
}
-void RollingAnimatedImageCache::CheckFrontFrame( bool wasReady )
+void RollingAnimatedImageCache::CheckFrontFrame(bool wasReady)
{
- if( mWaitingForReadyFrame && wasReady == false && IsFrontReady() )
+ if(mWaitingForReadyFrame && wasReady == false && IsFrontReady())
{
mWaitingForReadyFrame = false;
- mObserver.FrameReady( GetFrontTextureSet() );
+ mObserver.FrameReady(GetFrontTextureSet());
}
}
TextureSet textureSet,
bool useAtlasing,
const Vector4& atlasRect,
- bool preMultiplied )
+ bool preMultiplied)
{
- DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::UploadComplete(textureId:%d) start\n", textureId);
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::UploadComplete(textureId:%d) start\n", textureId);
LOG_CACHE;
bool frontFrameReady = IsFrontReady();
- if( !mRequestingLoad )
+ if(!mRequestingLoad)
{
- SetImageFrameReady( textureId );
+ SetImageFrameReady(textureId);
- CheckFrontFrame( frontFrameReady );
+ CheckFrontFrame(frontFrameReady);
}
else
{
// The frames of a single animated image can not be loaded parallelly.
// Therefore, a frame is now loading, other orders are waiting.
// And, after the frame is loaded, requests load of next order.
- if( !mLoadWaitingQueue.empty() )
+ if(!mLoadWaitingQueue.empty())
{
uint32_t loadingIndex = mLoadWaitingQueue.front();
- mLoadWaitingQueue.erase( mLoadWaitingQueue.begin() );
+ mLoadWaitingQueue.erase(mLoadWaitingQueue.begin());
mOnLoading = true;
- RequestFrameLoading( loadingIndex );
+ RequestFrameLoading(loadingIndex);
}
LOG_CACHE;
}
void RollingAnimatedImageCache::LoadComplete(
- bool loadSuccess,
+ bool loadSuccess,
Devel::PixelBuffer pixelBuffer,
- const VisualUrl& url,
- bool preMultiplied )
+ const VisualUrl& url,
+ bool preMultiplied)
{
// LoadComplete is called if this TextureUploadObserver requested to load
// an image that will be returned as a type of PixelBuffer by using a method
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#if defined(DEBUG_ENABLED)
Debug::Filter* gAnimImgLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ANIMATED_IMAGE");
-#define LOG_CACHE \
- { \
- std::ostringstream oss; \
- oss<<"Size:"<<mQueue.Count()<<" [ "; \
- for(std::size_t _i=0; _i<mQueue.Count(); ++_i) \
- { \
- oss<<_i<< \
- "={ tex:"<<mImageUrls[mQueue[_i].mUrlIndex].mTextureId<< \
- " urlId:"<<mQueue[_i].mUrlIndex<< \
- " rdy:"<<(mQueue[_i].mReady?"T":"F")<< "}, "; \
- } \
- oss<<" ]"<<std::endl; \
- DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"%s",oss.str().c_str()); \
+#define LOG_CACHE \
+ { \
+ std::ostringstream oss; \
+ oss << "Size:" << mQueue.Count() << " [ "; \
+ for(std::size_t _i = 0; _i < mQueue.Count(); ++_i) \
+ { \
+ oss << _i << "={ tex:" << mImageUrls[mQueue[_i].mUrlIndex].mTextureId << " urlId:" << mQueue[_i].mUrlIndex << " rdy:" << (mQueue[_i].mReady ? "T" : "F") << "}, "; \
+ } \
+ oss << " ]" << std::endl; \
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "%s", oss.str().c_str()); \
}
#else
- #define LOG_CACHE
+#define LOG_CACHE
#endif
-const bool ENABLE_ORIENTATION_CORRECTION( true );
+const bool ENABLE_ORIENTATION_CORRECTION(true);
-}
+} // namespace
namespace Dali
{
{
namespace Internal
{
-
RollingImageCache::RollingImageCache(
- TextureManager& textureManager, UrlList& urlList, ImageCache::FrameReadyObserver& observer,
- uint16_t cacheSize, uint16_t batchSize )
-: ImageCache( textureManager, observer, batchSize ),
- mImageUrls( urlList ),
- mQueue( cacheSize )
+ TextureManager& textureManager, UrlList& urlList, ImageCache::FrameReadyObserver& observer, uint16_t cacheSize, uint16_t batchSize)
+: ImageCache(textureManager, observer, batchSize),
+ mImageUrls(urlList),
+ mQueue(cacheSize)
{
LoadBatch();
}
RollingImageCache::~RollingImageCache()
{
- if( mTextureManagerAlive )
+ if(mTextureManagerAlive)
{
- while( !mQueue.IsEmpty() )
+ while(!mQueue.IsEmpty())
{
ImageFrame imageFrame = mQueue.PopFront();
- mTextureManager.Remove( mImageUrls[ imageFrame.mUrlIndex ].mTextureId, this );
+ mTextureManager.Remove(mImageUrls[imageFrame.mUrlIndex].mTextureId, this);
}
}
}
-TextureSet RollingImageCache::Frame( uint32_t frameIndex )
+TextureSet RollingImageCache::Frame(uint32_t frameIndex)
{
// If a frame of frameIndex is not loaded, clear the queue and remove all loaded textures.
- if( mImageUrls[ frameIndex ].mTextureId == TextureManager::INVALID_TEXTURE_ID )
+ if(mImageUrls[frameIndex].mTextureId == TextureManager::INVALID_TEXTURE_ID)
{
mUrlIndex = frameIndex;
- while( !mQueue.IsEmpty() )
+ while(!mQueue.IsEmpty())
{
ImageFrame imageFrame = mQueue.PopFront();
- mTextureManager.Remove( mImageUrls[ imageFrame.mUrlIndex ].mTextureId, this );
- mImageUrls[ imageFrame.mUrlIndex ].mTextureId = TextureManager::INVALID_TEXTURE_ID;
+ mTextureManager.Remove(mImageUrls[imageFrame.mUrlIndex].mTextureId, this);
+ mImageUrls[imageFrame.mUrlIndex].mTextureId = TextureManager::INVALID_TEXTURE_ID;
}
LoadBatch();
}
else
{
bool popExist = false;
- while( !mQueue.IsEmpty() && mQueue.Front().mUrlIndex != frameIndex )
+ while(!mQueue.IsEmpty() && mQueue.Front().mUrlIndex != frameIndex)
{
ImageFrame imageFrame = mQueue.PopFront();
- mTextureManager.Remove( mImageUrls[ imageFrame.mUrlIndex ].mTextureId, this );
- mImageUrls[ imageFrame.mUrlIndex ].mTextureId = TextureManager::INVALID_TEXTURE_ID;
- popExist = true;
+ mTextureManager.Remove(mImageUrls[imageFrame.mUrlIndex].mTextureId, this);
+ mImageUrls[imageFrame.mUrlIndex].mTextureId = TextureManager::INVALID_TEXTURE_ID;
+ popExist = true;
}
- if( popExist )
+ if(popExist)
{
- mUrlIndex = ( mQueue.Back().mUrlIndex + 1 ) % mImageUrls.size();
+ mUrlIndex = (mQueue.Back().mUrlIndex + 1) % mImageUrls.size();
LoadBatch();
}
}
TextureSet textureSet;
- if( IsFrontReady() == true )
+ if(IsFrontReady() == true)
{
textureSet = GetFrontTextureSet();
}
TextureSet RollingImageCache::FirstFrame()
{
- return Frame( 0u );
+ return Frame(0u);
}
TextureSet RollingImageCache::NextFrame()
return textureSet;
}
-uint32_t RollingImageCache::GetFrameInterval( uint32_t frameIndex ) const
+uint32_t RollingImageCache::GetFrameInterval(uint32_t frameIndex) const
{
return 0u;
}
bool RollingImageCache::IsFrontReady() const
{
- return ( !mQueue.IsEmpty() && mQueue.Front().mReady );
+ return (!mQueue.IsEmpty() && mQueue.Front().mReady);
}
void RollingImageCache::LoadBatch()
// cleared, but not erased, and another image is loaded
bool frontFrameReady = IsFrontReady();
- for( unsigned int i=0; i< mBatchSize && !mQueue.IsFull(); ++i )
+ for(unsigned int i = 0; i < mBatchSize && !mQueue.IsFull(); ++i)
{
ImageFrame imageFrame;
- std::string& url = mImageUrls[ mUrlIndex ].mUrl;
+ std::string& url = mImageUrls[mUrlIndex].mUrl;
imageFrame.mUrlIndex = mUrlIndex;
- imageFrame.mReady = false;
+ imageFrame.mReady = false;
++mUrlIndex;
mUrlIndex %= mImageUrls.size();
- mQueue.PushBack( imageFrame );
+ mQueue.PushBack(imageFrame);
// Note, if the image is already loaded, then UploadComplete will get called
// from within this method. This means it won't yet have a texture id, so we
// need to account for this inside the UploadComplete method using mRequestingLoad.
mRequestingLoad = true;
- bool synchronousLoading = false;
- bool atlasingStatus = false;
- bool loadingStatus = false;
- TextureManager::MaskingDataPointer maskInfo = nullptr;
- AtlasUploadObserver* atlasObserver = nullptr;
- ImageAtlasManagerPtr imageAtlasManager = nullptr;
- Vector4 textureRect;
- Dali::ImageDimensions textureRectSize;
- auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
+ bool synchronousLoading = false;
+ bool atlasingStatus = false;
+ bool loadingStatus = false;
+ TextureManager::MaskingDataPointer maskInfo = nullptr;
+ AtlasUploadObserver* atlasObserver = nullptr;
+ ImageAtlasManagerPtr imageAtlasManager = nullptr;
+ Vector4 textureRect;
+ Dali::ImageDimensions textureRectSize;
+ auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
mTextureManager.LoadTexture(
- url, ImageDimensions(), FittingMode::SCALE_TO_FILL,
- SamplingMode::BOX_THEN_LINEAR, maskInfo,
- synchronousLoading, mImageUrls[ imageFrame.mUrlIndex ].mTextureId, textureRect, textureRectSize,
- atlasingStatus, loadingStatus, Dali::WrapMode::Type::DEFAULT,
- Dali::WrapMode::Type::DEFAULT, this,
- atlasObserver, imageAtlasManager, ENABLE_ORIENTATION_CORRECTION, TextureManager::ReloadPolicy::CACHED,
- preMultiply );
+ url, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, maskInfo, synchronousLoading, mImageUrls[imageFrame.mUrlIndex].mTextureId, textureRect, textureRectSize, atlasingStatus, loadingStatus, Dali::WrapMode::Type::DEFAULT, Dali::WrapMode::Type::DEFAULT, this, atlasObserver, imageAtlasManager, ENABLE_ORIENTATION_CORRECTION, TextureManager::ReloadPolicy::CACHED, preMultiply);
mRequestingLoad = false;
}
- CheckFrontFrame( frontFrameReady );
+ CheckFrontFrame(frontFrameReady);
}
-void RollingImageCache::SetImageFrameReady( TextureManager::TextureId textureId )
+void RollingImageCache::SetImageFrameReady(TextureManager::TextureId textureId)
{
- for( std::size_t i = 0; i < mQueue.Count() ; ++i )
+ for(std::size_t i = 0; i < mQueue.Count(); ++i)
{
- if( GetCachedTextureId(i) == textureId )
+ if(GetCachedTextureId(i) == textureId)
{
mQueue[i].mReady = true;
break;
TextureSet RollingImageCache::GetFrontTextureSet() const
{
- TextureManager::TextureId textureId = GetCachedTextureId( 0 );
- return mTextureManager.GetTextureSet( textureId );
+ TextureManager::TextureId textureId = GetCachedTextureId(0);
+ return mTextureManager.GetTextureSet(textureId);
}
-TextureManager::TextureId RollingImageCache::GetCachedTextureId( int index ) const
+TextureManager::TextureId RollingImageCache::GetCachedTextureId(int index) const
{
- return mImageUrls[ mQueue[ index ].mUrlIndex ].mTextureId;
+ return mImageUrls[mQueue[index].mUrlIndex].mTextureId;
}
-void RollingImageCache::CheckFrontFrame( bool wasReady )
+void RollingImageCache::CheckFrontFrame(bool wasReady)
{
- if( mWaitingForReadyFrame && wasReady == false && IsFrontReady() )
+ if(mWaitingForReadyFrame && wasReady == false && IsFrontReady())
{
mWaitingForReadyFrame = false;
- mObserver.FrameReady( GetFrontTextureSet() );
+ mObserver.FrameReady(GetFrontTextureSet());
}
}
TextureSet textureSet,
bool useAtlasing,
const Vector4& atlasRect,
- bool preMultiplied )
+ bool preMultiplied)
{
- DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::UploadComplete(textureId:%d) start\n", textureId);
+ DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::UploadComplete(textureId:%d) start\n", textureId);
LOG_CACHE;
bool frontFrameReady = IsFrontReady();
- if( ! mRequestingLoad )
+ if(!mRequestingLoad)
{
- SetImageFrameReady( textureId );
+ SetImageFrameReady(textureId);
- CheckFrontFrame( frontFrameReady );
+ CheckFrontFrame(frontFrameReady);
}
else
{
}
void RollingImageCache::LoadComplete(
- bool loadSuccess,
+ bool loadSuccess,
Devel::PixelBuffer pixelBuffer,
- const VisualUrl& url,
- bool preMultiplied )
+ const VisualUrl& url,
+ bool preMultiplied)
{
// LoadComplete is called if this TextureUploadObserver requested to load
// an image that will be returned as a type of PixelBuffer by using a method
#include <dali-toolkit/internal/visuals/animated-vector-image/animated-vector-image-visual.h>
// EXTERNAL INCLUDES
+#include <dali/devel-api/adaptor-framework/window-devel.h>
#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/rendering/renderer-devel.h>
-#include <dali/devel-api/adaptor-framework/window-devel.h>
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
#include <dali-toolkit/devel-api/visuals/animated-vector-image-visual-signals-devel.h>
+#include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
+#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
-#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
+#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-const Dali::Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f );
+const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
// stop behavior
-DALI_ENUM_TO_STRING_TABLE_BEGIN( STOP_BEHAVIOR )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME )
-DALI_ENUM_TO_STRING_TABLE_END( STOP_BEHAVIOR )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(STOP_BEHAVIOR)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME)
+DALI_ENUM_TO_STRING_TABLE_END(STOP_BEHAVIOR)
// looping mode
-DALI_ENUM_TO_STRING_TABLE_BEGIN( LOOPING_MODE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::LoopingMode, RESTART )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::LoopingMode, AUTO_REVERSE )
-DALI_ENUM_TO_STRING_TABLE_END( LOOPING_MODE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(LOOPING_MODE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::LoopingMode, RESTART)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::LoopingMode, AUTO_REVERSE)
+DALI_ENUM_TO_STRING_TABLE_END(LOOPING_MODE)
#if defined(DEBUG_ENABLED)
-Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" );
+Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
#endif
} // unnamed namespace
-AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties )
+AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
{
- AnimatedVectorImageVisualPtr visual( new AnimatedVectorImageVisual( factoryCache, shaderFactory, imageUrl ) );
- visual->SetProperties( properties );
+ AnimatedVectorImageVisualPtr visual(new AnimatedVectorImageVisual(factoryCache, shaderFactory, imageUrl));
+ visual->SetProperties(properties);
visual->Initialize();
return visual;
}
-AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl )
+AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
{
- AnimatedVectorImageVisualPtr visual( new AnimatedVectorImageVisual( factoryCache, shaderFactory, imageUrl ) );
+ AnimatedVectorImageVisualPtr visual(new AnimatedVectorImageVisual(factoryCache, shaderFactory, imageUrl));
visual->Initialize();
return visual;
}
-AnimatedVectorImageVisual::AnimatedVectorImageVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl )
-: Visual::Base( factoryCache, Visual::FittingMode::FILL, static_cast<Toolkit::Visual::Type>( Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE ) ),
- mUrl( imageUrl ),
+AnimatedVectorImageVisual::AnimatedVectorImageVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
+: Visual::Base(factoryCache, Visual::FittingMode::FILL, static_cast<Toolkit::Visual::Type>(Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE)),
+ mUrl(imageUrl),
mAnimationData(),
- mVectorAnimationTask( new VectorAnimationTask( factoryCache, imageUrl.GetUrl() ) ),
- mImageVisualShaderFactory( shaderFactory ),
+ mVectorAnimationTask(new VectorAnimationTask(factoryCache, imageUrl.GetUrl())),
+ mImageVisualShaderFactory(shaderFactory),
mVisualSize(),
- mVisualScale( Vector2::ONE ),
+ mVisualScale(Vector2::ONE),
mPlacementActor(),
- mPlayState( DevelImageVisual::PlayState::STOPPED ),
- mEventCallback( nullptr ),
- mRendererAdded( false ),
+ mPlayState(DevelImageVisual::PlayState::STOPPED),
+ mEventCallback(nullptr),
+ mRendererAdded(false),
mCoreShutdown(false),
mRedrawInScalingDown(true)
{
// the rasterized image is with pre-multiplied alpha format
mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
- mVectorAnimationTask->UploadCompletedSignal().Connect( this, &AnimatedVectorImageVisual::OnUploadCompleted );
- mVectorAnimationTask->SetAnimationFinishedCallback( new EventThreadCallback( MakeCallback( this, &AnimatedVectorImageVisual::OnAnimationFinished ) ) );
+ mVectorAnimationTask->UploadCompletedSignal().Connect(this, &AnimatedVectorImageVisual::OnUploadCompleted);
+ mVectorAnimationTask->SetAnimationFinishedCallback(new EventThreadCallback(MakeCallback(this, &AnimatedVectorImageVisual::OnAnimationFinished)));
auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
vectorAnimationManager.AddObserver(*this);
AnimatedVectorImageVisual::~AnimatedVectorImageVisual()
{
- if( ! mCoreShutdown )
+ if(!mCoreShutdown)
{
auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
vectorAnimationManager.RemoveObserver(*this);
- if( mEventCallback )
+ if(mEventCallback)
{
- mFactoryCache.GetVectorAnimationManager().UnregisterEventCallback( mEventCallback );
+ mFactoryCache.GetVectorAnimationManager().UnregisterEventCallback(mEventCallback);
}
// Finalize animation task and disconnect the signal in the main thread
- mVectorAnimationTask->UploadCompletedSignal().Disconnect( this, &AnimatedVectorImageVisual::OnUploadCompleted );
+ mVectorAnimationTask->UploadCompletedSignal().Disconnect(this, &AnimatedVectorImageVisual::OnUploadCompleted);
mVectorAnimationTask->Finalize();
}
}
mCoreShutdown = true;
}
-void AnimatedVectorImageVisual::GetNaturalSize( Vector2& naturalSize )
+void AnimatedVectorImageVisual::GetNaturalSize(Vector2& naturalSize)
{
- if( mVisualSize != Vector2::ZERO )
+ if(mVisualSize != Vector2::ZERO)
{
naturalSize = mVisualSize;
}
else
{
uint32_t width, height;
- mVectorAnimationTask->GetDefaultSize( width, height );
+ mVectorAnimationTask->GetDefaultSize(width, height);
naturalSize.x = width;
naturalSize.y = height;
}
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::GetNaturalSize: w = %f, h = %f [%p]\n", naturalSize.width, naturalSize.height, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::GetNaturalSize: w = %f, h = %f [%p]\n", naturalSize.width, naturalSize.height, this);
}
-void AnimatedVectorImageVisual::DoCreatePropertyMap( Property::Map& map ) const
+void AnimatedVectorImageVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE );
- if( mUrl.IsValid() )
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE);
+ if(mUrl.IsValid())
{
- map.Insert( Toolkit::ImageVisual::Property::URL, mUrl.GetUrl() );
+ map.Insert(Toolkit::ImageVisual::Property::URL, mUrl.GetUrl());
}
- map.Insert( Toolkit::DevelImageVisual::Property::LOOP_COUNT, mAnimationData.loopCount );
+ map.Insert(Toolkit::DevelImageVisual::Property::LOOP_COUNT, mAnimationData.loopCount);
uint32_t startFrame, endFrame;
- mVectorAnimationTask->GetPlayRange( startFrame, endFrame );
+ mVectorAnimationTask->GetPlayRange(startFrame, endFrame);
Property::Array playRange;
- playRange.PushBack( static_cast< int32_t >( startFrame ) );
- playRange.PushBack( static_cast< int32_t >( endFrame ) );
- map.Insert( Toolkit::DevelImageVisual::Property::PLAY_RANGE, playRange );
+ playRange.PushBack(static_cast<int32_t>(startFrame));
+ playRange.PushBack(static_cast<int32_t>(endFrame));
+ map.Insert(Toolkit::DevelImageVisual::Property::PLAY_RANGE, playRange);
- map.Insert( Toolkit::DevelImageVisual::Property::PLAY_STATE, static_cast< int32_t >( mPlayState ) );
- map.Insert( Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, static_cast< int32_t >( mVectorAnimationTask->GetCurrentFrameNumber() ) );
- map.Insert( Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, static_cast< int32_t >( mVectorAnimationTask->GetTotalFrameNumber() ) );
+ map.Insert(Toolkit::DevelImageVisual::Property::PLAY_STATE, static_cast<int32_t>(mPlayState));
+ map.Insert(Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, static_cast<int32_t>(mVectorAnimationTask->GetCurrentFrameNumber()));
+ map.Insert(Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, static_cast<int32_t>(mVectorAnimationTask->GetTotalFrameNumber()));
- map.Insert( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mAnimationData.stopBehavior );
- map.Insert( Toolkit::DevelImageVisual::Property::LOOPING_MODE, mAnimationData.loopingMode );
- map.Insert( Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, mRedrawInScalingDown );
+ map.Insert(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mAnimationData.stopBehavior);
+ map.Insert(Toolkit::DevelImageVisual::Property::LOOPING_MODE, mAnimationData.loopingMode);
+ map.Insert(Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, mRedrawInScalingDown);
Property::Map layerInfo;
- mVectorAnimationTask->GetLayerInfo( layerInfo );
- map.Insert( Toolkit::DevelImageVisual::Property::CONTENT_INFO, layerInfo );
+ mVectorAnimationTask->GetLayerInfo(layerInfo);
+ map.Insert(Toolkit::DevelImageVisual::Property::CONTENT_INFO, layerInfo);
}
-void AnimatedVectorImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void AnimatedVectorImageVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
-void AnimatedVectorImageVisual::DoSetProperties( const Property::Map& propertyMap )
+void AnimatedVectorImageVisual::DoSetProperties(const Property::Map& propertyMap)
{
// url already passed in from constructor
- for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
+ for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
{
- KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
- if( keyValue.first.type == Property::Key::INDEX )
+ KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
+ if(keyValue.first.type == Property::Key::INDEX)
{
- DoSetProperty( keyValue.first.indexKey, keyValue.second );
+ DoSetProperty(keyValue.first.indexKey, keyValue.second);
}
else
{
- if( keyValue.first == LOOP_COUNT_NAME )
- {
- DoSetProperty( Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second );
- }
- else if( keyValue.first == PLAY_RANGE_NAME )
- {
- DoSetProperty( Toolkit::DevelImageVisual::Property::PLAY_RANGE, keyValue.second );
- }
- else if( keyValue.first == STOP_BEHAVIOR_NAME )
- {
- DoSetProperty( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second );
- }
- else if( keyValue.first == LOOPING_MODE_NAME )
- {
- DoSetProperty( Toolkit::DevelImageVisual::Property::LOOPING_MODE, keyValue.second );
- }
- else if( keyValue.first == REDRAW_IN_SCALING_DOWN_NAME )
- {
- DoSetProperty( Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, keyValue.second );
- }
+ if(keyValue.first == LOOP_COUNT_NAME)
+ {
+ DoSetProperty(Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second);
+ }
+ else if(keyValue.first == PLAY_RANGE_NAME)
+ {
+ DoSetProperty(Toolkit::DevelImageVisual::Property::PLAY_RANGE, keyValue.second);
+ }
+ else if(keyValue.first == STOP_BEHAVIOR_NAME)
+ {
+ DoSetProperty(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second);
+ }
+ else if(keyValue.first == LOOPING_MODE_NAME)
+ {
+ DoSetProperty(Toolkit::DevelImageVisual::Property::LOOPING_MODE, keyValue.second);
+ }
+ else if(keyValue.first == REDRAW_IN_SCALING_DOWN_NAME)
+ {
+ DoSetProperty(Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, keyValue.second);
+ }
}
}
TriggerVectorRasterization();
}
-void AnimatedVectorImageVisual::DoSetProperty( Property::Index index, const Property::Value& value )
+void AnimatedVectorImageVisual::DoSetProperty(Property::Index index, const Property::Value& value)
{
switch(index)
{
case Toolkit::DevelImageVisual::Property::LOOP_COUNT:
{
int32_t loopCount;
- if( value.Get( loopCount ) )
+ if(value.Get(loopCount))
{
mAnimationData.loopCount = loopCount;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_LOOP_COUNT;
case Toolkit::DevelImageVisual::Property::PLAY_RANGE:
{
const Property::Array* array = value.GetArray();
- if( array )
+ if(array)
{
mAnimationData.playRange = *array;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_RANGE;
case Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR:
{
int32_t stopBehavior = mAnimationData.stopBehavior;
- if( Scripting::GetEnumerationProperty( value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior ) )
+ if(Scripting::GetEnumerationProperty(value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior))
{
- mAnimationData.stopBehavior = DevelImageVisual::StopBehavior::Type( stopBehavior );
+ mAnimationData.stopBehavior = DevelImageVisual::StopBehavior::Type(stopBehavior);
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_STOP_BEHAVIOR;
}
break;
case Toolkit::DevelImageVisual::Property::LOOPING_MODE:
{
int32_t loopingMode = mAnimationData.loopingMode;
- if( Scripting::GetEnumerationProperty( value, LOOPING_MODE_TABLE, LOOPING_MODE_TABLE_COUNT, loopingMode ) )
+ if(Scripting::GetEnumerationProperty(value, LOOPING_MODE_TABLE, LOOPING_MODE_TABLE_COUNT, loopingMode))
{
- mAnimationData.loopingMode = DevelImageVisual::LoopingMode::Type( loopingMode );
+ mAnimationData.loopingMode = DevelImageVisual::LoopingMode::Type(loopingMode);
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_LOOPING_MODE;
}
break;
case Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN:
{
bool redraw;
- if( value.Get( redraw ) )
+ if(value.Get(redraw))
{
mRedrawInScalingDown = redraw;
}
{
Shader shader;
- if( mImpl->mCustomShader )
+ if(mImpl->mCustomShader)
{
- shader = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader,
- mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader,
- mImpl->mCustomShader->mHints );
+ shader = Shader::New(mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader,
+ mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader,
+ mImpl->mCustomShader->mHints);
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
}
else
{
- shader = mImageVisualShaderFactory.GetShader( mFactoryCache, false, true, IsRoundedCornerRequired() );
+ shader = mImageVisualShaderFactory.GetShader(mFactoryCache, false, true, IsRoundedCornerRequired());
}
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
- mImpl->mRenderer = Renderer::New( geometry, shader );
+ mImpl->mRenderer = Renderer::New(geometry, shader);
TextureSet textureSet = TextureSet::New();
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
// Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
void AnimatedVectorImageVisual::DoSetOnScene(Actor& actor)
// Hold the weak handle of the placement actor and delay the adding of renderer until the rasterization is finished.
mPlacementActor = actor;
- mVectorAnimationTask->SetRenderer( mImpl->mRenderer );
+ mVectorAnimationTask->SetRenderer(mImpl->mRenderer);
// Add property notification for scaling & size
- mScaleNotification = actor.AddPropertyNotification( Actor::Property::WORLD_SCALE, StepCondition( 0.1f, 1.0f ) );
- mScaleNotification.NotifySignal().Connect( this, &AnimatedVectorImageVisual::OnScaleNotification );
+ mScaleNotification = actor.AddPropertyNotification(Actor::Property::WORLD_SCALE, StepCondition(0.1f, 1.0f));
+ mScaleNotification.NotifySignal().Connect(this, &AnimatedVectorImageVisual::OnScaleNotification);
- mSizeNotification = actor.AddPropertyNotification( Actor::Property::SIZE, StepCondition( 3.0f ) );
- mSizeNotification.NotifySignal().Connect( this, &AnimatedVectorImageVisual::OnSizeNotification );
+ mSizeNotification = actor.AddPropertyNotification(Actor::Property::SIZE, StepCondition(3.0f));
+ mSizeNotification.NotifySignal().Connect(this, &AnimatedVectorImageVisual::OnSizeNotification);
- DevelActor::VisibilityChangedSignal( actor ).Connect( this, &AnimatedVectorImageVisual::OnControlVisibilityChanged );
+ DevelActor::VisibilityChangedSignal(actor).Connect(this, &AnimatedVectorImageVisual::OnControlVisibilityChanged);
- Window window = DevelWindow::Get( actor );
- if( window )
+ Window window = DevelWindow::Get(actor);
+ if(window)
{
- DevelWindow::VisibilityChangedSignal( window ).Connect( this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged );
+ DevelWindow::VisibilityChangedSignal(window).Connect(this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged);
}
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOnScene [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOnScene [%p]\n", this);
}
-void AnimatedVectorImageVisual::DoSetOffScene( Actor& actor )
+void AnimatedVectorImageVisual::DoSetOffScene(Actor& actor)
{
StopAnimation();
SendAnimationData();
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- actor.RemoveRenderer( mImpl->mRenderer );
+ actor.RemoveRenderer(mImpl->mRenderer);
mRendererAdded = false;
}
// Remove property notification
- actor.RemovePropertyNotification( mScaleNotification );
- actor.RemovePropertyNotification( mSizeNotification );
+ actor.RemovePropertyNotification(mScaleNotification);
+ actor.RemovePropertyNotification(mSizeNotification);
- DevelActor::VisibilityChangedSignal( actor ).Disconnect( this, &AnimatedVectorImageVisual::OnControlVisibilityChanged );
+ DevelActor::VisibilityChangedSignal(actor).Disconnect(this, &AnimatedVectorImageVisual::OnControlVisibilityChanged);
- Window window = DevelWindow::Get( actor );
- if( window )
+ Window window = DevelWindow::Get(actor);
+ if(window)
{
- DevelWindow::VisibilityChangedSignal( window ).Disconnect( this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged );
+ DevelWindow::VisibilityChangedSignal(window).Disconnect(this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged);
}
mPlacementActor.Reset();
// Reset the visual size to zero so that when adding the actor back to stage the rasterization is forced
- mVisualSize = Vector2::ZERO;
+ mVisualSize = Vector2::ZERO;
mVisualScale = Vector2::ONE;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOffScene [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOffScene [%p]\n", this);
}
void AnimatedVectorImageVisual::OnSetTransform()
{
- Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize );
+ Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize);
- if( IsOnScene() && visualSize != mVisualSize )
+ if(IsOnScene() && visualSize != mVisualSize)
{
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSetTransform: width = %f, height = %f [%p]\n", visualSize.width, visualSize.height, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSetTransform: width = %f, height = %f [%p]\n", visualSize.width, visualSize.height, this);
mVisualSize = visualSize;
SetVectorImageSize();
- if( mPlayState == DevelImageVisual::PlayState::PLAYING && mAnimationData.playState != DevelImageVisual::PlayState::PLAYING )
+ if(mPlayState == DevelImageVisual::PlayState::PLAYING && mAnimationData.playState != DevelImageVisual::PlayState::PLAYING)
{
mAnimationData.playState = DevelImageVisual::PlayState::PLAYING;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
}
}
-void AnimatedVectorImageVisual::OnDoAction( const Property::Index actionId, const Property::Value& attributes )
+void AnimatedVectorImageVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes)
{
// Check if action is valid for this visual type and perform action if possible
- switch( actionId )
+ switch(actionId)
{
case DevelAnimatedVectorImageVisual::Action::PLAY:
{
- if( IsOnScene() && mVisualSize != Vector2::ZERO )
+ if(IsOnScene() && mVisualSize != Vector2::ZERO)
{
- if( mAnimationData.playState != DevelImageVisual::PlayState::PLAYING )
+ if(mAnimationData.playState != DevelImageVisual::PlayState::PLAYING)
{
mAnimationData.playState = DevelImageVisual::PlayState::PLAYING;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
}
case DevelAnimatedVectorImageVisual::Action::PAUSE:
{
- if( mAnimationData.playState == DevelImageVisual::PlayState::PLAYING )
+ if(mAnimationData.playState == DevelImageVisual::PlayState::PLAYING)
{
mAnimationData.playState = DevelImageVisual::PlayState::PAUSED;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
}
case DevelAnimatedVectorImageVisual::Action::STOP:
{
- if( mAnimationData.playState != DevelImageVisual::PlayState::STOPPED )
+ if(mAnimationData.playState != DevelImageVisual::PlayState::STOPPED)
{
mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
case DevelAnimatedVectorImageVisual::Action::JUMP_TO:
{
int32_t frameNumber;
- if( attributes.Get( frameNumber ) )
+ if(attributes.Get(frameNumber))
{
mAnimationData.currentFrame = frameNumber;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_CURRENT_FRAME;
case DevelAnimatedVectorImageVisual::Action::UPDATE_PROPERTY:
{
const Property::Map* map = attributes.GetMap();
- if( map )
+ if(map)
{
- DoSetProperties( *map );
+ DoSetProperties(*map);
}
break;
}
{
// If weak handle is holding a placement actor, it is the time to add the renderer to actor.
Actor actor = mPlacementActor.GetHandle();
- if( actor && !mRendererAdded )
+ if(actor && !mRendererAdded)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
mRendererAdded = true;
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnUploadCompleted: Renderer is added [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnUploadCompleted: Renderer is added [%p]\n", this);
}
}
void AnimatedVectorImageVisual::OnAnimationFinished()
{
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnAnimationFinished: action state = %d [%p]\n", mPlayState, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnAnimationFinished: action state = %d [%p]\n", mPlayState, this);
- if( mPlayState != DevelImageVisual::PlayState::STOPPED )
+ if(mPlayState != DevelImageVisual::PlayState::STOPPED)
{
mPlayState = DevelImageVisual::PlayState::STOPPED;
mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
- if( mImpl->mEventObserver )
+ if(mImpl->mEventObserver)
{
- mImpl->mEventObserver->NotifyVisualEvent( *this, DevelAnimatedVectorImageVisual::Signal::ANIMATION_FINISHED );
+ mImpl->mEventObserver->NotifyVisualEvent(*this, DevelAnimatedVectorImageVisual::Signal::ANIMATION_FINISHED);
}
}
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED );
+ mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED);
}
}
void AnimatedVectorImageVisual::SendAnimationData()
{
- if( mAnimationData.resendFlag )
+ if(mAnimationData.resendFlag)
{
- mVectorAnimationTask->SetAnimationData( mAnimationData );
+ mVectorAnimationTask->SetAnimationData(mAnimationData);
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- if( mAnimationData.playState == DevelImageVisual::PlayState::PLAYING )
+ if(mAnimationData.playState == DevelImageVisual::PlayState::PLAYING)
{
- mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY );
+ mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY);
}
else
{
- mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED );
+ mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED);
}
}
void AnimatedVectorImageVisual::SetVectorImageSize()
{
- uint32_t width = static_cast< uint32_t >( mVisualSize.width * mVisualScale.width );
- uint32_t height = static_cast< uint32_t >( mVisualSize.height * mVisualScale.height );
+ uint32_t width = static_cast<uint32_t>(mVisualSize.width * mVisualScale.width);
+ uint32_t height = static_cast<uint32_t>(mVisualSize.height * mVisualScale.height);
- mAnimationData.width = width;
+ mAnimationData.width = width;
mAnimationData.height = height;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_SIZE;
}
void AnimatedVectorImageVisual::StopAnimation()
{
- if( mAnimationData.playState != DevelImageVisual::PlayState::STOPPED )
+ if(mAnimationData.playState != DevelImageVisual::PlayState::STOPPED)
{
mAnimationData.playState = DevelImageVisual::PlayState::STOPPED;
mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE;
void AnimatedVectorImageVisual::TriggerVectorRasterization()
{
- if( !mEventCallback && !mCoreShutdown )
+ if(!mEventCallback && !mCoreShutdown)
{
- mEventCallback = MakeCallback( this, &AnimatedVectorImageVisual::OnProcessEvents );
+ mEventCallback = MakeCallback(this, &AnimatedVectorImageVisual::OnProcessEvents);
auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager();
- vectorAnimationManager.RegisterEventCallback( mEventCallback );
- Stage::GetCurrent().KeepRendering( 0.0f ); // Trigger event processing
+ vectorAnimationManager.RegisterEventCallback(mEventCallback);
+ Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
}
}
-void AnimatedVectorImageVisual::OnScaleNotification( PropertyNotification& source )
+void AnimatedVectorImageVisual::OnScaleNotification(PropertyNotification& source)
{
Actor actor = mPlacementActor.GetHandle();
- if( actor )
+ if(actor)
{
- Vector3 scale = actor.GetProperty< Vector3 >( Actor::Property::WORLD_SCALE );
+ Vector3 scale = actor.GetProperty<Vector3>(Actor::Property::WORLD_SCALE);
if(mRedrawInScalingDown || scale.width >= 1.0f || scale.height >= 1.0f)
{
- mVisualScale.width = scale.width;
+ mVisualScale.width = scale.width;
mVisualScale.height = scale.height;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnScaleNotification: scale = %f, %f [%p]\n", mVisualScale.width, mVisualScale.height, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnScaleNotification: scale = %f, %f [%p]\n", mVisualScale.width, mVisualScale.height, this);
SetVectorImageSize();
SendAnimationData();
- Stage::GetCurrent().KeepRendering( 0.0f ); // Trigger event processing
+ Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
}
}
}
-void AnimatedVectorImageVisual::OnSizeNotification( PropertyNotification& source )
+void AnimatedVectorImageVisual::OnSizeNotification(PropertyNotification& source)
{
Actor actor = mPlacementActor.GetHandle();
- if( actor )
+ if(actor)
{
- Vector3 size = actor.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
- mVisualSize.width = size.width;
+ Vector3 size = actor.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
+ mVisualSize.width = size.width;
mVisualSize.height = size.height;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSizeNotification: size = %f, %f [%p]\n", mVisualSize.width, mVisualSize.height, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSizeNotification: size = %f, %f [%p]\n", mVisualSize.width, mVisualSize.height, this);
SetVectorImageSize();
SendAnimationData();
- Stage::GetCurrent().KeepRendering( 0.0f ); // Trigger event processing
+ Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing
}
}
-void AnimatedVectorImageVisual::OnControlVisibilityChanged( Actor actor, bool visible, DevelActor::VisibilityChange::Type type )
+void AnimatedVectorImageVisual::OnControlVisibilityChanged(Actor actor, bool visible, DevelActor::VisibilityChange::Type type)
{
- if( !visible )
+ if(!visible)
{
StopAnimation();
TriggerVectorRasterization();
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnControlVisibilityChanged: invisibile. Pause animation [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnControlVisibilityChanged: invisibile. Pause animation [%p]\n", this);
}
}
-void AnimatedVectorImageVisual::OnWindowVisibilityChanged( Window window, bool visible )
+void AnimatedVectorImageVisual::OnWindowVisibilityChanged(Window window, bool visible)
{
- if( !visible )
+ if(!visible)
{
StopAnimation();
TriggerVectorRasterization();
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnWindowVisibilityChanged: invisibile. Pause animation [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnWindowVisibilityChanged: invisibile. Pause animation [%p]\n", this);
}
}
{
SendAnimationData();
- mEventCallback = nullptr; // The callback will be deleted in the VectorAnimationManager
+ mEventCallback = nullptr; // The callback will be deleted in the VectorAnimationManager
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
#include <dali/integration-api/adaptor-framework/adaptor.h>
+#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
#if defined(DEBUG_ENABLED)
-Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" );
+Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
#endif
} // unnamed namespace
VectorAnimationManager::VectorAnimationManager()
: mEventCallbacks(),
mLifecycleObservers(),
- mVectorAnimationThread( nullptr ),
- mProcessorRegistered( false )
+ mVectorAnimationThread(nullptr),
+ mProcessorRegistered(false)
{
}
VectorAnimationManager::~VectorAnimationManager()
{
- for( auto&& iter : mEventCallbacks )
+ for(auto&& iter : mEventCallbacks)
{
delete iter;
}
mEventCallbacks.clear();
- if( mProcessorRegistered )
+ if(mProcessorRegistered)
{
- Adaptor::Get().UnregisterProcessor( *this );
+ Adaptor::Get().UnregisterProcessor(*this);
}
- for( auto observer : mLifecycleObservers )
+ for(auto observer : mLifecycleObservers)
{
observer->VectorAnimationManagerDestroyed();
}
}
-void VectorAnimationManager::AddObserver( VectorAnimationManager::LifecycleObserver& observer )
+void VectorAnimationManager::AddObserver(VectorAnimationManager::LifecycleObserver& observer)
{
- DALI_ASSERT_DEBUG( mLifecycleObservers.end() == std::find( mLifecycleObservers.begin(), mLifecycleObservers.end(), &observer));
- mLifecycleObservers.push_back( &observer );
+ DALI_ASSERT_DEBUG(mLifecycleObservers.end() == std::find(mLifecycleObservers.begin(), mLifecycleObservers.end(), &observer));
+ mLifecycleObservers.push_back(&observer);
}
-void VectorAnimationManager::RemoveObserver( VectorAnimationManager::LifecycleObserver& observer)
+void VectorAnimationManager::RemoveObserver(VectorAnimationManager::LifecycleObserver& observer)
{
- auto iterator=std::find(mLifecycleObservers.begin(), mLifecycleObservers.end(), &observer);
- if( iterator != mLifecycleObservers.end() )
+ auto iterator = std::find(mLifecycleObservers.begin(), mLifecycleObservers.end(), &observer);
+ if(iterator != mLifecycleObservers.end())
{
mLifecycleObservers.erase(iterator);
}
VectorAnimationThread& VectorAnimationManager::GetVectorAnimationThread()
{
- if( !mVectorAnimationThread )
+ if(!mVectorAnimationThread)
{
- mVectorAnimationThread = std::unique_ptr< VectorAnimationThread >( new VectorAnimationThread() );
+ mVectorAnimationThread = std::unique_ptr<VectorAnimationThread>(new VectorAnimationThread());
mVectorAnimationThread->Start();
}
return *mVectorAnimationThread;
}
-void VectorAnimationManager::RegisterEventCallback( CallbackBase* callback )
+void VectorAnimationManager::RegisterEventCallback(CallbackBase* callback)
{
- mEventCallbacks.push_back( callback );
+ mEventCallbacks.push_back(callback);
- if( !mProcessorRegistered )
+ if(!mProcessorRegistered)
{
- Adaptor::Get().RegisterProcessor( *this );
+ Adaptor::Get().RegisterProcessor(*this);
mProcessorRegistered = true;
}
}
-void VectorAnimationManager::UnregisterEventCallback( CallbackBase* callback )
+void VectorAnimationManager::UnregisterEventCallback(CallbackBase* callback)
{
- auto iter = std::find( mEventCallbacks.begin(), mEventCallbacks.end(), callback );
- if( iter != mEventCallbacks.end() )
+ auto iter = std::find(mEventCallbacks.begin(), mEventCallbacks.end(), callback);
+ if(iter != mEventCallbacks.end())
{
- mEventCallbacks.erase( iter );
+ mEventCallbacks.erase(iter);
- if( mEventCallbacks.empty() )
+ if(mEventCallbacks.empty())
{
- if( Adaptor::IsAvailable() )
+ if(Adaptor::IsAvailable())
{
- Adaptor::Get().UnregisterProcessor( *this );
+ Adaptor::Get().UnregisterProcessor(*this);
mProcessorRegistered = false;
}
}
void VectorAnimationManager::Process()
{
- for( auto&& iter : mEventCallbacks )
+ for(auto&& iter : mEventCallbacks)
{
- CallbackBase::Execute( *iter );
+ CallbackBase::Execute(*iter);
delete iter;
}
mEventCallbacks.clear();
- Adaptor::Get().UnregisterProcessor( *this );
+ Adaptor::Get().UnregisterProcessor(*this);
mProcessorRegistered = false;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
-#include <dali/public-api/object/property-array.h>
#include <dali/public-api/math/math-utils.h>
+#include <dali/public-api/object/property-array.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
-#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.h>
#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
+#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.h>
+#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
constexpr auto LOOP_FOREVER = -1;
-constexpr auto NANOSECONDS_PER_SECOND( 1e+9 );
+constexpr auto NANOSECONDS_PER_SECOND(1e+9);
#if defined(DEBUG_ENABLED)
-Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" );
+Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
#endif
} // unnamed namespace
-VectorAnimationTask::VectorAnimationTask( VisualFactoryCache& factoryCache, const std::string& url )
-: mUrl( url ),
+VectorAnimationTask::VectorAnimationTask(VisualFactoryCache& factoryCache, const std::string& url)
+: mUrl(url),
mVectorRenderer(),
mAnimationData(),
- mVectorAnimationThread( factoryCache.GetVectorAnimationManager().GetVectorAnimationThread() ),
+ mVectorAnimationThread(factoryCache.GetVectorAnimationManager().GetVectorAnimationThread()),
mConditionalWait(),
mAnimationFinishedTrigger(),
- mPlayState( PlayState::STOPPED ),
- mStopBehavior( DevelImageVisual::StopBehavior::CURRENT_FRAME ),
- mLoopingMode( DevelImageVisual::LoopingMode::RESTART ),
+ mPlayState(PlayState::STOPPED),
+ mStopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME),
+ mLoopingMode(DevelImageVisual::LoopingMode::RESTART),
mNextFrameStartTime(),
- mFrameDurationNanoSeconds( 0 ),
- mFrameRate( 60.0f ),
- mCurrentFrame( 0 ),
- mTotalFrame( 0 ),
- mStartFrame( 0 ),
- mEndFrame( 0 ),
- mWidth( 0 ),
- mHeight( 0 ),
- mAnimationDataIndex( 0 ),
- mLoopCount( LOOP_FOREVER ),
- mCurrentLoop( 0 ),
- mForward( true ),
- mUpdateFrameNumber( false ),
- mNeedAnimationFinishedTrigger( true ),
- mAnimationDataUpdated( false ),
- mDestroyTask( false )
+ mFrameDurationNanoSeconds(0),
+ mFrameRate(60.0f),
+ mCurrentFrame(0),
+ mTotalFrame(0),
+ mStartFrame(0),
+ mEndFrame(0),
+ mWidth(0),
+ mHeight(0),
+ mAnimationDataIndex(0),
+ mLoopCount(LOOP_FOREVER),
+ mCurrentLoop(0),
+ mForward(true),
+ mUpdateFrameNumber(false),
+ mNeedAnimationFinishedTrigger(true),
+ mAnimationDataUpdated(false),
+ mDestroyTask(false)
{
Initialize();
}
VectorAnimationTask::~VectorAnimationTask()
{
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::~VectorAnimationTask: destructor [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::~VectorAnimationTask: destructor [%p]\n", this);
}
void VectorAnimationTask::Finalize()
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
// Release some objects in the main thread
- if( mAnimationFinishedTrigger )
+ if(mAnimationFinishedTrigger)
{
mAnimationFinishedTrigger.reset();
}
mDestroyTask = true;
}
-void VectorAnimationTask::SetRenderer( Renderer renderer )
+void VectorAnimationTask::SetRenderer(Renderer renderer)
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- mVectorRenderer.SetRenderer( renderer );
+ mVectorRenderer.SetRenderer(renderer);
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetRenderer [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetRenderer [%p]\n", this);
}
-void VectorAnimationTask::SetAnimationData( const AnimationData& data )
+void VectorAnimationTask::SetAnimationData(const AnimationData& data)
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetAnimationData [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetAnimationData [%p]\n", this);
- uint32_t index = mAnimationDataIndex == 0 ? 1 : 0; // Use the other buffer
+ uint32_t index = mAnimationDataIndex == 0 ? 1 : 0; // Use the other buffer
mAnimationData[index] = data;
mAnimationDataUpdated = true;
- if( data.resendFlag & VectorAnimationTask::RESEND_SIZE )
+ if(data.resendFlag & VectorAnimationTask::RESEND_SIZE)
{
// The size should be changed in the main thread.
- SetSize( data.width, data.height );
+ SetSize(data.width, data.height);
}
- mVectorAnimationThread.AddTask( this );
+ mVectorAnimationThread.AddTask(this);
}
-void VectorAnimationTask::SetSize( uint32_t width, uint32_t height )
+void VectorAnimationTask::SetSize(uint32_t width, uint32_t height)
{
- if( mWidth != width || mHeight != height )
+ if(mWidth != width || mHeight != height)
{
- mVectorRenderer.SetSize( width, height );
+ mVectorRenderer.SetSize(width, height);
- mWidth = width;
+ mWidth = width;
mHeight = height;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetSize: width = %d, height = %d [%p]\n", width, height, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetSize: width = %d, height = %d [%p]\n", width, height, this);
}
}
void VectorAnimationTask::PlayAnimation()
{
- if( mPlayState != PlayState::PLAYING )
+ if(mPlayState != PlayState::PLAYING)
{
mNeedAnimationFinishedTrigger = true;
- mUpdateFrameNumber = false;
- mPlayState = PlayState::PLAYING;
+ mUpdateFrameNumber = false;
+ mPlayState = PlayState::PLAYING;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PlayAnimation: Play [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PlayAnimation: Play [%p]\n", this);
}
}
void VectorAnimationTask::StopAnimation()
{
- if( mPlayState != PlayState::STOPPING )
+ if(mPlayState != PlayState::STOPPING)
{
mNeedAnimationFinishedTrigger = false;
- mPlayState = PlayState::STOPPING;
+ mPlayState = PlayState::STOPPING;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::StopAnimation: Stop [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::StopAnimation: Stop [%p]\n", this);
}
}
void VectorAnimationTask::PauseAnimation()
{
- if( mPlayState == PlayState::PLAYING )
+ if(mPlayState == PlayState::PLAYING)
{
mPlayState = PlayState::PAUSED;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PauseAnimation: Pause [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PauseAnimation: Pause [%p]\n", this);
}
}
-void VectorAnimationTask::SetAnimationFinishedCallback( EventThreadCallback* callback )
+void VectorAnimationTask::SetAnimationFinishedCallback(EventThreadCallback* callback)
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
- if( callback )
+ ConditionalWait::ScopedLock lock(mConditionalWait);
+ if(callback)
{
- mAnimationFinishedTrigger = std::unique_ptr< EventThreadCallback >( callback );
+ mAnimationFinishedTrigger = std::unique_ptr<EventThreadCallback>(callback);
}
}
-void VectorAnimationTask::SetLoopCount( int32_t count )
+void VectorAnimationTask::SetLoopCount(int32_t count)
{
- if( mLoopCount != count )
+ if(mLoopCount != count)
{
- mLoopCount = count;
+ mLoopCount = count;
mCurrentLoop = 0;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopCount: [%d] [%p]\n", count, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopCount: [%d] [%p]\n", count, this);
}
}
-void VectorAnimationTask::SetPlayRange( const Property::Array& playRange )
+void VectorAnimationTask::SetPlayRange(const Property::Array& playRange)
{
- bool valid = false;
+ bool valid = false;
uint32_t startFrame = 0, endFrame = 0;
- size_t count = playRange.Count();
+ size_t count = playRange.Count();
- if( count >= 2 )
+ if(count >= 2)
{
int32_t start = 0, end = 0;
- if( playRange.GetElementAt( 0 ).Get( start ) && playRange.GetElementAt( 1 ).Get( end ) )
+ if(playRange.GetElementAt(0).Get(start) && playRange.GetElementAt(1).Get(end))
{
- startFrame = static_cast< uint32_t >( start );
- endFrame = static_cast< uint32_t >( end );
- valid = true;
+ startFrame = static_cast<uint32_t>(start);
+ endFrame = static_cast<uint32_t>(end);
+ valid = true;
}
else
{
std::string startMarker, endMarker;
- if( playRange.GetElementAt( 0 ).Get( startMarker ) && playRange.GetElementAt( 1 ).Get( endMarker ) )
+ if(playRange.GetElementAt(0).Get(startMarker) && playRange.GetElementAt(1).Get(endMarker))
{
- if( mVectorRenderer )
+ if(mVectorRenderer)
{
- uint32_t frame; // We don't use this later
- if( mVectorRenderer.GetMarkerInfo( startMarker, startFrame, frame ) && mVectorRenderer.GetMarkerInfo( endMarker, frame, endFrame ) )
+ uint32_t frame; // We don't use this later
+ if(mVectorRenderer.GetMarkerInfo(startMarker, startFrame, frame) && mVectorRenderer.GetMarkerInfo(endMarker, frame, endFrame))
{
valid = true;
}
}
}
}
- else if( count == 1 )
+ else if(count == 1)
{
std::string marker;
- if( playRange.GetElementAt( 0 ).Get( marker ) )
+ if(playRange.GetElementAt(0).Get(marker))
{
- if( mVectorRenderer )
+ if(mVectorRenderer)
{
- mVectorRenderer.GetMarkerInfo( marker, startFrame, endFrame );
+ mVectorRenderer.GetMarkerInfo(marker, startFrame, endFrame);
valid = true;
}
}
}
- if( !valid )
+ if(!valid)
{
- DALI_LOG_ERROR( "VectorAnimationTask::SetPlayRange: Invalid range [%p]\n", this );
+ DALI_LOG_ERROR("VectorAnimationTask::SetPlayRange: Invalid range [%p]\n", this);
return;
}
// Make sure the range specified is between 0 and the total frame number
- if( startFrame < mTotalFrame && endFrame < mTotalFrame )
+ if(startFrame < mTotalFrame && endFrame < mTotalFrame)
{
// If the range is not in order swap values
- if( startFrame > endFrame )
+ if(startFrame > endFrame)
{
uint32_t temp = startFrame;
- startFrame = endFrame;
- endFrame = temp;
+ startFrame = endFrame;
+ endFrame = temp;
}
- if( startFrame != mStartFrame || endFrame != mEndFrame )
+ if(startFrame != mStartFrame || endFrame != mEndFrame)
{
mStartFrame = startFrame;
- mEndFrame = endFrame;
+ mEndFrame = endFrame;
// If the current frame is out of the range, change the current frame also.
- if( mStartFrame > mCurrentFrame )
+ if(mStartFrame > mCurrentFrame)
{
mCurrentFrame = mStartFrame;
}
- else if( mEndFrame < mCurrentFrame )
+ else if(mEndFrame < mCurrentFrame)
{
mCurrentFrame = mEndFrame;
}
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetPlayRange: [%d, %d] [%p]\n", mStartFrame, mEndFrame, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetPlayRange: [%d, %d] [%p]\n", mStartFrame, mEndFrame, this);
}
}
else
{
- DALI_LOG_ERROR( "VectorAnimationTask::SetPlayRange: Invalid range (%d, %d) [%p]\n", startFrame, endFrame, this );
+ DALI_LOG_ERROR("VectorAnimationTask::SetPlayRange: Invalid range (%d, %d) [%p]\n", startFrame, endFrame, this);
return;
}
}
-void VectorAnimationTask::GetPlayRange( uint32_t& startFrame, uint32_t& endFrame )
+void VectorAnimationTask::GetPlayRange(uint32_t& startFrame, uint32_t& endFrame)
{
startFrame = mStartFrame;
- endFrame = mEndFrame;
+ endFrame = mEndFrame;
}
-void VectorAnimationTask::SetCurrentFrameNumber( uint32_t frameNumber )
+void VectorAnimationTask::SetCurrentFrameNumber(uint32_t frameNumber)
{
- if( mCurrentFrame == frameNumber )
+ if(mCurrentFrame == frameNumber)
{
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: Set same frame [%d] [%p]\n", frameNumber, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: Set same frame [%d] [%p]\n", frameNumber, this);
return;
}
- if( frameNumber >= mStartFrame && frameNumber <= mEndFrame )
+ if(frameNumber >= mStartFrame && frameNumber <= mEndFrame)
{
- mCurrentFrame = frameNumber;
+ mCurrentFrame = frameNumber;
mUpdateFrameNumber = false;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: frame number = %d [%p]\n", mCurrentFrame, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: frame number = %d [%p]\n", mCurrentFrame, this);
}
else
{
- DALI_LOG_ERROR( "Invalid frame number [%d (%d, %d)]\n", frameNumber, mStartFrame, mEndFrame );
+ DALI_LOG_ERROR("Invalid frame number [%d (%d, %d)]\n", frameNumber, mStartFrame, mEndFrame);
}
}
return mTotalFrame;
}
-void VectorAnimationTask::GetDefaultSize( uint32_t& width, uint32_t& height ) const
+void VectorAnimationTask::GetDefaultSize(uint32_t& width, uint32_t& height) const
{
- mVectorRenderer.GetDefaultSize( width, height );
+ mVectorRenderer.GetDefaultSize(width, height);
}
-void VectorAnimationTask::SetStopBehavior( DevelImageVisual::StopBehavior::Type stopBehavior )
+void VectorAnimationTask::SetStopBehavior(DevelImageVisual::StopBehavior::Type stopBehavior)
{
mStopBehavior = stopBehavior;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetStopBehavior: stop behavor = %d [%p]\n", mStopBehavior, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetStopBehavior: stop behavor = %d [%p]\n", mStopBehavior, this);
}
-void VectorAnimationTask::SetLoopingMode( DevelImageVisual::LoopingMode::Type loopingMode )
+void VectorAnimationTask::SetLoopingMode(DevelImageVisual::LoopingMode::Type loopingMode)
{
mLoopingMode = loopingMode;
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopingMode: looping mode = %d [%p]\n", mLoopingMode, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopingMode: looping mode = %d [%p]\n", mLoopingMode, this);
}
-void VectorAnimationTask::GetLayerInfo( Property::Map& map ) const
+void VectorAnimationTask::GetLayerInfo(Property::Map& map) const
{
- mVectorRenderer.GetLayerInfo( map );
+ mVectorRenderer.GetLayerInfo(map);
}
VectorAnimationTask::UploadCompletedSignalType& VectorAnimationTask::UploadCompletedSignal()
void VectorAnimationTask::Initialize()
{
- mVectorRenderer = VectorAnimationRenderer::New( mUrl );
+ mVectorRenderer = VectorAnimationRenderer::New(mUrl);
mTotalFrame = mVectorRenderer.GetTotalFrameNumber();
mEndFrame = mTotalFrame - 1;
- mFrameRate = mVectorRenderer.GetFrameRate();
+ mFrameRate = mVectorRenderer.GetFrameRate();
mFrameDurationNanoSeconds = NANOSECONDS_PER_SECOND / mFrameRate;
uint32_t width, height;
- mVectorRenderer.GetDefaultSize( width, height );
+ mVectorRenderer.GetDefaultSize(width, height);
- SetSize( width, height );
+ SetSize(width, height);
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Initialize: file = %s [%d frames, %f fps] [%p]\n", mUrl.c_str(), mTotalFrame, mFrameRate, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Initialize: file = %s [%d frames, %f fps] [%p]\n", mUrl.c_str(), mTotalFrame, mFrameRate, this);
}
bool VectorAnimationTask::Rasterize()
{
- bool stopped = false;
+ bool stopped = false;
uint32_t currentFrame;
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
- if( mDestroyTask )
+ ConditionalWait::ScopedLock lock(mConditionalWait);
+ if(mDestroyTask)
{
// The task will be destroyed. We don't need rasterization.
return false;
ApplyAnimationData();
- if( mPlayState == PlayState::PLAYING && mUpdateFrameNumber )
+ if(mPlayState == PlayState::PLAYING && mUpdateFrameNumber)
{
mCurrentFrame = mForward ? mCurrentFrame + 1 : mCurrentFrame - 1;
- Dali::ClampInPlace( mCurrentFrame, mStartFrame, mEndFrame );
+ Dali::ClampInPlace(mCurrentFrame, mStartFrame, mEndFrame);
}
currentFrame = mCurrentFrame;
mUpdateFrameNumber = true;
- if( mPlayState == PlayState::STOPPING )
+ if(mPlayState == PlayState::STOPPING)
{
- mCurrentFrame = GetStoppedFrame( mStartFrame, mEndFrame, mCurrentFrame );
- currentFrame = mCurrentFrame;
- stopped = true;
+ mCurrentFrame = GetStoppedFrame(mStartFrame, mEndFrame, mCurrentFrame);
+ currentFrame = mCurrentFrame;
+ stopped = true;
}
- else if( mPlayState == PlayState::PLAYING )
+ else if(mPlayState == PlayState::PLAYING)
{
bool animationFinished = false;
- if( currentFrame >= mEndFrame ) // last frame
+ if(currentFrame >= mEndFrame) // last frame
{
- if( mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE )
+ if(mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE)
{
mForward = false;
}
else
{
- if( mLoopCount < 0 || ++mCurrentLoop < mLoopCount ) // repeat forever or before the last loop
+ if(mLoopCount < 0 || ++mCurrentLoop < mLoopCount) // repeat forever or before the last loop
{
- mCurrentFrame = mStartFrame;
+ mCurrentFrame = mStartFrame;
mUpdateFrameNumber = false;
}
else
{
- animationFinished = true; // end of animation
+ animationFinished = true; // end of animation
}
}
}
- else if( currentFrame == mStartFrame && !mForward ) // first frame
+ else if(currentFrame == mStartFrame && !mForward) // first frame
{
- if( mLoopCount < 0 || ++mCurrentLoop < mLoopCount ) // repeat forever or before the last loop
+ if(mLoopCount < 0 || ++mCurrentLoop < mLoopCount) // repeat forever or before the last loop
{
mForward = true;
}
else
{
- animationFinished = true; // end of animation
+ animationFinished = true; // end of animation
}
}
- if( animationFinished )
+ if(animationFinished)
{
- if( mStopBehavior == DevelImageVisual::StopBehavior::CURRENT_FRAME )
+ if(mStopBehavior == DevelImageVisual::StopBehavior::CURRENT_FRAME)
{
stopped = true;
}
// Rasterize
bool renderSuccess = false;
- if( mVectorRenderer )
+ if(mVectorRenderer)
{
- renderSuccess = mVectorRenderer.Render( currentFrame );
- if( !renderSuccess )
+ renderSuccess = mVectorRenderer.Render(currentFrame);
+ if(!renderSuccess)
{
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Rendering failed. Try again later.[%d] [%p]\n", currentFrame, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Rendering failed. Try again later.[%d] [%p]\n", currentFrame, this);
mUpdateFrameNumber = false;
}
}
- if( stopped && renderSuccess )
+ if(stopped && renderSuccess)
{
- mPlayState = PlayState::STOPPED;
- mForward = true;
+ mPlayState = PlayState::STOPPED;
+ mForward = true;
mCurrentLoop = 0;
// Animation is finished
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
- if( mNeedAnimationFinishedTrigger && mAnimationFinishedTrigger )
+ ConditionalWait::ScopedLock lock(mConditionalWait);
+ if(mNeedAnimationFinishedTrigger && mAnimationFinishedTrigger)
{
mAnimationFinishedTrigger->Trigger();
}
}
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Animation is finished [current = %d] [%p]\n", currentFrame, this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Animation is finished [current = %d] [%p]\n", currentFrame, this);
}
bool keepAnimation = true;
- if( mPlayState == PlayState::PAUSED || mPlayState == PlayState::STOPPED )
+ if(mPlayState == PlayState::PAUSED || mPlayState == PlayState::STOPPED)
{
keepAnimation = false;
}
return keepAnimation;
}
-uint32_t VectorAnimationTask::GetStoppedFrame( uint32_t startFrame, uint32_t endFrame, uint32_t currentFrame )
+uint32_t VectorAnimationTask::GetStoppedFrame(uint32_t startFrame, uint32_t endFrame, uint32_t currentFrame)
{
uint32_t frame = currentFrame;
- switch( mStopBehavior )
+ switch(mStopBehavior)
{
case DevelImageVisual::StopBehavior::FIRST_FRAME:
{
}
case DevelImageVisual::StopBehavior::LAST_FRAME:
{
- if( mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE )
+ if(mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE)
{
frame = startFrame;
}
return frame;
}
-std::chrono::time_point< std::chrono::system_clock > VectorAnimationTask::CalculateNextFrameTime( bool renderNow )
+std::chrono::time_point<std::chrono::system_clock> VectorAnimationTask::CalculateNextFrameTime(bool renderNow)
{
// std::chrono::time_point template has second parameter duration which defaults to the std::chrono::system_clock supported
// duration. In some C++11 implementations it is a milliseconds duration, so it fails to compile unless mNextFrameStartTime
// is casted to use the default duration.
- mNextFrameStartTime = std::chrono::time_point_cast< std::chrono::time_point< std::chrono::system_clock >::duration >(
- mNextFrameStartTime + std::chrono::nanoseconds( mFrameDurationNanoSeconds ) );
+ mNextFrameStartTime = std::chrono::time_point_cast<std::chrono::time_point<std::chrono::system_clock>::duration>(
+ mNextFrameStartTime + std::chrono::nanoseconds(mFrameDurationNanoSeconds));
auto current = std::chrono::system_clock::now();
- if( renderNow || mNextFrameStartTime < current )
+ if(renderNow || mNextFrameStartTime < current)
{
mNextFrameStartTime = current;
}
return mNextFrameStartTime;
}
-std::chrono::time_point< std::chrono::system_clock > VectorAnimationTask::GetNextFrameTime()
+std::chrono::time_point<std::chrono::system_clock> VectorAnimationTask::GetNextFrameTime()
{
return mNextFrameStartTime;
}
uint32_t index;
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- if( !mAnimationDataUpdated || mAnimationData[mAnimationDataIndex].resendFlag != 0 )
+ if(!mAnimationDataUpdated || mAnimationData[mAnimationDataIndex].resendFlag != 0)
{
// Data is not updated or the previous data is not applied yet.
return;
}
- mAnimationDataIndex = mAnimationDataIndex == 0 ? 1 : 0; // Swap index
+ mAnimationDataIndex = mAnimationDataIndex == 0 ? 1 : 0; // Swap index
mAnimationDataUpdated = false;
index = mAnimationDataIndex;
}
- if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOP_COUNT )
+ if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOP_COUNT)
{
- SetLoopCount( mAnimationData[index].loopCount );
+ SetLoopCount(mAnimationData[index].loopCount);
}
- if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_RANGE )
+ if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_RANGE)
{
- SetPlayRange( mAnimationData[index].playRange );
+ SetPlayRange(mAnimationData[index].playRange);
}
- if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_STOP_BEHAVIOR )
+ if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_STOP_BEHAVIOR)
{
- SetStopBehavior( mAnimationData[index].stopBehavior );
+ SetStopBehavior(mAnimationData[index].stopBehavior);
}
- if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOPING_MODE )
+ if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOPING_MODE)
{
- SetLoopingMode( mAnimationData[index].loopingMode );
+ SetLoopingMode(mAnimationData[index].loopingMode);
}
- if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_CURRENT_FRAME )
+ if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_CURRENT_FRAME)
{
- SetCurrentFrameNumber( mAnimationData[index].currentFrame );
+ SetCurrentFrameNumber(mAnimationData[index].currentFrame);
}
- if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_STATE )
+ if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_STATE)
{
- if( mAnimationData[index].playState == DevelImageVisual::PlayState::PLAYING )
+ if(mAnimationData[index].playState == DevelImageVisual::PlayState::PLAYING)
{
PlayAnimation();
}
- else if( mAnimationData[index].playState == DevelImageVisual::PlayState::PAUSED )
+ else if(mAnimationData[index].playState == DevelImageVisual::PlayState::PAUSED)
{
PauseAnimation();
}
- else if( mAnimationData[index].playState == DevelImageVisual::PlayState::STOPPED )
+ else if(mAnimationData[index].playState == DevelImageVisual::PlayState::STOPPED)
{
StopAnimation();
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.h>
// EXTERNAL INCLUDES
-#include <dali/devel-api/adaptor-framework/thread-settings.h>
#include <dali/devel-api/adaptor-framework/environment-variable.h>
+#include <dali/devel-api/adaptor-framework/thread-settings.h>
+#include <dali/integration-api/adaptor-framework/adaptor.h>
#include <dali/integration-api/debug.h>
#include <thread>
-#include <dali/integration-api/adaptor-framework/adaptor.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
+constexpr auto DEFAULT_NUMBER_OF_RASTERIZE_THREADS = size_t{4u};
+constexpr auto NUMBER_OF_RASTERIZE_THREADS_ENV = "DALI_VECTOR_RASTERIZE_THREADS";
-constexpr auto DEFAULT_NUMBER_OF_RASTERIZE_THREADS = size_t{ 4u };
-constexpr auto NUMBER_OF_RASTERIZE_THREADS_ENV = "DALI_VECTOR_RASTERIZE_THREADS";
-
-size_t GetNumberOfThreads( const char* environmentVariable, size_t defaultValue )
+size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
{
using Dali::EnvironmentVariable::GetEnvironmentVariable;
- auto numberString = GetEnvironmentVariable( environmentVariable );
- auto numberOfThreads = numberString ? std::strtoul( numberString, nullptr, 10 ) : 0;
+ auto numberString = GetEnvironmentVariable(environmentVariable);
+ auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
constexpr auto MAX_NUMBER_OF_THREADS = 100u;
- DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS );
- return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue;
+ DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS);
+ return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
}
#if defined(DEBUG_ENABLED)
-Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" );
+Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
#endif
} // unnamed namespace
: mAnimationTasks(),
mCompletedTasks(),
mWorkingTasks(),
- mRasterizers( GetNumberOfThreads( NUMBER_OF_RASTERIZE_THREADS_ENV, DEFAULT_NUMBER_OF_RASTERIZE_THREADS ), [&]() { return RasterizeHelper( *this ); } ),
- mSleepThread( MakeCallback( this, &VectorAnimationThread::OnAwakeFromSleep ) ),
+ mRasterizers(GetNumberOfThreads(NUMBER_OF_RASTERIZE_THREADS_ENV, DEFAULT_NUMBER_OF_RASTERIZE_THREADS), [&]() { return RasterizeHelper(*this); }),
+ mSleepThread(MakeCallback(this, &VectorAnimationThread::OnAwakeFromSleep)),
mConditionalWait(),
- mNeedToSleep( false ),
- mDestroyThread( false ),
- mLogFactory( Dali::Adaptor::Get().GetLogFactory() )
+ mNeedToSleep(false),
+ mDestroyThread(false),
+ mLogFactory(Dali::Adaptor::Get().GetLogFactory())
{
mSleepThread.Start();
}
{
// Stop the thread
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
mDestroyThread = true;
- mNeedToSleep = false;
- mConditionalWait.Notify( lock );
+ mNeedToSleep = false;
+ mConditionalWait.Notify(lock);
}
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::~VectorAnimationThread: Join [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::~VectorAnimationThread: Join [%p]\n", this);
Join();
}
-void VectorAnimationThread::AddTask( VectorAnimationTaskPtr task )
+void VectorAnimationThread::AddTask(VectorAnimationTaskPtr task)
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- if( mAnimationTasks.end() == std::find( mAnimationTasks.begin(), mAnimationTasks.end(), task ) )
+ if(mAnimationTasks.end() == std::find(mAnimationTasks.begin(), mAnimationTasks.end(), task))
{
- auto currentTime = task->CalculateNextFrameTime( true ); // Rasterize as soon as possible
+ auto currentTime = task->CalculateNextFrameTime(true); // Rasterize as soon as possible
bool inserted = false;
- for( auto iter = mAnimationTasks.begin(); iter != mAnimationTasks.end(); ++iter )
+ for(auto iter = mAnimationTasks.begin(); iter != mAnimationTasks.end(); ++iter)
{
auto nextTime = (*iter)->GetNextFrameTime();
- if( nextTime > currentTime )
+ if(nextTime > currentTime)
{
- mAnimationTasks.insert( iter, task );
+ mAnimationTasks.insert(iter, task);
inserted = true;
break;
}
}
- if( !inserted )
+ if(!inserted)
{
- mAnimationTasks.push_back( task );
+ mAnimationTasks.push_back(task);
}
mNeedToSleep = false;
// wake up the animation thread
- mConditionalWait.Notify( lock );
+ mConditionalWait.Notify(lock);
}
}
-void VectorAnimationThread::OnTaskCompleted( VectorAnimationTaskPtr task, bool keepAnimation )
+void VectorAnimationThread::OnTaskCompleted(VectorAnimationTaskPtr task, bool keepAnimation)
{
- if( !mDestroyThread )
+ if(!mDestroyThread)
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
- bool needRasterize = false;
+ ConditionalWait::ScopedLock lock(mConditionalWait);
+ bool needRasterize = false;
- auto workingTask = std::find( mWorkingTasks.begin(), mWorkingTasks.end(), task );
- if( workingTask != mWorkingTasks.end() )
+ auto workingTask = std::find(mWorkingTasks.begin(), mWorkingTasks.end(), task);
+ if(workingTask != mWorkingTasks.end())
{
- mWorkingTasks.erase( workingTask );
+ mWorkingTasks.erase(workingTask);
}
// Check pending task
- if( mAnimationTasks.end() != std::find( mAnimationTasks.begin(), mAnimationTasks.end(), task ) )
+ if(mAnimationTasks.end() != std::find(mAnimationTasks.begin(), mAnimationTasks.end(), task))
{
needRasterize = true;
}
- if( keepAnimation )
+ if(keepAnimation)
{
- if( mCompletedTasks.end() == std::find( mCompletedTasks.begin(), mCompletedTasks.end(), task ) )
+ if(mCompletedTasks.end() == std::find(mCompletedTasks.begin(), mCompletedTasks.end(), task))
{
- mCompletedTasks.push_back( task );
+ mCompletedTasks.push_back(task);
needRasterize = true;
}
}
- if( needRasterize )
+ if(needRasterize)
{
mNeedToSleep = false;
// wake up the animation thread
- mConditionalWait.Notify( lock );
+ mConditionalWait.Notify(lock);
}
}
}
void VectorAnimationThread::OnAwakeFromSleep()
{
- if( !mDestroyThread )
+ if(!mDestroyThread)
{
mNeedToSleep = false;
// wake up the animation thread
void VectorAnimationThread::Run()
{
- SetThreadName( "VectorAnimationThread" );
+ SetThreadName("VectorAnimationThread");
mLogFactory.InstallLogFunction();
- while( !mDestroyThread )
+ while(!mDestroyThread)
{
Rasterize();
}
void VectorAnimationThread::Rasterize()
{
// Lock while popping task out from the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
// conditional wait
- if( mNeedToSleep )
+ if(mNeedToSleep)
{
- mConditionalWait.Wait( lock );
+ mConditionalWait.Wait(lock);
}
mNeedToSleep = true;
// Process completed tasks
- for( auto&& task : mCompletedTasks )
+ for(auto&& task : mCompletedTasks)
{
- if( mAnimationTasks.end() == std::find( mAnimationTasks.begin(), mAnimationTasks.end(), task ) )
+ if(mAnimationTasks.end() == std::find(mAnimationTasks.begin(), mAnimationTasks.end(), task))
{
// Should use the frame rate of the animation file
- auto nextFrameTime = task->CalculateNextFrameTime( false );
+ auto nextFrameTime = task->CalculateNextFrameTime(false);
bool inserted = false;
- for( auto iter = mAnimationTasks.begin(); iter != mAnimationTasks.end(); ++iter )
+ for(auto iter = mAnimationTasks.begin(); iter != mAnimationTasks.end(); ++iter)
{
auto time = (*iter)->GetNextFrameTime();
- if( time > nextFrameTime )
+ if(time > nextFrameTime)
{
- mAnimationTasks.insert( iter, task );
+ mAnimationTasks.insert(iter, task);
inserted = true;
break;
}
}
- if( !inserted )
+ if(!inserted)
{
- mAnimationTasks.push_back( task );
+ mAnimationTasks.push_back(task);
}
}
}
mCompletedTasks.clear();
// pop out the next task from the queue
- for( auto it = mAnimationTasks.begin(); it != mAnimationTasks.end(); )
+ for(auto it = mAnimationTasks.begin(); it != mAnimationTasks.end();)
{
VectorAnimationTaskPtr nextTask = *it;
- auto currentTime = std::chrono::system_clock::now();
+ auto currentTime = std::chrono::system_clock::now();
auto nextFrameTime = nextTask->GetNextFrameTime();
#if defined(DEBUG_ENABLED)
- auto duration = std::chrono::duration_cast< std::chrono::milliseconds >( nextFrameTime - currentTime );
+ auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(nextFrameTime - currentTime);
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::Rasterize: [next time = %lld]\n", duration.count() );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::Rasterize: [next time = %lld]\n", duration.count());
#endif
- if( nextFrameTime <= currentTime )
+ if(nextFrameTime <= currentTime)
{
// If the task is not in the working list
- if( std::find( mWorkingTasks.begin(), mWorkingTasks.end(), nextTask ) == mWorkingTasks.end() )
+ if(std::find(mWorkingTasks.begin(), mWorkingTasks.end(), nextTask) == mWorkingTasks.end())
{
- it = mAnimationTasks.erase( it );
+ it = mAnimationTasks.erase(it);
// Add it to the working list
- mWorkingTasks.push_back( nextTask );
+ mWorkingTasks.push_back(nextTask);
auto rasterizerHelperIt = mRasterizers.GetNext();
- DALI_ASSERT_ALWAYS( rasterizerHelperIt != mRasterizers.End() );
+ DALI_ASSERT_ALWAYS(rasterizerHelperIt != mRasterizers.End());
- rasterizerHelperIt->Rasterize( nextTask );
+ rasterizerHelperIt->Rasterize(nextTask);
}
else
{
}
else
{
- mSleepThread.SleepUntil( nextFrameTime );
+ mSleepThread.SleepUntil(nextFrameTime);
break;
}
}
}
-VectorAnimationThread::RasterizeHelper::RasterizeHelper( VectorAnimationThread& animationThread )
-: RasterizeHelper( std::unique_ptr< VectorRasterizeThread >( new VectorRasterizeThread() ), animationThread )
+VectorAnimationThread::RasterizeHelper::RasterizeHelper(VectorAnimationThread& animationThread)
+: RasterizeHelper(std::unique_ptr<VectorRasterizeThread>(new VectorRasterizeThread()), animationThread)
{
}
-VectorAnimationThread::RasterizeHelper::RasterizeHelper( RasterizeHelper&& rhs )
-: RasterizeHelper( std::move( rhs.mRasterizer ), rhs.mAnimationThread )
+VectorAnimationThread::RasterizeHelper::RasterizeHelper(RasterizeHelper&& rhs)
+: RasterizeHelper(std::move(rhs.mRasterizer), rhs.mAnimationThread)
{
}
-VectorAnimationThread::RasterizeHelper::RasterizeHelper( std::unique_ptr< VectorRasterizeThread > rasterizer, VectorAnimationThread& animationThread )
-: mRasterizer( std::move( rasterizer ) ),
- mAnimationThread( animationThread )
+VectorAnimationThread::RasterizeHelper::RasterizeHelper(std::unique_ptr<VectorRasterizeThread> rasterizer, VectorAnimationThread& animationThread)
+: mRasterizer(std::move(rasterizer)),
+ mAnimationThread(animationThread)
{
- mRasterizer->SetCompletedCallback( MakeCallback( &mAnimationThread, &VectorAnimationThread::OnTaskCompleted ) );
+ mRasterizer->SetCompletedCallback(MakeCallback(&mAnimationThread, &VectorAnimationThread::OnTaskCompleted));
}
-void VectorAnimationThread::RasterizeHelper::Rasterize( VectorAnimationTaskPtr task )
+void VectorAnimationThread::RasterizeHelper::Rasterize(VectorAnimationTaskPtr task)
{
- if( task )
+ if(task)
{
- mRasterizer->AddTask( task );
+ mRasterizer->AddTask(task);
}
}
-VectorAnimationThread::SleepThread::SleepThread( CallbackBase* callback )
+VectorAnimationThread::SleepThread::SleepThread(CallbackBase* callback)
: mConditionalWait(),
- mAwakeCallback( std::unique_ptr< CallbackBase >( callback ) ),
+ mAwakeCallback(std::unique_ptr<CallbackBase>(callback)),
mSleepTimePoint(),
- mLogFactory( Dali::Adaptor::Get().GetLogFactory() ),
- mNeedToSleep( false ),
- mDestroyThread( false )
+ mLogFactory(Dali::Adaptor::Get().GetLogFactory()),
+ mNeedToSleep(false),
+ mDestroyThread(false)
{
}
{
// Stop the thread
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
mDestroyThread = true;
- mConditionalWait.Notify( lock );
+ mConditionalWait.Notify(lock);
}
Join();
}
-void VectorAnimationThread::SleepThread::SleepUntil( std::chrono::time_point< std::chrono::system_clock > timeToSleepUntil )
+void VectorAnimationThread::SleepThread::SleepUntil(std::chrono::time_point<std::chrono::system_clock> timeToSleepUntil)
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
mSleepTimePoint = timeToSleepUntil;
- mNeedToSleep = true;
- mConditionalWait.Notify( lock );
+ mNeedToSleep = true;
+ mConditionalWait.Notify(lock);
}
void VectorAnimationThread::SleepThread::Run()
{
- SetThreadName( "VectorSleepThread" );
+ SetThreadName("VectorSleepThread");
mLogFactory.InstallLogFunction();
- while( !mDestroyThread )
+ while(!mDestroyThread)
{
- bool needToSleep;
- std::chrono::time_point< std::chrono::system_clock > sleepTimePoint;
+ bool needToSleep;
+ std::chrono::time_point<std::chrono::system_clock> sleepTimePoint;
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- needToSleep = mNeedToSleep;
+ needToSleep = mNeedToSleep;
sleepTimePoint = mSleepTimePoint;
mNeedToSleep = false;
}
- if( needToSleep )
+ if(needToSleep)
{
#if defined(DEBUG_ENABLED)
- auto sleepDuration = std::chrono::duration_cast< std::chrono::milliseconds >( mSleepTimePoint - std::chrono::system_clock::now() );
+ auto sleepDuration = std::chrono::duration_cast<std::chrono::milliseconds>(mSleepTimePoint - std::chrono::system_clock::now());
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::SleepThread::Run: [sleep duration = %lld]\n", sleepDuration.count() );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::SleepThread::Run: [sleep duration = %lld]\n", sleepDuration.count());
#endif
- std::this_thread::sleep_until( sleepTimePoint );
+ std::this_thread::sleep_until(sleepTimePoint);
- if( mAwakeCallback )
+ if(mAwakeCallback)
{
- CallbackBase::Execute( *mAwakeCallback );
+ CallbackBase::Execute(*mAwakeCallback);
}
}
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
- if( !mDestroyThread && !mNeedToSleep )
+ ConditionalWait::ScopedLock lock(mConditionalWait);
+ if(!mDestroyThread && !mNeedToSleep)
{
- mConditionalWait.Wait( lock );
+ mConditionalWait.Wait(lock);
}
}
}
/*
- * Copyright (c) 2019 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
#include <dali/devel-api/adaptor-framework/thread-settings.h>
+#include <dali/integration-api/adaptor-framework/adaptor.h>
#include <dali/integration-api/debug.h>
#include <chrono>
#include <thread>
-#include <dali/integration-api/adaptor-framework/adaptor.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
#if defined(DEBUG_ENABLED)
-Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" );
+Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
#endif
} // unnamed namespace
: mRasterizeTasks(),
mConditionalWait(),
mCompletedCallback(),
- mDestroyThread( false ),
- mIsThreadStarted( false ),
- mLogFactory( Dali::Adaptor::Get().GetLogFactory() )
+ mDestroyThread(false),
+ mIsThreadStarted(false),
+ mLogFactory(Dali::Adaptor::Get().GetLogFactory())
{
}
{
// Stop the thread
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
mDestroyThread = true;
- mConditionalWait.Notify( lock );
+ mConditionalWait.Notify(lock);
}
- DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorRasterizeThread::~VectorRasterizeThread: Join [%p]\n", this );
+ DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorRasterizeThread::~VectorRasterizeThread: Join [%p]\n", this);
Join();
}
-void VectorRasterizeThread::SetCompletedCallback( CallbackBase* callback )
+void VectorRasterizeThread::SetCompletedCallback(CallbackBase* callback)
{
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- mCompletedCallback = std::unique_ptr< CallbackBase >( callback );
+ mCompletedCallback = std::unique_ptr<CallbackBase>(callback);
}
-void VectorRasterizeThread::AddTask( VectorAnimationTaskPtr task )
+void VectorRasterizeThread::AddTask(VectorAnimationTaskPtr task)
{
// Lock while adding task to the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- if( !mIsThreadStarted )
+ if(!mIsThreadStarted)
{
Start();
mIsThreadStarted = true;
}
- if( mRasterizeTasks.end() == std::find( mRasterizeTasks.begin(), mRasterizeTasks.end(), task ) )
+ if(mRasterizeTasks.end() == std::find(mRasterizeTasks.begin(), mRasterizeTasks.end(), task))
{
- mRasterizeTasks.push_back( task );
+ mRasterizeTasks.push_back(task);
// wake up the animation thread
- mConditionalWait.Notify( lock );
+ mConditionalWait.Notify(lock);
}
}
void VectorRasterizeThread::Run()
{
- SetThreadName( "VectorRasterizeThread" );
+ SetThreadName("VectorRasterizeThread");
mLogFactory.InstallLogFunction();
- while( !mDestroyThread )
+ while(!mDestroyThread)
{
Rasterize();
}
VectorAnimationTaskPtr nextTask;
{
// Lock while popping task out from the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
// conditional wait
- if( mRasterizeTasks.empty() )
+ if(mRasterizeTasks.empty())
{
- mConditionalWait.Wait( lock );
+ mConditionalWait.Wait(lock);
}
// pop out the next task from the queue
- if( !mRasterizeTasks.empty() )
+ if(!mRasterizeTasks.empty())
{
- std::vector< VectorAnimationTaskPtr >::iterator next = mRasterizeTasks.begin();
- nextTask = *next;
- mRasterizeTasks.erase( next );
+ std::vector<VectorAnimationTaskPtr>::iterator next = mRasterizeTasks.begin();
+ nextTask = *next;
+ mRasterizeTasks.erase(next);
}
}
- if( nextTask )
+ if(nextTask)
{
bool keepAnimation = nextTask->Rasterize();
- if( mCompletedCallback )
+ if(mCompletedCallback)
{
- CallbackBase::Execute( *mCompletedCallback, nextTask, keepAnimation );
+ CallbackBase::Execute(*mCompletedCallback, nextTask, keepAnimation);
}
}
}
#include <dali/integration-api/debug.h>
//INTERNAL INCLUDES
-#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
#include <dali-toolkit/devel-api/visuals/arc-visual-actions-devel.h>
-#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// cap
-DALI_ENUM_TO_STRING_TABLE_BEGIN( CAP )
-DALI_ENUM_TO_STRING_WITH_SCOPE( DevelArcVisual::Cap, BUTT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( DevelArcVisual::Cap, ROUND )
-DALI_ENUM_TO_STRING_TABLE_END( CAP )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(CAP)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(DevelArcVisual::Cap, BUTT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(DevelArcVisual::Cap, ROUND)
+DALI_ENUM_TO_STRING_TABLE_END(CAP)
-}
+} // namespace
-ArcVisualPtr ArcVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+ArcVisualPtr ArcVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
- ArcVisualPtr arcVisualPtr( new ArcVisual( factoryCache ) );
- arcVisualPtr->SetProperties( properties );
+ ArcVisualPtr arcVisualPtr(new ArcVisual(factoryCache));
+ arcVisualPtr->SetProperties(properties);
arcVisualPtr->Initialize();
return arcVisualPtr;
}
-ArcVisual::ArcVisual( VisualFactoryCache& factoryCache )
-: Visual::Base( factoryCache, Visual::FittingMode::FILL, static_cast<Toolkit::Visual::Type>( Toolkit::DevelVisual::ARC ) ),
- mThickness( 0.0f ),
- mRadius( 0.0f ),
- mStartAngle( 0.0f ),
- mSweepAngle( 360.0f ),
- mRadiusIndex( Property::INVALID_INDEX ),
- mThicknessIndex( Property::INVALID_INDEX ),
- mStartAngleIndex( Property::INVALID_INDEX ),
- mSweepAngleIndex( Property::INVALID_INDEX ),
- mCapType( DevelArcVisual::Cap::BUTT )
+ArcVisual::ArcVisual(VisualFactoryCache& factoryCache)
+: Visual::Base(factoryCache, Visual::FittingMode::FILL, static_cast<Toolkit::Visual::Type>(Toolkit::DevelVisual::ARC)),
+ mThickness(0.0f),
+ mRadius(0.0f),
+ mStartAngle(0.0f),
+ mSweepAngle(360.0f),
+ mRadiusIndex(Property::INVALID_INDEX),
+ mThicknessIndex(Property::INVALID_INDEX),
+ mStartAngleIndex(Property::INVALID_INDEX),
+ mSweepAngleIndex(Property::INVALID_INDEX),
+ mCapType(DevelArcVisual::Cap::BUTT)
{
}
{
}
-void ArcVisual::DoSetProperties( const Property::Map& propertyMap )
+void ArcVisual::DoSetProperties(const Property::Map& propertyMap)
{
- Property::Value* thicknessValue = propertyMap.Find( Toolkit::DevelArcVisual::Property::THICKNESS, THICKNESS_NAME );
- if( thicknessValue )
+ Property::Value* thicknessValue = propertyMap.Find(Toolkit::DevelArcVisual::Property::THICKNESS, THICKNESS_NAME);
+ if(thicknessValue)
{
- if( !thicknessValue->Get( mThickness ) )
+ if(!thicknessValue->Get(mThickness))
{
- DALI_LOG_ERROR( "ArcVisual:DoSetProperties:: THICKNESS property has incorrect type: %d\n", thicknessValue->GetType() );
+ DALI_LOG_ERROR("ArcVisual:DoSetProperties:: THICKNESS property has incorrect type: %d\n", thicknessValue->GetType());
}
else
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetProperty( mThicknessIndex, mThickness );
+ mImpl->mRenderer.SetProperty(mThicknessIndex, mThickness);
// Need to calculate radius again
OnSetTransform();
}
}
- Property::Value* startAngleValue = propertyMap.Find( Toolkit::DevelArcVisual::Property::START_ANGLE, START_ANGLE_NAME );
- if( startAngleValue )
+ Property::Value* startAngleValue = propertyMap.Find(Toolkit::DevelArcVisual::Property::START_ANGLE, START_ANGLE_NAME);
+ if(startAngleValue)
{
- if( !startAngleValue->Get( mStartAngle ) )
+ if(!startAngleValue->Get(mStartAngle))
{
- DALI_LOG_ERROR( "ArcVisual:DoSetProperties:: START_ANGLE property has incorrect type: %d\n", startAngleValue->GetType() );
+ DALI_LOG_ERROR("ArcVisual:DoSetProperties:: START_ANGLE property has incorrect type: %d\n", startAngleValue->GetType());
}
else
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetProperty( mStartAngleIndex, mStartAngle );
+ mImpl->mRenderer.SetProperty(mStartAngleIndex, mStartAngle);
}
}
}
- Property::Value* sweepAngleValue = propertyMap.Find( Toolkit::DevelArcVisual::Property::SWEEP_ANGLE, SWEEP_ANGLE_NAME );
- if( sweepAngleValue )
+ Property::Value* sweepAngleValue = propertyMap.Find(Toolkit::DevelArcVisual::Property::SWEEP_ANGLE, SWEEP_ANGLE_NAME);
+ if(sweepAngleValue)
{
- if( !sweepAngleValue->Get( mSweepAngle ) )
+ if(!sweepAngleValue->Get(mSweepAngle))
{
- DALI_LOG_ERROR( "ArcVisual:DoSetProperties:: SWEEP_ANGLE property has incorrect type: %d\n", sweepAngleValue->GetType() );
+ DALI_LOG_ERROR("ArcVisual:DoSetProperties:: SWEEP_ANGLE property has incorrect type: %d\n", sweepAngleValue->GetType());
}
else
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetProperty( mSweepAngleIndex, mSweepAngle );
+ mImpl->mRenderer.SetProperty(mSweepAngleIndex, mSweepAngle);
}
}
}
- Property::Value* capValue = propertyMap.Find( Toolkit::DevelArcVisual::Property::CAP, CAP_NAME );
- if( capValue )
+ Property::Value* capValue = propertyMap.Find(Toolkit::DevelArcVisual::Property::CAP, CAP_NAME);
+ if(capValue)
{
int capType = 0;
- Scripting::GetEnumerationProperty( *capValue, CAP_TABLE, CAP_TABLE_COUNT, capType );
- mCapType = Toolkit::DevelArcVisual::Cap::Type( capType );
+ Scripting::GetEnumerationProperty(*capValue, CAP_TABLE, CAP_TABLE_COUNT, capType);
+ mCapType = Toolkit::DevelArcVisual::Cap::Type(capType);
}
}
-void ArcVisual::DoSetOnScene( Actor& actor )
+void ArcVisual::DoSetOnScene(Actor& actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
// Arc Visual generated and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
void ArcVisual::DoSetOffScene(Actor& actor)
actor.RemoveRenderer(mImpl->mRenderer);
}
-void ArcVisual::DoCreatePropertyMap( Property::Map& map ) const
+void ArcVisual::DoCreatePropertyMap(Property::Map& map) const
{
float thickness, startAngle, sweepAngle;
if(mImpl->mRenderer)
}
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ARC );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ARC);
map.Insert(Toolkit::DevelArcVisual::Property::THICKNESS, thickness);
map.Insert(Toolkit::DevelArcVisual::Property::START_ANGLE, startAngle);
map.Insert(Toolkit::DevelArcVisual::Property::SWEEP_ANGLE, sweepAngle);
- map.Insert( Toolkit::DevelArcVisual::Property::CAP, mCapType );
+ map.Insert(Toolkit::DevelArcVisual::Property::CAP, mCapType);
}
-void ArcVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void ArcVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
void ArcVisual::OnSetTransform()
{
- Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize );
- mRadius = ( std::min( visualSize.width, visualSize.height ) - mThickness ) / 2.0f;
+ Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize);
+ mRadius = (std::min(visualSize.width, visualSize.height) - mThickness) / 2.0f;
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetProperty( mRadiusIndex, mRadius );
+ mImpl->mRenderer.SetProperty(mRadiusIndex, mRadius);
}
}
-void ArcVisual::OnDoAction( const Property::Index actionId, const Property::Value& attributes )
+void ArcVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes)
{
// Check if action is valid for this visual type and perform action if possible
- switch( actionId )
+ switch(actionId)
{
case DevelArcVisual::Action::UPDATE_PROPERTY:
{
const Property::Map* map = attributes.GetMap();
- if( map )
+ if(map)
{
- DoSetProperties( *map );
+ DoSetProperties(*map);
}
break;
}
void ArcVisual::OnInitialize()
{
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
Shader shader;
- if( mCapType == DevelArcVisual::Cap::BUTT )
+ if(mCapType == DevelArcVisual::Cap::BUTT)
{
- shader = mFactoryCache.GetShader( VisualFactoryCache::ARC_BUTT_CAP_SHADER );
- if( !shader )
+ shader = mFactoryCache.GetShader(VisualFactoryCache::ARC_BUTT_CAP_SHADER);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_ARC_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_ARC_VISUAL_BUTT_CAP_SHADER_FRAG.data() );
- mFactoryCache.SaveShader( VisualFactoryCache::ARC_BUTT_CAP_SHADER, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_ARC_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_ARC_VISUAL_BUTT_CAP_SHADER_FRAG.data());
+ mFactoryCache.SaveShader(VisualFactoryCache::ARC_BUTT_CAP_SHADER, shader);
}
}
else
{
- shader = mFactoryCache.GetShader( VisualFactoryCache::ARC_ROUND_CAP_SHADER );
- if( !shader )
+ shader = mFactoryCache.GetShader(VisualFactoryCache::ARC_ROUND_CAP_SHADER);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_ARC_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_ARC_VISUAL_ROUND_CAP_SHADER_FRAG.data() );
- mFactoryCache.SaveShader( VisualFactoryCache::ARC_ROUND_CAP_SHADER, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_ARC_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_ARC_VISUAL_ROUND_CAP_SHADER_FRAG.data());
+ mFactoryCache.SaveShader(VisualFactoryCache::ARC_ROUND_CAP_SHADER, shader);
}
}
- mImpl->mRenderer = Renderer::New( geometry, shader );
+ mImpl->mRenderer = Renderer::New(geometry, shader);
mThicknessIndex = mImpl->mRenderer.RegisterProperty(DevelArcVisual::Property::THICKNESS, THICKNESS_NAME, mThickness);
mStartAngleIndex = mImpl->mRenderer.RegisterProperty(DevelArcVisual::Property::START_ANGLE, START_ANGLE_NAME, mStartAngle);
mSweepAngleIndex = mImpl->mRenderer.RegisterProperty(DevelArcVisual::Property::SWEEP_ANGLE, SWEEP_ANGLE_NAME, mSweepAngle);
- mRadiusIndex = mImpl->mRenderer.RegisterProperty( RADIUS_NAME, mRadius );
+ mRadiusIndex = mImpl->mRenderer.RegisterProperty(RADIUS_NAME, mRadius);
- mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON );
+ mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
// Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
} // namespace Internal
#include "border-visual.h"
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
#include <dali/devel-api/rendering/renderer-devel.h>
+#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/border-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/border-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-const char * const POSITION_ATTRIBUTE_NAME("aPosition");
-const char * const DRIFT_ATTRIBUTE_NAME("aDrift");
-const char * const INDEX_NAME("indices");
-}
+const char* const POSITION_ATTRIBUTE_NAME("aPosition");
+const char* const DRIFT_ATTRIBUTE_NAME("aDrift");
+const char* const INDEX_NAME("indices");
+} // namespace
-BorderVisualPtr BorderVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+BorderVisualPtr BorderVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
- BorderVisualPtr borderVisualPtr( new BorderVisual( factoryCache ) );
- borderVisualPtr->SetProperties( properties );
+ BorderVisualPtr borderVisualPtr(new BorderVisual(factoryCache));
+ borderVisualPtr->SetProperties(properties);
borderVisualPtr->Initialize();
return borderVisualPtr;
}
-BorderVisual::BorderVisual( VisualFactoryCache& factoryCache )
-: Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::BORDER ),
- mBorderColor( Color::TRANSPARENT ),
- mBorderSize( 0.f ),
- mBorderColorIndex( Property::INVALID_INDEX ),
- mBorderSizeIndex( Property::INVALID_INDEX ),
- mAntiAliasing( false )
+BorderVisual::BorderVisual(VisualFactoryCache& factoryCache)
+: Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::BORDER),
+ mBorderColor(Color::TRANSPARENT),
+ mBorderSize(0.f),
+ mBorderColorIndex(Property::INVALID_INDEX),
+ mBorderSizeIndex(Property::INVALID_INDEX),
+ mAntiAliasing(false)
{
}
{
}
-void BorderVisual::DoSetProperties( const Property::Map& propertyMap )
+void BorderVisual::DoSetProperties(const Property::Map& propertyMap)
{
- for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
+ for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
{
- KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
- if( keyValue.first.type == Property::Key::INDEX )
+ KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
+ if(keyValue.first.type == Property::Key::INDEX)
{
- DoSetProperty( keyValue.first.indexKey, keyValue.second );
+ DoSetProperty(keyValue.first.indexKey, keyValue.second);
}
else
{
- if( keyValue.first == COLOR_NAME )
+ if(keyValue.first == COLOR_NAME)
{
- DoSetProperty( Toolkit::BorderVisual::Property::COLOR, keyValue.second );
+ DoSetProperty(Toolkit::BorderVisual::Property::COLOR, keyValue.second);
}
- else if( keyValue.first == SIZE_NAME )
+ else if(keyValue.first == SIZE_NAME)
{
- DoSetProperty( Toolkit::BorderVisual::Property::SIZE, keyValue.second );
+ DoSetProperty(Toolkit::BorderVisual::Property::SIZE, keyValue.second);
}
- else if( keyValue.first == ANTI_ALIASING )
+ else if(keyValue.first == ANTI_ALIASING)
{
- DoSetProperty( Toolkit::BorderVisual::Property::ANTI_ALIASING, keyValue.second );
+ DoSetProperty(Toolkit::BorderVisual::Property::ANTI_ALIASING, keyValue.second);
}
}
}
}
-void BorderVisual::DoSetProperty( Dali::Property::Index index,
- const Dali::Property::Value& value )
+void BorderVisual::DoSetProperty(Dali::Property::Index index,
+ const Dali::Property::Value& value)
{
- switch( index )
+ switch(index)
{
case Toolkit::BorderVisual::Property::COLOR:
{
- if( !value.Get( mBorderColor ) )
+ if(!value.Get(mBorderColor))
{
DALI_LOG_ERROR("BorderVisual: borderColor property has incorrect type\n");
}
}
case Toolkit::BorderVisual::Property::SIZE:
{
- if( !value.Get( mBorderSize ) )
+ if(!value.Get(mBorderSize))
{
DALI_LOG_ERROR("BorderVisual: borderSize property has incorrect type\n");
}
}
case Toolkit::BorderVisual::Property::ANTI_ALIASING:
{
- if( !value.Get( mAntiAliasing ) )
+ if(!value.Get(mAntiAliasing))
{
DALI_LOG_ERROR("BorderVisual: antiAliasing property has incorrect type\n");
}
}
}
-void BorderVisual::DoSetOnScene( Actor& actor )
+void BorderVisual::DoSetOnScene(Actor& actor)
{
- mBorderColorIndex = mImpl->mRenderer.RegisterProperty( Toolkit::BorderVisual::Property::COLOR, COLOR_NAME, mBorderColor );
- if( mBorderColor.a < 1.f || mAntiAliasing )
+ mBorderColorIndex = mImpl->mRenderer.RegisterProperty(Toolkit::BorderVisual::Property::COLOR, COLOR_NAME, mBorderColor);
+ if(mBorderColor.a < 1.f || mAntiAliasing)
{
- mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON );
+ mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
}
- mBorderSizeIndex = mImpl->mRenderer.RegisterProperty( Toolkit::BorderVisual::Property::SIZE, SIZE_NAME, mBorderSize );
+ mBorderSizeIndex = mImpl->mRenderer.RegisterProperty(Toolkit::BorderVisual::Property::SIZE, SIZE_NAME, mBorderSize);
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
// Border Visual Generated and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
-void BorderVisual::DoCreatePropertyMap( Property::Map& map ) const
+void BorderVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::BORDER );
- map.Insert( Toolkit::BorderVisual::Property::COLOR, mBorderColor );
- map.Insert( Toolkit::BorderVisual::Property::SIZE, mBorderSize );
- map.Insert( Toolkit::BorderVisual::Property::ANTI_ALIASING, mAntiAliasing );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::BORDER);
+ map.Insert(Toolkit::BorderVisual::Property::COLOR, mBorderColor);
+ map.Insert(Toolkit::BorderVisual::Property::SIZE, mBorderSize);
+ map.Insert(Toolkit::BorderVisual::Property::ANTI_ALIASING, mAntiAliasing);
}
-void BorderVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void BorderVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
void BorderVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
void BorderVisual::OnInitialize()
{
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::BORDER_GEOMETRY );
- if( !geometry )
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::BORDER_GEOMETRY);
+ if(!geometry)
{
- geometry = CreateBorderGeometry();
- mFactoryCache.SaveGeometry( VisualFactoryCache::BORDER_GEOMETRY, geometry );
+ geometry = CreateBorderGeometry();
+ mFactoryCache.SaveGeometry(VisualFactoryCache::BORDER_GEOMETRY, geometry);
}
- Shader shader = GetBorderShader();
- mImpl->mRenderer = Renderer::New( geometry, shader );
+ Shader shader = GetBorderShader();
+ mImpl->mRenderer = Renderer::New(geometry, shader);
//Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
Shader BorderVisual::GetBorderShader()
{
Shader shader;
- if( mAntiAliasing )
+ if(mAntiAliasing)
{
- shader = mFactoryCache.GetShader( VisualFactoryCache::BORDER_SHADER_ANTI_ALIASING );
- if( !shader )
+ shader = mFactoryCache.GetShader(VisualFactoryCache::BORDER_SHADER_ANTI_ALIASING);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_BORDER_VISUAL_ANTI_ALIASING_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_BORDER_VISUAL_ANTI_ALIASING_SHADER_FRAG.data() );
- mFactoryCache.SaveShader( VisualFactoryCache::BORDER_SHADER_ANTI_ALIASING, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_BORDER_VISUAL_ANTI_ALIASING_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_BORDER_VISUAL_ANTI_ALIASING_SHADER_FRAG.data());
+ mFactoryCache.SaveShader(VisualFactoryCache::BORDER_SHADER_ANTI_ALIASING, shader);
}
}
else
{
- shader = mFactoryCache.GetShader( VisualFactoryCache::BORDER_SHADER );
- if( !shader )
+ shader = mFactoryCache.GetShader(VisualFactoryCache::BORDER_SHADER);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_BORDER_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_BORDER_VISUAL_SHADER_FRAG.data() );
- mFactoryCache.SaveShader( VisualFactoryCache::BORDER_SHADER, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_BORDER_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_BORDER_VISUAL_SHADER_FRAG.data());
+ mFactoryCache.SaveShader(VisualFactoryCache::BORDER_SHADER, shader);
}
}
*/
Geometry BorderVisual::CreateBorderGeometry()
{
- const float halfWidth = 0.5f;
+ const float halfWidth = 0.5f;
const float halfHeight = 0.5f;
- struct BorderVertex { Vector2 position; Vector2 drift;};
- BorderVertex borderVertexData[16] =
+ struct BorderVertex
{
- { Vector2(-halfWidth, -halfHeight), Vector2(0.f, 0.f) },
- { Vector2(-halfWidth, -halfHeight), Vector2(1.f, 0.f) },
- { Vector2(halfWidth, -halfHeight), Vector2(-1.f, 0.f) },
- { Vector2(halfWidth, -halfHeight), Vector2(0.f, 0.f) },
-
- { Vector2(-halfWidth, -halfHeight), Vector2(0.f, 1.f) },
- { Vector2(-halfWidth, -halfHeight), Vector2(1.f, 1.f) },
- { Vector2(halfWidth, -halfHeight), Vector2(-1.f, 1.f) },
- { Vector2(halfWidth, -halfHeight), Vector2(0.f, 1.f) },
-
- { Vector2(-halfWidth, halfHeight), Vector2(0.f, -1.f) },
- { Vector2(-halfWidth, halfHeight), Vector2(1.f, -1.f) },
- { Vector2(halfWidth, halfHeight), Vector2(-1.f, -1.f) },
- { Vector2(halfWidth, halfHeight), Vector2(0.f, -1.f) },
-
- { Vector2(-halfWidth, halfHeight), Vector2(0.f, 0.f) },
- { Vector2(-halfWidth, halfHeight), Vector2(1.f, 0.f) },
- { Vector2(halfWidth, halfHeight), Vector2(-1.f, 0.f) },
- { Vector2(halfWidth, halfHeight), Vector2(0.f, 0.f) },
+ Vector2 position;
+ Vector2 drift;
};
+ BorderVertex borderVertexData[16] =
+ {
+ {Vector2(-halfWidth, -halfHeight), Vector2(0.f, 0.f)},
+ {Vector2(-halfWidth, -halfHeight), Vector2(1.f, 0.f)},
+ {Vector2(halfWidth, -halfHeight), Vector2(-1.f, 0.f)},
+ {Vector2(halfWidth, -halfHeight), Vector2(0.f, 0.f)},
+
+ {Vector2(-halfWidth, -halfHeight), Vector2(0.f, 1.f)},
+ {Vector2(-halfWidth, -halfHeight), Vector2(1.f, 1.f)},
+ {Vector2(halfWidth, -halfHeight), Vector2(-1.f, 1.f)},
+ {Vector2(halfWidth, -halfHeight), Vector2(0.f, 1.f)},
+
+ {Vector2(-halfWidth, halfHeight), Vector2(0.f, -1.f)},
+ {Vector2(-halfWidth, halfHeight), Vector2(1.f, -1.f)},
+ {Vector2(halfWidth, halfHeight), Vector2(-1.f, -1.f)},
+ {Vector2(halfWidth, halfHeight), Vector2(0.f, -1.f)},
+
+ {Vector2(-halfWidth, halfHeight), Vector2(0.f, 0.f)},
+ {Vector2(-halfWidth, halfHeight), Vector2(1.f, 0.f)},
+ {Vector2(halfWidth, halfHeight), Vector2(-1.f, 0.f)},
+ {Vector2(halfWidth, halfHeight), Vector2(0.f, 0.f)},
+ };
Property::Map borderVertexFormat;
borderVertexFormat[POSITION_ATTRIBUTE_NAME] = Property::VECTOR2;
- borderVertexFormat[DRIFT_ATTRIBUTE_NAME] = Property::VECTOR2;
- VertexBuffer borderVertices = VertexBuffer::New( borderVertexFormat );
- borderVertices.SetData( borderVertexData, 16 );
+ borderVertexFormat[DRIFT_ATTRIBUTE_NAME] = Property::VECTOR2;
+ VertexBuffer borderVertices = VertexBuffer::New(borderVertexFormat);
+ borderVertices.SetData(borderVertexData, 16);
// Create indices
- unsigned short indexData[24] = { 1,5,2,6,3,7,7,6,11,10,15,14,14,10,13,9,12,8,8,9,4,5,0,1};
+ unsigned short indexData[24] = {1, 5, 2, 6, 3, 7, 7, 6, 11, 10, 15, 14, 14, 10, 13, 9, 12, 8, 8, 9, 4, 5, 0, 1};
// Create the geometry object
Geometry geometry = Geometry::New();
- geometry.AddVertexBuffer( borderVertices );
- geometry.SetIndexBuffer( indexData, sizeof(indexData)/sizeof(indexData[0]) );
- geometry.SetType( Geometry::TRIANGLE_STRIP );
+ geometry.AddVertexBuffer(borderVertices);
+ geometry.SetIndexBuffer(indexData, sizeof(indexData) / sizeof(indexData[0]));
+ geometry.SetType(Geometry::TRIANGLE_STRIP);
return geometry;
}
#include "color-visual.h"
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
#include <dali/devel-api/rendering/renderer-devel.h>
+#include <dali/integration-api/debug.h>
//INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/devel-api/visuals/color-visual-properties-devel.h>
#include <dali-toolkit/devel-api/visuals/color-visual-actions-devel.h>
-#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/devel-api/visuals/color-visual-properties-devel.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-ColorVisualPtr ColorVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+ColorVisualPtr ColorVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
- ColorVisualPtr colorVisualPtr( new ColorVisual( factoryCache ) );
- colorVisualPtr->SetProperties( properties );
+ ColorVisualPtr colorVisualPtr(new ColorVisual(factoryCache));
+ colorVisualPtr->SetProperties(properties);
colorVisualPtr->Initialize();
return colorVisualPtr;
}
{
}
-void ColorVisual::DoSetProperties( const Property::Map& propertyMap )
+void ColorVisual::DoSetProperties(const Property::Map& propertyMap)
{
// By virtue of DoSetProperties being called last, this will override
// anything set by Toolkit::Visual::Property::MIX_COLOR
- Property::Value* colorValue = propertyMap.Find( Toolkit::ColorVisual::Property::MIX_COLOR, MIX_COLOR );
- if( colorValue )
+ Property::Value* colorValue = propertyMap.Find(Toolkit::ColorVisual::Property::MIX_COLOR, MIX_COLOR);
+ if(colorValue)
{
Vector4 color;
- if( colorValue->Get( color ) )
+ if(colorValue->Get(color))
{
Property::Type type = colorValue->GetType();
- if( type == Property::VECTOR4 )
+ if(type == Property::VECTOR4)
{
- SetMixColor( color );
+ SetMixColor(color);
}
- else if( type == Property::VECTOR3 )
+ else if(type == Property::VECTOR3)
{
Vector3 color3(color);
- SetMixColor( color3 );
+ SetMixColor(color3);
}
}
else
}
}
- Property::Value* renderIfTransparentValue = propertyMap.Find( Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, RENDER_IF_TRANSPARENT_NAME );
- if( renderIfTransparentValue )
+ Property::Value* renderIfTransparentValue = propertyMap.Find(Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, RENDER_IF_TRANSPARENT_NAME);
+ if(renderIfTransparentValue)
{
- if( ! renderIfTransparentValue->Get( mRenderIfTransparent ) )
+ if(!renderIfTransparentValue->Get(mRenderIfTransparent))
{
- DALI_LOG_ERROR( "ColorVisual: renderIfTransparent property has incorrect type: %d\n", renderIfTransparentValue->GetType() );
+ DALI_LOG_ERROR("ColorVisual: renderIfTransparent property has incorrect type: %d\n", renderIfTransparentValue->GetType());
}
}
- Property::Value* blurRadiusValue = propertyMap.Find( Toolkit::DevelColorVisual::Property::BLUR_RADIUS, BLUR_RADIUS_NAME );
- if( blurRadiusValue )
+ Property::Value* blurRadiusValue = propertyMap.Find(Toolkit::DevelColorVisual::Property::BLUR_RADIUS, BLUR_RADIUS_NAME);
+ if(blurRadiusValue)
{
- if( !blurRadiusValue->Get( mBlurRadius ) )
+ if(!blurRadiusValue->Get(mBlurRadius))
{
- DALI_LOG_ERROR( "ColorVisual:DoSetProperties:: BLUR_RADIUS property has incorrect type: %d\n", blurRadiusValue->GetType() );
+ DALI_LOG_ERROR("ColorVisual:DoSetProperties:: BLUR_RADIUS property has incorrect type: %d\n", blurRadiusValue->GetType());
}
}
}
-void ColorVisual::DoSetOnScene( Actor& actor )
+void ColorVisual::DoSetOnScene(Actor& actor)
{
// Only add the renderer if it's not fully transparent
// We cannot avoid creating a renderer as it's used in the base class
- if( mRenderIfTransparent || mImpl->mMixColor.a > 0.0f )
+ if(mRenderIfTransparent || mImpl->mMixColor.a > 0.0f)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
}
// Color Visual generated and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
void ColorVisual::DoSetOffScene(Actor& actor)
actor.RemoveRenderer(mImpl->mRenderer);
}
-void ColorVisual::DoCreatePropertyMap( Property::Map& map ) const
+void ColorVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR );
- map.Insert( Toolkit::ColorVisual::Property::MIX_COLOR, mImpl->mMixColor );
- map.Insert( Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, mRenderIfTransparent );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR);
+ map.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, mImpl->mMixColor);
+ map.Insert(Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, mRenderIfTransparent);
if(mImpl->mRenderer && mBlurRadiusIndex != Property::INVALID_INDEX)
{
}
}
-void ColorVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void ColorVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
void ColorVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
-void ColorVisual::OnDoAction( const Property::Index actionId, const Property::Value& attributes )
+void ColorVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes)
{
// Check if action is valid for this visual type and perform action if possible
- switch( actionId )
+ switch(actionId)
{
case DevelColorVisual::Action::UPDATE_PROPERTY:
{
const Property::Map* map = attributes.GetMap();
- if( map )
+ if(map)
{
- DoSetProperties( *map );
+ DoSetProperties(*map);
}
break;
}
void ColorVisual::OnInitialize()
{
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
Shader shader = GetShader();
Shader shader;
if(!EqualsZero(mBlurRadius) || mNeedBlurRadius)
{
- shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER_BLUR_EDGE );
- if( !shader )
+ shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER_BLUR_EDGE);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_FRAG.data() );
- mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER_BLUR_EDGE, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_FRAG.data());
+ mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER_BLUR_EDGE, shader);
}
}
- else if( !IsRoundedCornerRequired() )
+ else if(!IsRoundedCornerRequired())
{
- shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER );
- if( !shader )
+ shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_FRAG.data() );
- mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_FRAG.data());
+ mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER, shader);
}
}
else
{
- shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER );
- if( !shader )
+ shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data() );
- mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data());
+ mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER, shader);
}
}
#include "gradient-visual.h"
// EXTERNAL INCLUDES
-#include <typeinfo>
+#include <dali/devel-api/rendering/renderer-devel.h>
+#include <dali/devel-api/scripting/enum-helper.h>
+#include <dali/devel-api/scripting/scripting.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/common/dali-vector.h>
#include <dali/public-api/object/property-array.h>
-#include <dali/devel-api/scripting/enum-helper.h>
-#include <dali/devel-api/scripting/scripting.h>
-#include <dali/devel-api/rendering/renderer-devel.h>
+#include <typeinfo>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/gradient-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
-#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
-#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/gradient/linear-gradient.h>
-#include <dali-toolkit/internal/visuals/gradient/radial-gradient.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/graphics/generated/gradient-visual-bounding-box-rounded-corner-shader-vert.h>
#include <dali-toolkit/internal/graphics/generated/gradient-visual-bounding-box-shader-vert.h>
#include <dali-toolkit/internal/graphics/generated/gradient-visual-linear-rounded-corner-shader-frag.h>
#include <dali-toolkit/internal/graphics/generated/gradient-visual-radial-shader-frag.h>
#include <dali-toolkit/internal/graphics/generated/gradient-visual-user-space-rounded-corner-shader-vert.h>
#include <dali-toolkit/internal/graphics/generated/gradient-visual-user-space-shader-vert.h>
+#include <dali-toolkit/internal/visuals/gradient/linear-gradient.h>
+#include <dali-toolkit/internal/visuals/gradient/radial-gradient.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
+#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/internal/visuals/visual-string-constants.h>
+#include <dali-toolkit/public-api/visuals/gradient-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
+DALI_ENUM_TO_STRING_TABLE_BEGIN(UNITS)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::Units, OBJECT_BOUNDING_BOX)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::Units, USER_SPACE)
+DALI_ENUM_TO_STRING_TABLE_END(UNITS)
-DALI_ENUM_TO_STRING_TABLE_BEGIN( UNITS )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::Units, OBJECT_BOUNDING_BOX )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::Units, USER_SPACE )
-DALI_ENUM_TO_STRING_TABLE_END( UNITS )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( SPREAD_METHOD )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::SpreadMethod, PAD )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::SpreadMethod, REFLECT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::SpreadMethod, REPEAT )
-DALI_ENUM_TO_STRING_TABLE_END( SPREAD_METHOD )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(SPREAD_METHOD)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::SpreadMethod, PAD)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::SpreadMethod, REFLECT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::SpreadMethod, REPEAT)
+DALI_ENUM_TO_STRING_TABLE_END(SPREAD_METHOD)
// uniform names
-const char * const UNIFORM_ALIGNMENT_MATRIX_NAME( "uAlignmentMatrix" );
+const char* const UNIFORM_ALIGNMENT_MATRIX_NAME("uAlignmentMatrix");
// default offset value
const unsigned int DEFAULT_OFFSET_MINIMUM = 0.0f;
const unsigned int DEFAULT_OFFSET_MAXIMUM = 1.0f;
VisualFactoryCache::ShaderType SHADER_TYPE_TABLE[][4] =
-{
- {
- VisualFactoryCache::GRADIENT_SHADER_LINEAR_USER_SPACE,
- VisualFactoryCache::GRADIENT_SHADER_LINEAR_BOUNDING_BOX,
- VisualFactoryCache::GRADIENT_SHADER_LINEAR_USER_SPACE_ROUNDED_CORNER,
- VisualFactoryCache::GRADIENT_SHADER_LINEAR_BOUNDING_BOX_ROUNDED_CORNER
- },
{
- VisualFactoryCache::GRADIENT_SHADER_RADIAL_USER_SPACE,
- VisualFactoryCache::GRADIENT_SHADER_RADIAL_BOUNDING_BOX,
- VisualFactoryCache::GRADIENT_SHADER_RADIAL_USER_SPACE_ROUNDED_CORNER,
- VisualFactoryCache::GRADIENT_SHADER_RADIAL_BOUNDING_BOX_ROUNDED_CORNER
- }
-};
+ {VisualFactoryCache::GRADIENT_SHADER_LINEAR_USER_SPACE,
+ VisualFactoryCache::GRADIENT_SHADER_LINEAR_BOUNDING_BOX,
+ VisualFactoryCache::GRADIENT_SHADER_LINEAR_USER_SPACE_ROUNDED_CORNER,
+ VisualFactoryCache::GRADIENT_SHADER_LINEAR_BOUNDING_BOX_ROUNDED_CORNER},
+ {VisualFactoryCache::GRADIENT_SHADER_RADIAL_USER_SPACE,
+ VisualFactoryCache::GRADIENT_SHADER_RADIAL_BOUNDING_BOX,
+ VisualFactoryCache::GRADIENT_SHADER_RADIAL_USER_SPACE_ROUNDED_CORNER,
+ VisualFactoryCache::GRADIENT_SHADER_RADIAL_BOUNDING_BOX_ROUNDED_CORNER}};
const std::string_view VERTEX_SHADER[] =
-{
- // vertex shader for gradient units as OBJECT_BOUNDING_BOX
- SHADER_GRADIENT_VISUAL_BOUNDING_BOX_SHADER_VERT,
+ {
+ // vertex shader for gradient units as OBJECT_BOUNDING_BOX
+ SHADER_GRADIENT_VISUAL_BOUNDING_BOX_SHADER_VERT,
- // vertex shader for gradient units as USER_SPACE
- SHADER_GRADIENT_VISUAL_USER_SPACE_SHADER_VERT,
+ // vertex shader for gradient units as USER_SPACE
+ SHADER_GRADIENT_VISUAL_USER_SPACE_SHADER_VERT,
- // vertex shader for gradient units as OBJECT_BOUNDING_BOX with corner radius
- SHADER_GRADIENT_VISUAL_BOUNDING_BOX_ROUNDED_CORNER_SHADER_VERT,
+ // vertex shader for gradient units as OBJECT_BOUNDING_BOX with corner radius
+ SHADER_GRADIENT_VISUAL_BOUNDING_BOX_ROUNDED_CORNER_SHADER_VERT,
- // vertex shader for gradient units as USER_SPACE with corner radius
- SHADER_GRADIENT_VISUAL_USER_SPACE_ROUNDED_CORNER_SHADER_VERT
-};
+ // vertex shader for gradient units as USER_SPACE with corner radius
+ SHADER_GRADIENT_VISUAL_USER_SPACE_ROUNDED_CORNER_SHADER_VERT};
const std::string_view FRAGMENT_SHADER[] =
-{
- // fragment shader for linear gradient
- SHADER_GRADIENT_VISUAL_LINEAR_SHADER_FRAG,
+ {
+ // fragment shader for linear gradient
+ SHADER_GRADIENT_VISUAL_LINEAR_SHADER_FRAG,
- // fragment shader for radial gradient
- SHADER_GRADIENT_VISUAL_RADIAL_SHADER_FRAG,
+ // fragment shader for radial gradient
+ SHADER_GRADIENT_VISUAL_RADIAL_SHADER_FRAG,
- // fragment shader for linear gradient with corner radius
- SHADER_GRADIENT_VISUAL_LINEAR_ROUNDED_CORNER_SHADER_FRAG,
+ // fragment shader for linear gradient with corner radius
+ SHADER_GRADIENT_VISUAL_LINEAR_ROUNDED_CORNER_SHADER_FRAG,
- // fragment shader for radial gradient with corner radius
- SHADER_GRADIENT_VISUAL_RADIAL_ROUNDED_CORNER_SHADER_FRAG
-};
+ // fragment shader for radial gradient with corner radius
+ SHADER_GRADIENT_VISUAL_RADIAL_ROUNDED_CORNER_SHADER_FRAG};
-Dali::WrapMode::Type GetWrapMode( Toolkit::GradientVisual::SpreadMethod::Type spread )
+Dali::WrapMode::Type GetWrapMode(Toolkit::GradientVisual::SpreadMethod::Type spread)
{
switch(spread)
{
} // unnamed namespace
-GradientVisualPtr GradientVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+GradientVisualPtr GradientVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
- GradientVisualPtr gradientVisualPtr( new GradientVisual( factoryCache ) );
- gradientVisualPtr->SetProperties( properties );
+ GradientVisualPtr gradientVisualPtr(new GradientVisual(factoryCache));
+ gradientVisualPtr->SetProperties(properties);
gradientVisualPtr->Initialize();
return gradientVisualPtr;
}
-GradientVisual::GradientVisual( VisualFactoryCache& factoryCache )
-: Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::GRADIENT ),
- mGradientType( LINEAR ),
- mIsOpaque( true )
+GradientVisual::GradientVisual(VisualFactoryCache& factoryCache)
+: Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::GRADIENT),
+ mGradientType(LINEAR),
+ mIsOpaque(true)
{
mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
}
{
}
-void GradientVisual::DoSetProperties( const Property::Map& propertyMap )
+void GradientVisual::DoSetProperties(const Property::Map& propertyMap)
{
Toolkit::GradientVisual::Units::Type gradientUnits = Toolkit::GradientVisual::Units::OBJECT_BOUNDING_BOX;
- Property::Value* unitsValue = propertyMap.Find( Toolkit::GradientVisual::Property::UNITS, UNITS_NAME );
- if( unitsValue )
+ Property::Value* unitsValue = propertyMap.Find(Toolkit::GradientVisual::Property::UNITS, UNITS_NAME);
+ if(unitsValue)
{
- Scripting::GetEnumerationProperty( *unitsValue, UNITS_TABLE, UNITS_TABLE_COUNT, gradientUnits );
+ Scripting::GetEnumerationProperty(*unitsValue, UNITS_TABLE, UNITS_TABLE_COUNT, gradientUnits);
}
mGradientType = LINEAR;
- if( propertyMap.Find( Toolkit::GradientVisual::Property::RADIUS, RADIUS_NAME ) )
+ if(propertyMap.Find(Toolkit::GradientVisual::Property::RADIUS, RADIUS_NAME))
{
mGradientType = RADIAL;
}
- if( NewGradient( mGradientType, propertyMap ) )
+ if(NewGradient(mGradientType, propertyMap))
{
- mGradient->SetGradientUnits( gradientUnits );
+ mGradient->SetGradientUnits(gradientUnits);
mGradientTransform = mGradient->GetAlignmentTransform();
}
else
{
- DALI_LOG_ERROR( "Fail to provide valid properties to create a GradientVisual object\n" );
+ DALI_LOG_ERROR("Fail to provide valid properties to create a GradientVisual object\n");
}
}
void GradientVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
-void GradientVisual::DoSetOnScene( Actor& actor )
+void GradientVisual::DoSetOnScene(Actor& actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
// Gradient Visual generated and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
void GradientVisual::UpdateShader()
}
}
-void GradientVisual::DoCreatePropertyMap( Property::Map& map ) const
+void GradientVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::GRADIENT );
- map.Insert( Toolkit::GradientVisual::Property::UNITS, mGradient->GetGradientUnits() );
- map.Insert( Toolkit::GradientVisual::Property::SPREAD_METHOD, mGradient->GetSpreadMethod() );
-
- const Vector<Gradient::GradientStop>& stops( mGradient->GetStops() );
- Property::Array offsets;
- Property::Array colors;
- for( unsigned int i=0; i<stops.Count(); i++ )
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::GRADIENT);
+ map.Insert(Toolkit::GradientVisual::Property::UNITS, mGradient->GetGradientUnits());
+ map.Insert(Toolkit::GradientVisual::Property::SPREAD_METHOD, mGradient->GetSpreadMethod());
+
+ const Vector<Gradient::GradientStop>& stops(mGradient->GetStops());
+ Property::Array offsets;
+ Property::Array colors;
+ for(unsigned int i = 0; i < stops.Count(); i++)
{
- offsets.PushBack( stops[i].mOffset );
- if( EqualsZero(stops[i].mStopColor.a) )
+ offsets.PushBack(stops[i].mOffset);
+ if(EqualsZero(stops[i].mStopColor.a))
{
- colors.PushBack( Vector4::ZERO );
+ colors.PushBack(Vector4::ZERO);
}
else
{
- colors.PushBack( Vector4( stops[i].mStopColor.r / stops[i].mStopColor.a,
- stops[i].mStopColor.g / stops[i].mStopColor.a,
- stops[i].mStopColor.b / stops[i].mStopColor.a,
- stops[i].mStopColor.a));
+ colors.PushBack(Vector4(stops[i].mStopColor.r / stops[i].mStopColor.a,
+ stops[i].mStopColor.g / stops[i].mStopColor.a,
+ stops[i].mStopColor.b / stops[i].mStopColor.a,
+ stops[i].mStopColor.a));
}
}
- map.Insert( Toolkit::GradientVisual::Property::STOP_OFFSET, offsets );
- map.Insert( Toolkit::GradientVisual::Property::STOP_COLOR, colors );
+ map.Insert(Toolkit::GradientVisual::Property::STOP_OFFSET, offsets);
+ map.Insert(Toolkit::GradientVisual::Property::STOP_COLOR, colors);
- if( &typeid( *mGradient ) == &typeid(LinearGradient) )
+ if(&typeid(*mGradient) == &typeid(LinearGradient))
{
- LinearGradient* gradient = static_cast<LinearGradient*>( mGradient.Get() );
- map.Insert( Toolkit::GradientVisual::Property::START_POSITION, gradient->GetStartPosition() );
- map.Insert( Toolkit::GradientVisual::Property::END_POSITION, gradient->GetEndPosition() );
+ LinearGradient* gradient = static_cast<LinearGradient*>(mGradient.Get());
+ map.Insert(Toolkit::GradientVisual::Property::START_POSITION, gradient->GetStartPosition());
+ map.Insert(Toolkit::GradientVisual::Property::END_POSITION, gradient->GetEndPosition());
}
else // if( &typeid( *mGradient ) == &typeid(RadialGradient) )
{
- RadialGradient* gradient = static_cast<RadialGradient*>( mGradient.Get() );
- map.Insert( Toolkit::GradientVisual::Property::CENTER, gradient->GetCenter() );
- map.Insert( Toolkit::GradientVisual::Property::RADIUS, gradient->GetRadius() );
+ RadialGradient* gradient = static_cast<RadialGradient*>(mGradient.Get());
+ map.Insert(Toolkit::GradientVisual::Property::CENTER, gradient->GetCenter());
+ map.Insert(Toolkit::GradientVisual::Property::RADIUS, gradient->GetRadius());
}
}
-void GradientVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void GradientVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
void GradientVisual::OnInitialize()
{
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
Shader shader = GetShader();
//Set up the texture set
- TextureSet textureSet = TextureSet::New();
+ TextureSet textureSet = TextureSet::New();
Dali::Texture lookupTexture = mGradient->GenerateLookupTexture();
- textureSet.SetTexture( 0u, lookupTexture );
- Dali::WrapMode::Type wrap = GetWrapMode( mGradient->GetSpreadMethod() );
- Sampler sampler = Sampler::New();
- sampler.SetWrapMode( wrap, wrap );
- textureSet.SetSampler( 0u, sampler );
+ textureSet.SetTexture(0u, lookupTexture);
+ Dali::WrapMode::Type wrap = GetWrapMode(mGradient->GetSpreadMethod());
+ Sampler sampler = Sampler::New();
+ sampler.SetWrapMode(wrap, wrap);
+ textureSet.SetSampler(0u, sampler);
- mImpl->mRenderer = Renderer::New( geometry, shader );
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer = Renderer::New(geometry, shader);
+ mImpl->mRenderer.SetTextures(textureSet);
// If opaque and then no need to have blending
- if( mIsOpaque )
+ if(mIsOpaque)
{
- mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::OFF );
+ mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::OFF);
}
- mImpl->mRenderer.RegisterProperty( UNIFORM_ALIGNMENT_MATRIX_NAME, mGradientTransform );
+ mImpl->mRenderer.RegisterProperty(UNIFORM_ALIGNMENT_MATRIX_NAME, mGradientTransform);
//Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
bool GradientVisual::NewGradient(Type gradientType, const Property::Map& propertyMap)
{
- if( gradientType == LINEAR )
+ if(gradientType == LINEAR)
{
- Property::Value* startPositionValue = propertyMap.Find( Toolkit::GradientVisual::Property::START_POSITION, START_POSITION_NAME );
- Property::Value* endPositionValue = propertyMap.Find( Toolkit::GradientVisual::Property::END_POSITION, END_POSITION_NAME );
- Vector2 startPosition;
- Vector2 endPosition;
+ Property::Value* startPositionValue = propertyMap.Find(Toolkit::GradientVisual::Property::START_POSITION, START_POSITION_NAME);
+ Property::Value* endPositionValue = propertyMap.Find(Toolkit::GradientVisual::Property::END_POSITION, END_POSITION_NAME);
+ Vector2 startPosition;
+ Vector2 endPosition;
- if( startPositionValue && startPositionValue->Get(startPosition)
- && endPositionValue && endPositionValue->Get( endPosition ) )
+ if(startPositionValue && startPositionValue->Get(startPosition) && endPositionValue && endPositionValue->Get(endPosition))
{
- mGradient = new LinearGradient( startPosition, endPosition );
+ mGradient = new LinearGradient(startPosition, endPosition);
}
else
{
}
else // type==RADIAL
{
- Property::Value* centerValue = propertyMap.Find( Toolkit::GradientVisual::Property::CENTER, CENTER_NAME );
- Property::Value* radiusValue = propertyMap.Find( Toolkit::GradientVisual::Property::RADIUS, RADIUS_NAME );
- Vector2 center;
- float radius;
- if( centerValue && centerValue->Get(center)
- && radiusValue && radiusValue->Get(radius) )
+ Property::Value* centerValue = propertyMap.Find(Toolkit::GradientVisual::Property::CENTER, CENTER_NAME);
+ Property::Value* radiusValue = propertyMap.Find(Toolkit::GradientVisual::Property::RADIUS, RADIUS_NAME);
+ Vector2 center;
+ float radius;
+ if(centerValue && centerValue->Get(center) && radiusValue && radiusValue->Get(radius))
{
- mGradient = new RadialGradient( center, radius );
+ mGradient = new RadialGradient(center, radius);
}
else
{
}
}
- unsigned int numValidStop = 0u;
- Property::Value* stopOffsetValue = propertyMap.Find( Toolkit::GradientVisual::Property::STOP_OFFSET, STOP_OFFSET_NAME );
- Property::Value* stopColorValue = propertyMap.Find( Toolkit::GradientVisual::Property::STOP_COLOR, STOP_COLOR_NAME );
- if( stopColorValue )
+ unsigned int numValidStop = 0u;
+ Property::Value* stopOffsetValue = propertyMap.Find(Toolkit::GradientVisual::Property::STOP_OFFSET, STOP_OFFSET_NAME);
+ Property::Value* stopColorValue = propertyMap.Find(Toolkit::GradientVisual::Property::STOP_COLOR, STOP_COLOR_NAME);
+ if(stopColorValue)
{
- Vector<float> offsetArray;
+ Vector<float> offsetArray;
Property::Array* colorArray = stopColorValue->GetArray();
- if( colorArray )
+ if(colorArray)
{
- GetStopOffsets( stopOffsetValue, offsetArray );
- unsigned int numStop = offsetArray.Count() < colorArray->Count() ?
- offsetArray.Count() : colorArray->Count();
- Vector4 color;
- for( unsigned int i=0; i<numStop; i++ )
+ GetStopOffsets(stopOffsetValue, offsetArray);
+ unsigned int numStop = offsetArray.Count() < colorArray->Count() ? offsetArray.Count() : colorArray->Count();
+ Vector4 color;
+ for(unsigned int i = 0; i < numStop; i++)
{
- if( (colorArray->GetElementAt(i)).Get(color) )
+ if((colorArray->GetElementAt(i)).Get(color))
{
- mGradient->AddStop( offsetArray[i], Vector4(color.r*color.a, color.g*color.a, color.b*color.a, color.a));
+ mGradient->AddStop(offsetArray[i], Vector4(color.r * color.a, color.g * color.a, color.b * color.a, color.a));
numValidStop++;
- if( ! Equals( color.a, 1.0f, Math::MACHINE_EPSILON_1 ) )
+ if(!Equals(color.a, 1.0f, Math::MACHINE_EPSILON_1))
{
mIsOpaque = false;
}
}
}
- if( numValidStop < 1u ) // no valid stop
+ if(numValidStop < 1u) // no valid stop
{
return false;
}
- Property::Value* spread = propertyMap.Find( Toolkit::GradientVisual::Property::SPREAD_METHOD, SPREAD_METHOD_NAME );
+ Property::Value* spread = propertyMap.Find(Toolkit::GradientVisual::Property::SPREAD_METHOD, SPREAD_METHOD_NAME);
// The default spread method is PAD. Only need to set new spread if it's anything else.
- if( spread )
+ if(spread)
{
Toolkit::GradientVisual::SpreadMethod::Type spreadMethod = Toolkit::GradientVisual::SpreadMethod::PAD;
- if( Scripting::GetEnumerationProperty( *spread, SPREAD_METHOD_TABLE, SPREAD_METHOD_TABLE_COUNT, spreadMethod ) )
+ if(Scripting::GetEnumerationProperty(*spread, SPREAD_METHOD_TABLE, SPREAD_METHOD_TABLE_COUNT, spreadMethod))
{
- mGradient->SetSpreadMethod( spreadMethod );
+ mGradient->SetSpreadMethod(spreadMethod);
}
}
void GradientVisual::GetStopOffsets(const Property::Value* value, Vector<float>& stopOffsets)
{
-
- if ( value ) // Only check valve type if a valid Property has been passed in
+ if(value) // Only check valve type if a valid Property has been passed in
{
- switch ( value->GetType() )
+ switch(value->GetType())
{
case Property::VECTOR2:
{
Vector2 offset2;
- value->Get( offset2 );
- stopOffsets.PushBack( offset2.x );
- stopOffsets.PushBack( offset2.y );
+ value->Get(offset2);
+ stopOffsets.PushBack(offset2.x);
+ stopOffsets.PushBack(offset2.y);
break;
}
case Property::VECTOR3:
{
Vector3 offset3;
- value->Get( offset3 );
- stopOffsets.PushBack( offset3.x );
- stopOffsets.PushBack( offset3.y );
- stopOffsets.PushBack( offset3.z );
+ value->Get(offset3);
+ stopOffsets.PushBack(offset3.x);
+ stopOffsets.PushBack(offset3.y);
+ stopOffsets.PushBack(offset3.z);
break;
}
case Property::VECTOR4:
{
Vector4 offset4;
- value->Get( offset4 );
- stopOffsets.PushBack( offset4.x );
- stopOffsets.PushBack( offset4.y );
- stopOffsets.PushBack( offset4.z );
- stopOffsets.PushBack( offset4.w );
+ value->Get(offset4);
+ stopOffsets.PushBack(offset4.x);
+ stopOffsets.PushBack(offset4.y);
+ stopOffsets.PushBack(offset4.z);
+ stopOffsets.PushBack(offset4.w);
break;
}
case Property::ARRAY:
{
const Property::Array* offsetArray = value->GetArray();
- if( offsetArray )
+ if(offsetArray)
{
unsigned int numStop = offsetArray->Count();
- float offset;
- for( unsigned int i=0; i<numStop; i++ )
+ float offset;
+ for(unsigned int i = 0; i < numStop; i++)
{
- if( offsetArray->GetElementAt(i).Get(offset) )
+ if(offsetArray->GetElementAt(i).Get(offset))
{
- stopOffsets.PushBack( offset );
+ stopOffsets.PushBack(offset);
}
}
}
}
}
- if ( stopOffsets.Empty() )
+ if(stopOffsets.Empty())
{
// Set default offset if none set by Property system, need a minimum and maximum
- stopOffsets.PushBack( DEFAULT_OFFSET_MINIMUM );
- stopOffsets.PushBack( DEFAULT_OFFSET_MAXIMUM );
+ stopOffsets.PushBack(DEFAULT_OFFSET_MINIMUM);
+ stopOffsets.PushBack(DEFAULT_OFFSET_MAXIMUM);
}
}
/*
- * Copyright (c) 2016 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "gradient.h"
-#include <algorithm> // std::sort
#include <dali/public-api/math/vector4.h>
+#include <algorithm> // std::sort
namespace
{
// The maximum width of the lookup texture ( it is a 1-dimension texture with the height as 1 )
const unsigned int MAXIMUM_TEXTURE_RESOLUTION(128u);
-}
+} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
Gradient::Gradient()
-: mGradientUnits( Toolkit::GradientVisual::Units::OBJECT_BOUNDING_BOX ),
- mSpreadMethod( Toolkit::GradientVisual::SpreadMethod::PAD )
-{}
+: mGradientUnits(Toolkit::GradientVisual::Units::OBJECT_BOUNDING_BOX),
+ mSpreadMethod(Toolkit::GradientVisual::SpreadMethod::PAD)
+{
+}
Gradient::~Gradient()
-{}
+{
+}
-void Gradient::AddStop( float offset, const Vector4& color )
+void Gradient::AddStop(float offset, const Vector4& color)
{
// the offset is clamped to the range [0.0, 1.0]
- mGradientStops.PushBack( GradientStop( Clamp( offset, 0.f, 1.f ), color) );
+ mGradientStops.PushBack(GradientStop(Clamp(offset, 0.f, 1.f), color));
}
const Vector<Gradient::GradientStop>& Gradient::GetStops()
return mGradientStops;
}
-void Gradient::SetGradientUnits( Toolkit::GradientVisual::Units::Type gradientUnits )
+void Gradient::SetGradientUnits(Toolkit::GradientVisual::Units::Type gradientUnits)
{
mGradientUnits = gradientUnits;
}
return mGradientUnits;
}
-void Gradient::SetSpreadMethod( Toolkit::GradientVisual::SpreadMethod::Type spread )
+void Gradient::SetSpreadMethod(Toolkit::GradientVisual::SpreadMethod::Type spread)
{
mSpreadMethod = spread;
}
*/
Dali::Texture Gradient::GenerateLookupTexture()
{
- std::sort( mGradientStops.Begin(), mGradientStops.End() );
+ std::sort(mGradientStops.Begin(), mGradientStops.End());
unsigned int numStops = mGradientStops.Count();
* for REPEAT, mix the two color of the first and last stop to fill the remainder
*/
bool tempFirstStop = false;
- if( mGradientStops[0].mOffset > 0.f )
+ if(mGradientStops[0].mOffset > 0.f)
{
tempFirstStop = true;
- Vector4 firstStopColor( mGradientStops[0].mStopColor ); // If spread method is PAD or REFLECT
- if( mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT )
+ Vector4 firstStopColor(mGradientStops[0].mStopColor); // If spread method is PAD or REFLECT
+ if(mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT)
{
- firstStopColor = ( mGradientStops[0].mStopColor * (1.f-mGradientStops[numStops-1].mOffset)
- + mGradientStops[numStops-1].mStopColor * mGradientStops[0].mOffset )
- / ( mGradientStops[0].mOffset+1.f-mGradientStops[numStops-1].mOffset);
+ firstStopColor = (mGradientStops[0].mStopColor * (1.f - mGradientStops[numStops - 1].mOffset) + mGradientStops[numStops - 1].mStopColor * mGradientStops[0].mOffset) / (mGradientStops[0].mOffset + 1.f - mGradientStops[numStops - 1].mOffset);
}
- mGradientStops.Insert( mGradientStops.Begin(), GradientStop(0.f, firstStopColor) );
+ mGradientStops.Insert(mGradientStops.Begin(), GradientStop(0.f, firstStopColor));
numStops++;
}
bool tempLastStop = false;
- if( mGradientStops[numStops-1].mOffset < 1.f )
+ if(mGradientStops[numStops - 1].mOffset < 1.f)
{
tempLastStop = true;
- Vector4 lastStopColor( mGradientStops[numStops-1].mStopColor ); // If spread method is PAD or REFLECT
- if( mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT )
+ Vector4 lastStopColor(mGradientStops[numStops - 1].mStopColor); // If spread method is PAD or REFLECT
+ if(mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT)
{
lastStopColor = mGradientStops[0].mStopColor;
}
- mGradientStops.PushBack( GradientStop(1.f, lastStopColor) );
+ mGradientStops.PushBack(GradientStop(1.f, lastStopColor));
numStops++;
}
*/
unsigned int resolution = EstimateTextureResolution();
- unsigned int bufferSize = resolution * 4u;
- unsigned char* pixels = new unsigned char[ bufferSize ];
- PixelData pixelData = PixelData::New( pixels, bufferSize, resolution, 1u, Pixel::RGBA8888, PixelData::DELETE_ARRAY );
+ unsigned int bufferSize = resolution * 4u;
+ unsigned char* pixels = new unsigned char[bufferSize];
+ PixelData pixelData = PixelData::New(pixels, bufferSize, resolution, 1u, Pixel::RGBA8888, PixelData::DELETE_ARRAY);
- int segmentStart = 0;
- int segmentEnd = 0;
- int k = 0;
- float length = static_cast<float>(resolution);
- for( unsigned int i=0; i<numStops-1u; i++ )
+ int segmentStart = 0;
+ int segmentEnd = 0;
+ int k = 0;
+ float length = static_cast<float>(resolution);
+ for(unsigned int i = 0; i < numStops - 1u; i++)
{
- segmentEnd = floorf(mGradientStops[i+1].mOffset * length + 0.5f);
- if( segmentEnd == segmentStart )
+ segmentEnd = floorf(mGradientStops[i + 1].mOffset * length + 0.5f);
+ if(segmentEnd == segmentStart)
{
continue;
}
- float segmentWidth = static_cast<float>(segmentEnd-segmentStart);
+ float segmentWidth = static_cast<float>(segmentEnd - segmentStart);
- for( int j = segmentStart; j<segmentEnd; j++ )
+ for(int j = segmentStart; j < segmentEnd; j++)
{
- float ratio = static_cast<float>(j-segmentStart)/(segmentWidth - 1);
- Vector4 currentColor = mGradientStops[i].mStopColor * (1.f-ratio) + mGradientStops[i+1].mStopColor * ratio;
- pixels[k*4] = static_cast<unsigned char>( 255.f * Clamp( currentColor.r, 0.f, 1.f ) );
- pixels[k*4+1] = static_cast<unsigned char>( 255.f * Clamp( currentColor.g, 0.f, 1.f ) );
- pixels[k*4+2] = static_cast<unsigned char>( 255.f * Clamp( currentColor.b, 0.f, 1.f ) );
- pixels[k*4+3] = static_cast<unsigned char>( 255.f * Clamp( currentColor.a, 0.f, 1.f ) );
+ float ratio = static_cast<float>(j - segmentStart) / (segmentWidth - 1);
+ Vector4 currentColor = mGradientStops[i].mStopColor * (1.f - ratio) + mGradientStops[i + 1].mStopColor * ratio;
+ pixels[k * 4] = static_cast<unsigned char>(255.f * Clamp(currentColor.r, 0.f, 1.f));
+ pixels[k * 4 + 1] = static_cast<unsigned char>(255.f * Clamp(currentColor.g, 0.f, 1.f));
+ pixels[k * 4 + 2] = static_cast<unsigned char>(255.f * Clamp(currentColor.b, 0.f, 1.f));
+ pixels[k * 4 + 3] = static_cast<unsigned char>(255.f * Clamp(currentColor.a, 0.f, 1.f));
k++;
}
segmentStart = segmentEnd;
}
- Texture texture = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, resolution, 1u );
- texture.Upload( pixelData );
+ Texture texture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, resolution, 1u);
+ texture.Upload(pixelData);
// remove the stops added temporarily for generating the pixels, as the spread method might get changed later
- if( tempLastStop )
+ if(tempLastStop)
{
- mGradientStops.Erase( mGradientStops.Begin()+numStops-1 );
+ mGradientStops.Erase(mGradientStops.Begin() + numStops - 1);
}
- if( tempFirstStop )
+ if(tempFirstStop)
{
- mGradientStops.Erase( mGradientStops.Begin());
+ mGradientStops.Erase(mGradientStops.Begin());
}
return texture;
unsigned int Gradient::EstimateTextureResolution()
{
float minInterval = 1.0;
- for( unsigned int i=0, numStops = mGradientStops.Count(); i<numStops-1u; i++ )
+ for(unsigned int i = 0, numStops = mGradientStops.Count(); i < numStops - 1u; i++)
{
- float interval = mGradientStops[i+1].mOffset - mGradientStops[i].mOffset;
- minInterval = interval > minInterval ? minInterval:interval;
+ float interval = mGradientStops[i + 1].mOffset - mGradientStops[i].mOffset;
+ minInterval = interval > minInterval ? minInterval : interval;
}
// Use at least three pixels for each segment between two stops
- unsigned int resolution = static_cast<int>(3.f/(minInterval+Math::MACHINE_EPSILON_100)+0.5f);
+ unsigned int resolution = static_cast<int>(3.f / (minInterval + Math::MACHINE_EPSILON_100) + 0.5f);
// Clamp the resolution to handle the overlapping stops
- if( resolution > MAXIMUM_TEXTURE_RESOLUTION )
+ if(resolution > MAXIMUM_TEXTURE_RESOLUTION)
{
return MAXIMUM_TEXTURE_RESOLUTION;
}
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-LinearGradient::LinearGradient( const Vector2& startPosition, const Vector2& endPosition )
+LinearGradient::LinearGradient(const Vector2& startPosition, const Vector2& endPosition)
: Gradient()
{
- SetStartAndEndPosition( startPosition, endPosition );
+ SetStartAndEndPosition(startPosition, endPosition);
}
LinearGradient::~LinearGradient()
-{}
+{
+}
-void LinearGradient::SetStartAndEndPosition( const Vector2& startPosition, const Vector2& endPosition )
+void LinearGradient::SetStartAndEndPosition(const Vector2& startPosition, const Vector2& endPosition)
{
mStartPosition = startPosition;
- mEndPosition = endPosition;
+ mEndPosition = endPosition;
// Calculate the transform aligning to the gradient line
- float dx = mEndPosition.x - mStartPosition.x;
- float dy = mEndPosition.y - mStartPosition.y;
- Matrix3 alignMatrix( dy, -dx, 0.f, dx, dy, 0.f, mStartPosition.x, mStartPosition.y, 1.f );
+ float dx = mEndPosition.x - mStartPosition.x;
+ float dy = mEndPosition.y - mStartPosition.y;
+ Matrix3 alignMatrix(dy, -dx, 0.f, dx, dy, 0.f, mStartPosition.x, mStartPosition.y, 1.f);
alignMatrix.Invert();
mAlignmentTransform = alignMatrix;
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-RadialGradient::RadialGradient( const Vector2& center, float radius )
+RadialGradient::RadialGradient(const Vector2& center, float radius)
: Gradient()
{
- SetCenterAndRadius( center, radius );
+ SetCenterAndRadius(center, radius);
}
RadialGradient::~RadialGradient()
-{}
+{
+}
-void RadialGradient::SetCenterAndRadius( const Vector2& center, float radius )
+void RadialGradient::SetCenterAndRadius(const Vector2& center, float radius)
{
mCenter = center;
mRadius = radius;
// Calculate the transform aligning to the circle
- Matrix3 alignMatrix( mRadius, 0.f, 0.f, 0.f, mRadius, 0.f, mCenter.x, mCenter.y, 1.f );
+ Matrix3 alignMatrix(mRadius, 0.f, 0.f, 0.f, mRadius, 0.f, mCenter.x, mCenter.y, 1.f);
alignMatrix.Invert();
mAlignmentTransform = alignMatrix;
- /*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); // this size can fit 8 by 8 images of average size 128*128
-const uint32_t MAX_ITEM_SIZE( 512u );
-const uint32_t MAX_ITEM_AREA( MAX_ITEM_SIZE*MAX_ITEM_SIZE );
-}
+const uint32_t DEFAULT_ATLAS_SIZE(1024u); // this size can fit 8 by 8 images of average size 128*128
+const uint32_t MAX_ITEM_SIZE(512u);
+const uint32_t MAX_ITEM_AREA(MAX_ITEM_SIZE* MAX_ITEM_SIZE);
+} // namespace
ImageAtlasManager::ImageAtlasManager()
-: mBrokenImageUrl( "" )
+: mBrokenImageUrl("")
{
}
{
}
-TextureSet ImageAtlasManager::Add( Vector4& textureRect,
- const std::string& url,
- ImageDimensions& size,
- FittingMode::Type fittingMode,
- bool orientationCorrection,
- AtlasUploadObserver* atlasUploadObserver )
+TextureSet ImageAtlasManager::Add(Vector4& textureRect,
+ const std::string& url,
+ ImageDimensions& size,
+ FittingMode::Type fittingMode,
+ bool orientationCorrection,
+ AtlasUploadObserver* atlasUploadObserver)
{
ImageDimensions dimensions = size;
ImageDimensions zero;
- if( size == zero )
+ if(size == zero)
{
- dimensions = Dali::GetClosestImageSize( url );
+ dimensions = Dali::GetClosestImageSize(url);
}
// big image, atlasing is not applied
- if( static_cast<uint32_t>(dimensions.GetWidth()) * static_cast<uint32_t>(dimensions.GetHeight()) > MAX_ITEM_AREA
- || dimensions.GetWidth()>DEFAULT_ATLAS_SIZE
- || dimensions.GetHeight()>DEFAULT_ATLAS_SIZE)
+ if(static_cast<uint32_t>(dimensions.GetWidth()) * static_cast<uint32_t>(dimensions.GetHeight()) > MAX_ITEM_AREA || dimensions.GetWidth() > DEFAULT_ATLAS_SIZE || dimensions.GetHeight() > DEFAULT_ATLAS_SIZE)
{
return TextureSet();
}
size = dimensions;
unsigned int i = 0;
- for( AtlasContainer::iterator iter = mAtlasList.begin(); iter != mAtlasList.end(); ++iter)
+ for(AtlasContainer::iterator iter = mAtlasList.begin(); iter != mAtlasList.end(); ++iter)
{
- if( (*iter).Upload( textureRect, url, size, fittingMode, orientationCorrection, atlasUploadObserver ) )
+ if((*iter).Upload(textureRect, url, size, fittingMode, orientationCorrection, atlasUploadObserver))
{
return mTextureSetList[i];
}
}
CreateNewAtlas();
- mAtlasList.back().Upload( textureRect, url, size, fittingMode, orientationCorrection, atlasUploadObserver );
+ mAtlasList.back().Upload(textureRect, url, size, fittingMode, orientationCorrection, atlasUploadObserver);
return mTextureSetList.back();
}
-TextureSet ImageAtlasManager::Add( Vector4& textureRect,
- PixelData pixelData )
+TextureSet ImageAtlasManager::Add(Vector4& textureRect,
+ PixelData pixelData)
{
-
// big buffer, atlasing is not applied
- if( static_cast<uint32_t>(pixelData.GetWidth()) * static_cast<uint32_t>(pixelData.GetHeight()) > MAX_ITEM_AREA
- || pixelData.GetWidth()>DEFAULT_ATLAS_SIZE
- || pixelData.GetHeight()>DEFAULT_ATLAS_SIZE )
+ if(static_cast<uint32_t>(pixelData.GetWidth()) * static_cast<uint32_t>(pixelData.GetHeight()) > MAX_ITEM_AREA || pixelData.GetWidth() > DEFAULT_ATLAS_SIZE || pixelData.GetHeight() > DEFAULT_ATLAS_SIZE)
{
return TextureSet();
}
unsigned int i = 0;
- for( AtlasContainer::iterator iter = mAtlasList.begin(); iter != mAtlasList.end(); ++iter)
+ for(AtlasContainer::iterator iter = mAtlasList.begin(); iter != mAtlasList.end(); ++iter)
{
- if( (*iter).Upload( textureRect, pixelData ) )
+ if((*iter).Upload(textureRect, pixelData))
{
return mTextureSetList[i];
}
}
CreateNewAtlas();
- mAtlasList.back().Upload( textureRect, pixelData );
+ mAtlasList.back().Upload(textureRect, pixelData);
return mTextureSetList.back();
-
}
-void ImageAtlasManager::Remove( TextureSet textureSet, const Vector4& textureRect )
+void ImageAtlasManager::Remove(TextureSet textureSet, const Vector4& textureRect)
{
unsigned int i = 0;
- for( TextureSetContainer::iterator iter = mTextureSetList.begin(); iter != mTextureSetList.end(); ++iter)
+ for(TextureSetContainer::iterator iter = mTextureSetList.begin(); iter != mTextureSetList.end(); ++iter)
{
- if( (*iter) == textureSet )
+ if((*iter) == textureSet)
{
mAtlasList[i].Remove(textureRect);
return;
}
}
-void ImageAtlasManager::SetBrokenImage( const std::string& brokenImageUrl )
+void ImageAtlasManager::SetBrokenImage(const std::string& brokenImageUrl)
{
- if( !brokenImageUrl.empty() )
+ if(!brokenImageUrl.empty())
{
mBrokenImageUrl = brokenImageUrl;
}
void ImageAtlasManager::CreateNewAtlas()
{
- Toolkit::ImageAtlas newAtlas = Toolkit::ImageAtlas::New( DEFAULT_ATLAS_SIZE, DEFAULT_ATLAS_SIZE );
- if( !mBrokenImageUrl.empty() )
+ Toolkit::ImageAtlas newAtlas = Toolkit::ImageAtlas::New(DEFAULT_ATLAS_SIZE, DEFAULT_ATLAS_SIZE);
+ if(!mBrokenImageUrl.empty())
{
- newAtlas.SetBrokenImage( mBrokenImageUrl );
+ newAtlas.SetBrokenImage(mBrokenImageUrl);
}
- mAtlasList.push_back( newAtlas );
+ mAtlasList.push_back(newAtlas);
TextureSet textureSet = TextureSet::New();
- textureSet.SetTexture( 0u, newAtlas.GetAtlas() );
- mTextureSetList.push_back( textureSet );
+ textureSet.SetTexture(0u, newAtlas.GetAtlas());
+ mTextureSetList.push_back(textureSet);
}
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/visuals/visual-string-constants.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-string-constants.h>
#include <dali/integration-api/debug.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
// global string variable to caching complate vertex shader
{
}
-Shader ImageVisualShaderFactory::GetShader( VisualFactoryCache& factoryCache, bool atlasing, bool defaultTextureWrapping, bool roundedCorner )
+Shader ImageVisualShaderFactory::GetShader(VisualFactoryCache& factoryCache, bool atlasing, bool defaultTextureWrapping, bool roundedCorner)
{
Shader shader;
- if( atlasing )
+ if(atlasing)
{
- if( defaultTextureWrapping )
+ if(defaultTextureWrapping)
{
- shader = factoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(),
- Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ATLAS_CLAMP_SHADER_FRAG.data() );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(),
+ Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ATLAS_CLAMP_SHADER_FRAG.data());
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP, shader);
}
}
else
{
- shader = factoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_CUSTOM_WRAP );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::IMAGE_SHADER_ATLAS_CUSTOM_WRAP);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(),
- Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ATLAS_VARIOUS_WRAP_SHADER_FRAG.data() );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_CUSTOM_WRAP, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(),
+ Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ATLAS_VARIOUS_WRAP_SHADER_FRAG.data());
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::IMAGE_SHADER_ATLAS_CUSTOM_WRAP, shader);
}
}
}
else
{
- if( roundedCorner )
+ if(roundedCorner)
{
- shader = factoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER_ROUNDED_CORNER );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::IMAGE_SHADER_ROUNDED_CORNER);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(),
- Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data() );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ROUNDED_CORNER, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(),
+ Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data());
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::IMAGE_SHADER_ROUNDED_CORNER, shader);
}
}
else
{
- shader = factoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::IMAGE_SHADER);
+ if(!shader)
{
- shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(),
- Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_NO_ATLAS_SHADER_FRAG.data() );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER, shader );
+ shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(),
+ Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_NO_ATLAS_SHADER_FRAG.data());
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::IMAGE_SHADER, shader);
}
}
}
#include <dali-toolkit/internal/visuals/image/image-visual.h>
// EXTERNAL HEADERS
-#include <cstring> // for strlen()
-#include <dali/public-api/actors/layer.h>
-#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
+#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/rendering/renderer-devel.h>
#include <dali/devel-api/rendering/texture-devel.h>
#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/devel-api/scripting/scripting.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/actors/layer.h>
+#include <cstring> // for strlen()
// INTERNAL HEADERS
-#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/visuals/image-visual-actions-devel.h>
-#include <dali-toolkit/internal/visuals/texture-manager-impl.h>
-#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
-#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
-#include <dali-toolkit/internal/visuals/visual-base-impl.h>
#include <dali-toolkit/internal/visuals/image-atlas-manager.h>
+#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
+#include <dali-toolkit/internal/visuals/texture-manager-impl.h>
#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
+#include <dali-toolkit/internal/visuals/visual-base-impl.h>
+#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/internal/visuals/visual-string-constants.h>
#include <dali-toolkit/internal/visuals/visual-url.h>
-#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
+#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// fitting modes
-DALI_ENUM_TO_STRING_TABLE_BEGIN( FITTING_MODE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, SHRINK_TO_FIT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, SCALE_TO_FILL )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, FIT_WIDTH )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, FIT_HEIGHT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, DEFAULT )
-DALI_ENUM_TO_STRING_TABLE_END( FITTING_MODE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(FITTING_MODE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, SHRINK_TO_FIT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, SCALE_TO_FILL)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, FIT_WIDTH)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, FIT_HEIGHT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, DEFAULT)
+DALI_ENUM_TO_STRING_TABLE_END(FITTING_MODE)
// sampling modes
-DALI_ENUM_TO_STRING_TABLE_BEGIN( SAMPLING_MODE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, NEAREST )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, LINEAR )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX_THEN_NEAREST )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX_THEN_LINEAR )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, NO_FILTER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, DONT_CARE )
-DALI_ENUM_TO_STRING_TABLE_END( SAMPLING_MODE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(SAMPLING_MODE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, NEAREST)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, LINEAR)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX_THEN_NEAREST)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX_THEN_LINEAR)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, NO_FILTER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, DONT_CARE)
+DALI_ENUM_TO_STRING_TABLE_END(SAMPLING_MODE)
// wrap modes
-DALI_ENUM_TO_STRING_TABLE_BEGIN( WRAP_MODE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, DEFAULT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, CLAMP_TO_EDGE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, REPEAT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, MIRRORED_REPEAT )
-DALI_ENUM_TO_STRING_TABLE_END( WRAP_MODE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(WRAP_MODE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, DEFAULT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, CLAMP_TO_EDGE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, REPEAT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, MIRRORED_REPEAT)
+DALI_ENUM_TO_STRING_TABLE_END(WRAP_MODE)
// load policies
-DALI_ENUM_TO_STRING_TABLE_BEGIN( LOAD_POLICY )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::LoadPolicy, IMMEDIATE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::LoadPolicy, ATTACHED )
-DALI_ENUM_TO_STRING_TABLE_END( LOAD_POLICY )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(LOAD_POLICY)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::LoadPolicy, IMMEDIATE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::LoadPolicy, ATTACHED)
+DALI_ENUM_TO_STRING_TABLE_END(LOAD_POLICY)
// release policies
-DALI_ENUM_TO_STRING_TABLE_BEGIN( RELEASE_POLICY )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, DETACHED )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, DESTROYED )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, NEVER )
-DALI_ENUM_TO_STRING_TABLE_END( RELEASE_POLICY )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(RELEASE_POLICY)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::ReleasePolicy, DETACHED)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::ReleasePolicy, DESTROYED)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::ReleasePolicy, NEVER)
+DALI_ENUM_TO_STRING_TABLE_END(RELEASE_POLICY)
const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
-const float PIXEL_ALIGN_ON = 1.0f;
+const float PIXEL_ALIGN_ON = 1.0f;
const float PIXEL_ALIGN_OFF = 0.0f;
-Geometry CreateGeometry( VisualFactoryCache& factoryCache, ImageDimensions gridSize )
+Geometry CreateGeometry(VisualFactoryCache& factoryCache, ImageDimensions gridSize)
{
Geometry geometry;
- if( gridSize == ImageDimensions( 1, 1 ) )
+ if(gridSize == ImageDimensions(1, 1))
{
- geometry = factoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
+ geometry = factoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
}
else
{
- geometry = VisualFactoryCache::CreateGridGeometry( gridSize );
+ geometry = VisualFactoryCache::CreateGridGeometry(gridSize);
}
return geometry;
} // unnamed namespace
-
-ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache,
- ImageVisualShaderFactory& shaderFactory,
- const VisualUrl& imageUrl,
- const Property::Map& properties,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- Dali::SamplingMode::Type samplingMode )
+ImageVisualPtr ImageVisual::New(VisualFactoryCache& factoryCache,
+ ImageVisualShaderFactory& shaderFactory,
+ const VisualUrl& imageUrl,
+ const Property::Map& properties,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ Dali::SamplingMode::Type samplingMode)
{
- ImageVisualPtr imageVisualPtr( new ImageVisual( factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode ) );
- imageVisualPtr->SetProperties( properties );
+ ImageVisualPtr imageVisualPtr(new ImageVisual(factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode));
+ imageVisualPtr->SetProperties(properties);
imageVisualPtr->Initialize();
return imageVisualPtr;
}
-ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache,
- ImageVisualShaderFactory& shaderFactory,
- const VisualUrl& imageUrl,
- ImageDimensions size,
- FittingMode::Type fittingMode,
- Dali::SamplingMode::Type samplingMode )
+ImageVisualPtr ImageVisual::New(VisualFactoryCache& factoryCache,
+ ImageVisualShaderFactory& shaderFactory,
+ const VisualUrl& imageUrl,
+ ImageDimensions size,
+ FittingMode::Type fittingMode,
+ Dali::SamplingMode::Type samplingMode)
{
ImageVisualPtr imageVisualPtr(new ImageVisual(factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode));
imageVisualPtr->Initialize();
mAttemptAtlasing(false),
mOrientationCorrection(true)
{
- EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
+ EnablePreMultipliedAlpha(mFactoryCache.GetPreMultiplyOnLoad());
}
ImageVisual::~ImageVisual()
{
- if( Stage::IsInstalled() )
+ if(Stage::IsInstalled())
{
- if( mMaskingData )
+ if(mMaskingData)
{
// TextureManager could have been deleted before the actor that contains this
// ImageVisual is destroyed (e.g. due to stage shutdown). Ensure the stage
// is still valid before accessing texture manager.
- if( mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID )
+ if(mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID)
{
TextureManager& textureManager = mFactoryCache.GetTextureManager();
- textureManager.Remove( mMaskingData->mAlphaMaskId, this );
+ textureManager.Remove(mMaskingData->mAlphaMaskId, this);
}
}
// ImageVisual destroyed so remove texture unless ReleasePolicy is set to never release
- if( ( mTextureId != TextureManager::INVALID_TEXTURE_ID ) && ( mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER ) )
+ if((mTextureId != TextureManager::INVALID_TEXTURE_ID) && (mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER))
{
RemoveTexture();
}
}
}
-void ImageVisual::DoSetProperties( const Property::Map& propertyMap )
+void ImageVisual::DoSetProperties(const Property::Map& propertyMap)
{
// Url is already received in constructor
- for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
+ for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
{
- KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
- if( keyValue.first.type == Property::Key::INDEX )
+ KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
+ if(keyValue.first.type == Property::Key::INDEX)
{
- DoSetProperty( keyValue.first.indexKey, keyValue.second );
+ DoSetProperty(keyValue.first.indexKey, keyValue.second);
}
else
{
- if( keyValue.first == IMAGE_FITTING_MODE )
+ if(keyValue.first == IMAGE_FITTING_MODE)
{
- DoSetProperty( Toolkit::ImageVisual::Property::FITTING_MODE, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::FITTING_MODE, keyValue.second);
}
- else if( keyValue.first == IMAGE_SAMPLING_MODE )
+ else if(keyValue.first == IMAGE_SAMPLING_MODE)
{
- DoSetProperty( Toolkit::ImageVisual::Property::SAMPLING_MODE, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::SAMPLING_MODE, keyValue.second);
}
- else if( keyValue.first == IMAGE_DESIRED_WIDTH )
+ else if(keyValue.first == IMAGE_DESIRED_WIDTH)
{
- DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second);
}
- else if( keyValue.first == IMAGE_DESIRED_HEIGHT )
+ else if(keyValue.first == IMAGE_DESIRED_HEIGHT)
{
- DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second);
}
- else if( keyValue.first == PIXEL_AREA_UNIFORM_NAME )
+ else if(keyValue.first == PIXEL_AREA_UNIFORM_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second);
}
- else if( keyValue.first == IMAGE_WRAP_MODE_U )
+ else if(keyValue.first == IMAGE_WRAP_MODE_U)
{
- DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second);
}
- else if( keyValue.first == IMAGE_WRAP_MODE_V )
+ else if(keyValue.first == IMAGE_WRAP_MODE_V)
{
- DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second);
}
- else if( keyValue.first == SYNCHRONOUS_LOADING )
+ else if(keyValue.first == SYNCHRONOUS_LOADING)
{
- DoSetProperty( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second);
}
- else if( keyValue.first == IMAGE_ATLASING )
+ else if(keyValue.first == IMAGE_ATLASING)
{
- DoSetProperty( Toolkit::ImageVisual::Property::ATLASING, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::ATLASING, keyValue.second);
}
- else if( keyValue.first == ALPHA_MASK_URL )
+ else if(keyValue.first == ALPHA_MASK_URL)
{
- DoSetProperty( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::ALPHA_MASK_URL, keyValue.second);
}
- else if( keyValue.first == MASK_CONTENT_SCALE_NAME )
+ else if(keyValue.first == MASK_CONTENT_SCALE_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, keyValue.second);
}
- else if( keyValue.first == CROP_TO_MASK_NAME )
+ else if(keyValue.first == CROP_TO_MASK_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::CROP_TO_MASK, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::CROP_TO_MASK, keyValue.second);
}
- else if ( keyValue.first == LOAD_POLICY_NAME )
+ else if(keyValue.first == LOAD_POLICY_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::LOAD_POLICY, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::LOAD_POLICY, keyValue.second);
}
- else if( keyValue.first == RELEASE_POLICY_NAME )
+ else if(keyValue.first == RELEASE_POLICY_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::RELEASE_POLICY, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::RELEASE_POLICY, keyValue.second);
}
- else if( keyValue.first == ORIENTATION_CORRECTION_NAME )
+ else if(keyValue.first == ORIENTATION_CORRECTION_NAME)
{
- DoSetProperty( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, keyValue.second);
}
}
}
// Load image immediately if LOAD_POLICY requires it
- if ( mLoadPolicy == Toolkit::ImageVisual::LoadPolicy::IMMEDIATE )
+ if(mLoadPolicy == Toolkit::ImageVisual::LoadPolicy::IMMEDIATE)
{
auto attemptAtlasing = AttemptAtlasing();
- LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
- TextureManager::ReloadPolicy::CACHED );
+ LoadTexture(attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, TextureManager::ReloadPolicy::CACHED);
}
}
-void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& value )
+void ImageVisual::DoSetProperty(Property::Index index, const Property::Value& value)
{
- switch( index )
+ switch(index)
{
case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
{
bool sync = false;
- if( value.Get( sync ) )
+ if(value.Get(sync))
{
- if( sync )
+ if(sync)
{
mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
}
case Toolkit::ImageVisual::Property::DESIRED_WIDTH:
{
float desiredWidth = 0.0f;
- if( value.Get( desiredWidth ) )
+ if(value.Get(desiredWidth))
{
- mDesiredSize.SetWidth( desiredWidth );
+ mDesiredSize.SetWidth(desiredWidth);
}
else
{
case Toolkit::ImageVisual::Property::DESIRED_HEIGHT:
{
float desiredHeight = 0.0f;
- if( value.Get( desiredHeight ) )
+ if(value.Get(desiredHeight))
{
- mDesiredSize.SetHeight( desiredHeight );
+ mDesiredSize.SetHeight(desiredHeight);
}
else
{
case Toolkit::ImageVisual::Property::FITTING_MODE:
{
int fittingMode = 0;
- Scripting::GetEnumerationProperty( value, FITTING_MODE_TABLE, FITTING_MODE_TABLE_COUNT, fittingMode );
- mFittingMode = Dali::FittingMode::Type( fittingMode );
+ Scripting::GetEnumerationProperty(value, FITTING_MODE_TABLE, FITTING_MODE_TABLE_COUNT, fittingMode);
+ mFittingMode = Dali::FittingMode::Type(fittingMode);
break;
}
case Toolkit::ImageVisual::Property::SAMPLING_MODE:
{
int samplingMode = 0;
- Scripting::GetEnumerationProperty( value, SAMPLING_MODE_TABLE, SAMPLING_MODE_TABLE_COUNT, samplingMode );
- mSamplingMode = Dali::SamplingMode::Type( samplingMode );
+ Scripting::GetEnumerationProperty(value, SAMPLING_MODE_TABLE, SAMPLING_MODE_TABLE_COUNT, samplingMode);
+ mSamplingMode = Dali::SamplingMode::Type(samplingMode);
break;
}
case Toolkit::ImageVisual::Property::PIXEL_AREA:
{
- value.Get( mPixelArea );
+ value.Get(mPixelArea);
break;
}
case Toolkit::ImageVisual::Property::WRAP_MODE_U:
{
int wrapMode = 0;
- Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode );
- mWrapModeU = Dali::WrapMode::Type( wrapMode );
+ Scripting::GetEnumerationProperty(value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode);
+ mWrapModeU = Dali::WrapMode::Type(wrapMode);
break;
}
case Toolkit::ImageVisual::Property::WRAP_MODE_V:
{
int wrapMode = 0;
- Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode );
- mWrapModeV = Dali::WrapMode::Type( wrapMode );
+ Scripting::GetEnumerationProperty(value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode);
+ mWrapModeV = Dali::WrapMode::Type(wrapMode);
break;
}
case Toolkit::ImageVisual::Property::ATLASING:
{
- value.Get( mAttemptAtlasing );
+ value.Get(mAttemptAtlasing);
break;
}
case Toolkit::ImageVisual::Property::ALPHA_MASK_URL:
{
std::string alphaUrl = "";
- if( value.Get( alphaUrl ) )
+ if(value.Get(alphaUrl))
{
AllocateMaskData();
mMaskingData->mAlphaMaskUrl = alphaUrl;
case Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE:
{
float scale = 1.0f;
- if( value.Get( scale ) )
+ if(value.Get(scale))
{
AllocateMaskData();
mMaskingData->mContentScaleFactor = scale;
case Toolkit::ImageVisual::Property::CROP_TO_MASK:
{
- bool crop=false;
- if( value.Get( crop ) )
+ bool crop = false;
+ if(value.Get(crop))
{
AllocateMaskData();
mMaskingData->mCropToMask = crop;
case Toolkit::ImageVisual::Property::RELEASE_POLICY:
{
int releasePolicy = 0;
- Scripting::GetEnumerationProperty( value, RELEASE_POLICY_TABLE, RELEASE_POLICY_TABLE_COUNT, releasePolicy );
- mReleasePolicy = Toolkit::ImageVisual::ReleasePolicy::Type( releasePolicy );
+ Scripting::GetEnumerationProperty(value, RELEASE_POLICY_TABLE, RELEASE_POLICY_TABLE_COUNT, releasePolicy);
+ mReleasePolicy = Toolkit::ImageVisual::ReleasePolicy::Type(releasePolicy);
break;
}
case Toolkit::ImageVisual::Property::LOAD_POLICY:
{
int loadPolicy = 0;
- Scripting::GetEnumerationProperty( value, LOAD_POLICY_TABLE, LOAD_POLICY_TABLE_COUNT, loadPolicy );
- mLoadPolicy = Toolkit::ImageVisual::LoadPolicy::Type( loadPolicy );
+ Scripting::GetEnumerationProperty(value, LOAD_POLICY_TABLE, LOAD_POLICY_TABLE_COUNT, loadPolicy);
+ mLoadPolicy = Toolkit::ImageVisual::LoadPolicy::Type(loadPolicy);
break;
}
case Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION:
{
- bool orientationCorrection( mOrientationCorrection );
- if( value.Get( orientationCorrection ) )
+ bool orientationCorrection(mOrientationCorrection);
+ if(value.Get(orientationCorrection))
{
mOrientationCorrection = orientationCorrection;
}
void ImageVisual::AllocateMaskData()
{
- if( !mMaskingData )
+ if(!mMaskingData)
{
mMaskingData.reset(new TextureManager::MaskingData());
}
}
-void ImageVisual::GetNaturalSize( Vector2& naturalSize )
+void ImageVisual::GetNaturalSize(Vector2& naturalSize)
{
- if( mDesiredSize.GetWidth()>0 && mDesiredSize.GetHeight()>0)
+ if(mDesiredSize.GetWidth() > 0 && mDesiredSize.GetHeight() > 0)
{
naturalSize.x = mDesiredSize.GetWidth();
naturalSize.y = mDesiredSize.GetHeight();
return;
}
- else if( mImpl->mRenderer ) // Check if we have a loaded image
+ else if(mImpl->mRenderer) // Check if we have a loaded image
{
- if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
+ if(mImpl->mFlags & Impl::IS_ATLASING_APPLIED)
{
naturalSize.x = mAtlasRectSize.GetWidth();
naturalSize.y = mAtlasRectSize.GetHeight();
}
auto textureSet = mImpl->mRenderer.GetTextures();
- if( textureSet )
+ if(textureSet)
{
auto texture = textureSet.GetTexture(0);
- if( texture )
+ if(texture)
{
naturalSize.x = texture.GetWidth();
naturalSize.y = texture.GetHeight();
}
}
- if( mMaskingData != NULL && mMaskingData->mAlphaMaskUrl.IsValid() &&
- mMaskingData->mCropToMask )
+ if(mMaskingData != NULL && mMaskingData->mAlphaMaskUrl.IsValid() &&
+ mMaskingData->mCropToMask)
{
- ImageDimensions dimensions = Dali::GetClosestImageSize( mMaskingData->mAlphaMaskUrl.GetUrl() );
- if( dimensions != ImageDimensions( 0, 0 ) )
+ ImageDimensions dimensions = Dali::GetClosestImageSize(mMaskingData->mAlphaMaskUrl.GetUrl());
+ if(dimensions != ImageDimensions(0, 0))
{
naturalSize.x = dimensions.GetWidth();
naturalSize.y = dimensions.GetHeight();
}
return;
}
- else if( mImageUrl.IsValid() )
+ else if(mImageUrl.IsValid())
{
- if( mImageUrl.GetProtocolType() == VisualUrl::LOCAL )
+ if(mImageUrl.GetProtocolType() == VisualUrl::LOCAL)
{
- ImageDimensions dimensions = Dali::GetClosestImageSize( mImageUrl.GetUrl() );
+ ImageDimensions dimensions = Dali::GetClosestImageSize(mImageUrl.GetUrl());
- if( dimensions != ImageDimensions( 0, 0 ) )
+ if(dimensions != ImageDimensions(0, 0))
{
naturalSize.x = dimensions.GetWidth();
naturalSize.y = dimensions.GetHeight();
Geometry geometry;
// Get the geometry
- if( mImpl->mCustomShader )
+ if(mImpl->mCustomShader)
{
- geometry = CreateGeometry( mFactoryCache, mImpl->mCustomShader->mGridSize );
+ geometry = CreateGeometry(mFactoryCache, mImpl->mCustomShader->mGridSize);
}
else // Get any geometry associated with the texture
{
TextureManager& textureManager = mFactoryCache.GetTextureManager();
- uint32_t firstElementCount {0u};
- uint32_t secondElementCount {0u};
+ uint32_t firstElementCount{0u};
+ uint32_t secondElementCount{0u};
geometry = textureManager.GetRenderGeometry(mTextureId, firstElementCount, secondElementCount);
if(!firstElementCount && !secondElementCount) // Otherwise use quad
{
- geometry = CreateGeometry( mFactoryCache, ImageDimensions( 1, 1 ) );
+ geometry = CreateGeometry(mFactoryCache, ImageDimensions(1, 1));
}
}
Shader shader = GetShader();
// Create the renderer
- mImpl->mRenderer = Renderer::New( geometry, shader );
+ mImpl->mRenderer = Renderer::New(geometry, shader);
//Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
- EnablePreMultipliedAlpha( IsPreMultipliedAlphaEnabled() );
+ EnablePreMultipliedAlpha(IsPreMultipliedAlphaEnabled());
}
-void ImageVisual::LoadTexture( bool& atlasing, Vector4& atlasRect, TextureSet& textures, bool orientationCorrection,
- TextureManager::ReloadPolicy forceReload )
+void ImageVisual::LoadTexture(bool& atlasing, Vector4& atlasRect, TextureSet& textures, bool orientationCorrection, TextureManager::ReloadPolicy forceReload)
{
TextureManager& textureManager = mFactoryCache.GetTextureManager();
- ImageAtlasManagerPtr atlasManager = nullptr;
+ ImageAtlasManagerPtr atlasManager = nullptr;
AtlasUploadObserver* atlasUploadObserver = nullptr;
- auto textureObserver = this;
+ auto textureObserver = this;
- if( atlasing )
+ if(atlasing)
{
- atlasManager = mFactoryCache.GetAtlasManager();
+ atlasManager = mFactoryCache.GetAtlasManager();
atlasUploadObserver = this;
}
auto preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader
- ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD
- : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
+ ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD
+ : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
bool synchronousLoading = IsSynchronousLoadingRequired();
bool loadingStatus;
textures = textureManager.LoadTexture(mImageUrl, mDesiredSize, mFittingMode, mSamplingMode, mMaskingData, synchronousLoading, mTextureId, atlasRect, mAtlasRectSize, atlasing, loadingStatus, mWrapModeU, mWrapModeV, textureObserver, atlasUploadObserver, atlasManager, mOrientationCorrection, forceReload, preMultiplyOnLoad);
- if( textures )
+ if(textures)
{
if(loadingStatus)
{
mLoadState = TextureManager::LoadState::LOAD_FINISHED;
}
- EnablePreMultipliedAlpha( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
+ EnablePreMultipliedAlpha(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
}
else if(synchronousLoading)
{
mLoadState = TextureManager::LoadState::LOAD_FAILED;
}
- if( atlasing ) // Flag needs to be set before creating renderer
+ if(atlasing) // Flag needs to be set before creating renderer
{
mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
}
bool ImageVisual::AttemptAtlasing()
{
- return ( ! mImpl->mCustomShader && mImageUrl.GetProtocolType() == VisualUrl::LOCAL && mAttemptAtlasing );
+ return (!mImpl->mCustomShader && mImageUrl.GetProtocolType() == VisualUrl::LOCAL && mAttemptAtlasing);
}
void ImageVisual::InitializeRenderer()
// - If ReleasePolicy is DESTROYED, InitializeRenderer called every on stage called.
// - Then every resources those contained in Visual are Reset but mTextureId is remained when the Off stage time,
// - So, mTextures needed to be get from texture manager to created resources like mImpl->mRenderer.
- if( ! mTextures )
+ if(!mTextures)
{
- if( mTextureId == TextureManager::INVALID_TEXTURE_ID )
+ if(mTextureId == TextureManager::INVALID_TEXTURE_ID)
{
- LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
- TextureManager::ReloadPolicy::CACHED );
+ LoadTexture(attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, TextureManager::ReloadPolicy::CACHED);
}
else
{
- mTextures = mFactoryCache.GetTextureManager().GetTextureSet( mTextureId );
+ mTextures = mFactoryCache.GetTextureManager().GetTextureSet(mTextureId);
}
}
mTextures.Reset(); // Visual should not keep a handle to the texture after this point.
}
- if( attemptAtlasing ) // the texture is packed inside atlas
+ if(attemptAtlasing) // the texture is packed inside atlas
{
- mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
+ mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, mAtlasRect);
bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE;
- if( !defaultWrapMode ) // custom wrap mode
+ if(!defaultWrapMode) // custom wrap mode
{
- Vector2 wrapMode(mWrapModeU-WrapMode::CLAMP_TO_EDGE, mWrapModeV-WrapMode::CLAMP_TO_EDGE);
- wrapMode.Clamp( Vector2::ZERO, Vector2( 2.f, 2.f ) );
- mImpl->mRenderer.RegisterProperty( WRAP_MODE_UNIFORM_NAME, wrapMode );
+ Vector2 wrapMode(mWrapModeU - WrapMode::CLAMP_TO_EDGE, mWrapModeV - WrapMode::CLAMP_TO_EDGE);
+ wrapMode.Clamp(Vector2::ZERO, Vector2(2.f, 2.f));
+ mImpl->mRenderer.RegisterProperty(WRAP_MODE_UNIFORM_NAME, wrapMode);
}
}
}
-void ImageVisual::DoSetOnScene( Actor& actor )
+void ImageVisual::DoSetOnScene(Actor& actor)
{
- if( mImageUrl.IsValid() )
+ if(mImageUrl.IsValid())
{
InitializeRenderer();
}
- if( !mImpl->mRenderer )
+ if(!mImpl->mRenderer)
{
return;
}
mPlacementActor = actor;
// Search the Actor tree to find if Layer UI behaviour set.
Layer layer = actor.GetLayer();
- if( layer && layer.GetProperty<Layer::Behavior>( Layer::Property::BEHAVIOR ) == Layer::LAYER_3D )
+ if(layer && layer.GetProperty<Layer::Behavior>(Layer::Property::BEHAVIOR) == Layer::LAYER_3D)
{
- // Layer 3D set, do not align pixels
- mImpl->mRenderer.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF );
+ // Layer 3D set, do not align pixels
+ mImpl->mRenderer.RegisterProperty(PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF);
}
- if( mPixelArea != FULL_TEXTURE_RECT )
+ if(mPixelArea != FULL_TEXTURE_RECT)
{
- mImpl->mRenderer.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, mPixelArea );
+ mImpl->mRenderer.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, mPixelArea);
}
if(mLoadState == TextureManager::LoadState::LOAD_FINISHED)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
mPlacementActor.Reset();
// Image loaded and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
else if(mLoadState == TextureManager::LoadState::LOAD_FAILED)
{
}
}
-void ImageVisual::DoSetOffScene( Actor& actor )
+void ImageVisual::DoSetOffScene(Actor& actor)
{
// Visual::Base::SetOffScene only calls DoSetOffScene if mRenderer exists (is on onstage)
// Image release is dependent on the ReleasePolicy, renderer is removed.
- actor.RemoveRenderer( mImpl->mRenderer);
- if( mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED )
+ actor.RemoveRenderer(mImpl->mRenderer);
+ if(mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED)
{
RemoveTexture(); // If INVALID_TEXTURE_ID then removal will be attempted on atlas
mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING;
mPlacementActor.Reset();
}
-void ImageVisual::DoCreatePropertyMap( Property::Map& map ) const
+void ImageVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE);
bool sync = IsSynchronousLoadingRequired();
- map.Insert( SYNCHRONOUS_LOADING, sync );
- if( mImageUrl.IsValid() )
+ map.Insert(SYNCHRONOUS_LOADING, sync);
+ if(mImageUrl.IsValid())
{
- map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
- map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() );
- map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() );
+ map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
+ map.Insert(Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth());
+ map.Insert(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight());
}
- map.Insert( Toolkit::ImageVisual::Property::FITTING_MODE, mFittingMode );
- map.Insert( Toolkit::ImageVisual::Property::SAMPLING_MODE, mSamplingMode );
+ map.Insert(Toolkit::ImageVisual::Property::FITTING_MODE, mFittingMode);
+ map.Insert(Toolkit::ImageVisual::Property::SAMPLING_MODE, mSamplingMode);
- map.Insert( Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea );
- map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU );
- map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV );
+ map.Insert(Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea);
+ map.Insert(Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU);
+ map.Insert(Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV);
- map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing );
+ map.Insert(Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing);
- if( mMaskingData != NULL )
+ if(mMaskingData != NULL)
{
- map.Insert( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, mMaskingData->mAlphaMaskUrl.GetUrl() );
- map.Insert( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, mMaskingData->mContentScaleFactor );
- map.Insert( Toolkit::ImageVisual::Property::CROP_TO_MASK, mMaskingData->mCropToMask );
+ map.Insert(Toolkit::ImageVisual::Property::ALPHA_MASK_URL, mMaskingData->mAlphaMaskUrl.GetUrl());
+ map.Insert(Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, mMaskingData->mContentScaleFactor);
+ map.Insert(Toolkit::ImageVisual::Property::CROP_TO_MASK, mMaskingData->mCropToMask);
}
- map.Insert( Toolkit::ImageVisual::Property::LOAD_POLICY, mLoadPolicy );
- map.Insert( Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy );
- map.Insert( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, mOrientationCorrection );
+ map.Insert(Toolkit::ImageVisual::Property::LOAD_POLICY, mLoadPolicy);
+ map.Insert(Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy);
+ map.Insert(Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, mOrientationCorrection);
}
-void ImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void ImageVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE );
- if( mImageUrl.IsValid() )
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE);
+ if(mImageUrl.IsValid())
{
- map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() );
- map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() );
+ map.Insert(Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth());
+ map.Insert(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight());
}
}
-void ImageVisual::OnDoAction( const Dali::Property::Index actionName, const Dali::Property::Value& attributes )
+void ImageVisual::OnDoAction(const Dali::Property::Index actionName, const Dali::Property::Value& attributes)
{
// Check if action is valid for this visual type and perform action if possible
- switch ( actionName )
+ switch(actionName)
{
case DevelImageVisual::Action::RELOAD:
{
auto attemptAtlasing = AttemptAtlasing();
- LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
- TextureManager::ReloadPolicy::FORCED );
+ LoadTexture(attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, TextureManager::ReloadPolicy::FORCED);
break;
}
}
void ImageVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
bool ImageVisual::IsResourceReady() const
{
- return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
- mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED );
+ return (mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
+ mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED);
}
void ImageVisual::UpdateShader()
// Texture has been uploaded. If weak handle is holding a placement actor,
// it is the time to add the renderer to actor.
Actor actor = mPlacementActor.GetHandle();
- if( actor )
+ if(actor)
{
- mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
- actor.AddRenderer( mImpl->mRenderer );
+ mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, mAtlasRect);
+ actor.AddRenderer(mImpl->mRenderer);
// reset the weak handle so that the renderer only get added to actor once
mPlacementActor.Reset();
}
// Image loaded
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
mLoadState = TextureManager::LoadState::LOAD_FINISHED;
}
// From Texture Manager
-void ImageVisual::UploadComplete( bool loadingSuccess, int32_t textureId, TextureSet textureSet, bool usingAtlas,
- const Vector4& atlasRectangle, bool preMultiplied )
+void ImageVisual::UploadComplete(bool loadingSuccess, int32_t textureId, TextureSet textureSet, bool usingAtlas, const Vector4& atlasRectangle, bool preMultiplied)
{
Toolkit::Visual::ResourceStatus resourceStatus;
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- if( usingAtlas )
+ if(usingAtlas)
{
- mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
+ mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, mAtlasRect);
}
- EnablePreMultipliedAlpha( preMultiplied );
+ EnablePreMultipliedAlpha(preMultiplied);
Actor actor = mPlacementActor.GetHandle();
- if( actor )
+ if(actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
// reset the weak handle so that the renderer only get added to actor once
mPlacementActor.Reset();
}
- if( !loadingSuccess )
+ if(!loadingSuccess)
{
Texture brokenImage = mFactoryCache.GetBrokenVisualImage();
textureSet = TextureSet::New();
textureSet.SetTexture(0u, brokenImage);
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
}
Sampler sampler = Sampler::New();
- sampler.SetWrapMode( mWrapModeU, mWrapModeV );
- textureSet.SetSampler( 0u, sampler );
+ sampler.SetWrapMode(mWrapModeU, mWrapModeV);
+ textureSet.SetSampler(0u, sampler);
mImpl->mRenderer.SetTextures(textureSet);
-
}
// Storing TextureSet needed when renderer staged.
- if( ! mImpl->mRenderer )
+ if(!mImpl->mRenderer)
{
mTextures = textureSet;
}
// Image loaded, set status regardless of staged status.
- if( loadingSuccess )
+ if(loadingSuccess)
{
resourceStatus = Toolkit::Visual::ResourceStatus::READY;
mLoadState = TextureManager::LoadState::LOAD_FINISHED;
}
// use geometry if needed
- if( loadingSuccess )
+ if(loadingSuccess)
{
uint32_t firstElementCount{0u};
uint32_t secondElementCount{0u};
- auto geometry = mFactoryCache.GetTextureManager().GetRenderGeometry(mTextureId, firstElementCount, secondElementCount);
- if (mImpl->mRenderer && geometry)
+ auto geometry = mFactoryCache.GetTextureManager().GetRenderGeometry(mTextureId, firstElementCount, secondElementCount);
+ if(mImpl->mRenderer && geometry)
{
mImpl->mRenderer.SetGeometry(geometry);
Dali::DevelRenderer::DrawCommand drawCommand{};
drawCommand.drawType = DevelRenderer::DrawType::INDEXED;
- if (firstElementCount)
+ if(firstElementCount)
{
- drawCommand.firstIndex = 0;
+ drawCommand.firstIndex = 0;
drawCommand.elementCount = firstElementCount;
- drawCommand.queue = DevelRenderer::RENDER_QUEUE_OPAQUE;
+ drawCommand.queue = DevelRenderer::RENDER_QUEUE_OPAQUE;
DevelRenderer::AddDrawCommand(mImpl->mRenderer, drawCommand);
}
- if (secondElementCount)
+ if(secondElementCount)
{
- drawCommand.firstIndex = firstElementCount;
+ drawCommand.firstIndex = firstElementCount;
drawCommand.elementCount = secondElementCount;
- drawCommand.queue = DevelRenderer::RENDER_QUEUE_TRANSPARENT;
+ drawCommand.queue = DevelRenderer::RENDER_QUEUE_TRANSPARENT;
DevelRenderer::AddDrawCommand(mImpl->mRenderer, drawCommand);
}
}
}
// Signal to observers ( control ) that resources are ready. Must be all resources.
- ResourceReady( resourceStatus );
+ ResourceReady(resourceStatus);
}
void ImageVisual::RemoveTexture()
{
- if( mTextureId != TextureManager::INVALID_TEXTURE_ID )
+ if(mTextureId != TextureManager::INVALID_TEXTURE_ID)
{
- mFactoryCache.GetTextureManager().Remove( mTextureId, this );
+ mFactoryCache.GetTextureManager().Remove(mTextureId, this);
mTextureId = TextureManager::INVALID_TEXTURE_ID;
}
else
{
- Vector4 atlasRect( 0.f, 0.f, 1.f, 1.f );
- Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
- if( index != Property::INVALID_INDEX )
+ Vector4 atlasRect(0.f, 0.f, 1.f, 1.f);
+ Property::Index index = mImpl->mRenderer.GetPropertyIndex(ATLAS_RECT_UNIFORM_NAME);
+ if(index != Property::INVALID_INDEX)
{
- Property::Value atlasRectValue = mImpl->mRenderer.GetProperty( index );
- atlasRectValue.Get( atlasRect );
+ Property::Value atlasRectValue = mImpl->mRenderer.GetProperty(index);
+ atlasRectValue.Get(atlasRect);
}
TextureSet textureSet = mImpl->mRenderer.GetTextures();
- if( index != Property::INVALID_INDEX )
+ if(index != Property::INVALID_INDEX)
{
- mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
+ mFactoryCache.GetAtlasManager()->Remove(textureSet, atlasRect);
}
}
}
Shader shader;
std::string_view vertexShaderView;
- bool usesWholeTexture = true;
+ bool usesWholeTexture = true;
if(mImpl->mCustomShader && !mImpl->mCustomShader->mVertexShader.empty())
{
vertexShaderView = mImpl->mCustomShader->mVertexShader;
// If the texture is native, we may need to change prefix and sampler in
// the fragment shader
- bool modifiedFragmentShader = false;
+ bool modifiedFragmentShader = false;
std::string fragmentShaderString;
if(mTextures && DevelTexture::IsNative(mTextures.GetTexture(0)))
{
- Texture nativeTexture = mTextures.GetTexture(0);
+ Texture nativeTexture = mTextures.GetTexture(0);
fragmentShaderString = std::string(fragmentShaderView);
modifiedFragmentShader = DevelTexture::ApplyNativeFragmentShader(nativeTexture, fragmentShaderString);
fragmentShaderView = fragmentShaderString;
mFactoryCache,
mImpl->mFlags & Impl::IS_ATLASING_APPLIED,
mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE,
- IsRoundedCornerRequired() );
+ IsRoundedCornerRequired());
}
else if(mImpl->mCustomShader)
{
if(usesWholeTexture)
{
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
}
// Set pixel align off as default.
// ToDo: Pixel align causes issues such as rattling image animation.
// We should trun it off until issues are resolved
- shader.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF );
+ shader.RegisterProperty(PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF);
return shader;
}
#include "mesh-visual.h"
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/devel-api/adaptor-framework/image-loading.h>
#include <dali/devel-api/adaptor-framework/file-loader.h>
+#include <dali/devel-api/adaptor-framework/image-loading.h>
+#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/devel-api/scripting/scripting.h>
+#include <dali/integration-api/debug.h>
//INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace
{
- /**
+/**
* @brief Loads a texture from a file
* @param[in] imageUrl The url of the file
* @param[in] generateMipmaps Indicates whether to generate mipmaps for the texture
* @return A texture if loading succeeds, an empty handle otherwise
*/
- Texture LoadTexture( const char* imageUrl, bool generateMipmaps )
+Texture LoadTexture(const char* imageUrl, bool generateMipmaps)
+{
+ Texture texture;
+
+ Devel::PixelBuffer pixelBuffer = LoadImageFromFile(imageUrl);
+ if(pixelBuffer)
{
- Texture texture;
+ texture = Texture::New(TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
+ PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
+ texture.Upload(pixelData);
- Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl );
- if( pixelBuffer )
+ if(generateMipmaps)
{
- texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
- PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
- texture.Upload( pixelData );
-
- if( generateMipmaps )
- {
- texture.GenerateMipmaps();
- }
+ texture.GenerateMipmaps();
}
-
- return texture;
}
-}// unnamed namespace
+
+ return texture;
+}
+} // unnamed namespace
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
//Defines ordering of textures for shaders.
//All shaders, if including certain texture types, must include them in the same order.
//Within the texture set for the renderer, textures are ordered in the same manner.
enum TextureIndex
{
DIFFUSE_INDEX = 0u,
- NORMAL_INDEX = 1u,
- GLOSS_INDEX = 2u
+ NORMAL_INDEX = 1u,
+ GLOSS_INDEX = 2u
};
-
//Shading mode
-DALI_ENUM_TO_STRING_TABLE_BEGIN( SHADING_MODE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURELESS_WITH_DIFFUSE_LIGHTING )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_SPECULAR_LIGHTING )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
-DALI_ENUM_TO_STRING_TABLE_END( SHADING_MODE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(SHADING_MODE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::MeshVisual::ShadingMode, TEXTURELESS_WITH_DIFFUSE_LIGHTING)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_SPECULAR_LIGHTING)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING)
+DALI_ENUM_TO_STRING_TABLE_END(SHADING_MODE)
//Shader properties
-const char * const OBJECT_MATRIX_UNIFORM_NAME( "uObjectMatrix" );
-const char * const STAGE_OFFSET_UNIFORM_NAME( "uStageOffset" );
+const char* const OBJECT_MATRIX_UNIFORM_NAME("uObjectMatrix");
+const char* const STAGE_OFFSET_UNIFORM_NAME("uStageOffset");
} // unnamed namespace
-MeshVisualPtr MeshVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+MeshVisualPtr MeshVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
- MeshVisualPtr meshVisualPtr( new MeshVisual( factoryCache ) );
- meshVisualPtr->SetProperties( properties );
+ MeshVisualPtr meshVisualPtr(new MeshVisual(factoryCache));
+ meshVisualPtr->SetProperties(properties);
meshVisualPtr->Initialize();
return meshVisualPtr;
}
-MeshVisual::MeshVisual( VisualFactoryCache& factoryCache )
-: Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::MESH ),
- mShadingMode( Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ),
- mUseTexture( true ),
- mUseMipmapping( true ),
- mUseSoftNormals( true )
+MeshVisual::MeshVisual(VisualFactoryCache& factoryCache)
+: Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::MESH),
+ mShadingMode(Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING),
+ mUseTexture(true),
+ mUseMipmapping(true),
+ mUseSoftNormals(true)
{
}
{
}
-void MeshVisual::DoSetProperties( const Property::Map& propertyMap )
+void MeshVisual::DoSetProperties(const Property::Map& propertyMap)
{
- for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
+ for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
{
- KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
- if( keyValue.first.type == Property::Key::INDEX )
+ KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
+ if(keyValue.first.type == Property::Key::INDEX)
{
- DoSetProperty( keyValue.first.indexKey, keyValue.second );
+ DoSetProperty(keyValue.first.indexKey, keyValue.second);
}
else
{
- if( keyValue.first == OBJECT_URL_NAME )
+ if(keyValue.first == OBJECT_URL_NAME)
{
- DoSetProperty( Toolkit::MeshVisual::Property::OBJECT_URL, keyValue.second );
+ DoSetProperty(Toolkit::MeshVisual::Property::OBJECT_URL, keyValue.second);
}
- else if( keyValue.first == MATERIAL_URL_NAME )
+ else if(keyValue.first == MATERIAL_URL_NAME)
{
- DoSetProperty( Toolkit::MeshVisual::Property::MATERIAL_URL, keyValue.second );
+ DoSetProperty(Toolkit::MeshVisual::Property::MATERIAL_URL, keyValue.second);
}
- else if( keyValue.first == TEXTURES_PATH_NAME )
+ else if(keyValue.first == TEXTURES_PATH_NAME)
{
- DoSetProperty( Toolkit::MeshVisual::Property::TEXTURES_PATH, keyValue.second );
+ DoSetProperty(Toolkit::MeshVisual::Property::TEXTURES_PATH, keyValue.second);
}
- else if( keyValue.first == SHADING_MODE_NAME )
+ else if(keyValue.first == SHADING_MODE_NAME)
{
- DoSetProperty( Toolkit::MeshVisual::Property::SHADING_MODE, keyValue.second );
+ DoSetProperty(Toolkit::MeshVisual::Property::SHADING_MODE, keyValue.second);
}
- else if( keyValue.first == USE_MIPMAPPING_NAME )
+ else if(keyValue.first == USE_MIPMAPPING_NAME)
{
- DoSetProperty( Toolkit::MeshVisual::Property::USE_MIPMAPPING, keyValue.second );
+ DoSetProperty(Toolkit::MeshVisual::Property::USE_MIPMAPPING, keyValue.second);
}
- else if( keyValue.first == USE_SOFT_NORMALS_NAME )
+ else if(keyValue.first == USE_SOFT_NORMALS_NAME)
{
- DoSetProperty( Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, keyValue.second );
+ DoSetProperty(Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, keyValue.second);
}
- else if( keyValue.first == LIGHT_POSITION_NAME )
+ else if(keyValue.first == LIGHT_POSITION_NAME)
{
- DoSetProperty( Toolkit::MeshVisual::Property::LIGHT_POSITION, keyValue.second );
+ DoSetProperty(Toolkit::MeshVisual::Property::LIGHT_POSITION, keyValue.second);
}
}
}
- if( mMaterialUrl.empty() )
+ if(mMaterialUrl.empty())
{
mUseTexture = false;
}
- if( mLightPosition == Vector3::ZERO )
+ if(mLightPosition == Vector3::ZERO)
{
// Default behaviour is to place the light directly in front of the object,
// at a reasonable distance to light everything on screen.
Stage stage = Stage::GetCurrent();
- mLightPosition = Vector3( stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5 );
+ mLightPosition = Vector3(stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5);
}
}
-void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& value )
+void MeshVisual::DoSetProperty(Property::Index index, const Property::Value& value)
{
- switch( index )
+ switch(index)
{
case Toolkit::MeshVisual::Property::OBJECT_URL:
{
- if( !value.Get( mObjectUrl ) )
+ if(!value.Get(mObjectUrl))
{
DALI_LOG_ERROR("MeshVisual: property objectUrl is the wrong type, use STRING\n");
}
}
case Toolkit::MeshVisual::Property::MATERIAL_URL:
{
- if( ! value.Get( mMaterialUrl ) )
+ if(!value.Get(mMaterialUrl))
{
DALI_LOG_ERROR("MeshVisual: property materialUrl is the wrong type, use STRING\n");
}
}
case Toolkit::MeshVisual::Property::TEXTURES_PATH:
{
- if( ! value.Get( mTexturesPath ) )
+ if(!value.Get(mTexturesPath))
{
mTexturesPath.clear();
}
}
case Toolkit::MeshVisual::Property::SHADING_MODE:
{
- Scripting::GetEnumerationProperty( value, SHADING_MODE_TABLE, SHADING_MODE_TABLE_COUNT, mShadingMode );
+ Scripting::GetEnumerationProperty(value, SHADING_MODE_TABLE, SHADING_MODE_TABLE_COUNT, mShadingMode);
break;
}
case Toolkit::MeshVisual::Property::USE_MIPMAPPING:
{
- if( !value.Get( mUseMipmapping ) )
+ if(!value.Get(mUseMipmapping))
{
DALI_LOG_ERROR("MeshVisual: property useMipmapping is the wrong type, use BOOLEAN\n");
}
}
case Toolkit::MeshVisual::Property::USE_SOFT_NORMALS:
{
- if( !value.Get( mUseSoftNormals ) )
+ if(!value.Get(mUseSoftNormals))
{
DALI_LOG_ERROR("MeshVisual: property useSoftNormals is the wrong type, use BOOLEAN\n");
}
}
case Toolkit::MeshVisual::Property::LIGHT_POSITION:
{
- if( !value.Get( mLightPosition ) )
+ if(!value.Get(mLightPosition))
{
mLightPosition = Vector3::ZERO;
DALI_LOG_ERROR("MeshVisual: property lightPosition is the wrong type, use VECTOR3\n");
void MeshVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
-void MeshVisual::DoSetOnScene( Actor& actor )
+void MeshVisual::DoSetOnScene(Actor& actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
// Mesh loaded and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
-void MeshVisual::DoCreatePropertyMap( Property::Map& map ) const
+void MeshVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::MESH );
- map.Insert( Toolkit::MeshVisual::Property::OBJECT_URL, mObjectUrl );
- map.Insert( Toolkit::MeshVisual::Property::MATERIAL_URL, mMaterialUrl );
- map.Insert( Toolkit::MeshVisual::Property::TEXTURES_PATH, mTexturesPath );
- map.Insert( Toolkit::MeshVisual::Property::SHADING_MODE, mShadingMode );
- map.Insert( Toolkit::MeshVisual::Property::USE_MIPMAPPING, mUseMipmapping );
- map.Insert( Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, mUseSoftNormals );
- map.Insert( Toolkit::MeshVisual::Property::LIGHT_POSITION, mLightPosition );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::MESH);
+ map.Insert(Toolkit::MeshVisual::Property::OBJECT_URL, mObjectUrl);
+ map.Insert(Toolkit::MeshVisual::Property::MATERIAL_URL, mMaterialUrl);
+ map.Insert(Toolkit::MeshVisual::Property::TEXTURES_PATH, mTexturesPath);
+ map.Insert(Toolkit::MeshVisual::Property::SHADING_MODE, mShadingMode);
+ map.Insert(Toolkit::MeshVisual::Property::USE_MIPMAPPING, mUseMipmapping);
+ map.Insert(Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, mUseSoftNormals);
+ map.Insert(Toolkit::MeshVisual::Property::LIGHT_POSITION, mLightPosition);
}
-void MeshVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void MeshVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
void MeshVisual::OnInitialize()
{
//Try to load the geometry from the file.
- if( !LoadGeometry() )
+ if(!LoadGeometry())
{
SupplyEmptyGeometry();
return;
}
//If a texture is used by the obj file, load the supplied material file.
- if( mObjLoader.IsTexturePresent() && !mMaterialUrl.empty() )
+ if(mObjLoader.IsTexturePresent() && !mMaterialUrl.empty())
{
- if( !LoadMaterial() )
+ if(!LoadMaterial())
{
SupplyEmptyGeometry();
return;
}
//Now that the required parts are loaded, create the geometry for the object.
- if( !CreateGeometry() )
+ if(!CreateGeometry())
{
SupplyEmptyGeometry();
return;
CreateShader();
//Load the various texture files supplied by the material file.
- if( !LoadTextures() )
+ if(!LoadTextures())
{
SupplyEmptyGeometry();
return;
}
- mImpl->mRenderer = Renderer::New( mGeometry, mShader );
- mImpl->mRenderer.SetTextures( mTextureSet );
- mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
- mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON );
+ mImpl->mRenderer = Renderer::New(mGeometry, mShader);
+ mImpl->mRenderer.SetTextures(mTextureSet);
+ mImpl->mRenderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON);
+ mImpl->mRenderer.SetProperty(Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON);
//Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
void MeshVisual::SupplyEmptyGeometry()
{
- mGeometry = Geometry::New();
- mShader = Shader::New( SHADER_MESH_VISUAL_SIMPLE_SHADER_VERT, SHADER_MESH_VISUAL_SIMPLE_SHADER_FRAG );
- mImpl->mRenderer = Renderer::New( mGeometry, mShader );
+ mGeometry = Geometry::New();
+ mShader = Shader::New(SHADER_MESH_VISUAL_SIMPLE_SHADER_VERT, SHADER_MESH_VISUAL_SIMPLE_SHADER_FRAG);
+ mImpl->mRenderer = Renderer::New(mGeometry, mShader);
- DALI_LOG_ERROR( "Initialisation error in mesh visual.\n" );
+ DALI_LOG_ERROR("Initialisation error in mesh visual.\n");
}
void MeshVisual::UpdateShaderUniforms()
{
- Stage stage = Stage::GetCurrent();
- float width = stage.GetSize().width;
+ Stage stage = Stage::GetCurrent();
+ float width = stage.GetSize().width;
float height = stage.GetSize().height;
Matrix scaleMatrix;
- scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) );
+ scaleMatrix.SetIdentityAndScale(Vector3(1.0, -1.0, 1.0));
- mShader.RegisterProperty( STAGE_OFFSET_UNIFORM_NAME, Vector2( width, height ) / 2.0f );
- mShader.RegisterProperty( LIGHT_POSITION_NAME, mLightPosition );
- mShader.RegisterProperty( OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix );
+ mShader.RegisterProperty(STAGE_OFFSET_UNIFORM_NAME, Vector2(width, height) / 2.0f);
+ mShader.RegisterProperty(LIGHT_POSITION_NAME, mLightPosition);
+ mShader.RegisterProperty(OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix);
}
void MeshVisual::CreateShader()
{
- if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
+ if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING)
{
- mShader = Shader::New( SHADER_MESH_VISUAL_NORMAL_MAP_SHADER_VERT, SHADER_MESH_VISUAL_NORMAL_MAP_SHADER_FRAG );
+ mShader = Shader::New(SHADER_MESH_VISUAL_NORMAL_MAP_SHADER_VERT, SHADER_MESH_VISUAL_NORMAL_MAP_SHADER_FRAG);
}
- else if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING )
+ else if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING)
{
- mShader = Shader::New( SHADER_MESH_VISUAL_SHADER_VERT, SHADER_MESH_VISUAL_SHADER_FRAG );
+ mShader = Shader::New(SHADER_MESH_VISUAL_SHADER_VERT, SHADER_MESH_VISUAL_SHADER_FRAG);
}
else //Textureless
{
- mShader = Shader::New( SHADER_MESH_VISUAL_SIMPLE_SHADER_VERT, SHADER_MESH_VISUAL_SIMPLE_SHADER_FRAG );
+ mShader = Shader::New(SHADER_MESH_VISUAL_SIMPLE_SHADER_VERT, SHADER_MESH_VISUAL_SIMPLE_SHADER_FRAG);
}
UpdateShaderUniforms();
bool MeshVisual::CreateGeometry()
{
//Determine if we need to use a simpler shader to handle the provided data
- if( !mUseTexture || !mObjLoader.IsDiffuseMapPresent() )
+ if(!mUseTexture || !mObjLoader.IsDiffuseMapPresent())
{
mShadingMode = Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING;
}
- else if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()) )
+ else if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()))
{
mShadingMode = Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING;
}
int objectProperties = 0;
- if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING ||
- mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
+ if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING ||
+ mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING)
{
objectProperties |= ObjLoader::TEXTURE_COORDINATES;
}
- if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING )
+ if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING)
{
objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS;
}
//Create geometry with attributes required by shader.
- mGeometry = mObjLoader.CreateGeometry( objectProperties, mUseSoftNormals );
+ mGeometry = mObjLoader.CreateGeometry(objectProperties, mUseSoftNormals);
- if( mGeometry )
+ if(mGeometry)
{
return true;
}
- DALI_LOG_ERROR( "Failed to load geometry in mesh visual.\n" );
+ DALI_LOG_ERROR("Failed to load geometry in mesh visual.\n");
return false;
}
bool MeshVisual::LoadGeometry()
{
- std::streampos fileSize;
+ std::streampos fileSize;
Dali::Vector<char> fileContent;
- if( FileLoader::ReadFile( mObjectUrl, fileSize, fileContent, FileLoader::TEXT ) )
+ if(FileLoader::ReadFile(mObjectUrl, fileSize, fileContent, FileLoader::TEXT))
{
mObjLoader.ClearArrays();
- mObjLoader.LoadObject( fileContent.Begin(), fileSize );
+ mObjLoader.LoadObject(fileContent.Begin(), fileSize);
//Get size information from the obj loaded
mSceneCenter = mObjLoader.GetCenter();
- mSceneSize = mObjLoader.GetSize();
+ mSceneSize = mObjLoader.GetSize();
return true;
}
- DALI_LOG_ERROR( "Failed to find object to load in mesh visual.\n" );
+ DALI_LOG_ERROR("Failed to find object to load in mesh visual.\n");
return false;
}
bool MeshVisual::LoadMaterial()
{
- std::streampos fileSize;
+ std::streampos fileSize;
Dali::Vector<char> fileContent;
- if( FileLoader::ReadFile( mMaterialUrl, fileSize, fileContent, FileLoader::TEXT ) )
+ if(FileLoader::ReadFile(mMaterialUrl, fileSize, fileContent, FileLoader::TEXT))
{
//Load data into obj (usable) form
- mObjLoader.LoadMaterial( fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl );
+ mObjLoader.LoadMaterial(fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl);
return true;
}
- DALI_LOG_ERROR( "Failed to find texture set to load in mesh visual.\n" );
+ DALI_LOG_ERROR("Failed to find texture set to load in mesh visual.\n");
mUseTexture = false;
return false;
}
{
mTextureSet = TextureSet::New();
- if( mShadingMode != Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING )
+ if(mShadingMode != Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING)
{
Sampler sampler = Sampler::New();
- if( mUseMipmapping )
+ if(mUseMipmapping)
{
- sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR );
+ sampler.SetFilterMode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR);
}
- if( !mDiffuseTextureUrl.empty() )
+ if(!mDiffuseTextureUrl.empty())
{
std::string imageUrl = mTexturesPath + mDiffuseTextureUrl;
//Load textures
- Texture diffuseTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
- if( diffuseTexture )
+ Texture diffuseTexture = LoadTexture(imageUrl.c_str(), mUseMipmapping);
+ if(diffuseTexture)
{
- mTextureSet.SetTexture( DIFFUSE_INDEX, diffuseTexture );
- mTextureSet.SetSampler( DIFFUSE_INDEX, sampler );
+ mTextureSet.SetTexture(DIFFUSE_INDEX, diffuseTexture);
+ mTextureSet.SetSampler(DIFFUSE_INDEX, sampler);
}
else
{
- DALI_LOG_ERROR( "Failed to load diffuse map texture in mesh visual.\n");
+ DALI_LOG_ERROR("Failed to load diffuse map texture in mesh visual.\n");
return false;
}
}
- if( !mNormalTextureUrl.empty() && ( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) )
+ if(!mNormalTextureUrl.empty() && (mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING))
{
std::string imageUrl = mTexturesPath + mNormalTextureUrl;
//Load textures
- Texture normalTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
- if( normalTexture )
+ Texture normalTexture = LoadTexture(imageUrl.c_str(), mUseMipmapping);
+ if(normalTexture)
{
- mTextureSet.SetTexture( NORMAL_INDEX, normalTexture );
- mTextureSet.SetSampler( NORMAL_INDEX, sampler );
+ mTextureSet.SetTexture(NORMAL_INDEX, normalTexture);
+ mTextureSet.SetSampler(NORMAL_INDEX, sampler);
}
else
{
- DALI_LOG_ERROR( "Failed to load normal map texture in mesh visual.\n");
+ DALI_LOG_ERROR("Failed to load normal map texture in mesh visual.\n");
return false;
}
}
- if( !mGlossTextureUrl.empty() && ( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) )
+ if(!mGlossTextureUrl.empty() && (mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING))
{
std::string imageUrl = mTexturesPath + mGlossTextureUrl;
//Load textures
- Texture glossTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping );
- if( glossTexture )
+ Texture glossTexture = LoadTexture(imageUrl.c_str(), mUseMipmapping);
+ if(glossTexture)
{
- mTextureSet.SetTexture( GLOSS_INDEX, glossTexture );
- mTextureSet.SetSampler( GLOSS_INDEX, sampler );
+ mTextureSet.SetTexture(GLOSS_INDEX, glossTexture);
+ mTextureSet.SetSampler(GLOSS_INDEX, sampler);
}
else
{
- DALI_LOG_ERROR( "Failed to load gloss map texture in mesh visual.\n");
+ DALI_LOG_ERROR("Failed to load gloss map texture in mesh visual.\n");
return false;
}
}
- /*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
NPatchData::NPatchData()
: mId(INVALID_NPATCH_DATA_ID),
mUrl(),
NPatchData::~NPatchData()
{
// If there is an opacity map, it has to be destroyed using addon call
- if( mRenderingMap )
+ if(mRenderingMap)
{
- RenderingAddOn::Get().DestroyNPatch( mRenderingMap );
+ RenderingAddOn::Get().DestroyNPatch(mRenderingMap);
}
}
void NPatchData::AddObserver(TextureUploadObserver* textureObserver)
{
- mObserverList.PushBack( textureObserver );
+ mObserverList.PushBack(textureObserver);
}
void NPatchData::RemoveObserver(TextureUploadObserver* textureObserver)
{
- for(uint32_t index = 0; index < mObserverList.Count(); ++index )
+ for(uint32_t index = 0; index < mObserverList.Count(); ++index)
{
if(textureObserver == mObserverList[index])
{
- mObserverList.Erase( mObserverList.begin() + index );
+ mObserverList.Erase(mObserverList.begin() + index);
break;
}
}
return mRenderingMap;
}
-void NPatchData::SetLoadedNPatchData( Devel::PixelBuffer& pixelBuffer, bool preMultiplied )
+void NPatchData::SetLoadedNPatchData(Devel::PixelBuffer& pixelBuffer, bool preMultiplied)
{
- if( mBorder == Rect< int >( 0, 0, 0, 0 ) )
+ if(mBorder == Rect<int>(0, 0, 0, 0))
{
- NPatchUtility::ParseBorders( pixelBuffer, mStretchPixelsX, mStretchPixelsY );
+ NPatchUtility::ParseBorders(pixelBuffer, mStretchPixelsX, mStretchPixelsY);
// Crop the image
- pixelBuffer.Crop( 1, 1, pixelBuffer.GetWidth() - 2, pixelBuffer.GetHeight() - 2 );
+ pixelBuffer.Crop(1, 1, pixelBuffer.GetWidth() - 2, pixelBuffer.GetHeight() - 2);
}
else
{
- mStretchPixelsX.PushBack( Uint16Pair( mBorder.left, ( (pixelBuffer.GetWidth() >= static_cast< unsigned int >( mBorder.right )) ? pixelBuffer.GetWidth() - mBorder.right : 0 ) ) );
- mStretchPixelsY.PushBack( Uint16Pair( mBorder.top, ( (pixelBuffer.GetHeight() >= static_cast< unsigned int >( mBorder.bottom )) ? pixelBuffer.GetHeight() - mBorder.bottom : 0 ) ) );
+ mStretchPixelsX.PushBack(Uint16Pair(mBorder.left, ((pixelBuffer.GetWidth() >= static_cast<unsigned int>(mBorder.right)) ? pixelBuffer.GetWidth() - mBorder.right : 0)));
+ mStretchPixelsY.PushBack(Uint16Pair(mBorder.top, ((pixelBuffer.GetHeight() >= static_cast<unsigned int>(mBorder.bottom)) ? pixelBuffer.GetHeight() - mBorder.bottom : 0)));
}
- mCroppedWidth = pixelBuffer.GetWidth();
+ mCroppedWidth = pixelBuffer.GetWidth();
mCroppedHeight = pixelBuffer.GetHeight();
// Create opacity map
mRenderingMap = RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().BuildNPatch(pixelBuffer, this) : nullptr;
- PixelData pixels = Devel::PixelBuffer::Convert( pixelBuffer ); // takes ownership of buffer
+ PixelData pixels = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
- Texture texture = Texture::New( TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight() );
- texture.Upload( pixels );
+ Texture texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight());
+ texture.Upload(pixels);
mTextureSet = TextureSet::New();
- mTextureSet.SetTexture( 0u, texture );
+ mTextureSet.SetTexture(0u, texture);
mPreMultiplyOnLoad = preMultiplied;
mLoadingState = LoadingState::LOAD_COMPLETE;
}
-void NPatchData::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied )
+void NPatchData::LoadComplete(bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied)
{
if(loadSuccess)
{
- SetLoadedNPatchData( pixelBuffer, preMultiplied );
+ SetLoadedNPatchData(pixelBuffer, preMultiplied);
}
else
{
- /*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
constexpr auto INVALID_CACHE_INDEX = int32_t{-1}; ///< Invalid Cache index
-constexpr auto UNINITIALIZED_ID = int32_t{0}; ///< uninitialised id, use to initialize ids
+constexpr auto UNINITIALIZED_ID = int32_t{0}; ///< uninitialised id, use to initialize ids
} // Anonymous namespace
return mCurrentNPatchDataId++;
}
-std::size_t NPatchLoader::Load( TextureManager& textureManager, TextureUploadObserver* textureObserver, const std::string& url, const Rect< int >& border, bool& preMultiplyOnLoad, bool synchronousLoading )
+std::size_t NPatchLoader::Load(TextureManager& textureManager, TextureUploadObserver* textureObserver, const std::string& url, const Rect<int>& border, bool& preMultiplyOnLoad, bool synchronousLoading)
{
- std::size_t hash = CalculateHash( url );
- OwnerContainer< NPatchData* >::SizeType index = UNINITIALIZED_ID;
- const OwnerContainer< NPatchData* >::SizeType count = mCache.Count();
+ std::size_t hash = CalculateHash(url);
+ OwnerContainer<NPatchData*>::SizeType index = UNINITIALIZED_ID;
+ const OwnerContainer<NPatchData*>::SizeType count = mCache.Count();
- for( ; index < count; ++index )
+ for(; index < count; ++index)
{
- if( mCache[ index ]->GetHash() == hash )
+ if(mCache[index]->GetHash() == hash)
{
// hash match, check url as well in case of hash collision
- if(mCache[ index ]->GetUrl() == url)
+ if(mCache[index]->GetUrl() == url)
{
// Use cached data
- if( mCache[ index ]->GetBorder() == border )
+ if(mCache[index]->GetBorder() == border)
{
- if( mCache[ index ]->GetLoadingState() == NPatchData::LoadingState::LOADING )
+ if(mCache[index]->GetLoadingState() == NPatchData::LoadingState::LOADING)
{
- mCache[ index ]->AddObserver( textureObserver );
+ mCache[index]->AddObserver(textureObserver);
}
- return mCache[ index ]->GetId(); // valid indices are from 1 onwards
+ return mCache[index]->GetId(); // valid indices are from 1 onwards
}
else
{
- if( mCache[ index ]->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE )
+ if(mCache[index]->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
{
// Same url but border is different - use the existing texture
NPatchData* newData = new NPatchData();
newData->SetId(GenerateUniqueNPatchDataId());
newData->SetHash(hash);
newData->SetUrl(url);
- newData->SetCroppedWidth(mCache[ index ]->GetCroppedWidth());
- newData->SetCroppedHeight(mCache[ index ]->GetCroppedHeight());
+ newData->SetCroppedWidth(mCache[index]->GetCroppedWidth());
+ newData->SetCroppedHeight(mCache[index]->GetCroppedHeight());
- newData->SetTextures(mCache[ index ]->GetTextures());
+ newData->SetTextures(mCache[index]->GetTextures());
NPatchUtility::StretchRanges stretchRangesX;
- stretchRangesX.PushBack( Uint16Pair( border.left, ( (newData->GetCroppedWidth() >= static_cast< unsigned int >( border.right )) ? newData->GetCroppedHeight() - border.right : 0 ) ) );
+ stretchRangesX.PushBack(Uint16Pair(border.left, ((newData->GetCroppedWidth() >= static_cast<unsigned int>(border.right)) ? newData->GetCroppedHeight() - border.right : 0)));
NPatchUtility::StretchRanges stretchRangesY;
- stretchRangesY.PushBack( Uint16Pair( border.top, ( (newData->GetCroppedWidth() >= static_cast< unsigned int >( border.bottom )) ? newData->GetCroppedHeight() - border.bottom : 0 ) ) );
+ stretchRangesY.PushBack(Uint16Pair(border.top, ((newData->GetCroppedWidth() >= static_cast<unsigned int>(border.bottom)) ? newData->GetCroppedHeight() - border.bottom : 0)));
newData->SetStretchPixelsX(stretchRangesX);
newData->SetStretchPixelsY(stretchRangesY);
newData->SetBorder(border);
- newData->SetPreMultiplyOnLoad(mCache[ index ]->IsPreMultiplied());
+ newData->SetPreMultiplyOnLoad(mCache[index]->IsPreMultiplied());
newData->SetLoadingState(NPatchData::LoadingState::LOAD_COMPLETE);
- newData->AddObserver( textureObserver );
+ newData->AddObserver(textureObserver);
- mCache.PushBack( newData );
+ mCache.PushBack(newData);
return newData->GetId(); // valid ids start from 1u
}
auto preMultiplyOnLoading = preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD
: TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
- Devel::PixelBuffer pixelBuffer = textureManager.LoadPixelBuffer( url, Dali::ImageDimensions(), FittingMode::DEFAULT,
- SamplingMode::BOX_THEN_LINEAR, synchronousLoading,
- data, true, preMultiplyOnLoading );
+ Devel::PixelBuffer pixelBuffer = textureManager.LoadPixelBuffer(url, Dali::ImageDimensions(), FittingMode::DEFAULT, SamplingMode::BOX_THEN_LINEAR, synchronousLoading, data, true, preMultiplyOnLoading);
- if( pixelBuffer )
+ if(pixelBuffer)
{
- preMultiplyOnLoad = ( preMultiplyOnLoading == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD ) ? true : false;
- data->SetLoadedNPatchData( pixelBuffer, preMultiplyOnLoad );
+ preMultiplyOnLoad = (preMultiplyOnLoading == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD) ? true : false;
+ data->SetLoadedNPatchData(pixelBuffer, preMultiplyOnLoad);
}
return data->GetId();
}
-int32_t NPatchLoader::GetCacheIndexFromId( const NPatchData::NPatchDataId id )
+int32_t NPatchLoader::GetCacheIndexFromId(const NPatchData::NPatchDataId id)
{
const unsigned int size = mCache.Count();
- for( unsigned int i = 0; i < size; ++i )
+ for(unsigned int i = 0; i < size; ++i)
{
- if( mCache[i]->GetId() == id )
+ if(mCache[i]->GetId() == id)
{
return i;
}
return INVALID_CACHE_INDEX;
}
-bool NPatchLoader::GetNPatchData( const NPatchData::NPatchDataId id, const NPatchData*& data )
+bool NPatchLoader::GetNPatchData(const NPatchData::NPatchDataId id, const NPatchData*& data)
{
int32_t cacheIndex = GetCacheIndexFromId(id);
- if( cacheIndex != INVALID_CACHE_INDEX )
+ if(cacheIndex != INVALID_CACHE_INDEX)
{
data = mCache[cacheIndex];
return true;
return false;
}
-void NPatchLoader::Remove( std::size_t id, TextureUploadObserver* textureObserver )
+void NPatchLoader::Remove(std::size_t id, TextureUploadObserver* textureObserver)
{
int32_t cacheIndex = GetCacheIndexFromId(id);
- if( cacheIndex == INVALID_CACHE_INDEX )
+ if(cacheIndex == INVALID_CACHE_INDEX)
{
return;
}
if(data->GetObserverCount() == 0)
{
- mCache.Erase( mCache.Begin() + cacheIndex );
+ mCache.Erase(mCache.Begin() + cacheIndex);
}
}
#include "npatch-visual.h"
// EXTERNAL INCLUDES
-#include <dali/devel-api/rendering/renderer-devel.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
+#include <dali/devel-api/rendering/renderer-devel.h>
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
/**
* @brief Creates the geometry formed from the vertices and indices
*
* @param[in] indices The indices to generate the geometry from
* @return The geometry formed from the vertices and indices
*/
-Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
+Geometry GenerateGeometry(const Vector<Vector2>& vertices, const Vector<unsigned short>& indices)
{
Property::Map vertexFormat;
- vertexFormat[ "aPosition" ] = Property::VECTOR2;
- VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat );
- if( vertices.Size() > 0 )
+ vertexFormat["aPosition"] = Property::VECTOR2;
+ VertexBuffer vertexBuffer = VertexBuffer::New(vertexFormat);
+ if(vertices.Size() > 0)
{
- vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() );
+ vertexBuffer.SetData(&vertices[0], vertices.Size());
}
// Create the geometry object
Geometry geometry = Geometry::New();
- geometry.AddVertexBuffer( vertexBuffer );
- if( indices.Size() > 0 )
+ geometry.AddVertexBuffer(vertexBuffer);
+ if(indices.Size() > 0)
{
- geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
+ geometry.SetIndexBuffer(&indices[0], indices.Size());
}
-
return geometry;
}
* @param[in] rowIdx The row index to start the quad
* @param[in] nextRowIdx The index to the next row
*/
-void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
+void AddQuadIndices(Vector<unsigned short>& indices, unsigned int rowIdx, unsigned int nextRowIdx)
{
- indices.PushBack( rowIdx );
- indices.PushBack( nextRowIdx + 1 );
- indices.PushBack( rowIdx + 1 );
+ indices.PushBack(rowIdx);
+ indices.PushBack(nextRowIdx + 1);
+ indices.PushBack(rowIdx + 1);
- indices.PushBack( rowIdx );
- indices.PushBack( nextRowIdx );
- indices.PushBack( nextRowIdx + 1 );
+ indices.PushBack(rowIdx);
+ indices.PushBack(nextRowIdx);
+ indices.PushBack(nextRowIdx + 1);
}
-void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
+void AddVertex(Vector<Vector2>& vertices, unsigned int x, unsigned int y)
{
- vertices.PushBack( Vector2( x, y ) );
+ vertices.PushBack(Vector2(x, y));
}
-void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NPatchUtility::StretchRanges& stretchPixels, uint16_t imageExtent)
+void RegisterStretchProperties(Renderer& renderer, const char* uniformName, const NPatchUtility::StretchRanges& stretchPixels, uint16_t imageExtent)
{
- uint16_t prevEnd = 0;
- uint16_t prevFix = 0;
- uint16_t prevStretch = 0;
- unsigned int i = 1;
- for( NPatchUtility::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
+ uint16_t prevEnd = 0;
+ uint16_t prevFix = 0;
+ uint16_t prevStretch = 0;
+ unsigned int i = 1;
+ for(NPatchUtility::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i)
{
uint16_t start = it->GetX();
- uint16_t end = it->GetY();
+ uint16_t end = it->GetY();
- uint16_t fix = prevFix + start - prevEnd;
+ uint16_t fix = prevFix + start - prevEnd;
uint16_t stretch = prevStretch + end - start;
std::stringstream uniform;
uniform << uniformName << "[" << i << "]";
- renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
+ renderer.RegisterProperty(uniform.str(), Vector2(fix, stretch));
- prevEnd = end;
- prevFix = fix;
+ prevEnd = end;
+ prevFix = fix;
prevStretch = stretch;
}
prevFix += imageExtent - prevEnd;
std::stringstream uniform;
uniform << uniformName << "[" << i << "]";
- renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
+ renderer.RegisterProperty(uniform.str(), Vector2(prevFix, prevStretch));
}
}
{
NPatchVisualPtr nPatchVisual(new NPatchVisual(factoryCache, shaderFactory));
nPatchVisual->mImageUrl = imageUrl;
- nPatchVisual->SetProperties( properties );
+ nPatchVisual->SetProperties(properties);
nPatchVisual->Initialize();
return nPatchVisual;
}
void NPatchVisual::LoadImages()
{
- TextureManager& textureManager = mFactoryCache.GetTextureManager();
- bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
+ TextureManager& textureManager = mFactoryCache.GetTextureManager();
+ bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
- if( mId == NPatchData::INVALID_NPATCH_DATA_ID && mImageUrl.IsLocalResource() )
+ if(mId == NPatchData::INVALID_NPATCH_DATA_ID && mImageUrl.IsLocalResource())
{
bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false;
- mId = mLoader.Load( textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading );
+ mId = mLoader.Load(textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading);
const NPatchData* data;
- if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE )
+ if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
{
- EnablePreMultipliedAlpha( data->IsPreMultiplied() );
+ EnablePreMultipliedAlpha(data->IsPreMultiplied());
}
}
- if( !mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource() )
+ if(!mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource())
{
// Load the auxiliary image
auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
- mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer( mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT,
- SamplingMode::BOX_THEN_LINEAR, synchronousLoading,
- this, true, preMultiplyOnLoading );
+ mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer(mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT, SamplingMode::BOX_THEN_LINEAR, synchronousLoading, this, true, preMultiplyOnLoading);
}
}
-void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
+void NPatchVisual::GetNaturalSize(Vector2& naturalSize)
{
naturalSize.x = 0u;
naturalSize.y = 0u;
// load now if not already loaded
const NPatchData* data;
- if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() != NPatchData::LoadingState::LOADING )
+ if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() != NPatchData::LoadingState::LOADING)
{
naturalSize.x = data->GetCroppedWidth();
naturalSize.y = data->GetCroppedHeight();
}
else
{
- if( mImageUrl.IsValid() )
+ if(mImageUrl.IsValid())
{
- ImageDimensions dimensions = Dali::GetOriginalImageSize( mImageUrl.GetUrl() );
- if( dimensions != ImageDimensions( 0, 0 ) )
+ ImageDimensions dimensions = Dali::GetOriginalImageSize(mImageUrl.GetUrl());
+ if(dimensions != ImageDimensions(0, 0))
{
naturalSize.x = dimensions.GetWidth();
naturalSize.y = dimensions.GetHeight();
}
}
- if( mAuxiliaryPixelBuffer )
+ if(mAuxiliaryPixelBuffer)
{
- naturalSize.x = std::max( naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()) );
- naturalSize.y = std::max( naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()) );
+ naturalSize.x = std::max(naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()));
+ naturalSize.y = std::max(naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()));
}
}
-void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
+void NPatchVisual::DoSetProperties(const Property::Map& propertyMap)
{
// URL is already passed in via constructor
- Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
- if( borderOnlyValue )
+ Property::Value* borderOnlyValue = propertyMap.Find(Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY);
+ if(borderOnlyValue)
{
- borderOnlyValue->Get( mBorderOnly );
+ borderOnlyValue->Get(mBorderOnly);
}
- Property::Value* borderValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER, BORDER );
- if( borderValue && ! borderValue->Get( mBorder ) ) // If value exists and is rect, just set mBorder
+ Property::Value* borderValue = propertyMap.Find(Toolkit::ImageVisual::Property::BORDER, BORDER);
+ if(borderValue && !borderValue->Get(mBorder)) // If value exists and is rect, just set mBorder
{
// Not a rect so try vector4
Vector4 border;
- if( borderValue->Get( border ) )
+ if(borderValue->Get(border))
{
- mBorder.left = static_cast< int >( border.x );
- mBorder.right = static_cast< int >( border.y );
- mBorder.bottom = static_cast< int >( border.z );
- mBorder.top = static_cast< int >( border.w );
+ mBorder.left = static_cast<int>(border.x);
+ mBorder.right = static_cast<int>(border.y);
+ mBorder.bottom = static_cast<int>(border.z);
+ mBorder.top = static_cast<int>(border.w);
}
}
- Property::Value* auxImage = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME );
- if( auxImage )
+ Property::Value* auxImage = propertyMap.Find(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME);
+ if(auxImage)
{
std::string url;
- if( auxImage->Get( url ) )
+ if(auxImage->Get(url))
{
mAuxiliaryUrl = url;
}
}
- Property::Value* auxImageAlpha = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME );
- if( auxImageAlpha )
+ Property::Value* auxImageAlpha = propertyMap.Find(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME);
+ if(auxImageAlpha)
{
- auxImageAlpha->Get( mAuxiliaryImageAlpha );
+ auxImageAlpha->Get(mAuxiliaryImageAlpha);
}
- Property::Value* synchronousLoading = propertyMap.Find( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING );
- if( synchronousLoading )
+ Property::Value* synchronousLoading = propertyMap.Find(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING);
+ if(synchronousLoading)
{
bool sync = false;
- synchronousLoading->Get( sync );
- if( sync )
+ synchronousLoading->Get(sync);
+ if(sync)
{
mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
}
}
}
- Property::Value* releasePolicy = propertyMap.Find( Toolkit::ImageVisual::Property::RELEASE_POLICY, RELEASE_POLICY_NAME );
- if( releasePolicy )
+ Property::Value* releasePolicy = propertyMap.Find(Toolkit::ImageVisual::Property::RELEASE_POLICY, RELEASE_POLICY_NAME);
+ if(releasePolicy)
{
- releasePolicy->Get( mReleasePolicy );
+ releasePolicy->Get(mReleasePolicy);
}
}
-void NPatchVisual::DoSetOnScene( Actor& actor )
+void NPatchVisual::DoSetOnScene(Actor& actor)
{
// load when first go on stage
LoadImages();
const NPatchData* data;
- if( mLoader.GetNPatchData( mId, data ) )
+ if(mLoader.GetNPatchData(mId, data))
{
Geometry geometry = CreateGeometry();
- Shader shader = CreateShader();
+ Shader shader = CreateShader();
mImpl->mRenderer.SetGeometry(geometry);
mImpl->mRenderer.SetShader(shader);
mPlacementActor = actor;
- if( data->GetLoadingState() != NPatchData::LoadingState::LOADING )
+ if(data->GetLoadingState() != NPatchData::LoadingState::LOADING)
{
- if( RenderingAddOn::Get().IsValid() )
+ if(RenderingAddOn::Get().IsValid())
{
- RenderingAddOn::Get().SubmitRenderTask( mImpl->mRenderer, data->GetRenderingMap() );
+ RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
}
ApplyTextureAndUniforms();
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
mPlacementActor.Reset();
// npatch loaded and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
}
}
-void NPatchVisual::DoSetOffScene( Actor& actor )
+void NPatchVisual::DoSetOffScene(Actor& actor)
{
if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED)
{
mLoader.Remove(mId, this);
mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING;
- mId = NPatchData::INVALID_NPATCH_DATA_ID;
+ mId = NPatchData::INVALID_NPATCH_DATA_ID;
}
- actor.RemoveRenderer( mImpl->mRenderer );
+ actor.RemoveRenderer(mImpl->mRenderer);
mPlacementActor.Reset();
}
void NPatchVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
-void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
+void NPatchVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
bool sync = IsSynchronousLoadingRequired();
- map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync );
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH );
- map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
- map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
- map.Insert( Toolkit::ImageVisual::Property::BORDER, mBorder );
- map.Insert( Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy );
+ map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync);
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH);
+ map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
+ map.Insert(Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly);
+ map.Insert(Toolkit::ImageVisual::Property::BORDER, mBorder);
+ map.Insert(Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy);
- if( mAuxiliaryUrl.IsValid() )
+ if(mAuxiliaryUrl.IsValid())
{
- map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
- map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
+ map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl());
+ map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha);
}
}
-void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void NPatchVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
- if( mAuxiliaryUrl.IsValid() )
+ if(mAuxiliaryUrl.IsValid())
{
- map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
- map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
+ map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl());
+ map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha);
}
}
mAuxiliaryImageAlpha(0.0f),
mReleasePolicy(Toolkit::ImageVisual::ReleasePolicy::DETACHED)
{
- EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
+ EnablePreMultipliedAlpha(mFactoryCache.GetPreMultiplyOnLoad());
}
NPatchVisual::~NPatchVisual()
{
- if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && ( mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER ))
+ if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && (mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER))
{
mLoader.Remove(mId, this);
mId = NPatchData::INVALID_NPATCH_DATA_ID;
Geometry NPatchVisual::CreateGeometry()
{
- Geometry geometry;
+ Geometry geometry;
const NPatchData* data;
- if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE )
+ if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
{
- if( data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1 )
+ if(data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1)
{
- if( DALI_UNLIKELY( mBorderOnly ) )
+ if(DALI_UNLIKELY(mBorderOnly))
{
- geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
+ geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY);
}
else
{
- if( data->GetRenderingMap() )
+ if(data->GetRenderingMap())
{
uint32_t elementCount[2];
- geometry = RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), Uint16Pair(3, 3), elementCount );
- if( mImpl->mRenderer )
+ geometry = RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), Uint16Pair(3, 3), elementCount);
+ if(mImpl->mRenderer)
{
RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
}
}
else
{
- geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
+ geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_GEOMETRY);
}
}
}
- else if( data->GetStretchPixelsX().Size() > 0 || data->GetStretchPixelsY().Size() > 0)
+ else if(data->GetStretchPixelsX().Size() > 0 || data->GetStretchPixelsY().Size() > 0)
{
- Uint16Pair gridSize( 2 * data->GetStretchPixelsX().Size() + 1, 2 * data->GetStretchPixelsY().Size() + 1 );
- if( !data->GetRenderingMap() )
+ Uint16Pair gridSize(2 * data->GetStretchPixelsX().Size() + 1, 2 * data->GetStretchPixelsY().Size() + 1);
+ if(!data->GetRenderingMap())
{
- geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
+ geometry = !mBorderOnly ? CreateGridGeometry(gridSize) : CreateBorderGeometry(gridSize);
}
else
{
uint32_t elementCount[2];
- geometry = !mBorderOnly ?
- RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), gridSize, elementCount ) : CreateBorderGeometry(gridSize );
- if( mImpl->mRenderer )
+ geometry = !mBorderOnly ? RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), gridSize, elementCount) : CreateBorderGeometry(gridSize);
+ if(mImpl->mRenderer)
{
RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
}
else
{
// no N patch data so use default geometry
- geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
+ geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_GEOMETRY);
}
return geometry;
}
Shader NPatchVisual::CreateShader()
{
- Shader shader;
+ Shader shader;
const NPatchData* data;
// 0 is either no data (load failed?) or no stretch regions on image
// for both cases we use the default shader
auto fragmentShader = mAuxiliaryPixelBuffer ? SHADER_NPATCH_VISUAL_MASK_SHADER_FRAG
: SHADER_NPATCH_VISUAL_SHADER_FRAG;
- auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER
- : VisualFactoryCache::NINE_PATCH_SHADER;
+ auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER
+ : VisualFactoryCache::NINE_PATCH_SHADER;
// ask loader for the regions
- if( mLoader.GetNPatchData( mId, data ) )
+ if(mLoader.GetNPatchData(mId, data))
{
xStretchCount = data->GetStretchPixelsX().Count();
yStretchCount = data->GetStretchPixelsY().Count();
}
- if( DALI_LIKELY( !mImpl->mCustomShader ) )
+ if(DALI_LIKELY(!mImpl->mCustomShader))
{
- if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) ||
- ( xStretchCount == 0 && yStretchCount == 0 ) ) )
+ if(DALI_LIKELY((xStretchCount == 1 && yStretchCount == 1) ||
+ (xStretchCount == 0 && yStretchCount == 0)))
{
- shader = mFactoryCache.GetShader( shaderType );
- if( DALI_UNLIKELY( !shader ) )
+ shader = mFactoryCache.GetShader(shaderType);
+ if(DALI_UNLIKELY(!shader))
{
- shader = Shader::New( SHADER_NPATCH_VISUAL_3X3_SHADER_VERT, fragmentShader );
+ shader = Shader::New(SHADER_NPATCH_VISUAL_3X3_SHADER_VERT, fragmentShader);
// Only cache vanilla 9 patch shaders
- mFactoryCache.SaveShader( shaderType, shader );
+ mFactoryCache.SaveShader(shaderType, shader);
}
}
- else if( xStretchCount > 0 || yStretchCount > 0)
+ else if(xStretchCount > 0 || yStretchCount > 0)
{
std::stringstream vertexShader;
vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
<< "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
<< SHADER_NPATCH_VISUAL_SHADER_VERT;
- shader = Shader::New( vertexShader.str(), fragmentShader );
+ shader = Shader::New(vertexShader.str(), fragmentShader);
}
}
else
{
Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
- if( !mImpl->mCustomShader->mFragmentShader.empty() )
+ if(!mImpl->mCustomShader->mFragmentShader.empty())
{
fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
}
hints = mImpl->mCustomShader->mHints;
/* Apply Custom Vertex Shader only if image is 9-patch */
- if( ( xStretchCount == 1 && yStretchCount == 1 ) ||
- ( xStretchCount == 0 && yStretchCount == 0 ) )
+ if((xStretchCount == 1 && yStretchCount == 1) ||
+ (xStretchCount == 0 && yStretchCount == 0))
{
const char* vertexShader = SHADER_NPATCH_VISUAL_3X3_SHADER_VERT.data();
- if( !mImpl->mCustomShader->mVertexShader.empty() )
+ if(!mImpl->mCustomShader->mVertexShader.empty())
{
vertexShader = mImpl->mCustomShader->mVertexShader.c_str();
}
- shader = Shader::New( vertexShader, fragmentShader, hints );
+ shader = Shader::New(vertexShader, fragmentShader, hints);
}
- else if( xStretchCount > 0 || yStretchCount > 0)
+ else if(xStretchCount > 0 || yStretchCount > 0)
{
std::stringstream vertexShader;
vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
<< "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
<< SHADER_NPATCH_VISUAL_SHADER_VERT;
- shader = Shader::New( vertexShader.str(), fragmentShader, hints );
+ shader = Shader::New(vertexShader.str(), fragmentShader, hints);
}
}
void NPatchVisual::ApplyTextureAndUniforms()
{
const NPatchData* data;
- TextureSet textureSet;
+ TextureSet textureSet;
- if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE )
+ if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
{
textureSet = data->GetTextures();
- if( data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1 )
+ if(data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1)
{
//special case for 9 patch
- Uint16Pair stretchX = data->GetStretchPixelsX()[ 0 ];
- Uint16Pair stretchY = data->GetStretchPixelsY()[ 0 ];
+ Uint16Pair stretchX = data->GetStretchPixelsX()[0];
+ Uint16Pair stretchY = data->GetStretchPixelsY()[0];
- uint16_t stretchWidth = ( stretchX.GetY() >= stretchX.GetX() ) ? stretchX.GetY() - stretchX.GetX() : 0;
- uint16_t stretchHeight = ( stretchY.GetY() >= stretchY.GetX() ) ? stretchY.GetY() - stretchY.GetX() : 0;
+ uint16_t stretchWidth = (stretchX.GetY() >= stretchX.GetX()) ? stretchX.GetY() - stretchX.GetX() : 0;
+ uint16_t stretchHeight = (stretchY.GetY() >= stretchY.GetX()) ? stretchY.GetY() - stretchY.GetX() : 0;
- mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
- mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
- mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->GetCroppedWidth() - stretchWidth, data->GetCroppedHeight() - stretchHeight ) );
- mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
+ mImpl->mRenderer.RegisterProperty("uFixed[0]", Vector2::ZERO);
+ mImpl->mRenderer.RegisterProperty("uFixed[1]", Vector2(stretchX.GetX(), stretchY.GetX()));
+ mImpl->mRenderer.RegisterProperty("uFixed[2]", Vector2(data->GetCroppedWidth() - stretchWidth, data->GetCroppedHeight() - stretchHeight));
+ mImpl->mRenderer.RegisterProperty("uStretchTotal", Vector2(stretchWidth, stretchHeight));
}
else
{
- mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
- mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
+ mImpl->mRenderer.RegisterProperty("uNinePatchFactorsX[0]", Vector2::ZERO);
+ mImpl->mRenderer.RegisterProperty("uNinePatchFactorsY[0]", Vector2::ZERO);
- RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->GetStretchPixelsX(), data->GetCroppedWidth() );
- RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->GetStretchPixelsY(), data->GetCroppedHeight() );
+ RegisterStretchProperties(mImpl->mRenderer, "uNinePatchFactorsX", data->GetStretchPixelsX(), data->GetCroppedWidth());
+ RegisterStretchProperties(mImpl->mRenderer, "uNinePatchFactorsY", data->GetStretchPixelsY(), data->GetCroppedHeight());
}
}
else
{
- DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str() );
+ DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str());
textureSet = TextureSet::New();
Texture croppedImage = mFactoryCache.GetBrokenVisualImage();
- textureSet.SetTexture( 0u, croppedImage );
- mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
- mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
- mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
- mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) );
+ textureSet.SetTexture(0u, croppedImage);
+ mImpl->mRenderer.RegisterProperty("uFixed[0]", Vector2::ZERO);
+ mImpl->mRenderer.RegisterProperty("uFixed[1]", Vector2::ZERO);
+ mImpl->mRenderer.RegisterProperty("uFixed[2]", Vector2::ZERO);
+ mImpl->mRenderer.RegisterProperty("uStretchTotal", Vector2(croppedImage.GetWidth(), croppedImage.GetHeight()));
}
- if( mAuxiliaryPixelBuffer )
+ if(mAuxiliaryPixelBuffer)
{
// If the auxiliary image is smaller than the un-stretched NPatch, use CPU resizing to enlarge it to the
// same size as the unstretched NPatch. This will give slightly higher quality results than just relying
// on GL interpolation alone.
- if( mAuxiliaryPixelBuffer.GetWidth() < data->GetCroppedWidth() &&
- mAuxiliaryPixelBuffer.GetHeight() < data->GetCroppedHeight() )
+ if(mAuxiliaryPixelBuffer.GetWidth() < data->GetCroppedWidth() &&
+ mAuxiliaryPixelBuffer.GetHeight() < data->GetCroppedHeight())
{
- mAuxiliaryPixelBuffer.Resize( data->GetCroppedWidth(), data->GetCroppedHeight() );
+ mAuxiliaryPixelBuffer.Resize(data->GetCroppedWidth(), data->GetCroppedHeight());
}
// Note, this resets mAuxiliaryPixelBuffer handle
- auto auxiliaryPixelData = Devel::PixelBuffer::Convert( mAuxiliaryPixelBuffer );
+ auto auxiliaryPixelData = Devel::PixelBuffer::Convert(mAuxiliaryPixelBuffer);
- auto texture = Texture::New( TextureType::TEXTURE_2D,
- auxiliaryPixelData.GetPixelFormat(), auxiliaryPixelData.GetWidth(),
- auxiliaryPixelData.GetHeight() );
- texture.Upload( auxiliaryPixelData );
- textureSet.SetTexture( 1, texture );
- mImpl->mRenderer.RegisterProperty( DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
- AUXILIARY_IMAGE_ALPHA_NAME, mAuxiliaryImageAlpha );
+ auto texture = Texture::New(TextureType::TEXTURE_2D,
+ auxiliaryPixelData.GetPixelFormat(),
+ auxiliaryPixelData.GetWidth(),
+ auxiliaryPixelData.GetHeight());
+ texture.Upload(auxiliaryPixelData);
+ textureSet.SetTexture(1, texture);
+ mImpl->mRenderer.RegisterProperty(DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
+ AUXILIARY_IMAGE_ALPHA_NAME,
+ mAuxiliaryImageAlpha);
}
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
// Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
-Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType )
+Geometry NPatchVisual::GetNinePatchGeometry(VisualFactoryCache::GeometryType subType)
{
- Geometry geometry = mFactoryCache.GetGeometry( subType );
- if( !geometry )
+ Geometry geometry = mFactoryCache.GetGeometry(subType);
+ if(!geometry)
{
- if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) )
+ if(DALI_LIKELY(VisualFactoryCache::NINE_PATCH_GEOMETRY == subType))
{
- geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) );
+ geometry = CreateGridGeometry(Uint16Pair(3, 3));
}
- else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType )
+ else if(VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType)
{
- geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) );
+ geometry = CreateBorderGeometry(Uint16Pair(3, 3));
}
- mFactoryCache.SaveGeometry( subType, geometry );
+ mFactoryCache.SaveGeometry(subType, geometry);
}
return geometry;
}
-Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize )
+Geometry NPatchVisual::CreateGridGeometry(Uint16Pair gridSize)
{
- uint16_t gridWidth = gridSize.GetWidth();
+ uint16_t gridWidth = gridSize.GetWidth();
uint16_t gridHeight = gridSize.GetHeight();
// Create vertices
- Vector< Vector2 > vertices;
- vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
+ Vector<Vector2> vertices;
+ vertices.Reserve((gridWidth + 1) * (gridHeight + 1));
- for( int y = 0; y < gridHeight + 1; ++y )
+ for(int y = 0; y < gridHeight + 1; ++y)
{
- for( int x = 0; x < gridWidth + 1; ++x )
+ for(int x = 0; x < gridWidth + 1; ++x)
{
- AddVertex( vertices, x, y );
+ AddVertex(vertices, x, y);
}
}
// Create indices
- Vector< unsigned short > indices;
- indices.Reserve( gridWidth * gridHeight * 6 );
+ Vector<unsigned short> indices;
+ indices.Reserve(gridWidth * gridHeight * 6);
unsigned int rowIdx = 0;
unsigned int nextRowIdx = gridWidth + 1;
- for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
+ for(int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx)
{
- for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
+ for(int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx)
{
- AddQuadIndices( indices, rowIdx, nextRowIdx );
+ AddQuadIndices(indices, rowIdx, nextRowIdx);
}
}
- return GenerateGeometry( vertices, indices );
+ return GenerateGeometry(vertices, indices);
}
-Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
+Geometry NPatchVisual::CreateBorderGeometry(Uint16Pair gridSize)
{
- uint16_t gridWidth = gridSize.GetWidth();
+ uint16_t gridWidth = gridSize.GetWidth();
uint16_t gridHeight = gridSize.GetHeight();
// Create vertices
- Vector< Vector2 > vertices;
- vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
+ Vector<Vector2> vertices;
+ vertices.Reserve((gridWidth + 1) * (gridHeight + 1));
//top
int y = 0;
for(; y < 2; ++y)
{
- for( int x = 0; x < gridWidth + 1; ++x )
+ for(int x = 0; x < gridWidth + 1; ++x)
{
- AddVertex( vertices, x, y );
+ AddVertex(vertices, x, y);
}
}
for(; y < gridHeight - 1; ++y)
{
//left
- AddVertex( vertices, 0, y );
- AddVertex( vertices, 1, y );
+ AddVertex(vertices, 0, y);
+ AddVertex(vertices, 1, y);
//right
- AddVertex( vertices, gridWidth - 1, y );
- AddVertex( vertices, gridWidth, y );
+ AddVertex(vertices, gridWidth - 1, y);
+ AddVertex(vertices, gridWidth, y);
}
//bottom
for(; y < gridHeight + 1; ++y)
{
- for( int x = 0; x < gridWidth + 1; ++x )
+ for(int x = 0; x < gridWidth + 1; ++x)
{
- AddVertex( vertices, x, y );
+ AddVertex(vertices, x, y);
}
}
// Create indices
- Vector< unsigned short > indices;
- indices.Reserve( gridWidth * gridHeight * 6 );
+ Vector<unsigned short> indices;
+ indices.Reserve(gridWidth * gridHeight * 6);
//top
- unsigned int rowIdx = 0 ;
+ unsigned int rowIdx = 0;
unsigned int nextRowIdx = gridWidth + 1;
- for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
+ for(int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx)
{
- AddQuadIndices( indices, rowIdx, nextRowIdx );
+ AddQuadIndices(indices, rowIdx, nextRowIdx);
}
if(gridHeight > 2)
{
rowIdx = gridWidth + 1;
- nextRowIdx = ( gridWidth + 1 ) * 2;
+ nextRowIdx = (gridWidth + 1) * 2;
unsigned increment = gridWidth - 1;
if(gridHeight > 3)
{
increment = 2;
//second row left
- AddQuadIndices( indices, rowIdx, nextRowIdx );
+ AddQuadIndices(indices, rowIdx, nextRowIdx);
rowIdx = gridWidth * 2;
- nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
+ nextRowIdx = (gridWidth + 1) * 2 + 2;
//second row right
- AddQuadIndices( indices, rowIdx, nextRowIdx );
+ AddQuadIndices(indices, rowIdx, nextRowIdx);
//left and right
rowIdx = nextRowIdx - 2;
nextRowIdx = rowIdx + 4;
- for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
+ for(int y = 2; y < 2 * (gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
{
- AddQuadIndices( indices, rowIdx, nextRowIdx );
+ AddQuadIndices(indices, rowIdx, nextRowIdx);
}
}
//second row left
- AddQuadIndices( indices, rowIdx, nextRowIdx );
+ AddQuadIndices(indices, rowIdx, nextRowIdx);
- rowIdx += increment;
+ rowIdx += increment;
nextRowIdx += gridWidth - 1;
//second row right
- AddQuadIndices( indices, rowIdx, nextRowIdx );
+ AddQuadIndices(indices, rowIdx, nextRowIdx);
}
//bottom
rowIdx = nextRowIdx - gridWidth + 1;
nextRowIdx = rowIdx + gridWidth + 1;
- for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
+ for(int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx)
{
- AddQuadIndices( indices, rowIdx, nextRowIdx );
+ AddQuadIndices(indices, rowIdx, nextRowIdx);
}
- return GenerateGeometry( vertices, indices );
+ return GenerateGeometry(vertices, indices);
}
void NPatchVisual::SetResource()
{
const NPatchData* data;
- if( mImpl->mRenderer && mLoader.GetNPatchData( mId, data ) )
+ if(mImpl->mRenderer && mLoader.GetNPatchData(mId, data))
{
Geometry geometry = CreateGeometry();
- Shader shader = CreateShader();
+ Shader shader = CreateShader();
- mImpl->mRenderer.SetGeometry( geometry );
- mImpl->mRenderer.SetShader( shader );
+ mImpl->mRenderer.SetGeometry(geometry);
+ mImpl->mRenderer.SetShader(shader);
Actor actor = mPlacementActor.GetHandle();
- if( actor )
+ if(actor)
{
ApplyTextureAndUniforms();
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
mPlacementActor.Reset();
// npatch loaded and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
}
}
-void NPatchVisual::UploadComplete( bool loadSuccess, int32_t textureId, TextureSet textureSet, bool useAtlasing, const Vector4& atlasRect, bool preMultiplied )
+void NPatchVisual::UploadComplete(bool loadSuccess, int32_t textureId, TextureSet textureSet, bool useAtlasing, const Vector4& atlasRect, bool preMultiplied)
{
- EnablePreMultipliedAlpha( preMultiplied );
+ EnablePreMultipliedAlpha(preMultiplied);
if(!loadSuccess)
{
// Image loaded and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::FAILED );
+ ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
}
- if( mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid() )
+ if(mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid())
{
SetResource();
}
}
-void NPatchVisual::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied )
+void NPatchVisual::LoadComplete(bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied)
{
- if( loadSuccess && url.GetUrl() == mAuxiliaryUrl.GetUrl() )
+ if(loadSuccess && url.GetUrl() == mAuxiliaryUrl.GetUrl())
{
mAuxiliaryPixelBuffer = pixelBuffer;
SetResource();
else
{
// Image loaded and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::FAILED );
+ ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
}
}
#include "primitive-visual.h"
// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
#include <dali/devel-api/common/stage.h>
-#include <dali/public-api/common/constants.h>
#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/devel-api/scripting/scripting.h>
+#include <dali/integration-api/debug.h>
+#include <dali/public-api/common/constants.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
// shapes
-DALI_ENUM_TO_STRING_TABLE_BEGIN( SHAPE_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, SPHERE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, CONE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, CYLINDER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, CUBE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, OCTAHEDRON )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, BEVELLED_CUBE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, CONICAL_FRUSTUM )
-DALI_ENUM_TO_STRING_TABLE_END( SHAPE_TYPE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(SHAPE_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, SPHERE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, CONE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, CYLINDER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, CUBE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, OCTAHEDRON)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, BEVELLED_CUBE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, CONICAL_FRUSTUM)
+DALI_ENUM_TO_STRING_TABLE_END(SHAPE_TYPE)
//Primitive property defaults
-const int DEFAULT_SLICES = 128; ///< For spheres and conics
-const int DEFAULT_STACKS = 128; ///< For spheres and conics
-const float DEFAULT_SCALE_TOP_RADIUS = 1.0; ///< For conical frustums
-const float DEFAULT_SCALE_BOTTOM_RADIUS = 1.5; ///< For cones and conical frustums
-const float DEFAULT_SCALE_HEIGHT = 3.0; ///< For all conics
-const float DEFAULT_SCALE_RADIUS = 1.0; ///< For cylinders
-const float DEFAULT_BEVEL_PERCENTAGE = 0.0; ///< For bevelled cubes
-const float DEFAULT_BEVEL_SMOOTHNESS = 0.0; ///< For bevelled cubes
-const Vector4 DEFAULT_COLOR = Vector4( 0.5, 0.5, 0.5, 1.0 ); ///< Grey, for all.
+const int DEFAULT_SLICES = 128; ///< For spheres and conics
+const int DEFAULT_STACKS = 128; ///< For spheres and conics
+const float DEFAULT_SCALE_TOP_RADIUS = 1.0; ///< For conical frustums
+const float DEFAULT_SCALE_BOTTOM_RADIUS = 1.5; ///< For cones and conical frustums
+const float DEFAULT_SCALE_HEIGHT = 3.0; ///< For all conics
+const float DEFAULT_SCALE_RADIUS = 1.0; ///< For cylinders
+const float DEFAULT_BEVEL_PERCENTAGE = 0.0; ///< For bevelled cubes
+const float DEFAULT_BEVEL_SMOOTHNESS = 0.0; ///< For bevelled cubes
+const Vector4 DEFAULT_COLOR = Vector4(0.5, 0.5, 0.5, 1.0); ///< Grey, for all.
//Property limits
-const int MIN_SLICES = 3; ///< Minimum number of slices for spheres and conics
-const int MIN_STACKS = 2; ///< Minimum number of stacks for spheres and conics
-const int MAX_PARTITIONS = 255; ///< Maximum number of slices or stacks for spheres and conics
+const int MIN_SLICES = 3; ///< Minimum number of slices for spheres and conics
+const int MIN_STACKS = 2; ///< Minimum number of stacks for spheres and conics
+const int MAX_PARTITIONS = 255; ///< Maximum number of slices or stacks for spheres and conics
const float MIN_BEVEL_PERCENTAGE = 0.0; ///< Minimum bevel percentage for bevelled cubes
const float MAX_BEVEL_PERCENTAGE = 1.0; ///< Maximum bevel percentage for bevelled cubes
-const float MIN_SMOOTHNESS = 0.0; ///< Minimum bevel smoothness for bevelled cubes
-const float MAX_SMOOTHNESS = 1.0; ///< Maximum bevel smoothness for bevelled cubes
+const float MIN_SMOOTHNESS = 0.0; ///< Minimum bevel smoothness for bevelled cubes
+const float MAX_SMOOTHNESS = 1.0; ///< Maximum bevel smoothness for bevelled cubes
//Specific shape labels.
-const char * const SPHERE_LABEL( "SPHERE" );
-const char * const CONE_LABEL( "CONE" );
-const char * const CYLINDER_LABEL( "CYLINDER" );
-const char * const CUBE_LABEL( "CUBE" );
-const char * const OCTAHEDRON_LABEL( "OCTAHEDRON" );
-const char * const BEVELLED_CUBE_LABEL( "BEVELLED_CUBE" );
-const char * const CONICAL_FRUSTUM_LABEL( "CONICAL_FRUSTUM" );
+const char* const SPHERE_LABEL("SPHERE");
+const char* const CONE_LABEL("CONE");
+const char* const CYLINDER_LABEL("CYLINDER");
+const char* const CUBE_LABEL("CUBE");
+const char* const OCTAHEDRON_LABEL("OCTAHEDRON");
+const char* const BEVELLED_CUBE_LABEL("BEVELLED_CUBE");
+const char* const CONICAL_FRUSTUM_LABEL("CONICAL_FRUSTUM");
//Shader properties
-const char * const OBJECT_MATRIX_UNIFORM_NAME( "uObjectMatrix" );
-const char * const OBJECT_DIMENSIONS_UNIFORM_NAME( "uObjectDimensions" );
-const char * const STAGE_OFFSET_UNIFORM_NAME( "uStageOffset" );
+const char* const OBJECT_MATRIX_UNIFORM_NAME("uObjectMatrix");
+const char* const OBJECT_DIMENSIONS_UNIFORM_NAME("uObjectDimensions");
+const char* const STAGE_OFFSET_UNIFORM_NAME("uStageOffset");
//Vertex properties
-const char * const POSITION( "aPosition");
-const char * const NORMAL( "aNormal" );
-const char * const INDICES( "aIndices" );
+const char* const POSITION("aPosition");
+const char* const NORMAL("aNormal");
+const char* const INDICES("aIndices");
} // unnamed namespace
-PrimitiveVisualPtr PrimitiveVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+PrimitiveVisualPtr PrimitiveVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
- PrimitiveVisualPtr primitiveVisualPtr( new PrimitiveVisual( factoryCache ) );
- primitiveVisualPtr->SetProperties( properties );
+ PrimitiveVisualPtr primitiveVisualPtr(new PrimitiveVisual(factoryCache));
+ primitiveVisualPtr->SetProperties(properties);
primitiveVisualPtr->Initialize();
return primitiveVisualPtr;
}
-PrimitiveVisual::PrimitiveVisual( VisualFactoryCache& factoryCache )
-: Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::PRIMITIVE ),
- mScaleDimensions( Vector3::ONE ),
- mScaleTopRadius( DEFAULT_SCALE_TOP_RADIUS ),
- mScaleBottomRadius( DEFAULT_SCALE_BOTTOM_RADIUS ),
- mScaleHeight( DEFAULT_SCALE_HEIGHT ),
- mScaleRadius( DEFAULT_SCALE_RADIUS ),
- mBevelPercentage( DEFAULT_BEVEL_PERCENTAGE ),
- mBevelSmoothness( DEFAULT_BEVEL_SMOOTHNESS ),
- mSlices( DEFAULT_SLICES ),
- mStacks( DEFAULT_STACKS ),
- mPrimitiveType( Toolkit::PrimitiveVisual::Shape::SPHERE )
+PrimitiveVisual::PrimitiveVisual(VisualFactoryCache& factoryCache)
+: Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::PRIMITIVE),
+ mScaleDimensions(Vector3::ONE),
+ mScaleTopRadius(DEFAULT_SCALE_TOP_RADIUS),
+ mScaleBottomRadius(DEFAULT_SCALE_BOTTOM_RADIUS),
+ mScaleHeight(DEFAULT_SCALE_HEIGHT),
+ mScaleRadius(DEFAULT_SCALE_RADIUS),
+ mBevelPercentage(DEFAULT_BEVEL_PERCENTAGE),
+ mBevelSmoothness(DEFAULT_BEVEL_SMOOTHNESS),
+ mSlices(DEFAULT_SLICES),
+ mStacks(DEFAULT_STACKS),
+ mPrimitiveType(Toolkit::PrimitiveVisual::Shape::SPHERE)
{
mImpl->mMixColor = DEFAULT_COLOR;
}
{
}
-void PrimitiveVisual::DoSetProperties( const Property::Map& propertyMap )
+void PrimitiveVisual::DoSetProperties(const Property::Map& propertyMap)
{
//Find out which shape to renderer.
- Property::Value* primitiveTypeValue = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SHAPE, PRIMITIVE_SHAPE );
- if( primitiveTypeValue )
+ Property::Value* primitiveTypeValue = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SHAPE, PRIMITIVE_SHAPE);
+ if(primitiveTypeValue)
{
- Scripting::GetEnumerationProperty( *primitiveTypeValue, SHAPE_TYPE_TABLE, SHAPE_TYPE_TABLE_COUNT, mPrimitiveType );
+ Scripting::GetEnumerationProperty(*primitiveTypeValue, SHAPE_TYPE_TABLE, SHAPE_TYPE_TABLE_COUNT, mPrimitiveType);
}
else
{
- DALI_LOG_ERROR( "Fail to provide shape to the PrimitiveVisual object.\n" );
+ DALI_LOG_ERROR("Fail to provide shape to the PrimitiveVisual object.\n");
}
// By virtue of DoSetProperties being called last, this will override
// anything set by Toolkit::Visual::Property::MIX_COLOR
- Property::Value* colorValue = propertyMap.Find( Toolkit::PrimitiveVisual::Property::MIX_COLOR, MIX_COLOR );
- if( colorValue )
+ Property::Value* colorValue = propertyMap.Find(Toolkit::PrimitiveVisual::Property::MIX_COLOR, MIX_COLOR);
+ if(colorValue)
{
Vector4 color;
- if( colorValue->Get( color ) )
+ if(colorValue->Get(color))
{
Property::Type type = colorValue->GetType();
- if( type == Property::VECTOR4 )
+ if(type == Property::VECTOR4)
{
- SetMixColor( color );
+ SetMixColor(color);
}
- else if( type == Property::VECTOR3 )
+ else if(type == Property::VECTOR3)
{
Vector3 color3(color);
- SetMixColor( color3 );
+ SetMixColor(color3);
}
}
}
- Property::Value* slices = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SLICES, SLICES );
- if( slices )
+ Property::Value* slices = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SLICES, SLICES);
+ if(slices)
{
- if( slices->Get( mSlices ) )
+ if(slices->Get(mSlices))
{
//Clamp value.
- if( mSlices > MAX_PARTITIONS )
+ if(mSlices > MAX_PARTITIONS)
{
mSlices = MAX_PARTITIONS;
- DALI_LOG_WARNING( "Value for slices clamped.\n" );
+ DALI_LOG_WARNING("Value for slices clamped.\n");
}
- else if ( mSlices < MIN_SLICES )
+ else if(mSlices < MIN_SLICES)
{
mSlices = MIN_SLICES;
- DALI_LOG_WARNING( "Value for slices clamped.\n" );
+ DALI_LOG_WARNING("Value for slices clamped.\n");
}
}
else
{
- DALI_LOG_ERROR( "Invalid type for slices in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for slices in PrimitiveVisual.\n");
}
}
- Property::Value* stacks = propertyMap.Find( Toolkit::PrimitiveVisual::Property::STACKS, STACKS );
- if( stacks )
+ Property::Value* stacks = propertyMap.Find(Toolkit::PrimitiveVisual::Property::STACKS, STACKS);
+ if(stacks)
{
- if( stacks->Get( mStacks ) )
+ if(stacks->Get(mStacks))
{
//Clamp value.
- if( mStacks > MAX_PARTITIONS )
+ if(mStacks > MAX_PARTITIONS)
{
mStacks = MAX_PARTITIONS;
- DALI_LOG_WARNING( "Value for stacks clamped.\n" );
+ DALI_LOG_WARNING("Value for stacks clamped.\n");
}
- else if ( mStacks < MIN_STACKS )
+ else if(mStacks < MIN_STACKS)
{
mStacks = MIN_STACKS;
- DALI_LOG_WARNING( "Value for stacks clamped.\n" );
+ DALI_LOG_WARNING("Value for stacks clamped.\n");
}
}
else
{
- DALI_LOG_ERROR( "Invalid type for stacks in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for stacks in PrimitiveVisual.\n");
}
}
- Property::Value* scaleTop = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_TOP_RADIUS, SCALE_TOP_RADIUS );
- if( scaleTop && !scaleTop->Get( mScaleTopRadius ) )
+ Property::Value* scaleTop = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_TOP_RADIUS, SCALE_TOP_RADIUS);
+ if(scaleTop && !scaleTop->Get(mScaleTopRadius))
{
- DALI_LOG_ERROR( "Invalid type for scale top radius in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for scale top radius in PrimitiveVisual.\n");
}
- Property::Value* scaleBottom = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_BOTTOM_RADIUS, SCALE_BOTTOM_RADIUS );
- if( scaleBottom && !scaleBottom->Get( mScaleBottomRadius ) )
+ Property::Value* scaleBottom = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_BOTTOM_RADIUS, SCALE_BOTTOM_RADIUS);
+ if(scaleBottom && !scaleBottom->Get(mScaleBottomRadius))
{
- DALI_LOG_ERROR( "Invalid type for scale bottom radius in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for scale bottom radius in PrimitiveVisual.\n");
}
- Property::Value* scaleHeight = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_HEIGHT, SCALE_HEIGHT );
- if( scaleHeight && !scaleHeight->Get( mScaleHeight ) )
+ Property::Value* scaleHeight = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_HEIGHT, SCALE_HEIGHT);
+ if(scaleHeight && !scaleHeight->Get(mScaleHeight))
{
- DALI_LOG_ERROR( "Invalid type for scale height in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for scale height in PrimitiveVisual.\n");
}
- Property::Value* scaleRadius = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_RADIUS, SCALE_RADIUS );
- if( scaleRadius && !scaleRadius->Get( mScaleRadius ) )
+ Property::Value* scaleRadius = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_RADIUS, SCALE_RADIUS);
+ if(scaleRadius && !scaleRadius->Get(mScaleRadius))
{
- DALI_LOG_ERROR( "Invalid type for scale radius in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for scale radius in PrimitiveVisual.\n");
}
- Property::Value* dimensions = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_DIMENSIONS, SCALE_DIMENSIONS );
- if( dimensions )
+ Property::Value* dimensions = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_DIMENSIONS, SCALE_DIMENSIONS);
+ if(dimensions)
{
- if( dimensions->Get( mScaleDimensions ) )
+ if(dimensions->Get(mScaleDimensions))
{
//If any dimension is invalid, set it to a sensible default.
- if( mScaleDimensions.x <= 0.0 )
+ if(mScaleDimensions.x <= 0.0)
{
mScaleDimensions.x = 1.0;
- DALI_LOG_WARNING( "Value for scale dimensions clamped. Must be greater than zero.\n" );
+ DALI_LOG_WARNING("Value for scale dimensions clamped. Must be greater than zero.\n");
}
- if( mScaleDimensions.y <= 0.0 )
+ if(mScaleDimensions.y <= 0.0)
{
mScaleDimensions.y = 1.0;
- DALI_LOG_WARNING( "Value for scale dimensions clamped. Must be greater than zero.\n" );
+ DALI_LOG_WARNING("Value for scale dimensions clamped. Must be greater than zero.\n");
}
- if( mScaleDimensions.z <= 0.0 )
+ if(mScaleDimensions.z <= 0.0)
{
mScaleDimensions.z = 1.0;
- DALI_LOG_WARNING( "Value for scale dimensions clamped. Must be greater than zero.\n" );
+ DALI_LOG_WARNING("Value for scale dimensions clamped. Must be greater than zero.\n");
}
}
else
{
- DALI_LOG_ERROR( "Invalid type for scale dimensions in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for scale dimensions in PrimitiveVisual.\n");
}
}
- Property::Value* bevel = propertyMap.Find( Toolkit::PrimitiveVisual::Property::BEVEL_PERCENTAGE, BEVEL_PERCENTAGE );
- if( bevel )
+ Property::Value* bevel = propertyMap.Find(Toolkit::PrimitiveVisual::Property::BEVEL_PERCENTAGE, BEVEL_PERCENTAGE);
+ if(bevel)
{
- if( bevel->Get( mBevelPercentage ) )
+ if(bevel->Get(mBevelPercentage))
{
//Clamp value.
- if( mBevelPercentage < MIN_BEVEL_PERCENTAGE )
+ if(mBevelPercentage < MIN_BEVEL_PERCENTAGE)
{
mBevelPercentage = MIN_BEVEL_PERCENTAGE;
- DALI_LOG_WARNING( "Value for bevel percentage clamped.\n" );
+ DALI_LOG_WARNING("Value for bevel percentage clamped.\n");
}
- else if( mBevelPercentage > MAX_BEVEL_PERCENTAGE )
+ else if(mBevelPercentage > MAX_BEVEL_PERCENTAGE)
{
mBevelPercentage = MAX_BEVEL_PERCENTAGE;
- DALI_LOG_WARNING( "Value for bevel percentage clamped.\n" );
+ DALI_LOG_WARNING("Value for bevel percentage clamped.\n");
}
}
else
{
- DALI_LOG_ERROR( "Invalid type for bevel percentage in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for bevel percentage in PrimitiveVisual.\n");
}
}
- Property::Value* smoothness = propertyMap.Find( Toolkit::PrimitiveVisual::Property::BEVEL_SMOOTHNESS, BEVEL_SMOOTHNESS );
- if( smoothness )
+ Property::Value* smoothness = propertyMap.Find(Toolkit::PrimitiveVisual::Property::BEVEL_SMOOTHNESS, BEVEL_SMOOTHNESS);
+ if(smoothness)
{
- if( smoothness->Get( mBevelSmoothness ) )
+ if(smoothness->Get(mBevelSmoothness))
{
//Clamp value.
- if( mBevelSmoothness < MIN_SMOOTHNESS )
+ if(mBevelSmoothness < MIN_SMOOTHNESS)
{
mBevelSmoothness = MIN_SMOOTHNESS;
- DALI_LOG_WARNING( "Value for bevel smoothness clamped.\n" );
+ DALI_LOG_WARNING("Value for bevel smoothness clamped.\n");
}
- else if( mBevelSmoothness > MAX_SMOOTHNESS )
+ else if(mBevelSmoothness > MAX_SMOOTHNESS)
{
mBevelSmoothness = MAX_SMOOTHNESS;
- DALI_LOG_WARNING( "Value for bevel smoothness clamped.\n" );
+ DALI_LOG_WARNING("Value for bevel smoothness clamped.\n");
}
}
else
{
- DALI_LOG_ERROR( "Invalid type for bevel smoothness in PrimitiveVisual.\n" );
+ DALI_LOG_ERROR("Invalid type for bevel smoothness in PrimitiveVisual.\n");
}
}
//Read in light position.
- Property::Value* lightPosition = propertyMap.Find( Toolkit::PrimitiveVisual::Property::LIGHT_POSITION, LIGHT_POSITION_UNIFORM_NAME );
- if( lightPosition )
+ Property::Value* lightPosition = propertyMap.Find(Toolkit::PrimitiveVisual::Property::LIGHT_POSITION, LIGHT_POSITION_UNIFORM_NAME);
+ if(lightPosition)
{
- if( !lightPosition->Get( mLightPosition ) )
+ if(!lightPosition->Get(mLightPosition))
{
- DALI_LOG_ERROR( "Invalid value passed for light position in MeshVisual object.\n" );
+ DALI_LOG_ERROR("Invalid value passed for light position in MeshVisual object.\n");
mLightPosition = Vector3::ZERO;
}
}
// at a reasonable distance to light everything on screen.
Stage stage = Stage::GetCurrent();
- mLightPosition = Vector3( stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5 );
+ mLightPosition = Vector3(stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5);
}
}
-void PrimitiveVisual::GetNaturalSize( Vector2& naturalSize )
+void PrimitiveVisual::GetNaturalSize(Vector2& naturalSize)
{
- if( !mGeometry )
+ if(!mGeometry)
{
CreateGeometry();
}
naturalSize.y = mObjectDimensions.y;
}
-void PrimitiveVisual::DoSetOnScene( Actor& actor )
+void PrimitiveVisual::DoSetOnScene(Actor& actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
// Primitive generated and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
-void PrimitiveVisual::DoCreatePropertyMap( Property::Map& map ) const
+void PrimitiveVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::PRIMITIVE );
- map.Insert( Toolkit::PrimitiveVisual::Property::MIX_COLOR, mImpl->mMixColor );
- map.Insert( Toolkit::PrimitiveVisual::Property::SHAPE, mPrimitiveType );
- map.Insert( Toolkit::PrimitiveVisual::Property::SLICES, mSlices );
- map.Insert( Toolkit::PrimitiveVisual::Property::STACKS, mStacks );
- map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_TOP_RADIUS, mScaleTopRadius );
- map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_BOTTOM_RADIUS, mScaleBottomRadius );
- map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_HEIGHT, mScaleHeight );
- map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_RADIUS, mScaleRadius );
- map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_DIMENSIONS, mScaleDimensions );
- map.Insert( Toolkit::PrimitiveVisual::Property::BEVEL_PERCENTAGE, mBevelPercentage );
- map.Insert( Toolkit::PrimitiveVisual::Property::BEVEL_SMOOTHNESS, mBevelSmoothness );
- map.Insert( Toolkit::PrimitiveVisual::Property::LIGHT_POSITION, mLightPosition );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::PRIMITIVE);
+ map.Insert(Toolkit::PrimitiveVisual::Property::MIX_COLOR, mImpl->mMixColor);
+ map.Insert(Toolkit::PrimitiveVisual::Property::SHAPE, mPrimitiveType);
+ map.Insert(Toolkit::PrimitiveVisual::Property::SLICES, mSlices);
+ map.Insert(Toolkit::PrimitiveVisual::Property::STACKS, mStacks);
+ map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_TOP_RADIUS, mScaleTopRadius);
+ map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_BOTTOM_RADIUS, mScaleBottomRadius);
+ map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_HEIGHT, mScaleHeight);
+ map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_RADIUS, mScaleRadius);
+ map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_DIMENSIONS, mScaleDimensions);
+ map.Insert(Toolkit::PrimitiveVisual::Property::BEVEL_PERCENTAGE, mBevelPercentage);
+ map.Insert(Toolkit::PrimitiveVisual::Property::BEVEL_SMOOTHNESS, mBevelSmoothness);
+ map.Insert(Toolkit::PrimitiveVisual::Property::LIGHT_POSITION, mLightPosition);
}
-void PrimitiveVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void PrimitiveVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
void PrimitiveVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
void PrimitiveVisual::OnInitialize()
{
- if( !mGeometry )
+ if(!mGeometry)
{
CreateGeometry();
}
- if( !mShader )
+ if(!mShader)
{
CreateShader();
}
- mImpl->mRenderer = Renderer::New( mGeometry, mShader );
- mImpl->mRenderer.SetProperty( Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK );
+ mImpl->mRenderer = Renderer::New(mGeometry, mShader);
+ mImpl->mRenderer.SetProperty(Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK);
// Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
- mImpl->mMixColorIndex = mImpl->mRenderer.RegisterProperty( Toolkit::PrimitiveVisual::Property::MIX_COLOR, MIX_COLOR, Vector3(mImpl->mMixColor) );
+ mImpl->mMixColorIndex = mImpl->mRenderer.RegisterProperty(Toolkit::PrimitiveVisual::Property::MIX_COLOR, MIX_COLOR, Vector3(mImpl->mMixColor));
}
void PrimitiveVisual::UpdateShaderUniforms()
{
- Stage stage = Stage::GetCurrent();
- float width = stage.GetSize().width;
+ Stage stage = Stage::GetCurrent();
+ float width = stage.GetSize().width;
float height = stage.GetSize().height;
//Flip model to account for DALi starting with (0, 0) at the top left.
Matrix scaleMatrix;
- scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) );
+ scaleMatrix.SetIdentityAndScale(Vector3(1.0, -1.0, 1.0));
- mShader.RegisterProperty( STAGE_OFFSET_UNIFORM_NAME, Vector2( width, height ) / 2.0f );
- mShader.RegisterProperty( LIGHT_POSITION_UNIFORM_NAME, mLightPosition );
- mShader.RegisterProperty( OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix );
- mShader.RegisterProperty( OBJECT_DIMENSIONS_UNIFORM_NAME, mObjectDimensions );
+ mShader.RegisterProperty(STAGE_OFFSET_UNIFORM_NAME, Vector2(width, height) / 2.0f);
+ mShader.RegisterProperty(LIGHT_POSITION_UNIFORM_NAME, mLightPosition);
+ mShader.RegisterProperty(OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix);
+ mShader.RegisterProperty(OBJECT_DIMENSIONS_UNIFORM_NAME, mObjectDimensions);
}
void PrimitiveVisual::CreateShader()
{
- mShader = Shader::New( SHADER_PRIMITIVE_VISUAL_SHADER_VERT, SHADER_PRIMITIVE_VISUAL_SHADER_FRAG );
+ mShader = Shader::New(SHADER_PRIMITIVE_VISUAL_SHADER_VERT, SHADER_PRIMITIVE_VISUAL_SHADER_FRAG);
UpdateShaderUniforms();
}
void PrimitiveVisual::CreateGeometry()
{
- Dali::Vector<Vertex> vertices;
+ Dali::Vector<Vertex> vertices;
Dali::Vector<unsigned short> indices;
- switch( mPrimitiveType )
+ switch(mPrimitiveType)
{
case Toolkit::PrimitiveVisual::Shape::SPHERE:
{
- CreateSphere( vertices, indices, mSlices, mStacks );
+ CreateSphere(vertices, indices, mSlices, mStacks);
break;
}
case Toolkit::PrimitiveVisual::Shape::CONE:
{
//Create a conic with zero top radius.
- CreateConic( vertices, indices, 0, mScaleBottomRadius, mScaleHeight, mSlices );
+ CreateConic(vertices, indices, 0, mScaleBottomRadius, mScaleHeight, mSlices);
break;
}
case Toolkit::PrimitiveVisual::Shape::CYLINDER:
{
//Create a conic with equal radii on the top and bottom.
- CreateConic( vertices, indices, mScaleRadius, mScaleRadius, mScaleHeight, mSlices );
+ CreateConic(vertices, indices, mScaleRadius, mScaleRadius, mScaleHeight, mSlices);
break;
}
case Toolkit::PrimitiveVisual::Shape::CUBE:
{
//Create a cube by creating a bevelled cube with minimum bevel.
- CreateBevelledCube( vertices, indices, mScaleDimensions, 0.0, 0.0 );
+ CreateBevelledCube(vertices, indices, mScaleDimensions, 0.0, 0.0);
break;
}
case Toolkit::PrimitiveVisual::Shape::OCTAHEDRON:
{
//Create an octahedron by creating a bevelled cube with maximum bevel.
- CreateBevelledCube( vertices, indices, mScaleDimensions, 1.0, mBevelSmoothness );
+ CreateBevelledCube(vertices, indices, mScaleDimensions, 1.0, mBevelSmoothness);
break;
}
case Toolkit::PrimitiveVisual::Shape::BEVELLED_CUBE:
{
- CreateBevelledCube( vertices, indices, mScaleDimensions, mBevelPercentage, mBevelSmoothness );
+ CreateBevelledCube(vertices, indices, mScaleDimensions, mBevelPercentage, mBevelSmoothness);
break;
}
case Toolkit::PrimitiveVisual::Shape::CONICAL_FRUSTUM:
{
- CreateConic( vertices, indices, mScaleTopRadius, mScaleBottomRadius, mScaleHeight, mSlices );
+ CreateConic(vertices, indices, mScaleTopRadius, mScaleBottomRadius, mScaleHeight, mSlices);
break;
}
}
//Vertices
Property::Map vertexFormat;
- vertexFormat[POSITION] = Property::VECTOR3;
- vertexFormat[NORMAL] = Property::VECTOR3;
- VertexBuffer surfaceVertices = VertexBuffer::New( vertexFormat );
- surfaceVertices.SetData( &vertices[0], vertices.Size() );
+ vertexFormat[POSITION] = Property::VECTOR3;
+ vertexFormat[NORMAL] = Property::VECTOR3;
+ VertexBuffer surfaceVertices = VertexBuffer::New(vertexFormat);
+ surfaceVertices.SetData(&vertices[0], vertices.Size());
- mGeometry.AddVertexBuffer( surfaceVertices );
+ mGeometry.AddVertexBuffer(surfaceVertices);
//Indices for triangle formulation
- mGeometry.SetIndexBuffer( &indices[0], indices.Size() );
+ mGeometry.SetIndexBuffer(&indices[0], indices.Size());
}
-void PrimitiveVisual::CreateSphere( Vector<Vertex>& vertices, Vector<unsigned short>& indices, int slices, int stacks )
+void PrimitiveVisual::CreateSphere(Vector<Vertex>& vertices, Vector<unsigned short>& indices, int slices, int stacks)
{
- ComputeSphereVertices( vertices, slices, stacks );
- FormSphereTriangles( indices, slices, stacks );
+ ComputeSphereVertices(vertices, slices, stacks);
+ FormSphereTriangles(indices, slices, stacks);
mObjectDimensions = Vector3::ONE;
}
-void PrimitiveVisual::CreateConic( Vector<Vertex>& vertices, Vector<unsigned short>& indices, float scaleTopRadius,
- float scaleBottomRadius, float scaleHeight, int slices )
+void PrimitiveVisual::CreateConic(Vector<Vertex>& vertices, Vector<unsigned short>& indices, float scaleTopRadius, float scaleBottomRadius, float scaleHeight, int slices)
{
- ComputeConicVertices( vertices, scaleTopRadius, scaleBottomRadius, scaleHeight, slices );
- FormConicTriangles( indices, scaleTopRadius, scaleBottomRadius, slices );
+ ComputeConicVertices(vertices, scaleTopRadius, scaleBottomRadius, scaleHeight, slices);
+ FormConicTriangles(indices, scaleTopRadius, scaleBottomRadius, slices);
//Determine object dimensions, and scale them to be between 0.0 and 1.0.
- float xDimension = std::max( scaleTopRadius, scaleBottomRadius ) * 2.0f;
- float yDimension = scaleHeight;
- float largestDimension = std::max( xDimension, yDimension );
+ float xDimension = std::max(scaleTopRadius, scaleBottomRadius) * 2.0f;
+ float yDimension = scaleHeight;
+ float largestDimension = std::max(xDimension, yDimension);
- mObjectDimensions = Vector3( xDimension / largestDimension, yDimension / largestDimension,
- xDimension / largestDimension );
+ mObjectDimensions = Vector3(xDimension / largestDimension, yDimension / largestDimension, xDimension / largestDimension);
}
-void PrimitiveVisual::CreateBevelledCube( Vector<Vertex>& vertices, Vector<unsigned short>& indices,
- Vector3 dimensions, float bevelPercentage, float bevelSmoothness )
+void PrimitiveVisual::CreateBevelledCube(Vector<Vertex>& vertices, Vector<unsigned short>& indices, Vector3 dimensions, float bevelPercentage, float bevelSmoothness)
{
- float maxDimension = std::max( std::max( dimensions.x, dimensions.y ), dimensions.z );
- dimensions = dimensions / maxDimension;
+ float maxDimension = std::max(std::max(dimensions.x, dimensions.y), dimensions.z);
+ dimensions = dimensions / maxDimension;
- if( bevelPercentage <= MIN_BEVEL_PERCENTAGE ) //No bevel, form a cube.
+ if(bevelPercentage <= MIN_BEVEL_PERCENTAGE) //No bevel, form a cube.
{
- ComputeCubeVertices( vertices, dimensions );
- FormCubeTriangles( indices );
+ ComputeCubeVertices(vertices, dimensions);
+ FormCubeTriangles(indices);
}
- else if( bevelPercentage >= MAX_BEVEL_PERCENTAGE ) //Max bevel, form an octahedron.
+ else if(bevelPercentage >= MAX_BEVEL_PERCENTAGE) //Max bevel, form an octahedron.
{
- ComputeOctahedronVertices( vertices, dimensions, bevelSmoothness );
- FormOctahedronTriangles( indices );
+ ComputeOctahedronVertices(vertices, dimensions, bevelSmoothness);
+ FormOctahedronTriangles(indices);
}
else //In between, form a bevelled cube.
{
- ComputeBevelledCubeVertices( vertices, dimensions, bevelPercentage, bevelSmoothness );
- FormBevelledCubeTriangles( indices );
+ ComputeBevelledCubeVertices(vertices, dimensions, bevelPercentage, bevelSmoothness);
+ FormBevelledCubeTriangles(indices);
}
mObjectDimensions = dimensions;
}
-void PrimitiveVisual::ComputeCircleTables( Vector<float>& sinTable, Vector<float>& cosTable, int divisions,
- bool halfCircle )
+void PrimitiveVisual::ComputeCircleTables(Vector<float>& sinTable, Vector<float>& cosTable, int divisions, bool halfCircle)
{
- if( divisions < 0 )
+ if(divisions < 0)
{
return;
}
- const float angleDivision = ( halfCircle ? 1.0f : 2.0f ) * Dali::Math::PI / ( float ) divisions;
+ const float angleDivision = (halfCircle ? 1.0f : 2.0f) * Dali::Math::PI / (float)divisions;
- sinTable.Resize( divisions );
- cosTable.Resize( divisions );
+ sinTable.Resize(divisions);
+ cosTable.Resize(divisions);
- for( int i = 0; i < divisions; i++ )
+ for(int i = 0; i < divisions; i++)
{
- sinTable[i] = sin( angleDivision * i );
- cosTable[i] = cos( angleDivision * i );
+ sinTable[i] = sin(angleDivision * i);
+ cosTable[i] = cos(angleDivision * i);
}
}
-void PrimitiveVisual::ComputeSphereVertices( Vector<Vertex>& vertices, int slices, int stacks )
+void PrimitiveVisual::ComputeSphereVertices(Vector<Vertex>& vertices, int slices, int stacks)
{
//Tables for calculating slices angles and stacks angles, respectively.
Vector<float> sinTable1;
Vector<float> sinTable2;
Vector<float> cosTable2;
- ComputeCircleTables( sinTable1, cosTable1, slices, false );
- ComputeCircleTables( sinTable2, cosTable2, stacks, true );
+ ComputeCircleTables(sinTable1, cosTable1, slices, false);
+ ComputeCircleTables(sinTable2, cosTable2, stacks, true);
- int numVertices = slices * ( stacks - 1 ) + 2;
- vertices.Resize( numVertices );
+ int numVertices = slices * (stacks - 1) + 2;
+ vertices.Resize(numVertices);
- int vertexIndex = 0; //Track progress through vertices.
+ int vertexIndex = 0; //Track progress through vertices.
float x;
float y;
float z;
//Top stack.
- vertices[vertexIndex].position = Vector3( 0.0, 0.5, 0.0 );
- vertices[vertexIndex].normal = Vector3( 0.0, 1.0, 0.0 );
+ vertices[vertexIndex].position = Vector3(0.0, 0.5, 0.0);
+ vertices[vertexIndex].normal = Vector3(0.0, 1.0, 0.0);
vertexIndex++;
//Middle stacks.
- for( int i = 1; i < stacks; i++ )
+ for(int i = 1; i < stacks; i++)
{
- for( int j = 0; j < slices; j++, vertexIndex++ )
+ for(int j = 0; j < slices; j++, vertexIndex++)
{
x = cosTable1[j] * sinTable2[i];
y = cosTable2[i];
z = sinTable1[j] * sinTable2[i];
- vertices[vertexIndex].position = Vector3( x / 2.0f, y / 2.0f, z / 2.0f );
- vertices[vertexIndex].normal = Vector3( x, y, z );
+ vertices[vertexIndex].position = Vector3(x / 2.0f, y / 2.0f, z / 2.0f);
+ vertices[vertexIndex].normal = Vector3(x, y, z);
}
}
//Bottom stack.
- vertices[vertexIndex].position = Vector3( 0.0, -0.5, 0.0 );
- vertices[vertexIndex].normal = Vector3( 0.0, -1.0, 0.0 );
+ vertices[vertexIndex].position = Vector3(0.0, -0.5, 0.0);
+ vertices[vertexIndex].normal = Vector3(0.0, -1.0, 0.0);
}
-void PrimitiveVisual::FormSphereTriangles( Vector<unsigned short>& indices, int slices, int stacks )
+void PrimitiveVisual::FormSphereTriangles(Vector<unsigned short>& indices, int slices, int stacks)
{
- if( stacks <= 1 )
+ if(stacks <= 1)
{
//Set indices to placeholder "error" values.
//This will display nothing, which is the expected behaviour for this edge case.
- indices.Resize( 3 );
+ indices.Resize(3);
return;
}
- int numTriangles = 2 * slices * ( stacks - 1 );
+ int numTriangles = 2 * slices * (stacks - 1);
- indices.Resize( 3 * numTriangles );
+ indices.Resize(3 * numTriangles);
- int indiceIndex = 0; //Used to keep track of progress through indices.
- int previousCycleBeginning = 1; //Stores the index of the vertex that started the cycle of the previous stack.
- int currentCycleBeginning = 1 + slices;
+ int indiceIndex = 0; //Used to keep track of progress through indices.
+ int previousCycleBeginning = 1; //Stores the index of the vertex that started the cycle of the previous stack.
+ int currentCycleBeginning = 1 + slices;
//Top stack. Loop from index 1 to index slices, as not counting the very first vertex.
- for( int i = 1; i <= slices; i++, indiceIndex += 3 )
+ for(int i = 1; i <= slices; i++, indiceIndex += 3)
{
indices[indiceIndex] = 0;
- if( i == slices )
+ if(i == slices)
{
//End, so loop around.
indices[indiceIndex + 1] = 1;
}
//Middle Stacks. Want to form triangles between the top and bottom stacks, so loop up to the number of stacks - 2.
- for( int i = 0; i < stacks - 2; i++, previousCycleBeginning += slices, currentCycleBeginning += slices )
+ for(int i = 0; i < stacks - 2; i++, previousCycleBeginning += slices, currentCycleBeginning += slices)
{
- for( int j = 0; j < slices; j++, indiceIndex += 6 )
+ for(int j = 0; j < slices; j++, indiceIndex += 6)
{
- if( j == slices - 1 )
+ if(j == slices - 1)
{
//End, so loop around.
- indices[indiceIndex] = previousCycleBeginning + j;
+ indices[indiceIndex] = previousCycleBeginning + j;
indices[indiceIndex + 1] = previousCycleBeginning;
indices[indiceIndex + 2] = currentCycleBeginning + j;
indices[indiceIndex + 3] = currentCycleBeginning + j;
}
else
{
- indices[indiceIndex] = previousCycleBeginning + j;
+ indices[indiceIndex] = previousCycleBeginning + j;
indices[indiceIndex + 1] = previousCycleBeginning + 1 + j;
indices[indiceIndex + 2] = currentCycleBeginning + j;
indices[indiceIndex + 3] = currentCycleBeginning + j;
}
//Bottom stack. Loop around the last stack from the previous loop, and go up to the penultimate vertex.
- for( int i = 0; i < slices; i++, indiceIndex += 3 )
+ for(int i = 0; i < slices; i++, indiceIndex += 3)
{
- indices[indiceIndex] = previousCycleBeginning + slices;
+ indices[indiceIndex] = previousCycleBeginning + slices;
indices[indiceIndex + 1] = previousCycleBeginning + i;
- if( i == slices - 1 )
+ if(i == slices - 1)
{
//End, so loop around.
indices[indiceIndex + 2] = previousCycleBeginning;
}
}
-void PrimitiveVisual::ComputeConicVertices( Vector<Vertex>& vertices, float scaleTopRadius,
- float scaleBottomRadius, float scaleHeight, int slices )
+void PrimitiveVisual::ComputeConicVertices(Vector<Vertex>& vertices, float scaleTopRadius, float scaleBottomRadius, float scaleHeight, int slices)
{
- int vertexIndex = 0; //Track progress through vertices.
+ int vertexIndex = 0; //Track progress through vertices.
Vector<float> sinTable;
Vector<float> cosTable;
- ComputeCircleTables( sinTable, cosTable, slices, false );
+ ComputeCircleTables(sinTable, cosTable, slices, false);
- int numVertices = 2; //Always will have one at the top and one at the bottom.
+ int numVertices = 2; //Always will have one at the top and one at the bottom.
//Add vertices for each circle. Need two per point for different face normals.
- if( scaleTopRadius > 0.0 )
+ if(scaleTopRadius > 0.0)
{
numVertices += 2 * slices;
}
- if( scaleBottomRadius > 0.0 )
+ if(scaleBottomRadius > 0.0)
{
numVertices += 2 * slices;
}
- vertices.Resize( numVertices );
-
+ vertices.Resize(numVertices);
//Scale to bounding region of -0.5 to 0.5 (i.e range of 1).
- float biggestObjectDimension = std::max( std::max( scaleTopRadius * 2.0f, scaleBottomRadius * 2.0f ), scaleHeight );
- scaleTopRadius = scaleTopRadius / biggestObjectDimension;
- scaleBottomRadius = scaleBottomRadius / biggestObjectDimension;
+ float biggestObjectDimension = std::max(std::max(scaleTopRadius * 2.0f, scaleBottomRadius * 2.0f), scaleHeight);
+ scaleTopRadius = scaleTopRadius / biggestObjectDimension;
+ scaleBottomRadius = scaleBottomRadius / biggestObjectDimension;
//Dimensions for vertex coordinates. Y is constant, and so can be initialised now.
float x;
float z;
//Top center.
- vertices[0].position = Vector3( 0, y, 0 );
- vertices[0].normal = Vector3( 0, 1, 0 );
+ vertices[0].position = Vector3(0, y, 0);
+ vertices[0].normal = Vector3(0, 1, 0);
vertexIndex++;
//Top circle.
- if( scaleTopRadius > 0.0 )
+ if(scaleTopRadius > 0.0)
{
//Loop around the circle.
- for( int i = 0; i < slices; i++, vertexIndex++ )
+ for(int i = 0; i < slices; i++, vertexIndex++)
{
x = sinTable[i] * scaleTopRadius;
z = cosTable[i] * scaleTopRadius;
//Upward-facing normal.
- vertices[vertexIndex].position = Vector3( x, y, z );
- vertices[vertexIndex].normal = Vector3( 0, 1, 0 );
+ vertices[vertexIndex].position = Vector3(x, y, z);
+ vertices[vertexIndex].normal = Vector3(0, 1, 0);
//Outward-facing normal.
- vertices[vertexIndex + slices].position = Vector3( x, y, z );
- vertices[vertexIndex + slices].normal = Vector3( x, 0, z );
+ vertices[vertexIndex + slices].position = Vector3(x, y, z);
+ vertices[vertexIndex + slices].normal = Vector3(x, 0, z);
}
vertexIndex += slices;
}
//Bottom circle.
- if( scaleBottomRadius > 0.0 )
+ if(scaleBottomRadius > 0.0)
{
//Loop around the circle.
- for( int i = 0; i < slices; i++, vertexIndex++ )
+ for(int i = 0; i < slices; i++, vertexIndex++)
{
x = sinTable[i] * scaleBottomRadius;
z = cosTable[i] * scaleBottomRadius;
//Outward-facing normal.
- vertices[vertexIndex].position = Vector3( x, -y, z );
- vertices[vertexIndex].normal = Vector3( x, 0, z );
+ vertices[vertexIndex].position = Vector3(x, -y, z);
+ vertices[vertexIndex].normal = Vector3(x, 0, z);
//Downward-facing normal.
- vertices[vertexIndex + slices].position = Vector3( x, -y, z );
- vertices[vertexIndex + slices].normal = Vector3( 0, -1, 0 );
+ vertices[vertexIndex + slices].position = Vector3(x, -y, z);
+ vertices[vertexIndex + slices].normal = Vector3(0, -1, 0);
}
vertexIndex += slices;
}
//Bottom center.
- vertices[vertexIndex].position = Vector3( 0, -y, 0 );
- vertices[vertexIndex].normal = Vector3( 0, -1, 0 );
+ vertices[vertexIndex].position = Vector3(0, -y, 0);
+ vertices[vertexIndex].normal = Vector3(0, -1, 0);
vertexIndex++;
}
-void PrimitiveVisual::FormConicTriangles( Vector<unsigned short>& indices, float scaleTopRadius,
- float scaleBottomRadius, int slices )
+void PrimitiveVisual::FormConicTriangles(Vector<unsigned short>& indices, float scaleTopRadius, float scaleBottomRadius, int slices)
{
- int indiceIndex = 0; //Track progress through indices.
+ int indiceIndex = 0; //Track progress through indices.
int numTriangles = 0;
- bool coneTop = scaleTopRadius <= 0.0;
- bool coneBottom = scaleBottomRadius <= 0.0;
+ bool coneTop = scaleTopRadius <= 0.0;
+ bool coneBottom = scaleBottomRadius <= 0.0;
- if( coneTop && coneBottom )
+ if(coneTop && coneBottom)
{
//Set indices to placeholder "error" values.
//This will display nothing, which is the expected behaviour for this edge case.
- indices.Resize( 3 );
+ indices.Resize(3);
return;
}
- if( !coneTop )
+ if(!coneTop)
{
numTriangles += 2 * slices;
}
- if( !coneBottom )
+ if(!coneBottom)
{
numTriangles += 2 * slices;
}
- indices.Resize( 3 * numTriangles );
+ indices.Resize(3 * numTriangles);
//Switch on the type of conic we have.
- if( !coneTop && !coneBottom )
+ if(!coneTop && !coneBottom)
{
//Top circle. Start at index of first outer point and go around.
- for( int i = 1; i <= slices; i++, indiceIndex += 3 )
+ for(int i = 1; i <= slices; i++, indiceIndex += 3)
{
- indices[indiceIndex] = 0;
+ indices[indiceIndex] = 0;
indices[indiceIndex + 1] = i;
- if( i == slices )
+ if(i == slices)
{
//End, so loop around.
indices[indiceIndex + 2] = 1;
}
}
- int topCycleBeginning = slices + 1;
+ int topCycleBeginning = slices + 1;
int bottomCycleBeginning = topCycleBeginning + slices;
//Vertical edges.
- for( int i = 0; i < slices; i++, indiceIndex += 6 )
+ for(int i = 0; i < slices; i++, indiceIndex += 6)
{
- if( i == slices - 1 )
+ if(i == slices - 1)
{
//End, so loop around.
- indices[indiceIndex] = topCycleBeginning + i;
+ indices[indiceIndex] = topCycleBeginning + i;
indices[indiceIndex + 1] = bottomCycleBeginning + i;
indices[indiceIndex + 2] = topCycleBeginning;
indices[indiceIndex + 3] = bottomCycleBeginning + i;
}
else
{
- indices[indiceIndex] = topCycleBeginning + i;
+ indices[indiceIndex] = topCycleBeginning + i;
indices[indiceIndex + 1] = bottomCycleBeginning + i;
indices[indiceIndex + 2] = topCycleBeginning + 1 + i;
indices[indiceIndex + 3] = bottomCycleBeginning + i;
int bottomFaceCycleBeginning = bottomCycleBeginning + slices;
//Bottom circle.
- for( int i = 0; i < slices; i++, indiceIndex += 3 )
+ for(int i = 0; i < slices; i++, indiceIndex += 3)
{
indices[indiceIndex] = bottomFaceCycleBeginning;
- if( i == slices - 1 )
+ if(i == slices - 1)
{
//End, so loop around.
indices[indiceIndex + 1] = bottomFaceCycleBeginning;
indices[indiceIndex + 2] = bottomFaceCycleBeginning + i;
}
}
- else if( !coneTop || !coneBottom )
+ else if(!coneTop || !coneBottom)
{
//Top circle/edges. Start at index of first outer point and go around.
- for( int i = 1; i <= slices; i++, indiceIndex += 3 )
+ for(int i = 1; i <= slices; i++, indiceIndex += 3)
{
- indices[indiceIndex] = 0;
+ indices[indiceIndex] = 0;
indices[indiceIndex + 1] = i;
- if( i == slices )
+ if(i == slices)
{
//End, so loop around.
indices[indiceIndex + 2] = 1;
}
//Bottom circle/edges. Start at index of first outer point and go around.
- for( int i = 1; i <= slices; i++, indiceIndex += 3 )
+ for(int i = 1; i <= slices; i++, indiceIndex += 3)
{
indices[indiceIndex] = 2 * slices + 1;
- if( i == slices )
+ if(i == slices)
{
//End, so loop around.
indices[indiceIndex + 1] = slices + 1;
}
}
-void PrimitiveVisual::ComputeCubeVertices( Vector<Vertex>& vertices, Vector3 dimensions )
+void PrimitiveVisual::ComputeCubeVertices(Vector<Vertex>& vertices, Vector3 dimensions)
{
- int numVertices = 4 * 6; //Four per face.
- int vertexIndex = 0; //Tracks progress through vertices.
- float scaledX = 0.5 * dimensions.x;
- float scaledY = 0.5 * dimensions.y;
- float scaledZ = 0.5 * dimensions.z;
+ int numVertices = 4 * 6; //Four per face.
+ int vertexIndex = 0; //Tracks progress through vertices.
+ float scaledX = 0.5 * dimensions.x;
+ float scaledY = 0.5 * dimensions.y;
+ float scaledZ = 0.5 * dimensions.z;
- vertices.Resize( numVertices );
+ vertices.Resize(numVertices);
Vector<Vector3> positions; //Stores vertex positions, which are shared between vertexes at the same position but with a different normal.
positions.Resize(8);
Vector<Vector3> normals; //Stores normals, which are shared between vertexes of the same face.
normals.Resize(6);
- positions[0] = Vector3( -scaledX, scaledY, -scaledZ );
- positions[1] = Vector3( scaledX, scaledY, -scaledZ );
- positions[2] = Vector3( scaledX, scaledY, scaledZ );
- positions[3] = Vector3( -scaledX, scaledY, scaledZ );
- positions[4] = Vector3( -scaledX, -scaledY, -scaledZ );
- positions[5] = Vector3( scaledX, -scaledY, -scaledZ );
- positions[6] = Vector3( scaledX, -scaledY, scaledZ );
- positions[7] = Vector3( -scaledX, -scaledY, scaledZ );
-
- normals[0] = Vector3( 0, 1, 0 );
- normals[1] = Vector3( 0, 0, -1 );
- normals[2] = Vector3( 1, 0, 0 );
- normals[3] = Vector3( 0, 0, 1 );
- normals[4] = Vector3( -1, 0, 0 );
- normals[5] = Vector3( 0, -1, 0 );
+ positions[0] = Vector3(-scaledX, scaledY, -scaledZ);
+ positions[1] = Vector3(scaledX, scaledY, -scaledZ);
+ positions[2] = Vector3(scaledX, scaledY, scaledZ);
+ positions[3] = Vector3(-scaledX, scaledY, scaledZ);
+ positions[4] = Vector3(-scaledX, -scaledY, -scaledZ);
+ positions[5] = Vector3(scaledX, -scaledY, -scaledZ);
+ positions[6] = Vector3(scaledX, -scaledY, scaledZ);
+ positions[7] = Vector3(-scaledX, -scaledY, scaledZ);
+
+ normals[0] = Vector3(0, 1, 0);
+ normals[1] = Vector3(0, 0, -1);
+ normals[2] = Vector3(1, 0, 0);
+ normals[3] = Vector3(0, 0, 1);
+ normals[4] = Vector3(-1, 0, 0);
+ normals[5] = Vector3(0, -1, 0);
//Top face, upward normals.
- for( int i = 0; i < 4; i++, vertexIndex++ )
+ for(int i = 0; i < 4; i++, vertexIndex++)
{
vertices[vertexIndex].position = positions[i];
- vertices[vertexIndex].normal = normals[0];
+ vertices[vertexIndex].normal = normals[0];
}
//Top face, outward normals.
- for( int i = 0; i < 4; i++, vertexIndex += 2 )
+ for(int i = 0; i < 4; i++, vertexIndex += 2)
{
vertices[vertexIndex].position = positions[i];
- vertices[vertexIndex].normal = normals[i + 1];
+ vertices[vertexIndex].normal = normals[i + 1];
- if( i == 3 )
+ if(i == 3)
{
//End, so loop around.
vertices[vertexIndex + 1].position = positions[0];
}
//Bottom face, outward normals.
- for( int i = 0; i < 4; i++, vertexIndex += 2 )
+ for(int i = 0; i < 4; i++, vertexIndex += 2)
{
vertices[vertexIndex].position = positions[i + 4];
- vertices[vertexIndex].normal = normals[i + 1];
+ vertices[vertexIndex].normal = normals[i + 1];
- if( i == 3 )
+ if(i == 3)
{
//End, so loop around.
vertices[vertexIndex + 1].position = positions[4];
}
//Bottom face, downward normals.
- for( int i = 0; i < 4; i++, vertexIndex++ )
+ for(int i = 0; i < 4; i++, vertexIndex++)
{
vertices[vertexIndex].position = positions[i + 4];
- vertices[vertexIndex].normal = normals[5];
+ vertices[vertexIndex].normal = normals[5];
}
-
}
-void PrimitiveVisual::FormCubeTriangles( Vector<unsigned short>& indices )
+void PrimitiveVisual::FormCubeTriangles(Vector<unsigned short>& indices)
{
- int numTriangles = 12;
- int triangleIndex = 0; //Track progress through indices.
+ int numTriangles = 12;
+ int triangleIndex = 0; //Track progress through indices.
- indices.Resize( 3 * numTriangles );
+ indices.Resize(3 * numTriangles);
//Top face.
- indices[triangleIndex] = 0;
+ indices[triangleIndex] = 0;
indices[triangleIndex + 1] = 2;
indices[triangleIndex + 2] = 1;
indices[triangleIndex + 3] = 2;
indices[triangleIndex + 5] = 3;
triangleIndex += 6;
- int topFaceStart = 4;
+ int topFaceStart = 4;
int bottomFaceStart = 12;
//Side faces.
- for( int i = 0; i < 8; i += 2, triangleIndex += 6 )
+ for(int i = 0; i < 8; i += 2, triangleIndex += 6)
{
- indices[triangleIndex ] = i + topFaceStart;
+ indices[triangleIndex] = i + topFaceStart;
indices[triangleIndex + 1] = i + topFaceStart + 1;
indices[triangleIndex + 2] = i + bottomFaceStart + 1;
indices[triangleIndex + 3] = i + topFaceStart;
}
//Bottom face.
- indices[triangleIndex] = 20;
+ indices[triangleIndex] = 20;
indices[triangleIndex + 1] = 21;
indices[triangleIndex + 2] = 22;
indices[triangleIndex + 3] = 22;
indices[triangleIndex + 5] = 20;
}
-void PrimitiveVisual::ComputeOctahedronVertices( Vector<Vertex>& vertices, Vector3 dimensions, float smoothness )
+void PrimitiveVisual::ComputeOctahedronVertices(Vector<Vertex>& vertices, Vector3 dimensions, float smoothness)
{
- int numVertices = 3 * 8; //Three per face
- int vertexIndex = 0; //Tracks progress through vertices.
- float scaledX = 0.5 * dimensions.x;
- float scaledY = 0.5 * dimensions.y;
- float scaledZ = 0.5 * dimensions.z;
+ int numVertices = 3 * 8; //Three per face
+ int vertexIndex = 0; //Tracks progress through vertices.
+ float scaledX = 0.5 * dimensions.x;
+ float scaledY = 0.5 * dimensions.y;
+ float scaledZ = 0.5 * dimensions.z;
- vertices.Resize( numVertices );
+ vertices.Resize(numVertices);
Vector<Vector3> positions; //Stores vertex positions, which are shared between vertexes at the same position but with a different normal.
positions.Resize(6);
Vector<Vector3> normals; //Stores normals, which are shared between vertexes of the same face.
normals.Resize(8);
- Vector<Vector3> outerNormals; //Holds normals that point outwards at each vertex.
- outerNormals.Resize( 6 );
-
- positions[0] = Vector3( 0.0, scaledY, 0.0 );
- positions[1] = Vector3( -scaledX, 0.0, 0.0 );
- positions[2] = Vector3( 0.0, 0.0, -scaledZ );
- positions[3] = Vector3( scaledX, 0.0, 0.0 );
- positions[4] = Vector3( 0.0, 0.0, scaledZ );
- positions[5] = Vector3( 0.0, -scaledY, 0.0 );
-
- normals[0] = Vector3( -1, 1, -1 );
- normals[1] = Vector3( 1, 1, -1 );
- normals[2] = Vector3( 1, 1, 1 );
- normals[3] = Vector3( -1, 1, 1 );
- normals[4] = Vector3( -1, -1, -1 );
- normals[5] = Vector3( 1, -1, -1 );
- normals[6] = Vector3( 1, -1, 1 );
- normals[7] = Vector3( -1, -1, 1 );
-
- outerNormals[0] = Vector3( 0, 1, 0 );
- outerNormals[1] = Vector3( -1, 0, 0 );
- outerNormals[2] = Vector3( 0, 0, -1 );
- outerNormals[3] = Vector3( 1, 0, 0 );
- outerNormals[4] = Vector3( 0, 0, 1 );
- outerNormals[5] = Vector3( 0, -1, 0 );
+ Vector<Vector3> outerNormals; //Holds normals that point outwards at each vertex.
+ outerNormals.Resize(6);
+
+ positions[0] = Vector3(0.0, scaledY, 0.0);
+ positions[1] = Vector3(-scaledX, 0.0, 0.0);
+ positions[2] = Vector3(0.0, 0.0, -scaledZ);
+ positions[3] = Vector3(scaledX, 0.0, 0.0);
+ positions[4] = Vector3(0.0, 0.0, scaledZ);
+ positions[5] = Vector3(0.0, -scaledY, 0.0);
+
+ normals[0] = Vector3(-1, 1, -1);
+ normals[1] = Vector3(1, 1, -1);
+ normals[2] = Vector3(1, 1, 1);
+ normals[3] = Vector3(-1, 1, 1);
+ normals[4] = Vector3(-1, -1, -1);
+ normals[5] = Vector3(1, -1, -1);
+ normals[6] = Vector3(1, -1, 1);
+ normals[7] = Vector3(-1, -1, 1);
+
+ outerNormals[0] = Vector3(0, 1, 0);
+ outerNormals[1] = Vector3(-1, 0, 0);
+ outerNormals[2] = Vector3(0, 0, -1);
+ outerNormals[3] = Vector3(1, 0, 0);
+ outerNormals[4] = Vector3(0, 0, 1);
+ outerNormals[5] = Vector3(0, -1, 0);
//Loop through top faces.
- for( int i = 0; i < 4; i++, vertexIndex += 3 )
+ for(int i = 0; i < 4; i++, vertexIndex += 3)
{
- if( i == 3 )
+ if(i == 3)
{
//End, so loop around.
- vertices[vertexIndex ].position = positions[0];
- vertices[vertexIndex ].normal = outerNormals[0] * smoothness + normals[i] * (1 - smoothness);
+ vertices[vertexIndex].position = positions[0];
+ vertices[vertexIndex].normal = outerNormals[0] * smoothness + normals[i] * (1 - smoothness);
vertices[vertexIndex + 1].position = positions[1];
- vertices[vertexIndex + 1].normal = outerNormals[1] * smoothness + normals[i] * (1 - smoothness);
+ vertices[vertexIndex + 1].normal = outerNormals[1] * smoothness + normals[i] * (1 - smoothness);
vertices[vertexIndex + 2].position = positions[i + 1];
- vertices[vertexIndex + 2].normal = outerNormals[i + 1] * smoothness + normals[i] * (1 - smoothness);
+ vertices[vertexIndex + 2].normal = outerNormals[i + 1] * smoothness + normals[i] * (1 - smoothness);
}
else
{
- vertices[vertexIndex ].position = positions[0];
- vertices[vertexIndex ].normal = outerNormals[0] * smoothness + normals[i] * (1 - smoothness);
+ vertices[vertexIndex].position = positions[0];
+ vertices[vertexIndex].normal = outerNormals[0] * smoothness + normals[i] * (1 - smoothness);
vertices[vertexIndex + 1].position = positions[i + 2];
- vertices[vertexIndex + 1].normal = outerNormals[i + 2] * smoothness + normals[i] * (1 - smoothness);
+ vertices[vertexIndex + 1].normal = outerNormals[i + 2] * smoothness + normals[i] * (1 - smoothness);
vertices[vertexIndex + 2].position = positions[i + 1];
- vertices[vertexIndex + 2].normal = outerNormals[i + 1] * smoothness + normals[i] * (1 - smoothness);
+ vertices[vertexIndex + 2].normal = outerNormals[i + 1] * smoothness + normals[i] * (1 - smoothness);
}
}
//Loop through bottom faces.
- for( int i = 0; i < 4; i++, vertexIndex += 3 )
+ for(int i = 0; i < 4; i++, vertexIndex += 3)
{
- if( i == 3 )
+ if(i == 3)
{
//End, so loop around.
- vertices[vertexIndex ].position = positions[5];
- vertices[vertexIndex ].normal = outerNormals[5] * smoothness + normals[i + 4] * (1 - smoothness);
+ vertices[vertexIndex].position = positions[5];
+ vertices[vertexIndex].normal = outerNormals[5] * smoothness + normals[i + 4] * (1 - smoothness);
vertices[vertexIndex + 1].position = positions[i + 1];
- vertices[vertexIndex + 1].normal = outerNormals[i + 1] * smoothness + normals[i + 4] * (1 - smoothness);
+ vertices[vertexIndex + 1].normal = outerNormals[i + 1] * smoothness + normals[i + 4] * (1 - smoothness);
vertices[vertexIndex + 2].position = positions[1];
- vertices[vertexIndex + 2].normal = outerNormals[1] * smoothness + normals[i + 4] * (1 - smoothness);
+ vertices[vertexIndex + 2].normal = outerNormals[1] * smoothness + normals[i + 4] * (1 - smoothness);
}
else
{
- vertices[vertexIndex ].position = positions[5];
- vertices[vertexIndex ].normal = outerNormals[5] * smoothness + normals[i + 4] * (1 - smoothness);
+ vertices[vertexIndex].position = positions[5];
+ vertices[vertexIndex].normal = outerNormals[5] * smoothness + normals[i + 4] * (1 - smoothness);
vertices[vertexIndex + 1].position = positions[i + 1];
- vertices[vertexIndex + 1].normal = outerNormals[i + 1] * smoothness + normals[i + 4] * (1 - smoothness);
+ vertices[vertexIndex + 1].normal = outerNormals[i + 1] * smoothness + normals[i + 4] * (1 - smoothness);
vertices[vertexIndex + 2].position = positions[i + 2];
- vertices[vertexIndex + 2].normal = outerNormals[i + 2] * smoothness + normals[i + 4] * (1 - smoothness);
+ vertices[vertexIndex + 2].normal = outerNormals[i + 2] * smoothness + normals[i + 4] * (1 - smoothness);
}
}
}
-void PrimitiveVisual::FormOctahedronTriangles( Vector<unsigned short>& indices )
+void PrimitiveVisual::FormOctahedronTriangles(Vector<unsigned short>& indices)
{
int numTriangles = 8;
- int numIndices = numTriangles * 3;
+ int numIndices = numTriangles * 3;
- indices.Resize( numIndices );
+ indices.Resize(numIndices);
- for( unsigned short i = 0; i < numIndices; i++ )
+ for(unsigned short i = 0; i < numIndices; i++)
{
indices[i] = i;
}
}
-void PrimitiveVisual::ComputeBevelledCubeVertices( Vector<Vertex>& vertices, Vector3 dimensions,
- float bevelPercentage, float bevelSmoothness )
+void PrimitiveVisual::ComputeBevelledCubeVertices(Vector<Vertex>& vertices, Vector3 dimensions, float bevelPercentage, float bevelSmoothness)
{
- int numPositions = 24;
- int numFaces = 26;
+ int numPositions = 24;
+ int numFaces = 26;
int numOuterFaces = 6;
- int numVertices = 6 * 4 + 12 * 4 + 8 * 3; //Six outer faces, 12 slanting rectangles, 8 slanting triangles.
- int vertexIndex = 0; //Track progress through vertices.
- int normalIndex = 0; //Track progress through normals, as vertices are calculated per face.
+ int numVertices = 6 * 4 + 12 * 4 + 8 * 3; //Six outer faces, 12 slanting rectangles, 8 slanting triangles.
+ int vertexIndex = 0; //Track progress through vertices.
+ int normalIndex = 0; //Track progress through normals, as vertices are calculated per face.
- float minDimension = std::min( std::min( dimensions.x, dimensions.y ), dimensions.z );
- float bevelAmount = 0.5 * std::min( bevelPercentage, minDimension ); //Cap bevel amount if necessary.
+ float minDimension = std::min(std::min(dimensions.x, dimensions.y), dimensions.z);
+ float bevelAmount = 0.5 * std::min(bevelPercentage, minDimension); //Cap bevel amount if necessary.
//Distances from centre to outer edge points.
float outerX = 0.5 * dimensions.x;
float bevelY = outerY - bevelAmount;
float bevelZ = outerZ - bevelAmount;
- Vector<Vector3> positions; //Holds object points, to be shared between vertexes.
- positions.Resize( numPositions );
- Vector<Vector3> normals; //Holds face normals, to be shared between vertexes.
- normals.Resize( numFaces );
- Vector<Vector3> outerNormals; //Holds normals of the outermost faces specifically.
- outerNormals.Resize( numOuterFaces );
- vertices.Resize( numVertices );
+ Vector<Vector3> positions; //Holds object points, to be shared between vertexes.
+ positions.Resize(numPositions);
+ Vector<Vector3> normals; //Holds face normals, to be shared between vertexes.
+ normals.Resize(numFaces);
+ Vector<Vector3> outerNormals; //Holds normals of the outermost faces specifically.
+ outerNormals.Resize(numOuterFaces);
+ vertices.Resize(numVertices);
//Topmost face positions.
- positions[0 ] = Vector3( -bevelX, outerY, -bevelZ );
- positions[1 ] = Vector3( bevelX, outerY, -bevelZ );
- positions[2 ] = Vector3( bevelX, outerY, bevelZ );
- positions[3 ] = Vector3( -bevelX, outerY, bevelZ );
+ positions[0] = Vector3(-bevelX, outerY, -bevelZ);
+ positions[1] = Vector3(bevelX, outerY, -bevelZ);
+ positions[2] = Vector3(bevelX, outerY, bevelZ);
+ positions[3] = Vector3(-bevelX, outerY, bevelZ);
//Second layer positions.
- positions[4 ] = Vector3( -outerX, bevelY, -bevelZ );
- positions[5 ] = Vector3( -bevelX, bevelY, -outerZ );
- positions[6 ] = Vector3( bevelX, bevelY, -outerZ );
- positions[7 ] = Vector3( outerX, bevelY, -bevelZ );
- positions[8 ] = Vector3( outerX, bevelY, bevelZ );
- positions[9 ] = Vector3( bevelX, bevelY, outerZ );
- positions[10] = Vector3( -bevelX, bevelY, outerZ );
- positions[11] = Vector3( -outerX, bevelY, bevelZ );
+ positions[4] = Vector3(-outerX, bevelY, -bevelZ);
+ positions[5] = Vector3(-bevelX, bevelY, -outerZ);
+ positions[6] = Vector3(bevelX, bevelY, -outerZ);
+ positions[7] = Vector3(outerX, bevelY, -bevelZ);
+ positions[8] = Vector3(outerX, bevelY, bevelZ);
+ positions[9] = Vector3(bevelX, bevelY, outerZ);
+ positions[10] = Vector3(-bevelX, bevelY, outerZ);
+ positions[11] = Vector3(-outerX, bevelY, bevelZ);
//Third layer positions.
- positions[12] = Vector3( -outerX, -bevelY, -bevelZ );
- positions[13] = Vector3( -bevelX, -bevelY, -outerZ );
- positions[14] = Vector3( bevelX, -bevelY, -outerZ );
- positions[15] = Vector3( outerX, -bevelY, -bevelZ );
- positions[16] = Vector3( outerX, -bevelY, bevelZ );
- positions[17] = Vector3( bevelX, -bevelY, outerZ );
- positions[18] = Vector3( -bevelX, -bevelY, outerZ );
- positions[19] = Vector3( -outerX, -bevelY, bevelZ );
+ positions[12] = Vector3(-outerX, -bevelY, -bevelZ);
+ positions[13] = Vector3(-bevelX, -bevelY, -outerZ);
+ positions[14] = Vector3(bevelX, -bevelY, -outerZ);
+ positions[15] = Vector3(outerX, -bevelY, -bevelZ);
+ positions[16] = Vector3(outerX, -bevelY, bevelZ);
+ positions[17] = Vector3(bevelX, -bevelY, outerZ);
+ positions[18] = Vector3(-bevelX, -bevelY, outerZ);
+ positions[19] = Vector3(-outerX, -bevelY, bevelZ);
//Bottom-most face positions.
- positions[20] = Vector3( -bevelX, -outerY, -bevelZ );
- positions[21] = Vector3( bevelX, -outerY, -bevelZ );
- positions[22] = Vector3( bevelX, -outerY, bevelZ );
- positions[23] = Vector3( -bevelX, -outerY, bevelZ );
+ positions[20] = Vector3(-bevelX, -outerY, -bevelZ);
+ positions[21] = Vector3(bevelX, -outerY, -bevelZ);
+ positions[22] = Vector3(bevelX, -outerY, bevelZ);
+ positions[23] = Vector3(-bevelX, -outerY, bevelZ);
//Top face normal.
- normals[0 ] = Vector3( 0, 1, 0 );
+ normals[0] = Vector3(0, 1, 0);
//Top slope normals.
- normals[1 ] = Vector3( -1, 1, -1 );
- normals[2 ] = Vector3( 0, 1, -1 );
- normals[3 ] = Vector3( 1, 1, -1 );
- normals[4 ] = Vector3( 1, 1, 0 );
- normals[5 ] = Vector3( 1, 1, 1 );
- normals[6 ] = Vector3( 0, 1, 1 );
- normals[7 ] = Vector3( -1, 1, 1 );
- normals[8 ] = Vector3( -1, 1, 0 );
+ normals[1] = Vector3(-1, 1, -1);
+ normals[2] = Vector3(0, 1, -1);
+ normals[3] = Vector3(1, 1, -1);
+ normals[4] = Vector3(1, 1, 0);
+ normals[5] = Vector3(1, 1, 1);
+ normals[6] = Vector3(0, 1, 1);
+ normals[7] = Vector3(-1, 1, 1);
+ normals[8] = Vector3(-1, 1, 0);
//Side normals.
- normals[9 ] = Vector3( -1, 0, -1 );
- normals[10] = Vector3( 0, 0, -1 );
- normals[11] = Vector3( 1, 0, -1 );
- normals[12] = Vector3( 1, 0, 0 );
- normals[13] = Vector3( 1, 0, 1 );
- normals[14] = Vector3( 0, 0, 1 );
- normals[15] = Vector3( -1, 0, 1 );
- normals[16] = Vector3( -1, 0, 0 );
+ normals[9] = Vector3(-1, 0, -1);
+ normals[10] = Vector3(0, 0, -1);
+ normals[11] = Vector3(1, 0, -1);
+ normals[12] = Vector3(1, 0, 0);
+ normals[13] = Vector3(1, 0, 1);
+ normals[14] = Vector3(0, 0, 1);
+ normals[15] = Vector3(-1, 0, 1);
+ normals[16] = Vector3(-1, 0, 0);
//Bottom slope normals.
- normals[17] = Vector3( -1, -1, -1 );
- normals[18] = Vector3( 0, -1, -1 );
- normals[19] = Vector3( 1, -1, -1 );
- normals[20] = Vector3( 1, -1, 0 );
- normals[21] = Vector3( 1, -1, 1 );
- normals[22] = Vector3( 0, -1, 1 );
- normals[23] = Vector3( -1, -1, 1 );
- normals[24] = Vector3( -1, -1, 0 );
+ normals[17] = Vector3(-1, -1, -1);
+ normals[18] = Vector3(0, -1, -1);
+ normals[19] = Vector3(1, -1, -1);
+ normals[20] = Vector3(1, -1, 0);
+ normals[21] = Vector3(1, -1, 1);
+ normals[22] = Vector3(0, -1, 1);
+ normals[23] = Vector3(-1, -1, 1);
+ normals[24] = Vector3(-1, -1, 0);
//Bottom face normal.
- normals[25] = Vector3( 0, -1, 0 );
+ normals[25] = Vector3(0, -1, 0);
//Top, back, right, front, left and bottom faces, respectively.
- outerNormals[0] = Vector3( 0, 1, 0 );
- outerNormals[1] = Vector3( 0, 0, -1 );
- outerNormals[2] = Vector3( 1, 0, 0 );
- outerNormals[3] = Vector3( 0, 0, 1 );
- outerNormals[4] = Vector3( -1, 0, 0 );
- outerNormals[5] = Vector3( 0, -1, 0 );
+ outerNormals[0] = Vector3(0, 1, 0);
+ outerNormals[1] = Vector3(0, 0, -1);
+ outerNormals[2] = Vector3(1, 0, 0);
+ outerNormals[3] = Vector3(0, 0, 1);
+ outerNormals[4] = Vector3(-1, 0, 0);
+ outerNormals[5] = Vector3(0, -1, 0);
//Topmost face vertices.
- for( int i = 0; i < 4; i++, vertexIndex++ )
+ for(int i = 0; i < 4; i++, vertexIndex++)
{
vertices[vertexIndex].position = positions[i];
- vertices[vertexIndex].normal = normals[normalIndex];
+ vertices[vertexIndex].normal = normals[normalIndex];
}
normalIndex++;
//Top slope vertices.
- for( int i = 0; i < 4; i++, vertexIndex += 7, normalIndex += 2 )
+ for(int i = 0; i < 4; i++, vertexIndex += 7, normalIndex += 2)
{
//Triangle part
- vertices[vertexIndex ].position = positions[i];
- vertices[vertexIndex ].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex].position = positions[i];
+ vertices[vertexIndex].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
vertices[vertexIndex + 1].position = positions[2 * i + 4];
- vertices[vertexIndex + 1].normal = outerNormals[( i == 0 ) ? 4 : i] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 1].normal = outerNormals[(i == 0) ? 4 : i] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
vertices[vertexIndex + 2].position = positions[2 * i + 5];
- vertices[vertexIndex + 2].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 2].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
//Rectangle part
- if( i == 3 )
+ if(i == 3)
{
//End, so loop around.
vertices[vertexIndex + 3].position = positions[i];
- vertices[vertexIndex + 3].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 3].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 4].position = positions[0];
- vertices[vertexIndex + 4].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 4].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 5].position = positions[2 * i + 5];
- vertices[vertexIndex + 5].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 5].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 6].position = positions[4];
- vertices[vertexIndex + 6].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 6].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
}
else
{
vertices[vertexIndex + 3].position = positions[i];
- vertices[vertexIndex + 3].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 3].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 4].position = positions[i + 1];
- vertices[vertexIndex + 4].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 4].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 5].position = positions[2 * i + 5];
- vertices[vertexIndex + 5].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 5].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 6].position = positions[2 * i + 6];
- vertices[vertexIndex + 6].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 6].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
}
}
int secondCycleBeginning = 4;
- int thirdCycleBeginning = secondCycleBeginning + 8;
+ int thirdCycleBeginning = secondCycleBeginning + 8;
int bottomCycleBeginning = thirdCycleBeginning + 8;
//Side vertices.
- for( int i = 0; i < 8; i++, vertexIndex += 4, normalIndex++ )
+ for(int i = 0; i < 8; i++, vertexIndex += 4, normalIndex++)
{
- if( i == 7 )
+ if(i == 7)
{
//End, so loop around.
- vertices[vertexIndex ].position = positions[secondCycleBeginning + i];
- vertices[vertexIndex ].normal = normals[normalIndex];
+ vertices[vertexIndex].position = positions[secondCycleBeginning + i];
+ vertices[vertexIndex].normal = normals[normalIndex];
vertices[vertexIndex + 1].position = positions[secondCycleBeginning];
- vertices[vertexIndex + 1].normal = normals[normalIndex];
+ vertices[vertexIndex + 1].normal = normals[normalIndex];
vertices[vertexIndex + 2].position = positions[thirdCycleBeginning + i];
- vertices[vertexIndex + 2].normal = normals[normalIndex];
+ vertices[vertexIndex + 2].normal = normals[normalIndex];
vertices[vertexIndex + 3].position = positions[thirdCycleBeginning];
- vertices[vertexIndex + 3].normal = normals[normalIndex];
+ vertices[vertexIndex + 3].normal = normals[normalIndex];
}
- else if( (i % 2) == 0 )
+ else if((i % 2) == 0)
{
//'even' faces are corner ones, and need smoothing.
- vertices[vertexIndex ].position = positions[secondCycleBeginning + i];
- vertices[vertexIndex ].normal = outerNormals[( i == 0 ) ? 4 : i / 2] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex].position = positions[secondCycleBeginning + i];
+ vertices[vertexIndex].normal = outerNormals[(i == 0) ? 4 : i / 2] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
vertices[vertexIndex + 1].position = positions[secondCycleBeginning + i + 1];
- vertices[vertexIndex + 1].normal = outerNormals[i / 2 + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 1].normal = outerNormals[i / 2 + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
vertices[vertexIndex + 2].position = positions[thirdCycleBeginning + i];
- vertices[vertexIndex + 2].normal = outerNormals[( i == 0 ) ? 4 : i / 2] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 2].normal = outerNormals[(i == 0) ? 4 : i / 2] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
vertices[vertexIndex + 3].position = positions[thirdCycleBeginning + i + 1];
- vertices[vertexIndex + 3].normal = outerNormals[i / 2 + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 3].normal = outerNormals[i / 2 + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
}
else
{
//'odd' faces are outer ones, and so don't need smoothing.
- vertices[vertexIndex ].position = positions[secondCycleBeginning + i];
- vertices[vertexIndex ].normal = normals[normalIndex];
+ vertices[vertexIndex].position = positions[secondCycleBeginning + i];
+ vertices[vertexIndex].normal = normals[normalIndex];
vertices[vertexIndex + 1].position = positions[secondCycleBeginning + i + 1];
- vertices[vertexIndex + 1].normal = normals[normalIndex];
+ vertices[vertexIndex + 1].normal = normals[normalIndex];
vertices[vertexIndex + 2].position = positions[thirdCycleBeginning + i];
- vertices[vertexIndex + 2].normal = normals[normalIndex];
+ vertices[vertexIndex + 2].normal = normals[normalIndex];
vertices[vertexIndex + 3].position = positions[thirdCycleBeginning + i + 1];
- vertices[vertexIndex + 3].normal = normals[normalIndex];
+ vertices[vertexIndex + 3].normal = normals[normalIndex];
}
}
//Bottom slope vertices.
- for( int i = 0; i < 4; i++, vertexIndex += 7, normalIndex += 2 )
+ for(int i = 0; i < 4; i++, vertexIndex += 7, normalIndex += 2)
{
//Triangle part
- vertices[vertexIndex ].position = positions[thirdCycleBeginning + 2 * i];
- vertices[vertexIndex ].normal = outerNormals[( i == 0 ) ? 4 : i] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex].position = positions[thirdCycleBeginning + 2 * i];
+ vertices[vertexIndex].normal = outerNormals[(i == 0) ? 4 : i] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
vertices[vertexIndex + 1].position = positions[thirdCycleBeginning + 2 * i + 1];
- vertices[vertexIndex + 1].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 1].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
vertices[vertexIndex + 2].position = positions[bottomCycleBeginning + i];
- vertices[vertexIndex + 2].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 2].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness);
//Rectangle part
- if( i == 3 )
+ if(i == 3)
{
//End, so loop around.
vertices[vertexIndex + 3].position = positions[thirdCycleBeginning + 2 * i + 1];
- vertices[vertexIndex + 3].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 3].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 4].position = positions[thirdCycleBeginning];
- vertices[vertexIndex + 4].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 4].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 5].position = positions[bottomCycleBeginning + i];
- vertices[vertexIndex + 5].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 5].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 6].position = positions[bottomCycleBeginning];
- vertices[vertexIndex + 6].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 6].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
}
else
{
vertices[vertexIndex + 3].position = positions[thirdCycleBeginning + 2 * i + 1];
- vertices[vertexIndex + 3].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 3].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 4].position = positions[thirdCycleBeginning + 2 * i + 2];
- vertices[vertexIndex + 4].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 4].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 5].position = positions[bottomCycleBeginning + i];
- vertices[vertexIndex + 5].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 5].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
vertices[vertexIndex + 6].position = positions[bottomCycleBeginning + i + 1];
- vertices[vertexIndex + 6].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
+ vertices[vertexIndex + 6].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness);
}
}
//Bottom-most face vertices.
- for( int i = 0; i < 4; i++, vertexIndex++ )
+ for(int i = 0; i < 4; i++, vertexIndex++)
{
- vertices[vertexIndex].position = positions[ bottomCycleBeginning + i];
- vertices[vertexIndex].normal = normals[normalIndex];
+ vertices[vertexIndex].position = positions[bottomCycleBeginning + i];
+ vertices[vertexIndex].normal = normals[normalIndex];
}
normalIndex++;
}
-void PrimitiveVisual::FormBevelledCubeTriangles( Vector<unsigned short>& indices )
+void PrimitiveVisual::FormBevelledCubeTriangles(Vector<unsigned short>& indices)
{
int numTriangles = 44; //(Going from top to bottom, that's 2 + 12 + 16 + 12 + 2)
- int indiceIndex = 0; //Track progress through indices.
- int vertexIndex = 0; //Track progress through vertices as they're processed.
+ int indiceIndex = 0; //Track progress through indices.
+ int vertexIndex = 0; //Track progress through vertices as they're processed.
- indices.Resize( 3 * numTriangles );
+ indices.Resize(3 * numTriangles);
//Top face.
- indices[indiceIndex ] = vertexIndex;
+ indices[indiceIndex] = vertexIndex;
indices[indiceIndex + 1] = vertexIndex + 2;
indices[indiceIndex + 2] = vertexIndex + 1;
indices[indiceIndex + 3] = vertexIndex + 0;
vertexIndex += 4;
//Top slopes.
- for( int i = 0; i < 4; i++, indiceIndex += 9, vertexIndex += 7 )
+ for(int i = 0; i < 4; i++, indiceIndex += 9, vertexIndex += 7)
{
//Triangle part.
- indices[indiceIndex ] = vertexIndex;
+ indices[indiceIndex] = vertexIndex;
indices[indiceIndex + 1] = vertexIndex + 2;
indices[indiceIndex + 2] = vertexIndex + 1;
}
//Side faces.
- for( int i = 0; i < 8; i++, indiceIndex += 6, vertexIndex += 4 )
+ for(int i = 0; i < 8; i++, indiceIndex += 6, vertexIndex += 4)
{
- indices[indiceIndex ] = vertexIndex;
+ indices[indiceIndex] = vertexIndex;
indices[indiceIndex + 1] = vertexIndex + 1;
indices[indiceIndex + 2] = vertexIndex + 2;
indices[indiceIndex + 3] = vertexIndex + 1;
}
//Bottom slopes.
- for( int i = 0; i < 4; i++, indiceIndex += 9, vertexIndex += 7 )
+ for(int i = 0; i < 4; i++, indiceIndex += 9, vertexIndex += 7)
{
//Triangle part.
- indices[indiceIndex ] = vertexIndex;
+ indices[indiceIndex] = vertexIndex;
indices[indiceIndex + 1] = vertexIndex + 1;
indices[indiceIndex + 2] = vertexIndex + 2;
}
//Bottom face.
- indices[indiceIndex ] = vertexIndex;
+ indices[indiceIndex] = vertexIndex;
indices[indiceIndex + 1] = vertexIndex + 1;
indices[indiceIndex + 2] = vertexIndex + 2;
indices[indiceIndex + 3] = vertexIndex + 0;
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "svg-rasterize-thread.h"
// EXTERNAL INCLUDES
-#include <dali/devel-api/adaptor-framework/thread-settings.h>
#include <dali/devel-api/adaptor-framework/file-loader.h>
+#include <dali/devel-api/adaptor-framework/thread-settings.h>
#include <dali/integration-api/adaptor-framework/adaptor.h>
#include <dali/integration-api/debug.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
RasterizingTask::RasterizingTask(SvgVisual* svgRenderer, VectorImageRenderer vectorRenderer, const VisualUrl& url, float dpi, unsigned int width, unsigned int height)
mHeight(height),
mLoadSuccess(false)
{
-
}
RasterizingTask::~RasterizingTask()
}
SvgRasterizeThread::SvgRasterizeThread()
-: mTrigger( new EventThreadCallback( MakeCallback( this, &SvgRasterizeThread::ApplyRasterizedSVGToSampler ) ) ),
- mLogFactory( Dali::Adaptor::Get().GetLogFactory() ),
- mIsThreadWaiting( false ),
- mProcessorRegistered( false )
+: mTrigger(new EventThreadCallback(MakeCallback(this, &SvgRasterizeThread::ApplyRasterizedSVGToSampler))),
+ mLogFactory(Dali::Adaptor::Get().GetLogFactory()),
+ mIsThreadWaiting(false),
+ mProcessorRegistered(false)
{
}
SvgRasterizeThread::~SvgRasterizeThread()
{
- if( mProcessorRegistered )
+ if(mProcessorRegistered)
{
- Adaptor::Get().UnregisterProcessor( *this );
+ Adaptor::Get().UnregisterProcessor(*this);
}
}
-void SvgRasterizeThread::TerminateThread( SvgRasterizeThread*& thread )
+void SvgRasterizeThread::TerminateThread(SvgRasterizeThread*& thread)
{
- if( thread )
+ if(thread)
{
// add an empty task would stop the thread from conditional wait.
- thread->AddTask( RasterizingTaskPtr() );
+ thread->AddTask(RasterizingTaskPtr());
// stop the thread
thread->Join();
// delete the thread
}
}
-void SvgRasterizeThread::AddTask( RasterizingTaskPtr task )
+void SvgRasterizeThread::AddTask(RasterizingTaskPtr task)
{
bool wasEmpty = false;
{
// Lock while adding task to the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
wasEmpty = mRasterizeTasks.empty();
- if( !wasEmpty && task != NULL)
+ if(!wasEmpty && task != NULL)
{
// Remove the tasks with the same renderer.
// Older task which waiting to rasterize and apply the svg to the same renderer is expired.
- for( std::vector< RasterizingTaskPtr >::iterator it = mRasterizeTasks.begin(), endIt = mRasterizeTasks.end(); it != endIt; ++it )
+ for(std::vector<RasterizingTaskPtr>::iterator it = mRasterizeTasks.begin(), endIt = mRasterizeTasks.end(); it != endIt; ++it)
{
- if( (*it) && (*it)->GetSvgVisual() == task->GetSvgVisual() )
+ if((*it) && (*it)->GetSvgVisual() == task->GetSvgVisual())
{
- mRasterizeTasks.erase( it );
+ mRasterizeTasks.erase(it);
break;
}
}
}
- mRasterizeTasks.push_back( task );
+ mRasterizeTasks.push_back(task);
- if( !mProcessorRegistered )
+ if(!mProcessorRegistered)
{
- Adaptor::Get().RegisterProcessor( *this );
+ Adaptor::Get().RegisterProcessor(*this);
mProcessorRegistered = true;
}
}
- if( wasEmpty)
+ if(wasEmpty)
{
// wake up the image loading thread
mConditionalWait.Notify();
RasterizingTaskPtr SvgRasterizeThread::NextCompletedTask()
{
// Lock while popping task out from the queue
- Mutex::ScopedLock lock( mMutex );
+ Mutex::ScopedLock lock(mMutex);
- if( mCompletedTasks.empty() )
+ if(mCompletedTasks.empty())
{
return RasterizingTaskPtr();
}
- std::vector< RasterizingTaskPtr >::iterator next = mCompletedTasks.begin();
- RasterizingTaskPtr nextTask = *next;
- mCompletedTasks.erase( next );
+ std::vector<RasterizingTaskPtr>::iterator next = mCompletedTasks.begin();
+ RasterizingTaskPtr nextTask = *next;
+ mCompletedTasks.erase(next);
return nextTask;
}
-void SvgRasterizeThread::RemoveTask( SvgVisual* visual )
+void SvgRasterizeThread::RemoveTask(SvgVisual* visual)
{
// Lock while remove task from the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
- if( !mRasterizeTasks.empty() )
+ ConditionalWait::ScopedLock lock(mConditionalWait);
+ if(!mRasterizeTasks.empty())
{
- for( std::vector< RasterizingTaskPtr >::iterator it = mRasterizeTasks.begin(), endIt = mRasterizeTasks.end(); it != endIt; ++it )
+ for(std::vector<RasterizingTaskPtr>::iterator it = mRasterizeTasks.begin(), endIt = mRasterizeTasks.end(); it != endIt; ++it)
{
- if( (*it) && (*it)->GetSvgVisual() == visual )
+ if((*it) && (*it)->GetSvgVisual() == visual)
{
- mRasterizeTasks.erase( it );
+ mRasterizeTasks.erase(it);
break;
}
}
UnregisterProcessor();
}
-void SvgRasterizeThread::DeleteImage( VectorImageRenderer vectorRenderer )
+void SvgRasterizeThread::DeleteImage(VectorImageRenderer vectorRenderer)
{
// Lock while adding image to the delete queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
- if( mIsThreadWaiting ) // no rasterization is ongoing, save to delete
+ if(mIsThreadWaiting) // no rasterization is ongoing, save to delete
{
// TODO: what?
}
else // wait to delete until current rasterization completed.
{
- mDeleteSvg.PushBack( &vectorRenderer );
+ mDeleteSvg.PushBack(&vectorRenderer);
}
}
RasterizingTaskPtr SvgRasterizeThread::NextTaskToProcess()
{
// Lock while popping task out from the queue
- ConditionalWait::ScopedLock lock( mConditionalWait );
+ ConditionalWait::ScopedLock lock(mConditionalWait);
// Delete the image here to make sure that it is not used in the nsvgRasterize()
- if( !mDeleteSvg.Empty() )
+ if(!mDeleteSvg.Empty())
{
mDeleteSvg.Clear();
}
// conditional wait
- while( mRasterizeTasks.empty() )
+ while(mRasterizeTasks.empty())
{
mIsThreadWaiting = true;
- mConditionalWait.Wait( lock );
+ mConditionalWait.Wait(lock);
}
mIsThreadWaiting = false;
// pop out the next task from the queue
- std::vector< RasterizingTaskPtr >::iterator next = mRasterizeTasks.begin();
- RasterizingTaskPtr nextTask = *next;
- mRasterizeTasks.erase( next );
+ std::vector<RasterizingTaskPtr>::iterator next = mRasterizeTasks.begin();
+ RasterizingTaskPtr nextTask = *next;
+ mRasterizeTasks.erase(next);
return nextTask;
}
-void SvgRasterizeThread::AddCompletedTask( RasterizingTaskPtr task )
+void SvgRasterizeThread::AddCompletedTask(RasterizingTaskPtr task)
{
// Lock while adding task to the queue
- Mutex::ScopedLock lock( mMutex );
- mCompletedTasks.push_back( task );
+ Mutex::ScopedLock lock(mMutex);
+ mCompletedTasks.push_back(task);
// wake up the main thread
mTrigger->Trigger();
void SvgRasterizeThread::Run()
{
- SetThreadName( "SVGThread" );
+ SetThreadName("SVGThread");
mLogFactory.InstallLogFunction();
- while( RasterizingTaskPtr task = NextTaskToProcess() )
+ while(RasterizingTaskPtr task = NextTaskToProcess())
{
- task->Load( );
- task->Rasterize( );
- AddCompletedTask( task );
+ task->Load();
+ task->Rasterize();
+ AddCompletedTask(task);
}
}
void SvgRasterizeThread::ApplyRasterizedSVGToSampler()
{
- while( RasterizingTaskPtr task = NextCompletedTask() )
+ while(RasterizingTaskPtr task = NextCompletedTask())
{
task->GetSvgVisual()->ApplyRasterizedImage(task->GetVectorRenderer(), task->GetPixelData(), task->IsLoaded());
}
void SvgRasterizeThread::UnregisterProcessor()
{
- if ( mProcessorRegistered )
+ if(mProcessorRegistered)
{
- if( mRasterizeTasks.empty() && mCompletedTasks.empty() )
+ if(mRasterizeTasks.empty() && mCompletedTasks.empty())
{
- Adaptor::Get().UnregisterProcessor( *this );
+ Adaptor::Get().UnregisterProcessor(*this);
mProcessorRegistered = false;
}
}
}
-
} // namespace Internal
} // namespace Toolkit
#include "svg-visual.h"
// INTERNAL INCLUDES
-#include <dali-toolkit/internal/visuals/svg/svg-rasterize-thread.h>
#include <dali-toolkit/internal/visuals/image-atlas-manager.h>
-#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
+#include <dali-toolkit/internal/visuals/svg/svg-rasterize-thread.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
+#include <dali-toolkit/internal/visuals/visual-string-constants.h>
#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
// EXTERNAL INCLUDES
-#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/adaptor-framework/file-loader.h>
+#include <dali/devel-api/common/stage.h>
#include <dali/integration-api/debug.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
// property name
const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
-}
+} // namespace
-SvgVisualPtr SvgVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties )
+SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
{
- SvgVisualPtr svgVisual( new SvgVisual( factoryCache, shaderFactory, imageUrl ) );
+ SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl));
svgVisual->Load();
svgVisual->SetProperties(properties);
svgVisual->Initialize();
return svgVisual;
}
-SvgVisualPtr SvgVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl )
+SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
{
- SvgVisualPtr svgVisual( new SvgVisual( factoryCache, shaderFactory, imageUrl ) );
+ SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl));
svgVisual->Load();
svgVisual->Initialize();
return svgVisual;
mImpl->mRenderer = Renderer::New(geometry, shader);
}
-void SvgVisual::DoSetProperties( const Property::Map& propertyMap )
+void SvgVisual::DoSetProperties(const Property::Map& propertyMap)
{
// url already passed in from constructor
- for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
+ for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
{
- KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
- if( keyValue.first.type == Property::Key::INDEX )
+ KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
+ if(keyValue.first.type == Property::Key::INDEX)
{
- DoSetProperty( keyValue.first.indexKey, keyValue.second );
+ DoSetProperty(keyValue.first.indexKey, keyValue.second);
}
- else if( keyValue.first == IMAGE_ATLASING )
+ else if(keyValue.first == IMAGE_ATLASING)
{
- DoSetProperty( Toolkit::ImageVisual::Property::ATLASING, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::ATLASING, keyValue.second);
}
- else if( keyValue.first == SYNCHRONOUS_LOADING )
+ else if(keyValue.first == SYNCHRONOUS_LOADING)
{
- DoSetProperty( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second );
+ DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second);
}
}
}
-void SvgVisual::DoSetProperty( Property::Index index, const Property::Value& value )
+void SvgVisual::DoSetProperty(Property::Index index, const Property::Value& value)
{
- switch( index )
+ switch(index)
{
case Toolkit::ImageVisual::Property::ATLASING:
{
- value.Get( mAttemptAtlasing );
+ value.Get(mAttemptAtlasing);
break;
}
case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
{
bool sync = false;
- if( value.Get( sync ) )
+ if(value.Get(sync))
{
- if( sync )
+ if(sync)
{
mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
}
}
}
-void SvgVisual::DoSetOnScene( Actor& actor )
+void SvgVisual::DoSetOnScene(Actor& actor)
{
TextureSet textureSet = TextureSet::New();
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
// Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
// Defer the rasterisation task until we get given a size (by Size Negotiation algorithm)
}
}
-void SvgVisual::DoSetOffScene( Actor& actor )
+void SvgVisual::DoSetOffScene(Actor& actor)
{
- mFactoryCache.GetSVGRasterizationThread()->RemoveTask( this );
+ mFactoryCache.GetSVGRasterizationThread()->RemoveTask(this);
- actor.RemoveRenderer( mImpl->mRenderer );
+ actor.RemoveRenderer(mImpl->mRenderer);
mPlacementActor.Reset();
// Reset the visual size to zero so that when adding the actor back to stage the SVG rasterization is forced
mVisualSize = Vector2::ZERO;
}
-void SvgVisual::GetNaturalSize( Vector2& naturalSize )
+void SvgVisual::GetNaturalSize(Vector2& naturalSize)
{
naturalSize.x = mDefaultWidth;
naturalSize.y = mDefaultHeight;
}
-void SvgVisual::DoCreatePropertyMap( Property::Map& map ) const
+void SvgVisual::DoCreatePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG );
- if( mImageUrl.IsValid() )
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG);
+ if(mImageUrl.IsValid())
{
- map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
- map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing );
+ map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
+ map.Insert(Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing);
}
- map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired() );
+ map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired());
}
-void SvgVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void SvgVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
{
buffer.PushBack('\0');
- Vector2 dpi = Stage::GetCurrent().GetDpi();
- float meanDpi = (dpi.height + dpi.width) * 0.5f;
+ Vector2 dpi = Stage::GetCurrent().GetDpi();
+ float meanDpi = (dpi.height + dpi.width) * 0.5f;
if(!mVectorRenderer.Load(buffer, meanDpi))
{
mLoadFailed = true;
}
}
-void SvgVisual::AddRasterizationTask( const Vector2& size )
+void SvgVisual::AddRasterizationTask(const Vector2& size)
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- unsigned int width = static_cast<unsigned int>(size.width);
- unsigned int height = static_cast<unsigned int>( size.height );
+ unsigned int width = static_cast<unsigned int>(size.width);
+ unsigned int height = static_cast<unsigned int>(size.height);
- Vector2 dpi = Stage::GetCurrent().GetDpi();
- float meanDpi = ( dpi.height + dpi.width ) * 0.5f;
+ Vector2 dpi = Stage::GetCurrent().GetDpi();
+ float meanDpi = (dpi.height + dpi.width) * 0.5f;
RasterizingTaskPtr newTask = new RasterizingTask(this, mVectorRenderer, mImageUrl, meanDpi, width, height);
if(IsSynchronousLoadingRequired() && mImageUrl.IsLocalResource())
}
else
{
- mFactoryCache.GetSVGRasterizationThread()->AddTask( newTask );
+ mFactoryCache.GetSVGRasterizationThread()->AddTask(newTask);
}
}
}
-void SvgVisual::ApplyRasterizedImage( VectorImageRenderer vectorRenderer, PixelData rasterizedPixelData, bool isLoaded )
+void SvgVisual::ApplyRasterizedImage(VectorImageRenderer vectorRenderer, PixelData rasterizedPixelData, bool isLoaded)
{
if(isLoaded && rasterizedPixelData && IsOnScene())
{
TextureSet currentTextureSet = mImpl->mRenderer.GetTextures();
- if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
+ if(mImpl->mFlags & Impl::IS_ATLASING_APPLIED)
{
- mFactoryCache.GetAtlasManager()->Remove( currentTextureSet, mAtlasRect );
+ mFactoryCache.GetAtlasManager()->Remove(currentTextureSet, mAtlasRect);
}
TextureSet textureSet;
- if( mAttemptAtlasing && !mImpl->mCustomShader )
+ if(mAttemptAtlasing && !mImpl->mCustomShader)
{
Vector4 atlasRect;
- textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData );
- if( textureSet ) // atlasing
+ textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData);
+ if(textureSet) // atlasing
{
- if( textureSet != currentTextureSet )
+ if(textureSet != currentTextureSet)
{
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
}
- mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect );
+ mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, atlasRect);
mAtlasRect = atlasRect;
mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
}
}
- if( !textureSet ) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed
+ if(!textureSet) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed
{
- Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888,
- rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight() );
- texture.Upload( rasterizedPixelData );
+ Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight());
+ texture.Upload(rasterizedPixelData);
mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
- if( mAtlasRect == FULL_TEXTURE_RECT )
+ if(mAtlasRect == FULL_TEXTURE_RECT)
{
textureSet = currentTextureSet;
}
else
{
textureSet = TextureSet::New();
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
- mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT );
+ mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT);
mAtlasRect = FULL_TEXTURE_RECT;
}
- if( textureSet )
+ if(textureSet)
{
- textureSet.SetTexture( 0, texture );
+ textureSet.SetTexture(0, texture);
}
}
// Rasterized pixels are uploaded to texture. If weak handle is holding a placement actor, it is the time to add the renderer to actor.
Actor actor = mPlacementActor.GetHandle();
- if( actor )
+ if(actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
// reset the weak handle so that the renderer only get added to actor once
mPlacementActor.Reset();
}
// Svg loaded and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
else if(!isLoaded || !rasterizedPixelData)
{
actor.AddRenderer(mImpl->mRenderer);
}
- ResourceReady( Toolkit::Visual::ResourceStatus::FAILED );
+ ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
}
}
void SvgVisual::OnSetTransform()
{
- Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize );
+ Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize);
if(IsOnScene() && !mLoadFailed)
{
- if( visualSize != mVisualSize )
+ if(visualSize != mVisualSize)
{
- AddRasterizationTask( visualSize );
+ AddRasterizationTask(visualSize);
mVisualSize = visualSize;
}
}
bool SvgVisual::IsResourceReady() const
{
- return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
- mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED );
+ return (mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
+ mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED);
}
} // namespace Internal
#include <dali-toolkit/internal/visuals/text/text-visual.h>
// EXTERNAL INCLUDES
-#include <dali/public-api/animation/constraints.h>
-#include <dali/devel-api/rendering/renderer-devel.h>
-#include <dali/devel-api/text-abstraction/text-abstraction-definitions.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
#include <dali/devel-api/adaptor-framework/window-devel.h>
#include <dali/devel-api/images/pixel-data-devel.h>
+#include <dali/devel-api/rendering/renderer-devel.h>
+#include <dali/devel-api/text-abstraction/text-abstraction-definitions.h>
+#include <dali/public-api/animation/constraints.h>
#include <string.h>
// INTERNAL HEADER
-#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
-#include <dali-toolkit/devel-api/visuals/text-visual-properties-devel.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
+#include <dali-toolkit/devel-api/text/text-enumerations-devel.h>
+#include <dali-toolkit/devel-api/visuals/text-visual-properties-devel.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/text/script-run.h>
+#include <dali-toolkit/internal/text/text-effects-style.h>
+#include <dali-toolkit/internal/text/text-enumerations-impl.h>
+#include <dali-toolkit/internal/text/text-font-style.h>
#include <dali-toolkit/internal/visuals/image-atlas-manager.h>
-#include <dali-toolkit/internal/visuals/visual-base-impl.h>
#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
+#include <dali-toolkit/internal/visuals/visual-base-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/text/text-font-style.h>
-#include <dali-toolkit/internal/text/text-effects-style.h>
-#include <dali-toolkit/internal/text/script-run.h>
-#include <dali-toolkit/internal/text/text-enumerations-impl.h>
-#include <dali-toolkit/devel-api/text/text-enumerations-devel.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-const Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f );
+const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
/**
* Return Property index for the given string key
* return the key as an index
*/
-Dali::Property::Index StringKeyToIndexKey( const std::string& stringKey )
+Dali::Property::Index StringKeyToIndexKey(const std::string& stringKey)
{
Dali::Property::Index result = Property::INVALID_KEY;
- if( stringKey == VISUAL_TYPE )
+ if(stringKey == VISUAL_TYPE)
{
result = Toolkit::Visual::Property::TYPE;
}
- else if( stringKey == TEXT_PROPERTY )
+ else if(stringKey == TEXT_PROPERTY)
{
result = Toolkit::TextVisual::Property::TEXT;
}
- else if( stringKey == FONT_FAMILY_PROPERTY )
+ else if(stringKey == FONT_FAMILY_PROPERTY)
{
result = Toolkit::TextVisual::Property::FONT_FAMILY;
}
- else if( stringKey == FONT_STYLE_PROPERTY )
+ else if(stringKey == FONT_STYLE_PROPERTY)
{
result = Toolkit::TextVisual::Property::FONT_STYLE;
}
- else if( stringKey == POINT_SIZE_PROPERTY )
+ else if(stringKey == POINT_SIZE_PROPERTY)
{
result = Toolkit::TextVisual::Property::POINT_SIZE;
}
- else if( stringKey == MULTI_LINE_PROPERTY )
+ else if(stringKey == MULTI_LINE_PROPERTY)
{
result = Toolkit::TextVisual::Property::MULTI_LINE;
}
- else if( stringKey == HORIZONTAL_ALIGNMENT_PROPERTY )
+ else if(stringKey == HORIZONTAL_ALIGNMENT_PROPERTY)
{
result = Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT;
}
- else if( stringKey == VERTICAL_ALIGNMENT_PROPERTY )
+ else if(stringKey == VERTICAL_ALIGNMENT_PROPERTY)
{
result = Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT;
}
- else if( stringKey == TEXT_COLOR_PROPERTY )
+ else if(stringKey == TEXT_COLOR_PROPERTY)
{
result = Toolkit::TextVisual::Property::TEXT_COLOR;
}
- else if( stringKey == ENABLE_MARKUP_PROPERTY )
+ else if(stringKey == ENABLE_MARKUP_PROPERTY)
{
result = Toolkit::TextVisual::Property::ENABLE_MARKUP;
}
- else if( stringKey == SHADOW_PROPERTY )
+ else if(stringKey == SHADOW_PROPERTY)
{
result = Toolkit::TextVisual::Property::SHADOW;
}
- else if( stringKey == UNDERLINE_PROPERTY )
+ else if(stringKey == UNDERLINE_PROPERTY)
{
result = Toolkit::TextVisual::Property::UNDERLINE;
}
- else if( stringKey == OUTLINE_PROPERTY )
+ else if(stringKey == OUTLINE_PROPERTY)
{
result = Toolkit::DevelTextVisual::Property::OUTLINE;
}
- else if( stringKey == BACKGROUND_PROPERTY )
+ else if(stringKey == BACKGROUND_PROPERTY)
{
result = Toolkit::DevelTextVisual::Property::BACKGROUND;
}
return result;
}
-void TextColorConstraint( Vector4& current, const PropertyInputContainer& inputs )
+void TextColorConstraint(Vector4& current, const PropertyInputContainer& inputs)
{
Vector4 color = inputs[0]->GetVector4();
- current.r = color.r * color.a;
- current.g = color.g * color.a;
- current.b = color.b * color.a;
- current.a = color.a;
+ current.r = color.r * color.a;
+ current.g = color.g * color.a;
+ current.b = color.b * color.a;
+ current.a = color.a;
}
-void OpacityConstraint( float& current, const PropertyInputContainer& inputs )
+void OpacityConstraint(float& current, const PropertyInputContainer& inputs)
{
// Make zero if the alpha value of text color is zero to skip rendering text
- if( EqualsZero( inputs[0]->GetVector4().a ) )
+ if(EqualsZero(inputs[0]->GetVector4().a))
{
current = 0.0f;
}
} // unnamed namespace
-TextVisualPtr TextVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+TextVisualPtr TextVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
TextVisualPtr textVisualPtr(new TextVisual(factoryCache));
textVisualPtr->SetProperties(properties);
return textVisualPtr;
}
-Property::Map TextVisual::ConvertStringKeysToIndexKeys( const Property::Map& propertyMap )
+Property::Map TextVisual::ConvertStringKeysToIndexKeys(const Property::Map& propertyMap)
{
Property::Map outMap;
- for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
+ for(Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index)
{
- const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
+ const KeyValuePair& keyValue = propertyMap.GetKeyValue(index);
Property::Index indexKey = keyValue.first.indexKey;
- if ( keyValue.first.type == Property::Key::STRING )
+ if(keyValue.first.type == Property::Key::STRING)
{
- indexKey = StringKeyToIndexKey( keyValue.first.stringKey );
+ indexKey = StringKeyToIndexKey(keyValue.first.stringKey);
}
- outMap.Insert( indexKey, keyValue.second );
+ outMap.Insert(indexKey, keyValue.second);
}
return outMap;
}
-float TextVisual::GetHeightForWidth( float width )
+float TextVisual::GetHeightForWidth(float width)
{
- return mController->GetHeightForWidth( width );
+ return mController->GetHeightForWidth(width);
}
-void TextVisual::GetNaturalSize( Vector2& naturalSize )
+void TextVisual::GetNaturalSize(Vector2& naturalSize)
{
naturalSize = mController->GetNaturalSize().GetVectorXY();
}
-void TextVisual::DoCreatePropertyMap( Property::Map& map ) const
+void TextVisual::DoCreatePropertyMap(Property::Map& map) const
{
Property::Value value;
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT);
std::string text;
- mController->GetText( text );
- map.Insert( Toolkit::TextVisual::Property::TEXT, text );
+ mController->GetText(text);
+ map.Insert(Toolkit::TextVisual::Property::TEXT, text);
- map.Insert( Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily() );
+ map.Insert(Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily());
- GetFontStyleProperty( mController, value, Text::FontStyle::DEFAULT );
- map.Insert( Toolkit::TextVisual::Property::FONT_STYLE, value );
+ GetFontStyleProperty(mController, value, Text::FontStyle::DEFAULT);
+ map.Insert(Toolkit::TextVisual::Property::FONT_STYLE, value);
- map.Insert( Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ) );
+ map.Insert(Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultFontSize(Text::Controller::POINT_SIZE));
- map.Insert( Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled() );
+ map.Insert(Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled());
- map.Insert( Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, mController->GetHorizontalAlignment() );
+ map.Insert(Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, mController->GetHorizontalAlignment());
- map.Insert( Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, mController->GetVerticalAlignment() );
+ map.Insert(Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, mController->GetVerticalAlignment());
- map.Insert( Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor() );
+ map.Insert(Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor());
- map.Insert( Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled() );
+ map.Insert(Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled());
- GetShadowProperties( mController, value, Text::EffectStyle::DEFAULT );
- map.Insert( Toolkit::TextVisual::Property::SHADOW, value );
+ GetShadowProperties(mController, value, Text::EffectStyle::DEFAULT);
+ map.Insert(Toolkit::TextVisual::Property::SHADOW, value);
- GetUnderlineProperties( mController, value, Text::EffectStyle::DEFAULT );
- map.Insert( Toolkit::TextVisual::Property::UNDERLINE, value );
+ GetUnderlineProperties(mController, value, Text::EffectStyle::DEFAULT);
+ map.Insert(Toolkit::TextVisual::Property::UNDERLINE, value);
- GetOutlineProperties( mController, value, Text::EffectStyle::DEFAULT );
- map.Insert( Toolkit::DevelTextVisual::Property::OUTLINE, value );
+ GetOutlineProperties(mController, value, Text::EffectStyle::DEFAULT);
+ map.Insert(Toolkit::DevelTextVisual::Property::OUTLINE, value);
- GetBackgroundProperties( mController, value, Text::EffectStyle::DEFAULT );
- map.Insert( Toolkit::DevelTextVisual::Property::BACKGROUND, value );
+ GetBackgroundProperties(mController, value, Text::EffectStyle::DEFAULT);
+ map.Insert(Toolkit::DevelTextVisual::Property::BACKGROUND, value);
}
-void TextVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void TextVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT);
std::string text;
- mController->GetText( text );
- map.Insert( Toolkit::TextVisual::Property::TEXT, text );
+ mController->GetText(text);
+ map.Insert(Toolkit::TextVisual::Property::TEXT, text);
}
-
-TextVisual::TextVisual( VisualFactoryCache& factoryCache )
-: Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::TEXT ),
- mController( Text::Controller::New() ),
- mTypesetter( Text::Typesetter::New( mController->GetTextModel() ) ),
- mAnimatableTextColorPropertyIndex( Property::INVALID_INDEX ),
- mRendererUpdateNeeded( false )
+TextVisual::TextVisual(VisualFactoryCache& factoryCache)
+: Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::TEXT),
+ mController(Text::Controller::New()),
+ mTypesetter(Text::Typesetter::New(mController->GetTextModel())),
+ mAnimatableTextColorPropertyIndex(Property::INVALID_INDEX),
+ mRendererUpdateNeeded(false)
{
}
mImpl->mRenderer = Renderer::New(geometry, shader);
}
-void TextVisual::DoSetProperties( const Property::Map& propertyMap )
+void TextVisual::DoSetProperties(const Property::Map& propertyMap)
{
- for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index )
+ for(Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index)
{
- const KeyValuePair& keyValue = propertyMap.GetKeyValue( index );
+ const KeyValuePair& keyValue = propertyMap.GetKeyValue(index);
Property::Index indexKey = keyValue.first.indexKey;
- if( keyValue.first.type == Property::Key::STRING )
+ if(keyValue.first.type == Property::Key::STRING)
{
- indexKey = StringKeyToIndexKey( keyValue.first.stringKey );
+ indexKey = StringKeyToIndexKey(keyValue.first.stringKey);
}
- DoSetProperty( indexKey, keyValue.second );
+ DoSetProperty(indexKey, keyValue.second);
}
// Elide the text if it exceeds the boundaries.
- mController->SetTextElideEnabled( true );
+ mController->SetTextElideEnabled(true);
// Retrieve the layout engine to set the cursor's width.
Text::Layout::Engine& engine = mController->GetLayoutEngine();
// Sets 0 as cursor's width.
- engine.SetCursorWidth( 0u ); // Do not layout space for the cursor.
+ engine.SetCursorWidth(0u); // Do not layout space for the cursor.
}
-void TextVisual::DoSetOnScene( Actor& actor )
+void TextVisual::DoSetOnScene(Actor& actor)
{
mControl = actor;
- mImpl->mRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT );
+ mImpl->mRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT);
// Enable the pre-multiplied alpha to improve the text quality
EnablePreMultipliedAlpha(true);
- const Vector4& defaultColor = mController->GetTextModel()->GetDefaultColor();
- Dali::Property::Index shaderTextColorIndex = mImpl->mRenderer.RegisterProperty( "uTextColorAnimatable", defaultColor );
+ const Vector4& defaultColor = mController->GetTextModel()->GetDefaultColor();
+ Dali::Property::Index shaderTextColorIndex = mImpl->mRenderer.RegisterProperty("uTextColorAnimatable", defaultColor);
- if ( mAnimatableTextColorPropertyIndex != Property::INVALID_INDEX )
+ if(mAnimatableTextColorPropertyIndex != Property::INVALID_INDEX)
{
// Create constraint for the animatable text's color Property with uTextColorAnimatable in the renderer.
- if( shaderTextColorIndex != Property::INVALID_INDEX )
+ if(shaderTextColorIndex != Property::INVALID_INDEX)
{
- Constraint colorConstraint = Constraint::New<Vector4>( mImpl->mRenderer, shaderTextColorIndex, TextColorConstraint );
- colorConstraint.AddSource( Source( actor, mAnimatableTextColorPropertyIndex ) );
+ Constraint colorConstraint = Constraint::New<Vector4>(mImpl->mRenderer, shaderTextColorIndex, TextColorConstraint);
+ colorConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex));
colorConstraint.Apply();
// Make zero if the alpha value of text color is zero to skip rendering text
- Constraint opacityConstraint = Constraint::New< float >( mImpl->mRenderer, Dali::DevelRenderer::Property::OPACITY, OpacityConstraint );
- opacityConstraint.AddSource( Source( actor, mAnimatableTextColorPropertyIndex ) );
+ Constraint opacityConstraint = Constraint::New<float>(mImpl->mRenderer, Dali::DevelRenderer::Property::OPACITY, OpacityConstraint);
+ opacityConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex));
opacityConstraint.Apply();
}
}
// Renderer needs textures and to be added to control
mRendererUpdateNeeded = true;
- mRendererList.push_back( mImpl->mRenderer );
+ mRendererList.push_back(mImpl->mRenderer);
UpdateRenderer();
}
-void TextVisual::RemoveRenderer( Actor& actor )
+void TextVisual::RemoveRenderer(Actor& actor)
{
- for( RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
+ for(RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
{
Renderer renderer = (*iter);
- if( renderer )
+ if(renderer)
{
// Removes the renderer from the actor.
- actor.RemoveRenderer( renderer );
+ actor.RemoveRenderer(renderer);
}
}
// Clear the renderer list
mRendererList.clear();
}
-void TextVisual::DoSetOffScene( Actor& actor )
+void TextVisual::DoSetOffScene(Actor& actor)
{
- RemoveRenderer( actor );
+ RemoveRenderer(actor);
// Resets the control handle.
mControl.Reset();
UpdateRenderer();
}
-void TextVisual::DoSetProperty( Dali::Property::Index index, const Dali::Property::Value& propertyValue )
+void TextVisual::DoSetProperty(Dali::Property::Index index, const Dali::Property::Value& propertyValue)
{
- switch( index )
+ switch(index)
{
case Toolkit::TextVisual::Property::ENABLE_MARKUP:
{
const bool enableMarkup = propertyValue.Get<bool>();
- mController->SetMarkupProcessorEnabled( enableMarkup );
+ mController->SetMarkupProcessorEnabled(enableMarkup);
break;
}
case Toolkit::TextVisual::Property::TEXT:
{
- mController->SetText( propertyValue.Get<std::string>() );
+ mController->SetText(propertyValue.Get<std::string>());
break;
}
case Toolkit::TextVisual::Property::FONT_FAMILY:
{
- SetFontFamilyProperty( mController, propertyValue );
+ SetFontFamilyProperty(mController, propertyValue);
break;
}
case Toolkit::TextVisual::Property::FONT_STYLE:
{
- SetFontStyleProperty( mController, propertyValue, Text::FontStyle::DEFAULT );
+ SetFontStyleProperty(mController, propertyValue, Text::FontStyle::DEFAULT);
break;
}
case Toolkit::TextVisual::Property::POINT_SIZE:
{
const float pointSize = propertyValue.Get<float>();
- if( !Equals( mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) )
+ if(!Equals(mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize))
{
- mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE );
+ mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE);
}
break;
}
case Toolkit::TextVisual::Property::MULTI_LINE:
{
- mController->SetMultiLineEnabled( propertyValue.Get<bool>() );
+ mController->SetMultiLineEnabled(propertyValue.Get<bool>());
break;
}
case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT:
{
- if( mController )
+ if(mController)
{
- Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( Toolkit::Text::GetHorizontalAlignmentEnumeration( propertyValue, alignment ) )
+ Text::HorizontalAlignment::Type alignment(static_cast<Text::HorizontalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(Toolkit::Text::GetHorizontalAlignmentEnumeration(propertyValue, alignment))
{
- mController->SetHorizontalAlignment( alignment );
+ mController->SetHorizontalAlignment(alignment);
}
}
break;
}
case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT:
{
- if( mController )
+ if(mController)
{
- Toolkit::Text::VerticalAlignment::Type alignment( static_cast< Text::VerticalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set
- if( Toolkit::Text::GetVerticalAlignmentEnumeration( propertyValue, alignment) )
+ Toolkit::Text::VerticalAlignment::Type alignment(static_cast<Text::VerticalAlignment::Type>(-1)); // Set to invalid value to ensure a valid mode does get set
+ if(Toolkit::Text::GetVerticalAlignmentEnumeration(propertyValue, alignment))
{
- mController->SetVerticalAlignment( alignment );
+ mController->SetVerticalAlignment(alignment);
}
}
break;
}
case Toolkit::TextVisual::Property::TEXT_COLOR:
{
- const Vector4& textColor = propertyValue.Get< Vector4 >();
- if( mController->GetDefaultColor() != textColor )
+ const Vector4& textColor = propertyValue.Get<Vector4>();
+ if(mController->GetDefaultColor() != textColor)
{
- mController->SetDefaultColor( textColor );
+ mController->SetDefaultColor(textColor);
}
break;
}
case Toolkit::TextVisual::Property::SHADOW:
{
- SetShadowProperties( mController, propertyValue, Text::EffectStyle::DEFAULT );
+ SetShadowProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::TextVisual::Property::UNDERLINE:
{
- SetUnderlineProperties( mController, propertyValue, Text::EffectStyle::DEFAULT );
+ SetUnderlineProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::DevelTextVisual::Property::OUTLINE:
{
- SetOutlineProperties( mController, propertyValue, Text::EffectStyle::DEFAULT );
+ SetOutlineProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
break;
}
case Toolkit::DevelTextVisual::Property::BACKGROUND:
{
- SetBackgroundProperties( mController, propertyValue, Text::EffectStyle::DEFAULT );
+ SetBackgroundProperties(mController, propertyValue, Text::EffectStyle::DEFAULT);
break;
}
}
void TextVisual::UpdateRenderer()
{
Actor control = mControl.GetHandle();
- if( !control )
+ if(!control)
{
// Nothing to do.
return;
// Calculates the size to be used to relayout.
Vector2 relayoutSize;
- const bool isWidthRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.z ) < Math::MACHINE_EPSILON_1000;
- const bool isHeightRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.w ) < Math::MACHINE_EPSILON_1000;
+ const bool isWidthRelative = fabsf(mImpl->mTransform.mOffsetSizeMode.z) < Math::MACHINE_EPSILON_1000;
+ const bool isHeightRelative = fabsf(mImpl->mTransform.mOffsetSizeMode.w) < Math::MACHINE_EPSILON_1000;
// Round the size and offset to avoid pixel alignement issues.
- relayoutSize.width = floorf( 0.5f + ( isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width ) );
- relayoutSize.height = floorf( 0.5f + ( isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height ) );
+ relayoutSize.width = floorf(0.5f + (isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width));
+ relayoutSize.height = floorf(0.5f + (isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height));
std::string text;
- mController->GetText( text );
+ mController->GetText(text);
- if( ( fabsf( relayoutSize.width ) < Math::MACHINE_EPSILON_1000 ) || ( fabsf( relayoutSize.height ) < Math::MACHINE_EPSILON_1000 ) || text.empty() )
+ if((fabsf(relayoutSize.width) < Math::MACHINE_EPSILON_1000) || (fabsf(relayoutSize.height) < Math::MACHINE_EPSILON_1000) || text.empty())
{
// Remove the texture set and any renderer previously set.
- RemoveRenderer( control );
+ RemoveRenderer(control);
// Nothing else to do if the relayout size is zero.
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
return;
}
-
Dali::LayoutDirection::Type layoutDirection;
- if( mController->IsMatchSystemLanguageDirection() )
+ if(mController->IsMatchSystemLanguageDirection())
{
- layoutDirection = static_cast<Dali::LayoutDirection::Type>( DevelWindow::Get( control ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ layoutDirection = static_cast<Dali::LayoutDirection::Type>(DevelWindow::Get(control).GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
}
else
{
- layoutDirection = static_cast<Dali::LayoutDirection::Type>( control.GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get<int>() );
+ layoutDirection = static_cast<Dali::LayoutDirection::Type>(control.GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>());
}
- const Text::Controller::UpdateTextType updateTextType = mController->Relayout( relayoutSize, layoutDirection );
+ const Text::Controller::UpdateTextType updateTextType = mController->Relayout(relayoutSize, layoutDirection);
- if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType )
- || mRendererUpdateNeeded )
+ if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType) || mRendererUpdateNeeded)
{
mRendererUpdateNeeded = false;
// Remove the texture set and any renderer previously set.
- RemoveRenderer( control );
+ RemoveRenderer(control);
- if( ( relayoutSize.width > Math::MACHINE_EPSILON_1000 ) &&
- ( relayoutSize.height > Math::MACHINE_EPSILON_1000 ) )
+ if((relayoutSize.width > Math::MACHINE_EPSILON_1000) &&
+ (relayoutSize.height > Math::MACHINE_EPSILON_1000))
{
// Check whether it is a markup text with multiple text colors
- const Vector4* const colorsBuffer = mController->GetTextModel()->GetColors();
- bool hasMultipleTextColors = ( NULL != colorsBuffer );
+ const Vector4* const colorsBuffer = mController->GetTextModel()->GetColors();
+ bool hasMultipleTextColors = (NULL != colorsBuffer);
// Check whether the text contains any color glyph
bool containsColorGlyph = false;
- TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
- const Text::GlyphInfo* const glyphsBuffer = mController->GetTextModel()->GetGlyphs();
- const Text::Length numberOfGlyphs = mController->GetTextModel()->GetNumberOfGlyphs();
- for ( Text::Length glyphIndex = 0; glyphIndex < numberOfGlyphs; glyphIndex++ )
+ TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get();
+ const Text::GlyphInfo* const glyphsBuffer = mController->GetTextModel()->GetGlyphs();
+ const Text::Length numberOfGlyphs = mController->GetTextModel()->GetNumberOfGlyphs();
+ for(Text::Length glyphIndex = 0; glyphIndex < numberOfGlyphs; glyphIndex++)
{
// Retrieve the glyph's info.
const Text::GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
// Whether the current glyph is a color one.
- if( fontClient.IsColorGlyph( glyphInfo->fontId, glyphInfo->index ) )
+ if(fontClient.IsColorGlyph(glyphInfo->fontId, glyphInfo->index))
{
containsColorGlyph = true;
break;
// Check whether the text contains any style colors (e.g. underline color, shadow color, etc.)
- bool shadowEnabled = false;
- const Vector2& shadowOffset = mController->GetTextModel()->GetShadowOffset();
- if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
+ bool shadowEnabled = false;
+ const Vector2& shadowOffset = mController->GetTextModel()->GetShadowOffset();
+ if(fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1)
{
shadowEnabled = true;
}
- const bool underlineEnabled = mController->GetTextModel()->IsUnderlineEnabled();
- const bool outlineEnabled = ( mController->GetTextModel()->GetOutlineWidth() > Math::MACHINE_EPSILON_1 );
- const bool backgroundEnabled = mController->GetTextModel()->IsBackgroundEnabled();;
-
- const bool styleEnabled = ( shadowEnabled || underlineEnabled || outlineEnabled || backgroundEnabled );
+ const bool underlineEnabled = mController->GetTextModel()->IsUnderlineEnabled();
+ const bool outlineEnabled = (mController->GetTextModel()->GetOutlineWidth() > Math::MACHINE_EPSILON_1);
+ const bool backgroundEnabled = mController->GetTextModel()->IsBackgroundEnabled();
+ ;
+ const bool styleEnabled = (shadowEnabled || underlineEnabled || outlineEnabled || backgroundEnabled);
- AddRenderer( control, relayoutSize, hasMultipleTextColors, containsColorGlyph, styleEnabled );
+ AddRenderer(control, relayoutSize, hasMultipleTextColors, containsColorGlyph, styleEnabled);
// Text rendered and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
}
}
-void TextVisual::AddTexture( TextureSet& textureSet, PixelData& data, Sampler& sampler, unsigned int textureSetIndex )
+void TextVisual::AddTexture(TextureSet& textureSet, PixelData& data, Sampler& sampler, unsigned int textureSetIndex)
{
- Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D,
- data.GetPixelFormat(),
- data.GetWidth(),
- data.GetHeight() );
- texture.Upload( data );
-
- textureSet.SetTexture( textureSetIndex, texture );
- textureSet.SetSampler( textureSetIndex, sampler );
+ Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D,
+ data.GetPixelFormat(),
+ data.GetWidth(),
+ data.GetHeight());
+ texture.Upload(data);
+
+ textureSet.SetTexture(textureSetIndex, texture);
+ textureSet.SetSampler(textureSetIndex, sampler);
}
-PixelData TextVisual::ConvertToPixelData( unsigned char* buffer, int width, int height, int offsetPosition, const Pixel::Format textPixelFormat )
+PixelData TextVisual::ConvertToPixelData(unsigned char* buffer, int width, int height, int offsetPosition, const Pixel::Format textPixelFormat)
{
- int bpp = Pixel::GetBytesPerPixel( textPixelFormat );
- unsigned int bufferSize = width * height * bpp;
- unsigned char* dstBuffer = static_cast<unsigned char*>( malloc ( bufferSize ) );
- memcpy( dstBuffer, buffer + offsetPosition * bpp, bufferSize );
- PixelData pixelData = Dali::PixelData::New( dstBuffer,
- bufferSize,
- width,
- height,
- textPixelFormat,
- Dali::PixelData::FREE );
+ int bpp = Pixel::GetBytesPerPixel(textPixelFormat);
+ unsigned int bufferSize = width * height * bpp;
+ unsigned char* dstBuffer = static_cast<unsigned char*>(malloc(bufferSize));
+ memcpy(dstBuffer, buffer + offsetPosition * bpp, bufferSize);
+ PixelData pixelData = Dali::PixelData::New(dstBuffer,
+ bufferSize,
+ width,
+ height,
+ textPixelFormat,
+ Dali::PixelData::FREE);
return pixelData;
}
-void TextVisual::CreateTextureSet( TilingInfo& info, Renderer& renderer, Sampler& sampler, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled )
+void TextVisual::CreateTextureSet(TilingInfo& info, Renderer& renderer, Sampler& sampler, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled)
{
-
- TextureSet textureSet = TextureSet::New();
+ TextureSet textureSet = TextureSet::New();
unsigned int textureSetIndex = 0u;
// Convert the buffer to pixel data to make it a texture.
- if( info.textBuffer )
+ if(info.textBuffer)
{
- PixelData data = ConvertToPixelData( info.textBuffer, info.width, info.height, info.offsetPosition, info.textPixelFormat );
- AddTexture( textureSet, data, sampler, textureSetIndex );
+ PixelData data = ConvertToPixelData(info.textBuffer, info.width, info.height, info.offsetPosition, info.textPixelFormat);
+ AddTexture(textureSet, data, sampler, textureSetIndex);
++textureSetIndex;
}
- if( styleEnabled && info.styleBuffer )
+ if(styleEnabled && info.styleBuffer)
{
- PixelData styleData = ConvertToPixelData( info.styleBuffer, info.width, info.height, info.offsetPosition, Pixel::RGBA8888 );
- AddTexture( textureSet, styleData, sampler, textureSetIndex );
+ PixelData styleData = ConvertToPixelData(info.styleBuffer, info.width, info.height, info.offsetPosition, Pixel::RGBA8888);
+ AddTexture(textureSet, styleData, sampler, textureSetIndex);
++textureSetIndex;
}
- if( containsColorGlyph && !hasMultipleTextColors && info.maskBuffer )
+ if(containsColorGlyph && !hasMultipleTextColors && info.maskBuffer)
{
- PixelData maskData = ConvertToPixelData( info.maskBuffer, info.width, info.height, info.offsetPosition, Pixel::L8 );
- AddTexture( textureSet, maskData, sampler, textureSetIndex );
+ PixelData maskData = ConvertToPixelData(info.maskBuffer, info.width, info.height, info.offsetPosition, Pixel::L8);
+ AddTexture(textureSet, maskData, sampler, textureSetIndex);
}
- renderer.SetTextures( textureSet );
+ renderer.SetTextures(textureSet);
//Register transform properties
- mImpl->mTransform.RegisterUniforms( renderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(renderer, Direction::LEFT_TO_RIGHT);
// Enable the pre-multiplied alpha to improve the text quality
- renderer.SetProperty( Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, true );
- renderer.RegisterProperty( PREMULTIPLIED_ALPHA, 1.0f );
+ renderer.SetProperty(Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, true);
+ renderer.RegisterProperty(PREMULTIPLIED_ALPHA, 1.0f);
// Set size and offset for the tiling.
- renderer.RegisterProperty( SIZE, Vector2( info.width, info.height ) );
- renderer.RegisterProperty( OFFSET, Vector2( info.offSet.x, info.offSet.y ) );
- renderer.RegisterProperty( "uHasMultipleTextColors", static_cast<float>( hasMultipleTextColors ) );
- renderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON);
+ renderer.RegisterProperty(SIZE, Vector2(info.width, info.height));
+ renderer.RegisterProperty(OFFSET, Vector2(info.offSet.x, info.offSet.y));
+ renderer.RegisterProperty("uHasMultipleTextColors", static_cast<float>(hasMultipleTextColors));
+ renderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
- mRendererList.push_back( renderer );
+ mRendererList.push_back(renderer);
}
-
-void TextVisual::AddRenderer( Actor& actor, const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled )
+void TextVisual::AddRenderer(Actor& actor, const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled)
{
- Shader shader = GetTextShader( mFactoryCache, hasMultipleTextColors, containsColorGlyph, styleEnabled );
- mImpl->mRenderer.SetShader( shader );
+ Shader shader = GetTextShader(mFactoryCache, hasMultipleTextColors, containsColorGlyph, styleEnabled);
+ mImpl->mRenderer.SetShader(shader);
// Get the maximum size.
const int maxTextureSize = Dali::GetMaxTextureSize();
// No tiling required. Use the default renderer.
- if( size.height < maxTextureSize )
+ if(size.height < maxTextureSize)
{
- TextureSet textureSet = GetTextTexture( size, hasMultipleTextColors, containsColorGlyph, styleEnabled );
+ TextureSet textureSet = GetTextTexture(size, hasMultipleTextColors, containsColorGlyph, styleEnabled);
- mImpl->mRenderer.SetTextures( textureSet );
+ mImpl->mRenderer.SetTextures(textureSet);
//Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
- mImpl->mRenderer.RegisterProperty( "uHasMultipleTextColors", static_cast<float>( hasMultipleTextColors ) );
- mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON);
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
+ mImpl->mRenderer.RegisterProperty("uHasMultipleTextColors", static_cast<float>(hasMultipleTextColors));
+ mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
- mRendererList.push_back( mImpl->mRenderer );
+ mRendererList.push_back(mImpl->mRenderer);
}
// If the pixel data exceeds the maximum size, tiling is required.
else
{
// Filter mode needs to be set to linear to produce better quality while scaling.
Sampler sampler = Sampler::New();
- sampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
+ sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR);
// Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture
- Pixel::Format textPixelFormat = ( containsColorGlyph || hasMultipleTextColors ) ? Pixel::RGBA8888 : Pixel::L8;
+ Pixel::Format textPixelFormat = (containsColorGlyph || hasMultipleTextColors) ? Pixel::RGBA8888 : Pixel::L8;
// Check the text direction
Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection();
// Create a texture for the text without any styles
- PixelData data = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat );
+ PixelData data = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat);
- int verifiedWidth = data.GetWidth();
+ int verifiedWidth = data.GetWidth();
int verifiedHeight = data.GetHeight();
// Set information for creating textures.
- TilingInfo info( verifiedWidth, maxTextureSize, textPixelFormat );
+ TilingInfo info(verifiedWidth, maxTextureSize, textPixelFormat);
// Get the buffer of text.
- Dali::DevelPixelData::PixelDataBuffer textPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( data );
- info.textBuffer = textPixelData.buffer;
+ Dali::DevelPixelData::PixelDataBuffer textPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(data);
+ info.textBuffer = textPixelData.buffer;
- if( styleEnabled )
+ if(styleEnabled)
{
// Create RGBA texture for all the text styles (without the text itself)
- PixelData styleData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888 );
- Dali::DevelPixelData::PixelDataBuffer stylePixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( styleData );
- info.styleBuffer = stylePixelData.buffer;
+ PixelData styleData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888);
+ Dali::DevelPixelData::PixelDataBuffer stylePixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(styleData);
+ info.styleBuffer = stylePixelData.buffer;
}
- if ( containsColorGlyph && !hasMultipleTextColors )
+ if(containsColorGlyph && !hasMultipleTextColors)
{
// Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation
- PixelData maskData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8 );
- Dali::DevelPixelData::PixelDataBuffer maskPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( maskData );
- info.maskBuffer = maskPixelData.buffer;
+ PixelData maskData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8);
+ Dali::DevelPixelData::PixelDataBuffer maskPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(maskData);
+ info.maskBuffer = maskPixelData.buffer;
}
// Get the current offset for recalculate the offset when tiling.
Property::Map retMap;
- mImpl->mTransform.GetPropertyMap( retMap );
- Property::Value* offsetValue = retMap.Find( Dali::Toolkit::Visual::Transform::Property::OFFSET );
- if( offsetValue )
+ mImpl->mTransform.GetPropertyMap(retMap);
+ Property::Value* offsetValue = retMap.Find(Dali::Toolkit::Visual::Transform::Property::OFFSET);
+ if(offsetValue)
{
- offsetValue->Get( info.offSet );
+ offsetValue->Get(info.offSet);
}
// Create a textureset in the default renderer.
- CreateTextureSet( info, mImpl->mRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled );
+ CreateTextureSet(info, mImpl->mRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled);
verifiedHeight -= maxTextureSize;
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
int offsetPosition = verifiedWidth * maxTextureSize;
// Create a renderer by cutting maxTextureSize.
- while( verifiedHeight > 0 )
+ while(verifiedHeight > 0)
{
- Renderer tilingRenderer = Renderer::New( geometry, shader );
- tilingRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT );
+ Renderer tilingRenderer = Renderer::New(geometry, shader);
+ tilingRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT);
// New offset position of buffer for tiling.
info.offsetPosition += offsetPosition;
// New height for tiling.
- info.height = ( verifiedHeight - maxTextureSize ) > 0 ? maxTextureSize : verifiedHeight;
+ info.height = (verifiedHeight - maxTextureSize) > 0 ? maxTextureSize : verifiedHeight;
// New offset for tiling.
info.offSet.y += maxTextureSize;
// Create a textureset int the new tiling renderer.
- CreateTextureSet( info, tilingRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled );
+ CreateTextureSet(info, tilingRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled);
verifiedHeight -= maxTextureSize;
}
mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
- for( RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
+ for(RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter)
{
Renderer renderer = (*iter);
- if( renderer )
+ if(renderer)
{
- actor.AddRenderer( renderer );
+ actor.AddRenderer(renderer);
}
}
}
-
-TextureSet TextVisual::GetTextTexture( const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled )
+TextureSet TextVisual::GetTextTexture(const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled)
{
// Filter mode needs to be set to linear to produce better quality while scaling.
Sampler sampler = Sampler::New();
- sampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR );
+ sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR);
TextureSet textureSet = TextureSet::New();
// Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture
- Pixel::Format textPixelFormat = ( containsColorGlyph || hasMultipleTextColors ) ? Pixel::RGBA8888 : Pixel::L8;
+ Pixel::Format textPixelFormat = (containsColorGlyph || hasMultipleTextColors) ? Pixel::RGBA8888 : Pixel::L8;
// Check the text direction
Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection();
// Create a texture for the text without any styles
- PixelData data = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat );
+ PixelData data = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat);
// It may happen the image atlas can't handle a pixel data it exceeds the maximum size.
// In that case, create a texture. TODO: should tile the text.
unsigned int textureSetIndex = 0u;
- AddTexture( textureSet, data, sampler, textureSetIndex );
+ AddTexture(textureSet, data, sampler, textureSetIndex);
++textureSetIndex;
- if ( styleEnabled )
+ if(styleEnabled)
{
// Create RGBA texture for all the text styles (without the text itself)
- PixelData styleData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888 );
+ PixelData styleData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888);
- AddTexture( textureSet, styleData, sampler, textureSetIndex );
+ AddTexture(textureSet, styleData, sampler, textureSetIndex);
++textureSetIndex;
}
- if ( containsColorGlyph && !hasMultipleTextColors )
+ if(containsColorGlyph && !hasMultipleTextColors)
{
// Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation
- PixelData maskData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8 );
+ PixelData maskData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8);
- AddTexture( textureSet, maskData, sampler, textureSetIndex );
+ AddTexture(textureSet, maskData, sampler, textureSetIndex);
}
return textureSet;
}
-Shader TextVisual::GetTextShader( VisualFactoryCache& factoryCache, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled )
+Shader TextVisual::GetTextShader(VisualFactoryCache& factoryCache, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled)
{
Shader shader;
- if( hasMultipleTextColors && !styleEnabled )
+ if(hasMultipleTextColors && !styleEnabled)
{
// We don't animate text color if the text contains multiple colors
- shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT);
+ if(!shader)
{
- shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_SHADER_FRAG );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT, shader );
+ shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_SHADER_FRAG);
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT, shader);
}
}
- else if( hasMultipleTextColors && styleEnabled )
+ else if(hasMultipleTextColors && styleEnabled)
{
// We don't animate text color if the text contains multiple colors
- shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE);
+ if(!shader)
{
- shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_WITH_STYLE_SHADER_FRAG );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE, shader );
+ shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_WITH_STYLE_SHADER_FRAG);
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE, shader);
}
}
- else if( !hasMultipleTextColors && !containsColorGlyph && !styleEnabled )
+ else if(!hasMultipleTextColors && !containsColorGlyph && !styleEnabled)
{
- shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT);
+ if(!shader)
{
- shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_SHADER_FRAG );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT, shader );
+ shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_SHADER_FRAG);
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT, shader);
}
}
- else if( !hasMultipleTextColors && !containsColorGlyph && styleEnabled )
+ else if(!hasMultipleTextColors && !containsColorGlyph && styleEnabled)
{
- shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE);
+ if(!shader)
{
- shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_SHADER_FRAG );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE, shader );
+ shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_SHADER_FRAG);
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE, shader);
}
}
- else if( !hasMultipleTextColors && containsColorGlyph && !styleEnabled )
+ else if(!hasMultipleTextColors && containsColorGlyph && !styleEnabled)
{
- shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI);
+ if(!shader)
{
- shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_EMOJI_SHADER_FRAG );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI, shader );
+ shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_EMOJI_SHADER_FRAG);
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI, shader);
}
}
else // if( !hasMultipleTextColors && containsColorGlyph && styleEnabled )
{
- shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI );
- if( !shader )
+ shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI);
+ if(!shader)
{
- shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI_SHADER_FRAG );
- shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
- factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI, shader );
+ shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI_SHADER_FRAG);
+ shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
+ factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI, shader);
}
}
- /*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/visuals/texture-manager-impl.h>
// EXTERNAL HEADERS
-#include <cstdlib>
-#include <string>
-#include <dali/public-api/math/vector4.h>
#include <dali/devel-api/adaptor-framework/environment-variable.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
-#include <dali/devel-api/common/hash.h>
#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
+#include <dali/devel-api/common/hash.h>
#include <dali/integration-api/debug.h>
+#include <dali/public-api/math/vector4.h>
#include <dali/public-api/rendering/geometry.h>
+#include <cstdlib>
+#include <string>
// INTERNAL HEADERS
#include <dali-toolkit/internal/image-loader/image-atlas-impl.h>
-#include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
#include <dali-toolkit/internal/visuals/image-atlas-manager.h>
#include <dali-toolkit/internal/visuals/rendering-addon.h>
+#include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
namespace
{
-
-constexpr auto INITIAL_CACHE_NUMBER = size_t{0u};
-constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
+constexpr auto INITIAL_CACHE_NUMBER = size_t{0u};
+constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
-constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
+constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
{
using Dali::EnvironmentVariable::GetEnvironmentVariable;
- auto numberString = GetEnvironmentVariable(environmentVariable);
- auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
+ auto numberString = GetEnvironmentVariable(environmentVariable);
+ auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
constexpr auto MAX_NUMBER_OF_THREADS = 100u;
- DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS );
- return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue;
+ DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS);
+ return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
}
size_t GetNumberOfLocalLoaderThreads()
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
#ifdef DEBUG_ENABLED
-Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TEXTURE_MANAGER" );
-
-#define GET_LOAD_STATE_STRING( loadState ) \
- loadState == TextureManager::LoadState::NOT_STARTED ? "NOT_STARTED" : \
- loadState == TextureManager::LoadState::LOADING ? "LOADING" : \
- loadState == TextureManager::LoadState::LOAD_FINISHED ? "LOAD_FINISHED" : \
- loadState == TextureManager::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" : \
- loadState == TextureManager::LoadState::MASK_APPLYING ? "MASK_APPLYING" : \
- loadState == TextureManager::LoadState::MASK_APPLIED ? "MASK_APPLIED" : \
- loadState == TextureManager::LoadState::UPLOADED ? "UPLOADED" : \
- loadState == TextureManager::LoadState::CANCELLED ? "CANCELLED" : \
- loadState == TextureManager::LoadState::LOAD_FAILED ? "LOAD_FAILED" : "Unknown"
+Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXTURE_MANAGER");
+
+#define GET_LOAD_STATE_STRING(loadState) \
+ loadState == TextureManager::LoadState::NOT_STARTED ? "NOT_STARTED" : loadState == TextureManager::LoadState::LOADING ? "LOADING" \
+ : loadState == TextureManager::LoadState::LOAD_FINISHED ? "LOAD_FINISHED" \
+ : loadState == TextureManager::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" \
+ : loadState == TextureManager::LoadState::MASK_APPLYING ? "MASK_APPLYING" \
+ : loadState == TextureManager::LoadState::MASK_APPLIED ? "MASK_APPLIED" \
+ : loadState == TextureManager::LoadState::UPLOADED ? "UPLOADED" \
+ : loadState == TextureManager::LoadState::CANCELLED ? "CANCELLED" \
+ : loadState == TextureManager::LoadState::LOAD_FAILED ? "LOAD_FAILED" \
+ : "Unknown"
#endif
-const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); ///< This size can fit 8 by 8 images of average size 128 * 128
-const Vector4 FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f ); ///< UV Rectangle that covers the full Texture
-const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct
-const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
+const uint32_t DEFAULT_ATLAS_SIZE(1024u); ///< This size can fit 8 by 8 images of average size 128 * 128
+const Vector4 FULL_ATLAS_RECT(0.0f, 0.0f, 1.0f, 1.0f); ///< UV Rectangle that covers the full Texture
+const int INVALID_INDEX(-1); ///< Invalid index used to represent a non-existant TextureInfo struct
+const int INVALID_CACHE_INDEX(-1); ///< Invalid Cache index
-
-void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
+void PreMultiply(Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
{
- if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
+ if(Pixel::HasAlpha(pixelBuffer.GetPixelFormat()))
{
- if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
+ if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
{
pixelBuffer.MultiplyColorByAlpha();
}
TextureManager::MaskingData::MaskingData()
: mAlphaMaskUrl(),
- mAlphaMaskId( INVALID_TEXTURE_ID ),
- mContentScaleFactor( 1.0f ),
- mCropToMask( true )
+ mAlphaMaskId(INVALID_TEXTURE_ID),
+ mContentScaleFactor(1.0f),
+ mCropToMask(true)
{
}
TextureManager::TextureManager()
-: mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
- mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
+: mAsyncLocalLoaders(GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); }),
+ mAsyncRemoteLoaders(GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); }),
mExternalTextures(),
mLifecycleObservers(),
mLoadQueue(),
- mCurrentTextureId( 0 ),
+ mCurrentTextureId(0),
mQueueLoadFlag(false)
{
// Initialize the AddOn
TextureManager::~TextureManager()
{
- for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
+ for(auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
{
(*iter)->TextureManagerDestroyed();
}
}
TextureSet TextureManager::LoadAnimatedImageTexture(
- Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex, Dali::SamplingMode::Type samplingMode,
- bool synchronousLoading, TextureManager::TextureId& textureId, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver )
+ Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureManager::TextureId& textureId, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver)
{
TextureSet textureSet;
- if( synchronousLoading )
+ if(synchronousLoading)
{
Devel::PixelBuffer pixelBuffer;
- if( animatedImageLoading )
+ if(animatedImageLoading)
{
- pixelBuffer = animatedImageLoading.LoadFrame( frameIndex );
+ pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
}
- if( !pixelBuffer )
+ if(!pixelBuffer)
{
DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
}
else
{
PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
- if( !textureSet )
+ if(!textureSet)
{
- Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(),
- pixelData.GetWidth(), pixelData.GetHeight() );
- texture.Upload( pixelData );
+ Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
+ texture.Upload(pixelData);
textureSet = TextureSet::New();
- textureSet.SetTexture( 0u, texture );
+ textureSet.SetTexture(0u, texture);
}
}
}
else
{
- auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
- textureId = RequestLoadInternal( animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
- SamplingMode::BOX_THEN_LINEAR, TextureManager::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver,
- true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex );
- TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
- if( loadState == TextureManager::LoadState::UPLOADED )
+ auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
+ textureId = RequestLoadInternal(animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, TextureManager::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex);
+ TextureManager::LoadState loadState = GetTextureStateInternal(textureId);
+ if(loadState == TextureManager::LoadState::UPLOADED)
{
// UploadComplete has already been called - keep the same texture set
- textureSet = GetTextureSet( textureId );
+ textureSet = GetTextureSet(textureId);
}
}
- if( textureSet )
+ if(textureSet)
{
Sampler sampler = Sampler::New();
- sampler.SetWrapMode( wrapModeU, wrapModeV );
- textureSet.SetSampler( 0u, sampler );
+ sampler.SetWrapMode(wrapModeU, wrapModeV);
+ textureSet.SetSampler(0u, sampler);
}
return textureSet;
}
Devel::PixelBuffer TextureManager::LoadPixelBuffer(
- const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureUploadObserver* textureObserver, bool orientationCorrection, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
+ const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureUploadObserver* textureObserver, bool orientationCorrection, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
{
Devel::PixelBuffer pixelBuffer;
- if( synchronousLoading )
+ if(synchronousLoading)
{
- if( url.IsValid() )
+ if(url.IsValid())
{
- pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
- orientationCorrection );
- if( pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
+ pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
+ if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
{
- PreMultiply( pixelBuffer, preMultiplyOnLoad );
+ PreMultiply(pixelBuffer, preMultiplyOnLoad);
}
}
}
else
{
- RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
- false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED,
- preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u );
+ RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u);
}
return pixelBuffer;
}
TextureSet TextureManager::LoadTexture(
- const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
- Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo,
- bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
- Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus,
- Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
- AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
- TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
+ const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo, bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect, Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver, AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection, TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
{
TextureSet textureSet;
loadingStatus = false;
- textureRect = FULL_ATLAS_RECT;
+ textureRect = FULL_ATLAS_RECT;
- if( VisualUrl::TEXTURE == url.GetProtocolType())
+ if(VisualUrl::TEXTURE == url.GetProtocolType())
{
std::string location = url.GetLocation();
- if( location.size() > 0u )
+ if(location.size() > 0u)
{
- TextureId id = std::stoi( location );
- for( auto&& elem : mExternalTextures )
+ TextureId id = std::stoi(location);
+ for(auto&& elem : mExternalTextures)
{
- if( elem.textureId == id )
+ if(elem.textureId == id)
{
preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
- textureId = elem.textureId;
+ textureId = elem.textureId;
return elem.textureSet;
}
}
}
}
- else if( synchronousLoading )
+ else if(synchronousLoading)
{
PixelData data;
- if( url.IsValid() )
+ if(url.IsValid())
{
- Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
- orientationCorrection );
- if( maskInfo && maskInfo->mAlphaMaskUrl.IsValid() )
+ Devel::PixelBuffer pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
+ if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
{
- Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile( maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(),
- FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true );
- if( maskPixelBuffer )
+ Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
+ if(maskPixelBuffer)
{
- pixelBuffer.ApplyMask( maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask );
+ pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
}
}
- if( pixelBuffer )
+ if(pixelBuffer)
{
- PreMultiply( pixelBuffer, preMultiplyOnLoad );
+ PreMultiply(pixelBuffer, preMultiplyOnLoad);
data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
}
}
- if( !data )
+ if(!data)
{
DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous loading is failed\n");
}
else
{
- if( atlasingStatus ) // attempt atlasing
+ if(atlasingStatus) // attempt atlasing
{
- textureSet = imageAtlasManager->Add( textureRect, data );
+ textureSet = imageAtlasManager->Add(textureRect, data);
}
- if( !textureSet ) // big image, no atlasing or atlasing failed
+ if(!textureSet) // big image, no atlasing or atlasing failed
{
- atlasingStatus = false;
- Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
- data.GetWidth(), data.GetHeight() );
- texture.Upload( data );
+ atlasingStatus = false;
+ Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(), data.GetWidth(), data.GetHeight());
+ texture.Upload(data);
textureSet = TextureSet::New();
- textureSet.SetTexture( 0u, texture );
+ textureSet.SetTexture(0u, texture);
}
else
{
else
{
loadingStatus = true;
- if( atlasingStatus )
+ if(atlasingStatus)
{
- textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
+ textureSet = imageAtlasManager->Add(textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
}
- if( !textureSet ) // big image, no atlasing or atlasing failed
+ if(!textureSet) // big image, no atlasing or atlasing failed
{
atlasingStatus = false;
- if( !maskInfo || !maskInfo->mAlphaMaskUrl.IsValid() )
+ if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
{
- textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
- textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
+ textureId = RequestLoad(url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad);
}
else
{
- maskInfo->mAlphaMaskId = RequestMaskLoad( maskInfo->mAlphaMaskUrl );
- textureId = RequestLoad( url,
- maskInfo->mAlphaMaskId,
- maskInfo->mContentScaleFactor,
- desiredSize,
- fittingMode, samplingMode,
- TextureManager::NO_ATLAS,
- maskInfo->mCropToMask,
- textureObserver,
- orientationCorrection,
- reloadPolicy, preMultiplyOnLoad );
+ maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl);
+ textureId = RequestLoad(url,
+ maskInfo->mAlphaMaskId,
+ maskInfo->mContentScaleFactor,
+ desiredSize,
+ fittingMode,
+ samplingMode,
+ TextureManager::NO_ATLAS,
+ maskInfo->mCropToMask,
+ textureObserver,
+ orientationCorrection,
+ reloadPolicy,
+ preMultiplyOnLoad);
}
- TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
- if( loadState == TextureManager::LoadState::UPLOADED )
+ TextureManager::LoadState loadState = GetTextureStateInternal(textureId);
+ if(loadState == TextureManager::LoadState::UPLOADED)
{
// UploadComplete has already been called - keep the same texture set
- textureSet = GetTextureSet( textureId );
+ textureSet = GetTextureSet(textureId);
}
// If we are loading the texture, or waiting for the ready signal handler to complete, inform
// caller that they need to wait.
- loadingStatus = ( loadState == TextureManager::LoadState::LOADING ||
- loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
- loadState == TextureManager::LoadState::MASK_APPLYING ||
- loadState == TextureManager::LoadState::MASK_APPLIED ||
- loadState == TextureManager::LoadState::NOT_STARTED ||
- mQueueLoadFlag );
-
+ loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
+ loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
+ loadState == TextureManager::LoadState::MASK_APPLYING ||
+ loadState == TextureManager::LoadState::MASK_APPLIED ||
+ loadState == TextureManager::LoadState::NOT_STARTED ||
+ mQueueLoadFlag);
}
else
{
}
}
- if( ! atlasingStatus && textureSet )
+ if(!atlasingStatus && textureSet)
{
Sampler sampler = Sampler::New();
- sampler.SetWrapMode( wrapModeU, wrapModeV );
- textureSet.SetSampler( 0u, sampler );
+ sampler.SetWrapMode(wrapModeU, wrapModeV);
+ textureSet.SetSampler(0u, sampler);
}
return textureSet;
TextureUploadObserver* observer,
bool orientationCorrection,
TextureManager::ReloadPolicy reloadPolicy,
- TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
+ TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
{
- return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
- false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
- preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u );
+ return RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas, false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u);
}
TextureManager::TextureId TextureManager::RequestLoad(
TextureUploadObserver* observer,
bool orientationCorrection,
TextureManager::ReloadPolicy reloadPolicy,
- TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
+ TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
{
- return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
- cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
- preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u );
+ return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u);
}
-TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
+TextureManager::TextureId TextureManager::RequestMaskLoad(const VisualUrl& maskUrl)
{
// Use the normal load procedure to get the alpha mask.
auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
- return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
- SamplingMode::NO_FILTER, NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true,
- TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u );
+ return RequestLoadInternal(maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true, TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u);
}
TextureManager::TextureId TextureManager::RequestLoadInternal(
TextureManager::ReloadPolicy reloadPolicy,
TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
Dali::AnimatedImageLoading animatedImageLoading,
- uint32_t frameIndex )
+ uint32_t frameIndex)
{
// First check if the requested Texture is cached.
- bool isAnimatedImage = ( animatedImageLoading ) ? true : false;
+ bool isAnimatedImage = (animatedImageLoading) ? true : false;
TextureHash textureHash = INITIAL_CACHE_NUMBER;
- int cacheIndex = INVALID_CACHE_INDEX;
+ int cacheIndex = INVALID_CACHE_INDEX;
if(storageType != StorageType::RETURN_PIXEL_BUFFER && !isAnimatedImage)
{
textureHash = GenerateHash(url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId);
TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
// Check if the requested Texture exists in the cache.
- if( cacheIndex != INVALID_CACHE_INDEX )
+ if(cacheIndex != INVALID_CACHE_INDEX)
{
- if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
+ if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
{
// Mark this texture being used by another client resource. Forced reload would replace the current texture
// without the need for incrementing the reference count.
- ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
+ ++(mTextureInfoContainer[cacheIndex].referenceCount);
}
- textureId = mTextureInfoContainer[ cacheIndex ].textureId;
+ textureId = mTextureInfoContainer[cacheIndex].textureId;
// Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
- preMultiplyOnLoad = mTextureInfoContainer[ cacheIndex ].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
+ preMultiplyOnLoad = mTextureInfoContainer[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
- url.GetUrl().c_str(), observer, cacheIndex, textureId );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
}
- if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
+ if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
{
// We need a new Texture.
- textureId = GenerateUniqueTextureId();
- bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
- mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
- desiredSize, contentScale, fittingMode, samplingMode,
- false, cropToMask, useAtlas, textureHash, orientationCorrection,
- preMultiply, animatedImageLoading, frameIndex ) );
+ textureId = GenerateUniqueTextureId();
+ bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
+ mTextureInfoContainer.push_back(TextureInfo(textureId, maskTextureId, url.GetUrl(), desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
cacheIndex = mTextureInfoContainer.size() - 1u;
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
- url.GetUrl().c_str(), observer, cacheIndex, textureId );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
}
// The below code path is common whether we are using the cache or not.
// The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
// or a new TextureInfo just created.
- TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
- textureInfo.maskTextureId = maskTextureId;
- textureInfo.storageType = storageType;
+ TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
+ textureInfo.maskTextureId = maskTextureId;
+ textureInfo.storageType = storageType;
textureInfo.orientationCorrection = orientationCorrection;
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n",
- GET_LOAD_STATE_STRING(textureInfo.loadState ) );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
// Force reloading of texture by setting loadState unless already loading or cancelled.
- if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
- TextureManager::LoadState::LOADING != textureInfo.loadState &&
- TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
- TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
- TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
- TextureManager::LoadState::CANCELLED != textureInfo.loadState )
+ if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
+ TextureManager::LoadState::LOADING != textureInfo.loadState &&
+ TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
+ TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
+ TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
+ TextureManager::LoadState::CANCELLED != textureInfo.loadState)
{
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
- url.GetUrl().c_str(), observer, cacheIndex, textureId );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
}
// Check if we should add the observer.
// Only do this if we have not loaded yet and it will not have loaded by the end of this method.
- switch( textureInfo.loadState )
+ switch(textureInfo.loadState)
{
case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
case TextureManager::LoadState::NOT_STARTED:
{
- LoadOrQueueTexture( textureInfo, observer ); // If called inside NotifyObservers, queues until afterwards
+ LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
break;
}
case TextureManager::LoadState::LOADING:
case TextureManager::LoadState::MASK_APPLYING:
case TextureManager::LoadState::MASK_APPLIED:
{
- ObserveTexture( textureInfo, observer );
+ ObserveTexture(textureInfo, observer);
break;
}
case TextureManager::LoadState::UPLOADED:
{
- if( observer )
+ if(observer)
{
- LoadOrQueueTexture( textureInfo, observer );
+ LoadOrQueueTexture(textureInfo, observer);
}
break;
}
// A cancelled texture hasn't finished loading yet. Treat as a loading texture
// (it's ref count has already been incremented, above)
textureInfo.loadState = TextureManager::LoadState::LOADING;
- ObserveTexture( textureInfo, observer );
+ ObserveTexture(textureInfo, observer);
break;
}
case TextureManager::LoadState::LOAD_FINISHED:
{
// Loading has already completed.
- if( observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
+ if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
{
- LoadOrQueueTexture( textureInfo, observer );
+ LoadOrQueueTexture(textureInfo, observer);
}
break;
}
return textureId;
}
-void TextureManager::Remove( const TextureManager::TextureId textureId, TextureUploadObserver* observer )
+void TextureManager::Remove(const TextureManager::TextureId textureId, TextureUploadObserver* observer)
{
- int textureInfoIndex = GetCacheIndexFromId( textureId );
- if( textureInfoIndex != INVALID_INDEX )
+ int textureInfoIndex = GetCacheIndexFromId(textureId);
+ if(textureInfoIndex != INVALID_INDEX)
{
- TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
+ TextureInfo& textureInfo(mTextureInfoContainer[textureInfoIndex]);
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
- "TextureManager::Remove(%d) url:%s\n cacheIdx:%d loadState:%s reference count = %d\n",
- textureId, textureInfo.url.GetUrl().c_str(),
- textureInfoIndex, GET_LOAD_STATE_STRING( textureInfo.loadState ), textureInfo.referenceCount );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) url:%s\n cacheIdx:%d loadState:%s reference count = %d\n", textureId, textureInfo.url.GetUrl().c_str(), textureInfoIndex, GET_LOAD_STATE_STRING(textureInfo.loadState), textureInfo.referenceCount);
// Decrement the reference count and check if this is the last user of this Texture.
- if( --textureInfo.referenceCount <= 0 )
+ if(--textureInfo.referenceCount <= 0)
{
// This is the last remove for this Texture.
textureInfo.referenceCount = 0;
- bool removeTextureInfo = false;
+ bool removeTextureInfo = false;
// If loaded, we can remove the TextureInfo and the Atlas (if atlased).
- if( textureInfo.loadState == LoadState::UPLOADED )
+ if(textureInfo.loadState == LoadState::UPLOADED)
{
- if( textureInfo.atlas )
+ if(textureInfo.atlas)
{
- textureInfo.atlas.Remove( textureInfo.atlasRect );
+ textureInfo.atlas.Remove(textureInfo.atlasRect);
}
removeTextureInfo = true;
}
- else if( textureInfo.loadState == LoadState::LOADING )
+ else if(textureInfo.loadState == LoadState::LOADING)
{
// We mark the textureInfo for removal.
// Once the load has completed, this method will be called again.
}
// If the state allows us to remove the TextureInfo data, we do so.
- if( removeTextureInfo )
+ if(removeTextureInfo)
{
// Permanently remove the textureInfo struct.
- mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
+ mTextureInfoContainer.erase(mTextureInfoContainer.begin() + textureInfoIndex);
}
}
- if( observer )
+ if(observer)
{
// Remove element from the LoadQueue
- for( auto&& element : mLoadQueue )
+ for(auto&& element : mLoadQueue)
{
- if( element.mObserver == observer )
+ if(element.mObserver == observer)
{
- mLoadQueue.Erase( &element );
+ mLoadQueue.Erase(&element);
break;
}
}
}
}
-VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
+VisualUrl TextureManager::GetVisualUrl(TextureId textureId)
{
VisualUrl visualUrl("");
- int cacheIndex = GetCacheIndexFromId( textureId );
+ int cacheIndex = GetCacheIndexFromId(textureId);
- if( cacheIndex != INVALID_CACHE_INDEX )
+ if(cacheIndex != INVALID_CACHE_INDEX)
{
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
- cacheIndex, textureId );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n", cacheIndex, textureId);
- TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
+ TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
visualUrl = cachedTextureInfo.url;
}
return visualUrl;
}
-TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
+TextureManager::LoadState TextureManager::GetTextureState(TextureId textureId)
{
LoadState loadState = TextureManager::LoadState::NOT_STARTED;
- int cacheIndex = GetCacheIndexFromId( textureId );
- if( cacheIndex != INVALID_CACHE_INDEX )
+ int cacheIndex = GetCacheIndexFromId(textureId);
+ if(cacheIndex != INVALID_CACHE_INDEX)
{
- TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
+ TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
loadState = cachedTextureInfo.loadState;
}
else
{
- for( auto&& elem : mExternalTextures )
+ for(auto&& elem : mExternalTextures)
{
- if( elem.textureId == textureId )
+ if(elem.textureId == textureId)
{
loadState = LoadState::UPLOADED;
break;
return loadState;
}
-TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
+TextureManager::LoadState TextureManager::GetTextureStateInternal(TextureId textureId)
{
LoadState loadState = TextureManager::LoadState::NOT_STARTED;
- int cacheIndex = GetCacheIndexFromId( textureId );
- if( cacheIndex != INVALID_CACHE_INDEX )
+ int cacheIndex = GetCacheIndexFromId(textureId);
+ if(cacheIndex != INVALID_CACHE_INDEX)
{
- TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
+ TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
loadState = cachedTextureInfo.loadState;
}
return loadState;
}
-TextureSet TextureManager::GetTextureSet( TextureId textureId )
+TextureSet TextureManager::GetTextureSet(TextureId textureId)
{
- TextureSet textureSet;// empty handle
+ TextureSet textureSet; // empty handle
- int cacheIndex = GetCacheIndexFromId( textureId );
- if( cacheIndex != INVALID_CACHE_INDEX )
+ int cacheIndex = GetCacheIndexFromId(textureId);
+ if(cacheIndex != INVALID_CACHE_INDEX)
{
- TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
+ TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
textureSet = cachedTextureInfo.textureSet;
}
else
{
- for( auto&& elem : mExternalTextures )
+ for(auto&& elem : mExternalTextures)
{
- if( elem.textureId == textureId )
+ if(elem.textureId == textureId)
{
textureSet = elem.textureSet;
break;
return textureSet;
}
-std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
+std::string TextureManager::AddExternalTexture(TextureSet& textureSet)
{
TextureManager::ExternalTextureInfo info;
- info.textureId = GenerateUniqueTextureId();
+ info.textureId = GenerateUniqueTextureId();
info.textureSet = textureSet;
- mExternalTextures.emplace_back( info );
- return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
+ mExternalTextures.emplace_back(info);
+ return VisualUrl::CreateTextureUrl(std::to_string(info.textureId));
}
-TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
+TextureSet TextureManager::RemoveExternalTexture(const std::string& url)
{
- if( url.size() > 0u )
+ if(url.size() > 0u)
{
// get the location from the Url
- VisualUrl parseUrl( url );
- if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
+ VisualUrl parseUrl(url);
+ if(VisualUrl::TEXTURE == parseUrl.GetProtocolType())
{
std::string location = parseUrl.GetLocation();
- if( location.size() > 0u )
+ if(location.size() > 0u)
{
- TextureId id = std::stoi( location );
+ TextureId id = std::stoi(location);
const auto end = mExternalTextures.end();
- for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
+ for(auto iter = mExternalTextures.begin(); iter != end; ++iter)
{
- if( iter->textureId == id )
+ if(iter->textureId == id)
{
auto textureSet = iter->textureSet;
- mExternalTextures.erase( iter );
+ mExternalTextures.erase(iter);
return textureSet;
}
}
return TextureSet();
}
-void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
+void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
{
// make sure an observer doesn't observe the same object twice
// otherwise it will get multiple calls to ObjectDestroyed()
- DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
- mLifecycleObservers.PushBack( &observer );
+ DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
+ mLifecycleObservers.PushBack(&observer);
}
-void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
+void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
{
// Find the observer...
- auto endIter = mLifecycleObservers.End();
- for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
+ auto endIter = mLifecycleObservers.End();
+ for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
{
- if( (*iter) == &observer)
+ if((*iter) == &observer)
{
- mLifecycleObservers.Erase( iter );
+ mLifecycleObservers.Erase(iter);
break;
}
}
DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
}
-void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
+void TextureManager::LoadOrQueueTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
{
- switch( textureInfo.loadState )
+ switch(textureInfo.loadState)
{
case LoadState::NOT_STARTED:
case LoadState::LOAD_FAILED:
{
- if( mQueueLoadFlag )
+ if(mQueueLoadFlag)
{
- QueueLoadTexture( textureInfo, observer );
+ QueueLoadTexture(textureInfo, observer);
}
else
{
- LoadTexture( textureInfo, observer );
+ LoadTexture(textureInfo, observer);
}
break;
}
case LoadState::UPLOADED:
{
- if( mQueueLoadFlag )
+ if(mQueueLoadFlag)
{
- QueueLoadTexture( textureInfo, observer );
+ QueueLoadTexture(textureInfo, observer);
}
else
{
// The Texture has already loaded. The other observers have already been notified.
// We need to send a "late" loaded notification for this observer.
- observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
- textureInfo.useAtlas, textureInfo.atlasRect,
- textureInfo.preMultiplied );
+ observer->UploadComplete(true, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied);
}
break;
}
}
}
-void TextureManager::QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
+void TextureManager::QueueLoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
{
auto textureId = textureInfo.textureId;
- mLoadQueue.PushBack( LoadQueueElement( textureId, observer) );
+ mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
- observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
+ observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
}
-void TextureManager::LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
+void TextureManager::LoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
{
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n",
- textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
textureInfo.loadState = LoadState::LOADING;
- if( !textureInfo.loadSynchronously )
+ if(!textureInfo.loadSynchronously)
{
- auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
- auto loadingHelperIt = loadersContainer.GetNext();
- auto premultiplyOnLoad = ( textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID ) ?
- DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
+ auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
+ auto loadingHelperIt = loadersContainer.GetNext();
+ auto premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
- if( textureInfo.animatedImageLoading )
+ if(textureInfo.animatedImageLoading)
{
- loadingHelperIt->LoadAnimatedImage( textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex );
+ loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex);
}
else
{
- loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
- textureInfo.desiredSize, textureInfo.fittingMode,
- textureInfo.samplingMode, textureInfo.orientationCorrection,
- premultiplyOnLoad );
+ loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
}
}
- ObserveTexture( textureInfo, observer );
+ ObserveTexture(textureInfo, observer);
}
void TextureManager::ProcessQueuedTextures()
{
- for( auto&& element : mLoadQueue )
+ for(auto&& element : mLoadQueue)
{
- if( !element.mObserver )
+ if(!element.mObserver)
{
continue;
}
- int cacheIndex = GetCacheIndexFromId( element.mTextureId );
- if( cacheIndex != INVALID_CACHE_INDEX )
+ int cacheIndex = GetCacheIndexFromId(element.mTextureId);
+ if(cacheIndex != INVALID_CACHE_INDEX)
{
- TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
- if( textureInfo.loadState == LoadState::UPLOADED )
+ TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
+ if(textureInfo.loadState == LoadState::UPLOADED)
{
- element.mObserver->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
- textureInfo.useAtlas, textureInfo.atlasRect,
- textureInfo.preMultiplied );
+ element.mObserver->UploadComplete(true, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied);
}
- else if ( textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
+ else if(textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
{
- element.mObserver->LoadComplete( true, textureInfo.pixelBuffer, textureInfo.url, textureInfo.preMultiplied );
+ element.mObserver->LoadComplete(true, textureInfo.pixelBuffer, textureInfo.url, textureInfo.preMultiplied);
}
else
{
- LoadTexture( textureInfo, element.mObserver );
+ LoadTexture(textureInfo, element.mObserver);
}
}
}
mLoadQueue.Clear();
}
-void TextureManager::ObserveTexture( TextureInfo& textureInfo,
- TextureUploadObserver* observer )
+void TextureManager::ObserveTexture(TextureInfo& textureInfo,
+ TextureUploadObserver* observer)
{
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n",
- textureInfo.url.GetUrl().c_str(), observer );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
- if( observer )
+ if(observer)
{
- textureInfo.observerList.PushBack( observer );
- observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
+ textureInfo.observerList.PushBack(observer);
+ observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
}
}
-void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
- Devel::PixelBuffer pixelBuffer )
+void TextureManager::AsyncLoadComplete(AsyncLoadingInfoContainerType& loadingContainer, uint32_t id, Devel::PixelBuffer pixelBuffer)
{
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id);
- if( loadingContainer.size() >= 1u )
+ if(loadingContainer.size() >= 1u)
{
AsyncLoadingInfo loadingInfo = loadingContainer.front();
- if( loadingInfo.loadId == id )
+ if(loadingInfo.loadId == id)
{
- int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
- if( cacheIndex != INVALID_CACHE_INDEX )
+ int cacheIndex = GetCacheIndexFromId(loadingInfo.textureId);
+ if(cacheIndex != INVALID_CACHE_INDEX)
{
- TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
+ TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
- " textureId:%d Url:%s CacheIndex:%d LoadState: %d\n",
- textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, " textureId:%d Url:%s CacheIndex:%d LoadState: %d\n", textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState);
- if( textureInfo.loadState != LoadState::CANCELLED )
+ if(textureInfo.loadState != LoadState::CANCELLED)
{
// textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
- PostLoad( textureInfo, pixelBuffer );
+ PostLoad(textureInfo, pixelBuffer);
}
else
{
- Remove( textureInfo.textureId, nullptr );
+ Remove(textureInfo.textureId, nullptr);
}
}
}
}
}
-void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
+void TextureManager::PostLoad(TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
{
// Was the load successful?
- if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
+ if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
{
// No atlas support for now
- textureInfo.useAtlas = NO_ATLAS;
+ textureInfo.useAtlas = NO_ATLAS;
textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
- if( textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE )
+ if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
{
// If there is a mask texture ID associated with this texture, then apply the mask
// if it's already loaded. If it hasn't, and the mask is still loading,
// wait for the mask to finish loading.
- if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
+ if(textureInfo.maskTextureId != INVALID_TEXTURE_ID)
{
- if( textureInfo.loadState == LoadState::MASK_APPLYING )
+ if(textureInfo.loadState == LoadState::MASK_APPLYING)
{
textureInfo.loadState = LoadState::MASK_APPLIED;
- UploadTexture( pixelBuffer, textureInfo );
- NotifyObservers( textureInfo, true );
+ UploadTexture(pixelBuffer, textureInfo);
+ NotifyObservers(textureInfo, true);
}
else
{
- LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
+ LoadState maskLoadState = GetTextureStateInternal(textureInfo.maskTextureId);
textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
- if( maskLoadState == LoadState::LOADING )
+ if(maskLoadState == LoadState::LOADING)
{
textureInfo.loadState = LoadState::WAITING_FOR_MASK;
}
- else if( maskLoadState == LoadState::LOAD_FINISHED )
+ else if(maskLoadState == LoadState::LOAD_FINISHED)
{
// Send New Task to Thread
- ApplyMask( textureInfo, textureInfo.maskTextureId );
+ ApplyMask(textureInfo, textureInfo.maskTextureId);
}
}
}
else
{
- UploadTexture( pixelBuffer, textureInfo );
- NotifyObservers( textureInfo, true );
+ UploadTexture(pixelBuffer, textureInfo);
+ NotifyObservers(textureInfo, true);
}
}
else
{
textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
- textureInfo.loadState = LoadState::LOAD_FINISHED;
+ textureInfo.loadState = LoadState::LOAD_FINISHED;
- if( textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER )
+ if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
{
- NotifyObservers( textureInfo, true );
+ NotifyObservers(textureInfo, true);
}
else
{
// Check if there was another texture waiting for this load to complete
// (e.g. if this was an image mask, and its load is on a different thread)
- CheckForWaitingTexture( textureInfo );
+ CheckForWaitingTexture(textureInfo);
}
}
}
else
{
textureInfo.loadState = LoadState::LOAD_FAILED;
- CheckForWaitingTexture( textureInfo );
- NotifyObservers( textureInfo, false );
+ CheckForWaitingTexture(textureInfo);
+ NotifyObservers(textureInfo, false);
}
}
-void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
+void TextureManager::CheckForWaitingTexture(TextureInfo& maskTextureInfo)
{
// Search the cache, checking if any texture has this texture id as a
// maskTextureId:
const unsigned int size = mTextureInfoContainer.size();
- for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
+ for(unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex)
{
- if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
- mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK )
+ if(mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
+ mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
{
- TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
+ TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
- if( maskTextureInfo.loadState == LoadState::LOAD_FINISHED )
+ if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED)
{
// Send New Task to Thread
- ApplyMask( textureInfo, maskTextureInfo.textureId );
+ ApplyMask(textureInfo, maskTextureInfo.textureId);
}
else
{
textureInfo.pixelBuffer.Reset();
textureInfo.loadState = LoadState::LOAD_FAILED;
- NotifyObservers( textureInfo, false );
+ NotifyObservers(textureInfo, false);
}
}
}
}
-void TextureManager::ApplyMask( TextureInfo& textureInfo, TextureId maskTextureId )
+void TextureManager::ApplyMask(TextureInfo& textureInfo, TextureId maskTextureId)
{
- int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
- if( maskCacheIndex != INVALID_CACHE_INDEX )
+ int maskCacheIndex = GetCacheIndexFromId(maskTextureId);
+ if(maskCacheIndex != INVALID_CACHE_INDEX)
{
Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
- Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
+ Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
textureInfo.pixelBuffer.Reset();
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n",
- textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
- textureInfo.loadState = LoadState::MASK_APPLYING;
- auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
- auto loadingHelperIt = loadersContainer.GetNext();
- auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
+ textureInfo.loadState = LoadState::MASK_APPLYING;
+ auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
+ auto loadingHelperIt = loadersContainer.GetNext();
+ auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
- loadingHelperIt->ApplyMask( textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad );
+ loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
}
}
-void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
+void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo)
{
- if( textureInfo.useAtlas != USE_ATLAS )
+ if(textureInfo.useAtlas != USE_ATLAS)
{
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
// Check if this pixelBuffer is premultiplied
textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
auto& renderingAddOn = RenderingAddOn::Get();
- if( renderingAddOn.IsValid() )
+ if(renderingAddOn.IsValid())
{
- renderingAddOn.CreateGeometry( textureInfo.textureId, pixelBuffer );
+ renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
}
- Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
- pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
+ Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
- PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
- texture.Upload( pixelData );
- if ( ! textureInfo.textureSet )
+ PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
+ texture.Upload(pixelData);
+ if(!textureInfo.textureSet)
{
textureInfo.textureSet = TextureSet::New();
}
- textureInfo.textureSet.SetTexture( 0u, texture );
+ textureInfo.textureSet.SetTexture(0u, texture);
}
// Update the load state.
textureInfo.loadState = LoadState::UPLOADED;
}
-void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
+void TextureManager::NotifyObservers(TextureInfo& textureInfo, bool success)
{
TextureId textureId = textureInfo.textureId;
mQueueLoadFlag = true;
- while( info->observerList.Count() )
+ while(info->observerList.Count())
{
TextureUploadObserver* observer = info->observerList[0];
// invalidating the reference to the textureInfo struct.
// Texture load requests for the same URL are deferred until the end of this
// method.
- DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n",
- textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState ) );
+ DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n", textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState));
// It is possible for the observer to be deleted.
// Disconnect and remove the observer first.
- observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
+ observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
- info->observerList.Erase( info->observerList.begin() );
+ info->observerList.Erase(info->observerList.begin());
- if( info->storageType == StorageType::RETURN_PIXEL_BUFFER )
+ if(info->storageType == StorageType::RETURN_PIXEL_BUFFER)
{
- observer->LoadComplete( success, info->pixelBuffer, info->url, info->preMultiplied );
+ observer->LoadComplete(success, info->pixelBuffer, info->url, info->preMultiplied);
}
else
{
- observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
- info->preMultiplied );
+ observer->UploadComplete(success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect, info->preMultiplied);
}
// Get the textureInfo from the container again as it may have been invalidated.
- int textureInfoIndex = GetCacheIndexFromId( textureId );
- if( textureInfoIndex == INVALID_CACHE_INDEX)
+ int textureInfoIndex = GetCacheIndexFromId(textureId);
+ if(textureInfoIndex == INVALID_CACHE_INDEX)
{
break; // texture has been removed - can stop.
}
- info = &mTextureInfoContainer[ textureInfoIndex ];
+ info = &mTextureInfoContainer[textureInfoIndex];
}
mQueueLoadFlag = false;
ProcessQueuedTextures();
- if( info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0 )
+ if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
{
- Remove( info->textureId, nullptr );
+ Remove(info->textureId, nullptr);
}
}
return mCurrentTextureId++;
}
-int TextureManager::GetCacheIndexFromId( const TextureId textureId )
+int TextureManager::GetCacheIndexFromId(const TextureId textureId)
{
const unsigned int size = mTextureInfoContainer.size();
- for( unsigned int i = 0; i < size; ++i )
+ for(unsigned int i = 0; i < size; ++i)
{
- if( mTextureInfoContainer[i].textureId == textureId )
+ if(mTextureInfoContainer[i].textureId == textureId)
{
return i;
}
const UseAtlas useAtlas,
TextureId maskTextureId)
{
- std::string hashTarget( url );
- const size_t urlLength = hashTarget.length();
- const uint16_t width = size.GetWidth();
- const uint16_t height = size.GetWidth();
+ std::string hashTarget(url);
+ const size_t urlLength = hashTarget.length();
+ const uint16_t width = size.GetWidth();
+ const uint16_t height = size.GetWidth();
// If either the width or height has been specified, include the resizing options in the hash
- if( width != 0 || height != 0 )
+ if(width != 0 || height != 0)
{
// We are appending 5 bytes to the URL to form the hash input.
- hashTarget.resize( urlLength + 5u );
- char* hashTargetPtr = &( hashTarget[ urlLength ] );
+ hashTarget.resize(urlLength + 5u);
+ char* hashTargetPtr = &(hashTarget[urlLength]);
// Pack the width and height (4 bytes total).
*hashTargetPtr++ = size.GetWidth() & 0xff;
- *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
+ *hashTargetPtr++ = (size.GetWidth() >> 8u) & 0xff;
*hashTargetPtr++ = size.GetHeight() & 0xff;
- *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
+ *hashTargetPtr++ = (size.GetHeight() >> 8u) & 0xff;
// Bit-pack the FittingMode, SamplingMode and atlasing.
// FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
- *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
+ *hashTargetPtr = (fittingMode << 4u) | (samplingMode << 1) | useAtlas;
}
else
{
// We are not including sizing information, but we still need an extra byte for atlasing.
- hashTarget.resize( urlLength + 1u );
+ hashTarget.resize(urlLength + 1u);
// Add the atlasing to the hash input.
- switch( useAtlas )
+ switch(useAtlas)
{
case UseAtlas::NO_ATLAS:
{
- hashTarget[ urlLength ] = 'f';
+ hashTarget[urlLength] = 'f';
break;
}
case UseAtlas::USE_ATLAS:
{
- hashTarget[ urlLength ] = 't';
+ hashTarget[urlLength] = 't';
break;
}
}
}
- if( maskTextureId != INVALID_TEXTURE_ID )
+ if(maskTextureId != INVALID_TEXTURE_ID)
{
auto textureIdIndex = hashTarget.length();
- hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
- unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
+ hashTarget.resize(hashTarget.length() + sizeof(TextureId));
+ unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&(hashTarget[textureIdIndex]));
// Append the texture id to the end of the URL byte by byte:
// (to avoid SIGBUS / alignment issues)
- for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
+ for(size_t byteIter = 0; byteIter < sizeof(TextureId); ++byteIter)
{
*hashTargetPtr++ = maskTextureId & 0xff;
maskTextureId >>= 8u;
}
}
- return Dali::CalculateHash( hashTarget );
+ return Dali::CalculateHash(hashTarget);
}
int TextureManager::FindCachedTexture(
// Iterate through our hashes to find a match.
const unsigned int count = mTextureInfoContainer.size();
- for( unsigned int i = 0u; i < count; ++i )
+ for(unsigned int i = 0u; i < count; ++i)
{
- if( mTextureInfoContainer[i].hash == hash )
+ if(mTextureInfoContainer[i].hash == hash)
{
// We have a match, now we check all the original parameters in case of a hash collision.
- TextureInfo& textureInfo( mTextureInfoContainer[i] );
-
- if( ( url == textureInfo.url.GetUrl() ) &&
- ( useAtlas == textureInfo.useAtlas ) &&
- ( maskTextureId == textureInfo.maskTextureId ) &&
- ( size == textureInfo.desiredSize ) &&
- ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
- ( fittingMode == textureInfo.fittingMode &&
- samplingMode == textureInfo.samplingMode ) ) )
+ TextureInfo& textureInfo(mTextureInfoContainer[i]);
+
+ if((url == textureInfo.url.GetUrl()) &&
+ (useAtlas == textureInfo.useAtlas) &&
+ (maskTextureId == textureInfo.maskTextureId) &&
+ (size == textureInfo.desiredSize) &&
+ ((size.GetWidth() == 0 && size.GetHeight() == 0) ||
+ (fittingMode == textureInfo.fittingMode &&
+ samplingMode == textureInfo.samplingMode)))
{
// 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different.
// 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false.
- if( ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad )
- || ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied ) )
+ if((preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad) || (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied))
{
// The found Texture is a match.
cacheIndex = i;
return cacheIndex;
}
-void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
+void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
{
const unsigned int count = mTextureInfoContainer.size();
- for( unsigned int i = 0; i < count; ++i )
+ for(unsigned int i = 0; i < count; ++i)
{
- TextureInfo& textureInfo( mTextureInfoContainer[i] );
- for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
- j != textureInfo.observerList.End(); )
+ TextureInfo& textureInfo(mTextureInfoContainer[i]);
+ for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
+ j != textureInfo.observerList.End();)
{
- if( *j == observer )
+ if(*j == observer)
{
- j = textureInfo.observerList.Erase( j );
+ j = textureInfo.observerList.Erase(j);
}
else
{
}
// Remove element from the LoadQueue
- for( auto&& element : mLoadQueue )
+ for(auto&& element : mLoadQueue)
{
- if( element.mObserver == observer )
+ if(element.mObserver == observer)
{
element.mObserver = nullptr;
}
}
}
-
TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
-: AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
- AsyncLoadingInfoContainerType())
+: AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager, AsyncLoadingInfoContainerType())
{
}
-void TextureManager::AsyncLoadingHelper::LoadAnimatedImage( TextureId textureId,
- Dali::AnimatedImageLoading animatedImageLoading,
- uint32_t frameIndex )
+void TextureManager::AsyncLoadingHelper::LoadAnimatedImage(TextureId textureId,
+ Dali::AnimatedImageLoading animatedImageLoading,
+ uint32_t frameIndex)
{
- mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
- auto id = DevelAsyncImageLoader::LoadAnimatedImage( mLoader, animatedImageLoading, frameIndex );
+ mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
+ auto id = DevelAsyncImageLoader::LoadAnimatedImage(mLoader, animatedImageLoading, frameIndex);
mLoadingInfoContainer.back().loadId = id;
}
-void TextureManager::AsyncLoadingHelper::Load( TextureId textureId,
- const VisualUrl& url,
- ImageDimensions desiredSize,
- FittingMode::Type fittingMode,
- SamplingMode::Type samplingMode,
- bool orientationCorrection,
- DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
+void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
+ const VisualUrl& url,
+ ImageDimensions desiredSize,
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection,
+ DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
{
- mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
- auto id = DevelAsyncImageLoader::Load( mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad );
+ mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
+ auto id = DevelAsyncImageLoader::Load(mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad);
mLoadingInfoContainer.back().loadId = id;
}
-void TextureManager::AsyncLoadingHelper::ApplyMask( TextureId textureId,
- Devel::PixelBuffer pixelBuffer,
- Devel::PixelBuffer maskPixelBuffer,
- float contentScale,
- bool cropToMask,
- DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
+void TextureManager::AsyncLoadingHelper::ApplyMask(TextureId textureId,
+ Devel::PixelBuffer pixelBuffer,
+ Devel::PixelBuffer maskPixelBuffer,
+ float contentScale,
+ bool cropToMask,
+ DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
{
- mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) );
- auto id = DevelAsyncImageLoader::ApplyMask( mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad );
+ mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
+ auto id = DevelAsyncImageLoader::ApplyMask(mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad);
mLoadingInfoContainer.back().loadId = id;
}
}
TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
- Toolkit::AsyncImageLoader loader,
- TextureManager& textureManager,
- AsyncLoadingInfoContainerType&& loadingInfoContainer)
+ Toolkit::AsyncImageLoader loader,
+ TextureManager& textureManager,
+ AsyncLoadingInfoContainerType&& loadingInfoContainer)
: mLoader(loader),
mTextureManager(textureManager),
mLoadingInfoContainer(std::move(loadingInfoContainer))
{
DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
- this, &AsyncLoadingHelper::AsyncLoadComplete);
+ this, &AsyncLoadingHelper::AsyncLoadComplete);
}
void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
- Devel::PixelBuffer pixelBuffer )
+ Devel::PixelBuffer pixelBuffer)
{
- mTextureManager.AsyncLoadComplete( mLoadingInfoContainer, id, pixelBuffer );
+ mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
}
-Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements )
+Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements)
{
- return RenderingAddOn::Get().IsValid() ?
- RenderingAddOn::Get().GetGeometry( textureId, frontElements, backElements) :
- Geometry();
+ return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
}
} // namespace Internal
/*
- * Copyright (c) 2017 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali
{
-
namespace Toolkit
{
-
TextureUploadObserver::TextureUploadObserver()
{
}
TextureUploadObserver::~TextureUploadObserver()
{
- if( !mDestructionSignal.Empty() )
+ if(!mDestructionSignal.Empty())
{
- mDestructionSignal.Emit( this );
+ mDestructionSignal.Emit(this);
}
}
return mDestructionSignal;
}
-
} // namespace Toolkit
} // namespace Dali
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/internal/visuals/transition-data-impl.h>
// EXTERNAL HEADERS
+#include <dali-toolkit/public-api/controls/control-impl.h>
+#include <dali-toolkit/public-api/controls/control.h>
#include <dali/dali.h>
#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/integration-api/debug.h>
-#include <dali-toolkit/public-api/controls/control.h>
-#include <dali-toolkit/public-api/controls/control-impl.h>
#include <sstream>
using namespace Dali;
const char* TOKEN_DELAY("delay");
const char* TOKEN_ALPHA_FUNCTION("alphaFunction");
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( ALPHA_FUNCTION_BUILTIN )
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, LINEAR)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, REVERSE)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_OUT)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_SQUARE)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_SQUARE)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_SINE)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_SINE)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_OUT_SINE)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_BACK)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, BOUNCE)
-DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, SIN)
-DALI_ENUM_TO_STRING_TABLE_END( ALPHA_FUNCTION_BUILTIN )
-}
+DALI_ENUM_TO_STRING_TABLE_BEGIN(ALPHA_FUNCTION_BUILTIN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, LINEAR)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, REVERSE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_OUT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_SQUARE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_SQUARE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_SINE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_SINE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_OUT_SINE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_BACK)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, BOUNCE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, SIN)
+DALI_ENUM_TO_STRING_TABLE_END(ALPHA_FUNCTION_BUILTIN)
+} // namespace
namespace Dali
{
{
namespace Internal
{
-
namespace
{
-
/// Parses a Property::Array and sets up the animator appropriately
void ParseArray(TransitionData::Animator* animator, const Property::Array* array)
{
- bool valid = true;
+ bool valid = true;
Vector4 controlPoints;
- if( array && array->Count() >= 4 )
+ if(array && array->Count() >= 4)
{
- for( size_t vecIdx = 0; vecIdx < 4; ++vecIdx )
+ for(size_t vecIdx = 0; vecIdx < 4; ++vecIdx)
{
const Property::Value& v = array->GetElementAt(vecIdx);
- if( v.GetType() == Property::FLOAT )
+ if(v.GetType() == Property::FLOAT)
{
controlPoints[vecIdx] = v.Get<float>();
}
valid = false;
}
- if( valid )
+ if(valid)
{
- Vector2 controlPoint1( controlPoints.x, controlPoints.y );
- Vector2 controlPoint2( controlPoints.z, controlPoints.w );
- animator->alphaFunction = AlphaFunction( controlPoint1, controlPoint2 );
+ Vector2 controlPoint1(controlPoints.x, controlPoints.y);
+ Vector2 controlPoint2(controlPoints.z, controlPoints.w);
+ animator->alphaFunction = AlphaFunction(controlPoint1, controlPoint2);
}
else
{
/// Parses a string value and sets up the animator appropriately
void ParseString(TransitionData::Animator* animator, std::string alphaFunctionValue)
{
- if( alphaFunctionValue == "LINEAR" )
+ if(alphaFunctionValue == "LINEAR")
{
animator->alphaFunction = AlphaFunction(AlphaFunction::LINEAR);
}
- else if( ! alphaFunctionValue.compare(0, 5, "EASE_" ) )
+ else if(!alphaFunctionValue.compare(0, 5, "EASE_"))
{
- if( alphaFunctionValue == "EASE_IN" )
+ if(alphaFunctionValue == "EASE_IN")
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN);
}
- else if( alphaFunctionValue == "EASE_OUT" )
+ else if(alphaFunctionValue == "EASE_OUT")
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_OUT);
}
- else if( ! alphaFunctionValue.compare( 5, 3, "IN_" ) )
+ else if(!alphaFunctionValue.compare(5, 3, "IN_"))
{
- if( ! alphaFunctionValue.compare(8, -1, "SQUARE" ))
+ if(!alphaFunctionValue.compare(8, -1, "SQUARE"))
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN_SQUARE);
}
- else if( ! alphaFunctionValue.compare(8, -1, "OUT" ))
+ else if(!alphaFunctionValue.compare(8, -1, "OUT"))
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN_OUT);
}
- else if( ! alphaFunctionValue.compare(8, -1, "OUT_SINE" ))
+ else if(!alphaFunctionValue.compare(8, -1, "OUT_SINE"))
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN_OUT_SINE);
}
- else if( ! alphaFunctionValue.compare(8, -1, "SINE" ))
+ else if(!alphaFunctionValue.compare(8, -1, "SINE"))
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN_SINE);
}
}
- else if( ! alphaFunctionValue.compare( 5, 4, "OUT_" ) )
+ else if(!alphaFunctionValue.compare(5, 4, "OUT_"))
{
- if( ! alphaFunctionValue.compare(9, -1, "SQUARE" ) )
+ if(!alphaFunctionValue.compare(9, -1, "SQUARE"))
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_OUT_SQUARE);
}
- else if( ! alphaFunctionValue.compare(9, -1, "SINE" ) )
+ else if(!alphaFunctionValue.compare(9, -1, "SINE"))
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_OUT_SINE);
}
- else if( ! alphaFunctionValue.compare(9, -1, "BACK" ) )
+ else if(!alphaFunctionValue.compare(9, -1, "BACK"))
{
animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_OUT_BACK);
}
}
}
- else if( alphaFunctionValue == "REVERSE" )
+ else if(alphaFunctionValue == "REVERSE")
{
animator->alphaFunction = AlphaFunction(AlphaFunction::REVERSE);
}
- else if( alphaFunctionValue == "BOUNCE" )
+ else if(alphaFunctionValue == "BOUNCE")
{
animator->alphaFunction = AlphaFunction(AlphaFunction::BOUNCE);
}
- else if( alphaFunctionValue == "SIN" )
+ else if(alphaFunctionValue == "SIN")
{
animator->alphaFunction = AlphaFunction(AlphaFunction::SIN);
}
{
}
-TransitionDataPtr TransitionData::New( const Property::Array& value )
+TransitionDataPtr TransitionData::New(const Property::Array& value)
{
- TransitionDataPtr transitionData( new TransitionData() );
+ TransitionDataPtr transitionData(new TransitionData());
transitionData->Initialize(value);
return transitionData;
}
-TransitionDataPtr TransitionData::New( const Property::Map& value )
+TransitionDataPtr TransitionData::New(const Property::Map& value)
{
- TransitionDataPtr transitionData( new TransitionData() );
+ TransitionDataPtr transitionData(new TransitionData());
transitionData->Initialize(value);
return transitionData;
}
-
-void TransitionData::Initialize( const Property::Map& map )
+void TransitionData::Initialize(const Property::Map& map)
{
- TransitionData::Animator* animator = ConvertMap( map );
- Add( animator );
+ TransitionData::Animator* animator = ConvertMap(map);
+ Add(animator);
}
-void TransitionData::Initialize( const Property::Array& array )
+void TransitionData::Initialize(const Property::Array& array)
{
- for( unsigned int arrayIdx = 0, transitionArrayCount = array.Count(); arrayIdx < transitionArrayCount; ++arrayIdx )
+ for(unsigned int arrayIdx = 0, transitionArrayCount = array.Count(); arrayIdx < transitionArrayCount; ++arrayIdx)
{
- const Property::Value& element = array.GetElementAt( arrayIdx );
+ const Property::Value& element = array.GetElementAt(arrayIdx);
// Expect each child to be an object representing an animator:
const Property::Map* map = element.GetMap();
- if( map != NULL )
+ if(map != NULL)
{
- TransitionData::Animator* animator = ConvertMap( *map );
- Add( animator );
+ TransitionData::Animator* animator = ConvertMap(*map);
+ Add(animator);
}
}
}
-TransitionData::Animator* TransitionData::ConvertMap( const Property::Map& map)
+TransitionData::Animator* TransitionData::ConvertMap(const Property::Map& map)
{
TransitionData::Animator* animator = new TransitionData::Animator();
- animator->alphaFunction = AlphaFunction::LINEAR;
- animator->timePeriodDelay = 0.0f;
- animator->timePeriodDuration = 1.0f;
+ animator->alphaFunction = AlphaFunction::LINEAR;
+ animator->timePeriodDelay = 0.0f;
+ animator->timePeriodDuration = 1.0f;
- for( unsigned int mapIdx = 0; mapIdx < map.Count(); ++mapIdx )
+ for(unsigned int mapIdx = 0; mapIdx < map.Count(); ++mapIdx)
{
- const KeyValuePair pair( map.GetKeyValue( mapIdx ) );
- if( pair.first.type == Property::Key::INDEX )
+ const KeyValuePair pair(map.GetKeyValue(mapIdx));
+ if(pair.first.type == Property::Key::INDEX)
{
continue; // We don't consider index keys.
}
- const std::string& key( pair.first.stringKey );
- const Property::Value& value( pair.second );
+ const std::string& key(pair.first.stringKey);
+ const Property::Value& value(pair.second);
- if( key == TOKEN_TARGET )
+ if(key == TOKEN_TARGET)
{
- animator->objectName = value.Get< std::string >();
+ animator->objectName = value.Get<std::string>();
}
- else if( key == TOKEN_PROPERTY )
+ else if(key == TOKEN_PROPERTY)
{
- if( value.GetType() == Property::STRING )
+ if(value.GetType() == Property::STRING)
{
- animator->propertyKey = Property::Key( value.Get<std::string>() );
+ animator->propertyKey = Property::Key(value.Get<std::string>());
}
else
{
- animator->propertyKey = Property::Key( value.Get<int>() );
+ animator->propertyKey = Property::Key(value.Get<int>());
}
}
- else if( key == TOKEN_INITIAL_VALUE )
+ else if(key == TOKEN_INITIAL_VALUE)
{
animator->initialValue = value;
}
- else if( key == TOKEN_TARGET_VALUE )
+ else if(key == TOKEN_TARGET_VALUE)
{
animator->targetValue = value;
}
- else if( key == TOKEN_ANIMATOR )
+ else if(key == TOKEN_ANIMATOR)
{
- animator->animate = true;
- Property::Map animatorMap = value.Get< Property::Map >();
- for( size_t animatorMapIdx = 0; animatorMapIdx < animatorMap.Count(); ++animatorMapIdx )
+ animator->animate = true;
+ Property::Map animatorMap = value.Get<Property::Map>();
+ for(size_t animatorMapIdx = 0; animatorMapIdx < animatorMap.Count(); ++animatorMapIdx)
{
- const KeyValuePair pair( animatorMap.GetKeyValue( animatorMapIdx ) );
+ const KeyValuePair pair(animatorMap.GetKeyValue(animatorMapIdx));
- if( pair.first.type == Property::Key::INDEX )
+ if(pair.first.type == Property::Key::INDEX)
{
continue; // We don't consider index keys.
}
- const std::string& key( pair.first.stringKey );
- const Property::Value& value( pair.second );
+ const std::string& key(pair.first.stringKey);
+ const Property::Value& value(pair.second);
- if( key == TOKEN_ALPHA_FUNCTION )
+ if(key == TOKEN_ALPHA_FUNCTION)
{
- if( value.GetType() == Property::ARRAY )
+ if(value.GetType() == Property::ARRAY)
{
ParseArray(animator, value.GetArray());
}
- else if( value.GetType() == Property::VECTOR4 )
+ else if(value.GetType() == Property::VECTOR4)
{
Vector4 controlPoints = value.Get<Vector4>();
- Vector2 controlPoint1( controlPoints.x, controlPoints.y );
- Vector2 controlPoint2( controlPoints.z, controlPoints.w );
- animator->alphaFunction = AlphaFunction( controlPoint1, controlPoint2 );
+ Vector2 controlPoint1(controlPoints.x, controlPoints.y);
+ Vector2 controlPoint2(controlPoints.z, controlPoints.w);
+ animator->alphaFunction = AlphaFunction(controlPoint1, controlPoint2);
}
- else if( value.GetType() == Property::STRING )
+ else if(value.GetType() == Property::STRING)
{
- ParseString(animator, value.Get< std::string >());
+ ParseString(animator, value.Get<std::string>());
}
else
{
animator->animate = false;
}
}
- else if( key == TOKEN_TIME_PERIOD )
+ else if(key == TOKEN_TIME_PERIOD)
{
- Property::Map timeMap = value.Get< Property::Map >();
- for( size_t timeMapIdx = 0; timeMapIdx < timeMap.Count(); ++timeMapIdx )
+ Property::Map timeMap = value.Get<Property::Map>();
+ for(size_t timeMapIdx = 0; timeMapIdx < timeMap.Count(); ++timeMapIdx)
{
- const KeyValuePair pair( timeMap.GetKeyValue( timeMapIdx ) );
- if( pair.first.type == Property::Key::INDEX )
+ const KeyValuePair pair(timeMap.GetKeyValue(timeMapIdx));
+ if(pair.first.type == Property::Key::INDEX)
{
continue;
}
- const std::string& key( pair.first.stringKey );
+ const std::string& key(pair.first.stringKey);
- if( key == TOKEN_DELAY )
+ if(key == TOKEN_DELAY)
{
- animator->timePeriodDelay = pair.second.Get< float >();
+ animator->timePeriodDelay = pair.second.Get<float>();
}
- else if( key == TOKEN_DURATION )
+ else if(key == TOKEN_DURATION)
{
- animator->timePeriodDuration = pair.second.Get< float >();
+ animator->timePeriodDuration = pair.second.Get<float>();
}
}
}
return animator;
}
-void TransitionData::Add( Animator* animator )
+void TransitionData::Add(Animator* animator)
{
- mAnimators.PushBack( animator );
+ mAnimators.PushBack(animator);
}
TransitionData::Iterator TransitionData::Begin() const
return mAnimators.Count();
}
-Property::Map TransitionData::GetAnimatorAt( size_t index )
+Property::Map TransitionData::GetAnimatorAt(size_t index)
{
- DALI_ASSERT_ALWAYS( index < Count() && "index exceeds bounds" );
+ DALI_ASSERT_ALWAYS(index < Count() && "index exceeds bounds");
- Animator* animator = mAnimators[index];
+ Animator* animator = mAnimators[index];
Property::Map map;
map[TOKEN_TARGET] = animator->objectName;
- if( animator->propertyKey.type == Property::Key::INDEX )
+ if(animator->propertyKey.type == Property::Key::INDEX)
{
map[TOKEN_PROPERTY] = animator->propertyKey.indexKey;
}
{
map[TOKEN_PROPERTY] = animator->propertyKey.stringKey;
}
- if( animator->initialValue.GetType() != Property::NONE )
+ if(animator->initialValue.GetType() != Property::NONE)
{
map[TOKEN_INITIAL_VALUE] = animator->initialValue;
}
- if( animator->targetValue.GetType() != Property::NONE )
+ if(animator->targetValue.GetType() != Property::NONE)
{
map[TOKEN_TARGET_VALUE] = animator->targetValue;
}
- if( animator->animate )
+ if(animator->animate)
{
Property::Map animateMap;
- if( animator->alphaFunction.GetMode() == AlphaFunction::BUILTIN_FUNCTION )
+ if(animator->alphaFunction.GetMode() == AlphaFunction::BUILTIN_FUNCTION)
{
- animateMap.Add(TOKEN_ALPHA_FUNCTION, GetEnumerationName( animator->alphaFunction.GetBuiltinFunction(),
- ALPHA_FUNCTION_BUILTIN_TABLE,
- ALPHA_FUNCTION_BUILTIN_TABLE_COUNT ));
+ animateMap.Add(TOKEN_ALPHA_FUNCTION, GetEnumerationName(animator->alphaFunction.GetBuiltinFunction(), ALPHA_FUNCTION_BUILTIN_TABLE, ALPHA_FUNCTION_BUILTIN_TABLE_COUNT));
}
- else if( animator->alphaFunction.GetMode() == AlphaFunction::BEZIER )
+ else if(animator->alphaFunction.GetMode() == AlphaFunction::BEZIER)
{
Vector4 controlPoints = animator->alphaFunction.GetBezierControlPoints();
- animateMap.Add( TOKEN_ALPHA_FUNCTION, controlPoints );
+ animateMap.Add(TOKEN_ALPHA_FUNCTION, controlPoints);
}
- animateMap.Add(TOKEN_TIME_PERIOD, Property::Map()
- .Add( TOKEN_DELAY, animator->timePeriodDelay )
- .Add( TOKEN_DURATION, animator->timePeriodDuration ));
+ animateMap.Add(TOKEN_TIME_PERIOD, Property::Map().Add(TOKEN_DELAY, animator->timePeriodDelay).Add(TOKEN_DURATION, animator->timePeriodDuration));
map[TOKEN_ANIMATOR] = animateMap;
}
/*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
#include <dali-toolkit/internal/helpers/property-helper.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( SHADER_HINT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Shader::Hint, NONE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Shader::Hint, OUTPUT_IS_TRANSPARENT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Shader::Hint, MODIFIES_GEOMETRY )
-DALI_ENUM_TO_STRING_TABLE_END( SHADER_HINT )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( ALIGN )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, TOP_BEGIN )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, TOP_CENTER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, TOP_END )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, CENTER_BEGIN )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, CENTER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, CENTER_END )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, BOTTOM_BEGIN )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, BOTTOM_CENTER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, BOTTOM_END )
-DALI_ENUM_TO_STRING_TABLE_END( ALIGN )
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( POLICY )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual::Transform::Policy, RELATIVE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual::Transform::Policy, ABSOLUTE )
-DALI_ENUM_TO_STRING_TABLE_END( POLICY )
-
-Dali::Vector2 PointToVector2( Toolkit::Align::Type point, Toolkit::Direction::Type direction )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(SHADER_HINT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Shader::Hint, NONE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Shader::Hint, OUTPUT_IS_TRANSPARENT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Shader::Hint, MODIFIES_GEOMETRY)
+DALI_ENUM_TO_STRING_TABLE_END(SHADER_HINT)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(ALIGN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, TOP_BEGIN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, TOP_CENTER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, TOP_END)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, CENTER_BEGIN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, CENTER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, CENTER_END)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, BOTTOM_BEGIN)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, BOTTOM_CENTER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, BOTTOM_END)
+DALI_ENUM_TO_STRING_TABLE_END(ALIGN)
+
+DALI_ENUM_TO_STRING_TABLE_BEGIN(POLICY)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual::Transform::Policy, RELATIVE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual::Transform::Policy, ABSOLUTE)
+DALI_ENUM_TO_STRING_TABLE_END(POLICY)
+
+Dali::Vector2 PointToVector2(Toolkit::Align::Type point, Toolkit::Direction::Type direction)
{
- static const float pointToVector2[] = { 0.0f,0.0f,
- 0.5f,0.0f,
- 1.0f,0.0f,
- 0.0f,0.5f,
- 0.5f,0.5f,
- 1.0f,0.5f,
- 0.0f,1.0f,
- 0.5f,1.0f,
- 1.0f,1.0f };
-
- Vector2 result( &pointToVector2[point*2] );
- if( direction == Direction::RIGHT_TO_LEFT )
+ // clang-format off
+ static const float pointToVector2[] = {0.0f,0.0f,
+ 0.5f,0.0f,
+ 1.0f,0.0f,
+ 0.0f,0.5f,
+ 0.5f,0.5f,
+ 1.0f,0.5f,
+ 0.0f,1.0f,
+ 0.5f,1.0f,
+ 1.0f,1.0f};
+ // clang-format on
+
+ Vector2 result(&pointToVector2[point * 2]);
+ if(direction == Direction::RIGHT_TO_LEFT)
{
result.x = 1.0f - result.x;
}
return result;
}
-bool GetPolicyFromValue( const Property::Value& value, Vector2& policy )
+bool GetPolicyFromValue(const Property::Value& value, Vector2& policy)
{
bool success = false;
- if( value.Get( policy ) )
+ if(value.Get(policy))
{
success = true;
}
else
{
const Property::Array* array = value.GetArray();
- if( array && array->Size() == 2 )
+ if(array && array->Size() == 2)
{
- Toolkit::Visual::Transform::Policy::Type xPolicy = static_cast< Toolkit::Visual::Transform::Policy::Type >( -1 ); // Assign an invalid value so definitely changes
- Toolkit::Visual::Transform::Policy::Type yPolicy = static_cast< Toolkit::Visual::Transform::Policy::Type >( -1 ); // Assign an invalid value so definitely changes
+ Toolkit::Visual::Transform::Policy::Type xPolicy = static_cast<Toolkit::Visual::Transform::Policy::Type>(-1); // Assign an invalid value so definitely changes
+ Toolkit::Visual::Transform::Policy::Type yPolicy = static_cast<Toolkit::Visual::Transform::Policy::Type>(-1); // Assign an invalid value so definitely changes
- if( Scripting::GetEnumerationProperty< Toolkit::Visual::Transform::Policy::Type >( array->GetElementAt( 0 ), POLICY_TABLE, POLICY_TABLE_COUNT, xPolicy ) &&
- Scripting::GetEnumerationProperty< Toolkit::Visual::Transform::Policy::Type >( array->GetElementAt( 1 ), POLICY_TABLE, POLICY_TABLE_COUNT, yPolicy ) )
+ if(Scripting::GetEnumerationProperty<Toolkit::Visual::Transform::Policy::Type>(array->GetElementAt(0), POLICY_TABLE, POLICY_TABLE_COUNT, xPolicy) &&
+ Scripting::GetEnumerationProperty<Toolkit::Visual::Transform::Policy::Type>(array->GetElementAt(1), POLICY_TABLE, POLICY_TABLE_COUNT, yPolicy))
{
policy.x = xPolicy;
policy.y = yPolicy;
- success = true;
+ success = true;
}
}
}
delete mCustomShader;
}
-Internal::Visual::Base::Impl::CustomShader::CustomShader( const Property::Map& map )
-: mGridSize( 1, 1 ),
- mHints( Shader::Hint::NONE )
+Internal::Visual::Base::Impl::CustomShader::CustomShader(const Property::Map& map)
+: mGridSize(1, 1),
+ mHints(Shader::Hint::NONE)
{
- SetPropertyMap( map );
+ SetPropertyMap(map);
}
-void Internal::Visual::Base::Impl::CustomShader::SetPropertyMap( const Property::Map& shaderMap )
+void Internal::Visual::Base::Impl::CustomShader::SetPropertyMap(const Property::Map& shaderMap)
{
mVertexShader.clear();
mFragmentShader.clear();
- mGridSize = ImageDimensions( 1, 1 );
- mHints = Shader::Hint::NONE;
+ mGridSize = ImageDimensions(1, 1);
+ mHints = Shader::Hint::NONE;
- Property::Value* vertexShaderValue = shaderMap.Find( Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER );
- if( vertexShaderValue )
+ Property::Value* vertexShaderValue = shaderMap.Find(Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER);
+ if(vertexShaderValue)
{
- if( ! GetStringFromProperty( *vertexShaderValue, mVertexShader ) )
+ if(!GetStringFromProperty(*vertexShaderValue, mVertexShader))
{
- DALI_LOG_ERROR( "'%s' parameter does not correctly specify a string\n", CUSTOM_VERTEX_SHADER );
+ DALI_LOG_ERROR("'%s' parameter does not correctly specify a string\n", CUSTOM_VERTEX_SHADER);
}
}
- Property::Value* fragmentShaderValue = shaderMap.Find( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER );
- if( fragmentShaderValue )
+ Property::Value* fragmentShaderValue = shaderMap.Find(Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER);
+ if(fragmentShaderValue)
{
- if( ! GetStringFromProperty( *fragmentShaderValue, mFragmentShader ) )
+ if(!GetStringFromProperty(*fragmentShaderValue, mFragmentShader))
{
- DALI_LOG_ERROR( "'%s' parameter does not correctly specify a string\n", CUSTOM_FRAGMENT_SHADER );
+ DALI_LOG_ERROR("'%s' parameter does not correctly specify a string\n", CUSTOM_FRAGMENT_SHADER);
}
}
- Property::Value* subdivideXValue = shaderMap.Find( Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X, CUSTOM_SUBDIVIDE_GRID_X );
- if( subdivideXValue )
+ Property::Value* subdivideXValue = shaderMap.Find(Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X, CUSTOM_SUBDIVIDE_GRID_X);
+ if(subdivideXValue)
{
int subdivideX;
- if( !subdivideXValue->Get( subdivideX ) || subdivideX < 1 )
+ if(!subdivideXValue->Get(subdivideX) || subdivideX < 1)
{
- DALI_LOG_ERROR( "'%s' parameter does not correctly specify a value greater than 1\n", CUSTOM_SUBDIVIDE_GRID_X );
+ DALI_LOG_ERROR("'%s' parameter does not correctly specify a value greater than 1\n", CUSTOM_SUBDIVIDE_GRID_X);
}
else
{
- mGridSize = ImageDimensions( subdivideX, mGridSize.GetY() );
+ mGridSize = ImageDimensions(subdivideX, mGridSize.GetY());
}
}
- Property::Value* subdivideYValue = shaderMap.Find( Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y, CUSTOM_SUBDIVIDE_GRID_Y );
- if( subdivideYValue )
+ Property::Value* subdivideYValue = shaderMap.Find(Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y, CUSTOM_SUBDIVIDE_GRID_Y);
+ if(subdivideYValue)
{
int subdivideY;
- if( !subdivideYValue->Get( subdivideY ) || subdivideY < 1 )
+ if(!subdivideYValue->Get(subdivideY) || subdivideY < 1)
{
- DALI_LOG_ERROR( "'%s' parameter does not correctly specify a value greater than 1\n", CUSTOM_SUBDIVIDE_GRID_Y );
+ DALI_LOG_ERROR("'%s' parameter does not correctly specify a value greater than 1\n", CUSTOM_SUBDIVIDE_GRID_Y);
}
else
{
- mGridSize = ImageDimensions( mGridSize.GetX(), subdivideY );
+ mGridSize = ImageDimensions(mGridSize.GetX(), subdivideY);
}
}
- Property::Value* hintsValue = shaderMap.Find( Toolkit::Visual::Shader::Property::HINTS, CUSTOM_SHADER_HINTS );
- if( hintsValue )
+ Property::Value* hintsValue = shaderMap.Find(Toolkit::Visual::Shader::Property::HINTS, CUSTOM_SHADER_HINTS);
+ if(hintsValue)
{
- if ( ! Scripting::GetBitmaskEnumerationProperty( *hintsValue, SHADER_HINT_TABLE, SHADER_HINT_TABLE_COUNT, mHints ) )
+ if(!Scripting::GetBitmaskEnumerationProperty(*hintsValue, SHADER_HINT_TABLE, SHADER_HINT_TABLE_COUNT, mHints))
{
- DALI_LOG_ERROR( "'%s' parameter does not correctly specify a hint or an array of hint strings\n", CUSTOM_SHADER_HINTS );
+ DALI_LOG_ERROR("'%s' parameter does not correctly specify a hint or an array of hint strings\n", CUSTOM_SHADER_HINTS);
}
}
}
-void Internal::Visual::Base::Impl::CustomShader::CreatePropertyMap( Property::Map& map ) const
+void Internal::Visual::Base::Impl::CustomShader::CreatePropertyMap(Property::Map& map) const
{
- if( !mVertexShader.empty() || !mFragmentShader.empty() )
+ if(!mVertexShader.empty() || !mFragmentShader.empty())
{
Property::Map customShader;
- if( !mVertexShader.empty() )
+ if(!mVertexShader.empty())
{
- customShader.Insert( Toolkit::Visual::Shader::Property::VERTEX_SHADER, mVertexShader );
+ customShader.Insert(Toolkit::Visual::Shader::Property::VERTEX_SHADER, mVertexShader);
}
- if( !mFragmentShader.empty() )
+ if(!mFragmentShader.empty())
{
- customShader.Insert( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, mFragmentShader );
+ customShader.Insert(Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, mFragmentShader);
}
- if( mGridSize.GetWidth() != 1 )
+ if(mGridSize.GetWidth() != 1)
{
- customShader.Insert( Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X, mGridSize.GetWidth() );
+ customShader.Insert(Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X, mGridSize.GetWidth());
}
- if( mGridSize.GetHeight() != 1 )
+ if(mGridSize.GetHeight() != 1)
{
- customShader.Insert( Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y, mGridSize.GetHeight() );
+ customShader.Insert(Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y, mGridSize.GetHeight());
}
- if( mHints != Dali::Shader::Hint::NONE )
+ if(mHints != Dali::Shader::Hint::NONE)
{
- customShader.Insert( Toolkit::Visual::Shader::Property::HINTS, static_cast< int >( mHints ) );
+ customShader.Insert(Toolkit::Visual::Shader::Property::HINTS, static_cast<int>(mHints));
}
- map.Insert( Toolkit::Visual::Property::SHADER, customShader );
+ map.Insert(Toolkit::Visual::Property::SHADER, customShader);
}
}
{
}
-void Internal::Visual::Base::Impl::Transform::SetPropertyMap( const Property::Map& map )
+void Internal::Visual::Base::Impl::Transform::SetPropertyMap(const Property::Map& map)
{
// Set default values
- mOffset = Vector2( 0.0f,0.0f );
- mSize = Vector2( 1.0f,1.0f );
- mExtraSize = Vector2( 0.0f,0.0f );
- mOffsetSizeMode = Vector4( 0.0f,0.0f,0.0f,0.0f );
- mOrigin = Toolkit::Align::TOP_BEGIN;
- mAnchorPoint = Toolkit::Align::TOP_BEGIN;
-
- UpdatePropertyMap( map );
+ mOffset = Vector2(0.0f, 0.0f);
+ mSize = Vector2(1.0f, 1.0f);
+ mExtraSize = Vector2(0.0f, 0.0f);
+ mOffsetSizeMode = Vector4(0.0f, 0.0f, 0.0f, 0.0f);
+ mOrigin = Toolkit::Align::TOP_BEGIN;
+ mAnchorPoint = Toolkit::Align::TOP_BEGIN;
+
+ UpdatePropertyMap(map);
}
-void Internal::Visual::Base::Impl::Transform::UpdatePropertyMap( const Property::Map& map )
+void Internal::Visual::Base::Impl::Transform::UpdatePropertyMap(const Property::Map& map)
{
- for( Property::Map::SizeType i(0); i<map.Count(); ++i )
+ for(Property::Map::SizeType i(0); i < map.Count(); ++i)
{
- KeyValuePair keyValue = map.GetKeyValue( i );
- if( keyValue.first.type == Property::Key::INDEX )
+ KeyValuePair keyValue = map.GetKeyValue(i);
+ if(keyValue.first.type == Property::Key::INDEX)
{
- switch( keyValue.first.indexKey )
+ switch(keyValue.first.indexKey)
{
case Toolkit::Visual::Transform::Property::OFFSET:
{
- keyValue.second.Get( mOffset );
+ keyValue.second.Get(mOffset);
break;
}
case Toolkit::Visual::Transform::Property::SIZE:
{
- keyValue.second.Get( mSize );
+ keyValue.second.Get(mSize);
break;
}
case Toolkit::Visual::Transform::Property::ORIGIN:
{
- Scripting::GetEnumerationProperty< Toolkit::Align::Type >( keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mOrigin );
+ Scripting::GetEnumerationProperty<Toolkit::Align::Type>(keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mOrigin);
break;
}
case Toolkit::Visual::Transform::Property::ANCHOR_POINT:
{
- Scripting::GetEnumerationProperty< Toolkit::Align::Type >( keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mAnchorPoint );
+ Scripting::GetEnumerationProperty<Toolkit::Align::Type>(keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mAnchorPoint);
break;
}
case Toolkit::Visual::Transform::Property::OFFSET_POLICY:
{
Vector2 policy;
- if( GetPolicyFromValue( keyValue.second, policy ) )
+ if(GetPolicyFromValue(keyValue.second, policy))
{
mOffsetSizeMode.x = policy.x;
mOffsetSizeMode.y = policy.y;
case Toolkit::Visual::Transform::Property::SIZE_POLICY:
{
Vector2 policy;
- if( GetPolicyFromValue( keyValue.second, policy ) )
+ if(GetPolicyFromValue(keyValue.second, policy))
{
mOffsetSizeMode.z = policy.x;
mOffsetSizeMode.w = policy.y;
}
case Toolkit::DevelVisual::Transform::Property::EXTRA_SIZE:
{
- keyValue.second.Get( mExtraSize );
+ keyValue.second.Get(mExtraSize);
break;
}
}
}
- else // Key type is STRING
+ else // Key type is STRING
{
- if( keyValue.first == "offset" )
+ if(keyValue.first == "offset")
{
- keyValue.second.Get( mOffset );
+ keyValue.second.Get(mOffset);
}
- else if( keyValue.first == "size" )
+ else if(keyValue.first == "size")
{
- keyValue.second.Get( mSize );
+ keyValue.second.Get(mSize);
}
- else if( keyValue.first == "origin" )
+ else if(keyValue.first == "origin")
{
- Scripting::GetEnumerationProperty< Toolkit::Align::Type >( keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mOrigin );
+ Scripting::GetEnumerationProperty<Toolkit::Align::Type>(keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mOrigin);
}
- else if( keyValue.first == "anchorPoint" )
+ else if(keyValue.first == "anchorPoint")
{
- Scripting::GetEnumerationProperty< Toolkit::Align::Type >( keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mAnchorPoint );
+ Scripting::GetEnumerationProperty<Toolkit::Align::Type>(keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mAnchorPoint);
}
- else if( keyValue.first == "offsetPolicy" )
+ else if(keyValue.first == "offsetPolicy")
{
Vector2 policy;
- if( GetPolicyFromValue( keyValue.second, policy ) )
+ if(GetPolicyFromValue(keyValue.second, policy))
{
mOffsetSizeMode.x = policy.x;
mOffsetSizeMode.y = policy.y;
}
}
- else if( keyValue.first == "sizePolicy" )
+ else if(keyValue.first == "sizePolicy")
{
Vector2 policy;
- if( GetPolicyFromValue( keyValue.second, policy ) )
+ if(GetPolicyFromValue(keyValue.second, policy))
{
mOffsetSizeMode.z = policy.x;
mOffsetSizeMode.w = policy.y;
}
}
- else if( keyValue.first == "extraSize" )
+ else if(keyValue.first == "extraSize")
{
- keyValue.second.Get( mExtraSize );
+ keyValue.second.Get(mExtraSize);
}
}
}
}
-void Internal::Visual::Base::Impl::Transform::GetPropertyMap( Property::Map& map ) const
+void Internal::Visual::Base::Impl::Transform::GetPropertyMap(Property::Map& map) const
{
map.Clear();
- map.Add( Toolkit::Visual::Transform::Property::OFFSET, mOffset )
- .Add( Toolkit::Visual::Transform::Property::SIZE, mSize )
- .Add( Toolkit::Visual::Transform::Property::ORIGIN, mOrigin )
- .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, mAnchorPoint )
- .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( mOffsetSizeMode.x, mOffsetSizeMode.y ) )
- .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( mOffsetSizeMode.z, mOffsetSizeMode.w ) )
- .Add( Toolkit::DevelVisual::Transform::Property::EXTRA_SIZE, mExtraSize );
+ map.Add(Toolkit::Visual::Transform::Property::OFFSET, mOffset)
+ .Add(Toolkit::Visual::Transform::Property::SIZE, mSize)
+ .Add(Toolkit::Visual::Transform::Property::ORIGIN, mOrigin)
+ .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, mAnchorPoint)
+ .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(mOffsetSizeMode.x, mOffsetSizeMode.y))
+ .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(mOffsetSizeMode.z, mOffsetSizeMode.w))
+ .Add(Toolkit::DevelVisual::Transform::Property::EXTRA_SIZE, mExtraSize);
}
-void Internal::Visual::Base::Impl::Transform::RegisterUniforms( Dali::Renderer renderer, Toolkit::Direction::Type direction )
+void Internal::Visual::Base::Impl::Transform::RegisterUniforms(Dali::Renderer renderer, Toolkit::Direction::Type direction)
{
mSizeIndex = renderer.RegisterProperty(SIZE, mSize);
mOffsetIndex = renderer.RegisterProperty(OFFSET, direction == Toolkit::Direction::LEFT_TO_RIGHT ? mOffset : mOffset * Vector2(-1.0f, 1.0f));
- renderer.RegisterProperty( OFFSET_SIZE_MODE, mOffsetSizeMode );
- renderer.RegisterProperty( ORIGIN, PointToVector2( mOrigin, direction ) - Vector2(0.5,0.5) );
- renderer.RegisterProperty( ANCHOR_POINT, Vector2(0.5,0.5) - PointToVector2( mAnchorPoint, direction ) );
- renderer.RegisterProperty( EXTRA_SIZE, mExtraSize );
+ renderer.RegisterProperty(OFFSET_SIZE_MODE, mOffsetSizeMode);
+ renderer.RegisterProperty(ORIGIN, PointToVector2(mOrigin, direction) - Vector2(0.5, 0.5));
+ renderer.RegisterProperty(ANCHOR_POINT, Vector2(0.5, 0.5) - PointToVector2(mAnchorPoint, direction));
+ renderer.RegisterProperty(EXTRA_SIZE, mExtraSize);
}
-Vector2 Internal::Visual::Base::Impl::Transform::GetVisualSize( const Vector2& controlSize )
+Vector2 Internal::Visual::Base::Impl::Transform::GetVisualSize(const Vector2& controlSize)
{
- return Vector2( Lerp( mOffsetSizeMode.z, mSize.x * controlSize.x, mSize.x ) ,
- Lerp( mOffsetSizeMode.w, mSize.y * controlSize.y, mSize.y ) ) + mExtraSize;
+ return Vector2(Lerp(mOffsetSizeMode.z, mSize.x * controlSize.x, mSize.x),
+ Lerp(mOffsetSizeMode.w, mSize.y * controlSize.y, mSize.y)) +
+ mExtraSize;
}
} // namespace Internal
// EXTERNAL HEADER
#include <dali-toolkit/public-api/dali-toolkit-common.h>
-#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/devel-api/rendering/renderer-devel.h>
+#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/integration-api/debug.h>
//INTERNAL HEARDER
-#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/primitive-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
#include <dali-toolkit/internal/helpers/property-helper.h>
#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
+#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/primitive-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace
{
#if defined(DEBUG_ENABLED)
-Debug::Filter* gVisualBaseLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VISUAL_BASE" );
+Debug::Filter* gVisualBaseLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VISUAL_BASE");
#endif
-const char * const PRE_MULTIPLIED_ALPHA_PROPERTY( "preMultipliedAlpha" );
+const char* const PRE_MULTIPLIED_ALPHA_PROPERTY("preMultipliedAlpha");
} // namespace
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( VISUAL_FITTING_MODE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, FIT_KEEP_ASPECT_RATIO )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, FILL )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, OVER_FIT_KEEP_ASPECT_RATIO )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, CENTER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, FIT_WIDTH )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, FIT_HEIGHT )
-DALI_ENUM_TO_STRING_TABLE_END( VISUAL_FITTING_MODE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(VISUAL_FITTING_MODE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, FIT_KEEP_ASPECT_RATIO)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, FILL)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, OVER_FIT_KEEP_ASPECT_RATIO)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, CENTER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, FIT_WIDTH)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, FIT_HEIGHT)
+DALI_ENUM_TO_STRING_TABLE_END(VISUAL_FITTING_MODE)
} // namespace
-Visual::Base::Base( VisualFactoryCache& factoryCache, FittingMode fittingMode, Toolkit::Visual::Type type )
-: mImpl( new Impl( fittingMode, type ) ),
- mFactoryCache( factoryCache )
+Visual::Base::Base(VisualFactoryCache& factoryCache, FittingMode fittingMode, Toolkit::Visual::Type type)
+: mImpl(new Impl(fittingMode, type)),
+ mFactoryCache(factoryCache)
{
}
}
}
-void Visual::Base::SetCustomShader( const Property::Map& shaderMap )
+void Visual::Base::SetCustomShader(const Property::Map& shaderMap)
{
- if( mImpl->mCustomShader )
+ if(mImpl->mCustomShader)
{
- mImpl->mCustomShader->SetPropertyMap( shaderMap );
+ mImpl->mCustomShader->SetPropertyMap(shaderMap);
}
else
{
- mImpl->mCustomShader = new Impl::CustomShader( shaderMap );
+ mImpl->mCustomShader = new Impl::CustomShader(shaderMap);
}
// Let derived class know
UpdateShader();
}
-void Visual::Base::SetProperties( const Property::Map& propertyMap )
+void Visual::Base::SetProperties(const Property::Map& propertyMap)
{
- for( size_t i = 0; i < propertyMap.Count(); ++i )
+ for(size_t i = 0; i < propertyMap.Count(); ++i)
{
- const KeyValuePair& pair = propertyMap.GetKeyValue( i );
- const Property::Key& key = pair.first;
+ const KeyValuePair& pair = propertyMap.GetKeyValue(i);
+ const Property::Key& key = pair.first;
const Property::Value& value = pair.second;
Property::Key matchKey = key;
- if( matchKey.type == Property::Key::STRING )
+ if(matchKey.type == Property::Key::STRING)
{
- if( matchKey == CUSTOM_SHADER )
+ if(matchKey == CUSTOM_SHADER)
{
- matchKey = Property::Key( Toolkit::Visual::Property::SHADER );
+ matchKey = Property::Key(Toolkit::Visual::Property::SHADER);
}
- else if( matchKey == TRANSFORM )
+ else if(matchKey == TRANSFORM)
{
- matchKey = Property::Key( Toolkit::Visual::Property::TRANSFORM );
+ matchKey = Property::Key(Toolkit::Visual::Property::TRANSFORM);
}
- else if( matchKey == PREMULTIPLIED_ALPHA )
+ else if(matchKey == PREMULTIPLIED_ALPHA)
{
- matchKey = Property::Key( Toolkit::Visual::Property::PREMULTIPLIED_ALPHA );
+ matchKey = Property::Key(Toolkit::Visual::Property::PREMULTIPLIED_ALPHA);
}
- else if( matchKey == MIX_COLOR )
+ else if(matchKey == MIX_COLOR)
{
- matchKey = Property::Key( Toolkit::Visual::Property::MIX_COLOR );
+ matchKey = Property::Key(Toolkit::Visual::Property::MIX_COLOR);
}
- else if( matchKey == OPACITY )
+ else if(matchKey == OPACITY)
{
- matchKey = Property::Key( Toolkit::Visual::Property::OPACITY );
+ matchKey = Property::Key(Toolkit::Visual::Property::OPACITY);
}
- else if( matchKey == VISUAL_FITTING_MODE )
+ else if(matchKey == VISUAL_FITTING_MODE)
{
- matchKey = Property::Key( Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE );
+ matchKey = Property::Key(Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE);
}
- else if( matchKey == CORNER_RADIUS )
+ else if(matchKey == CORNER_RADIUS)
{
- matchKey = Property::Key( Toolkit::DevelVisual::Property::CORNER_RADIUS );
+ matchKey = Property::Key(Toolkit::DevelVisual::Property::CORNER_RADIUS);
}
- else if( matchKey == CORNER_RADIUS_POLICY )
+ else if(matchKey == CORNER_RADIUS_POLICY)
{
- matchKey = Property::Key( Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY );
+ matchKey = Property::Key(Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY);
}
}
- switch( matchKey.indexKey )
+ switch(matchKey.indexKey)
{
case Toolkit::Visual::Property::SHADER:
{
Property::Map shaderMap;
- if( value.Get( shaderMap ) )
+ if(value.Get(shaderMap))
{
- SetCustomShader( shaderMap );
+ SetCustomShader(shaderMap);
}
break;
}
case Toolkit::Visual::Property::TRANSFORM:
{
Property::Map map;
- if( value.Get( map ) )
+ if(value.Get(map))
{
- mImpl->mTransform.SetPropertyMap( map );
+ mImpl->mTransform.SetPropertyMap(map);
}
break;
}
case Toolkit::Visual::Property::PREMULTIPLIED_ALPHA:
{
bool premultipliedAlpha = false;
- if( value.Get( premultipliedAlpha ) )
+ if(value.Get(premultipliedAlpha))
{
- EnablePreMultipliedAlpha( premultipliedAlpha );
+ EnablePreMultipliedAlpha(premultipliedAlpha);
}
break;
}
case Toolkit::Visual::Property::MIX_COLOR:
{
Vector4 mixColor;
- if( value.Get( mixColor ) )
+ if(value.Get(mixColor))
{
- if( value.GetType() == Property::VECTOR4 )
+ if(value.GetType() == Property::VECTOR4)
{
- SetMixColor( mixColor );
+ SetMixColor(mixColor);
}
else
{
Vector3 mixColor3(mixColor);
- SetMixColor( mixColor3 );
+ SetMixColor(mixColor3);
}
}
break;
case Toolkit::Visual::Property::OPACITY:
{
float opacity;
- if( value.Get( opacity ) )
+ if(value.Get(opacity))
{
mImpl->mMixColor.a = opacity;
- SetMixColor( mImpl->mMixColor );
+ SetMixColor(mImpl->mMixColor);
}
break;
}
case Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE:
{
- Scripting::GetEnumerationProperty< Visual::FittingMode >(
- value, VISUAL_FITTING_MODE_TABLE, VISUAL_FITTING_MODE_TABLE_COUNT, mImpl->mFittingMode );
+ Scripting::GetEnumerationProperty<Visual::FittingMode>(
+ value, VISUAL_FITTING_MODE_TABLE, VISUAL_FITTING_MODE_TABLE_COUNT, mImpl->mFittingMode);
break;
}
case Toolkit::DevelVisual::Property::CORNER_RADIUS:
{
float radius;
- if( value.Get( radius ) )
+ if(value.Get(radius))
{
mImpl->mCornerRadius = radius;
}
case Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY:
{
int policy;
- if( value.Get( policy ) )
+ if(value.Get(policy))
{
- switch( policy )
+ switch(policy)
{
case Toolkit::Visual::Transform::Policy::RELATIVE:
case Toolkit::Visual::Transform::Policy::ABSOLUTE:
}
default:
{
- DALI_LOG_ERROR( "Unsupported policy: %d\n", policy );
+ DALI_LOG_ERROR("Unsupported policy: %d\n", policy);
break;
}
}
}
}
- DoSetProperties( propertyMap );
+ DoSetProperties(propertyMap);
}
-void Visual::Base::SetTransformAndSize( const Property::Map& transform, Size controlSize )
+void Visual::Base::SetTransformAndSize(const Property::Map& transform, Size controlSize)
{
mImpl->mControlSize = controlSize;
- mImpl->mTransform.UpdatePropertyMap( transform );
+ mImpl->mTransform.UpdatePropertyMap(transform);
#if defined(DEBUG_ENABLED)
std::ostringstream oss;
oss << transform;
- DALI_LOG_INFO( gVisualBaseLogFilter, Debug::General, "Visual::Base::SetTransformAndSize(%s) - [\e[1;32mtransform: %s controlSize: (%3.1f, %3.1f)]\e[0m\n",
- GetName().c_str(), oss.str().c_str(), controlSize.x, controlSize.y );
+ DALI_LOG_INFO(gVisualBaseLogFilter, Debug::General, "Visual::Base::SetTransformAndSize(%s) - [\e[1;32mtransform: %s controlSize: (%3.1f, %3.1f)]\e[0m\n", GetName().c_str(), oss.str().c_str(), controlSize.x, controlSize.y);
#endif
OnSetTransform();
}
-void Visual::Base::SetName( const std::string& name )
+void Visual::Base::SetName(const std::string& name)
{
mImpl->mName = name;
}
return mImpl->mName;
}
-float Visual::Base::GetHeightForWidth( float width )
+float Visual::Base::GetHeightForWidth(float width)
{
- float aspectCorrectedHeight = 0.f;
+ float aspectCorrectedHeight = 0.f;
Vector2 naturalSize;
- GetNaturalSize( naturalSize );
- if( naturalSize.width )
+ GetNaturalSize(naturalSize);
+ if(naturalSize.width)
{
aspectCorrectedHeight = naturalSize.height * width / naturalSize.width;
}
return aspectCorrectedHeight;
}
-float Visual::Base::GetWidthForHeight( float height )
+float Visual::Base::GetWidthForHeight(float height)
{
- float aspectCorrectedWidth = 0.f;
+ float aspectCorrectedWidth = 0.f;
Vector2 naturalSize;
- GetNaturalSize( naturalSize );
- if( naturalSize.height > 0.0f )
+ GetNaturalSize(naturalSize);
+ if(naturalSize.height > 0.0f)
{
aspectCorrectedWidth = naturalSize.width * height / naturalSize.height;
}
return aspectCorrectedWidth;
}
-void Visual::Base::GetNaturalSize( Vector2& naturalSize )
+void Visual::Base::GetNaturalSize(Vector2& naturalSize)
{
naturalSize = Vector2::ZERO;
}
-void Visual::Base::DoAction( const Property::Index actionId, const Property::Value attributes )
+void Visual::Base::DoAction(const Property::Index actionId, const Property::Value attributes)
{
- OnDoAction( actionId, attributes );
+ OnDoAction(actionId, attributes);
}
-void Visual::Base::SetDepthIndex( int index )
+void Visual::Base::SetDepthIndex(int index)
{
mImpl->mDepthIndex = index;
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, mImpl->mDepthIndex );
+ mImpl->mRenderer.SetProperty(Renderer::Property::DEPTH_INDEX, mImpl->mDepthIndex);
}
}
return mImpl->mDepthIndex;
}
-void Visual::Base::SetOnScene( Actor& actor )
+void Visual::Base::SetOnScene(Actor& actor)
{
- if( !IsOnScene() )
+ if(!IsOnScene())
{
// To display the actor correctly, renderer should not be added to actor until all required resources are ready.
// Thus the calling of actor.AddRenderer() should happen inside derived class as base class does not know the exact timing.
- DoSetOnScene( actor );
+ DoSetOnScene(actor);
if(mImpl->mRenderer)
{
}
}
-void Visual::Base::SetOffScene( Actor& actor )
+void Visual::Base::SetOffScene(Actor& actor)
{
- if( IsOnScene() )
+ if(IsOnScene())
{
- DoSetOffScene( actor );
+ DoSetOffScene(actor);
mImpl->mFlags &= ~Impl::IS_ON_SCENE;
}
}
-void Visual::Base::CreatePropertyMap( Property::Map& map ) const
+void Visual::Base::CreatePropertyMap(Property::Map& map) const
{
if(mImpl->mRenderer)
{
}
Property::Map transform;
- mImpl->mTransform.GetPropertyMap( transform );
- map.Insert( Toolkit::Visual::Property::TRANSFORM, transform );
+ mImpl->mTransform.GetPropertyMap(transform);
+ map.Insert(Toolkit::Visual::Property::TRANSFORM, transform);
- bool premultipliedAlpha( IsPreMultipliedAlphaEnabled() );
- map.Insert( Toolkit::Visual::Property::PREMULTIPLIED_ALPHA, premultipliedAlpha );
+ bool premultipliedAlpha(IsPreMultipliedAlphaEnabled());
+ map.Insert(Toolkit::Visual::Property::PREMULTIPLIED_ALPHA, premultipliedAlpha);
// Note, Color and Primitive will also insert their own mix color into the map
// which is ok, because they have a different key value range.
- map.Insert( Toolkit::Visual::Property::MIX_COLOR, mImpl->mMixColor ); // vec4
- map.Insert( Toolkit::Visual::Property::OPACITY, mImpl->mMixColor.a );
+ map.Insert(Toolkit::Visual::Property::MIX_COLOR, mImpl->mMixColor); // vec4
+ map.Insert(Toolkit::Visual::Property::OPACITY, mImpl->mMixColor.a);
- auto fittingModeString = Scripting::GetLinearEnumerationName< FittingMode >(
- mImpl->mFittingMode, VISUAL_FITTING_MODE_TABLE, VISUAL_FITTING_MODE_TABLE_COUNT );
- map.Insert( Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE, fittingModeString );
+ auto fittingModeString = Scripting::GetLinearEnumerationName<FittingMode>(
+ mImpl->mFittingMode, VISUAL_FITTING_MODE_TABLE, VISUAL_FITTING_MODE_TABLE_COUNT);
+ map.Insert(Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE, fittingModeString);
- map.Insert( Toolkit::DevelVisual::Property::CORNER_RADIUS, mImpl->mCornerRadius );
- map.Insert( Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY, static_cast< int >( mImpl->mCornerRadiusPolicy ) );
+ map.Insert(Toolkit::DevelVisual::Property::CORNER_RADIUS, mImpl->mCornerRadius);
+ map.Insert(Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY, static_cast<int>(mImpl->mCornerRadiusPolicy));
}
-void Visual::Base::CreateInstancePropertyMap( Property::Map& map ) const
+void Visual::Base::CreateInstancePropertyMap(Property::Map& map) const
{
- DoCreateInstancePropertyMap( map );
+ DoCreateInstancePropertyMap(map);
- if( mImpl->mCustomShader )
+ if(mImpl->mCustomShader)
{
- mImpl->mCustomShader->CreatePropertyMap( map );
+ mImpl->mCustomShader->CreatePropertyMap(map);
}
}
-
-void Visual::Base::EnablePreMultipliedAlpha( bool preMultiplied )
+void Visual::Base::EnablePreMultipliedAlpha(bool preMultiplied)
{
- if( preMultiplied )
+ if(preMultiplied)
{
mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
}
mImpl->mFlags &= ~Impl::IS_PREMULTIPLIED_ALPHA;
}
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, preMultiplied);
- mImpl->mRenderer.RegisterProperty( PRE_MULTIPLIED_ALPHA_PROPERTY, static_cast<float>( preMultiplied ) );
+ mImpl->mRenderer.RegisterProperty(PRE_MULTIPLIED_ALPHA_PROPERTY, static_cast<float>(preMultiplied));
}
}
return mImpl->mFlags & Impl::IS_PREMULTIPLIED_ALPHA;
}
-void Visual::Base::DoSetOffScene( Actor& actor )
+void Visual::Base::DoSetOffScene(Actor& actor)
{
- actor.RemoveRenderer( mImpl->mRenderer );
+ actor.RemoveRenderer(mImpl->mRenderer);
}
bool Visual::Base::IsOnScene() const
return !EqualsZero(mImpl->mCornerRadius) || mImpl->mNeedCornerRadius;
}
-void Visual::Base::OnDoAction( const Property::Index actionId, const Property::Value& attributes )
+void Visual::Base::OnDoAction(const Property::Index actionId, const Property::Value& attributes)
{
// May be overriden by derived class
}
{
// Only register if not already registered.
// (Color and Primitive visuals will register their own and save to this index)
- if( mImpl->mMixColorIndex == Property::INVALID_INDEX )
+ if(mImpl->mMixColorIndex == Property::INVALID_INDEX)
{
mImpl->mMixColorIndex = mImpl->mRenderer.RegisterProperty(
Toolkit::Visual::Property::MIX_COLOR,
MIX_COLOR,
- Vector3(mImpl->mMixColor) );
+ Vector3(mImpl->mMixColor));
}
- mImpl->mRenderer.SetProperty( DevelRenderer::Property::OPACITY, mImpl->mMixColor.a );
+ mImpl->mRenderer.SetProperty(DevelRenderer::Property::OPACITY, mImpl->mMixColor.a);
float preMultipliedAlpha = 0.0f;
- if( IsPreMultipliedAlphaEnabled() )
+ if(IsPreMultipliedAlphaEnabled())
{
preMultipliedAlpha = 1.0f;
}
- mImpl->mRenderer.RegisterProperty( PRE_MULTIPLIED_ALPHA_PROPERTY, preMultipliedAlpha );
+ mImpl->mRenderer.RegisterProperty(PRE_MULTIPLIED_ALPHA_PROPERTY, preMultipliedAlpha);
}
-void Visual::Base::SetMixColor( const Vector4& color )
+void Visual::Base::SetMixColor(const Vector4& color)
{
mImpl->mMixColor = color;
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetProperty( mImpl->mMixColorIndex, Vector3(color) );
- mImpl->mRenderer.SetProperty( DevelRenderer::Property::OPACITY, color.a );
+ mImpl->mRenderer.SetProperty(mImpl->mMixColorIndex, Vector3(color));
+ mImpl->mRenderer.SetProperty(DevelRenderer::Property::OPACITY, color.a);
}
}
-void Visual::Base::SetMixColor( const Vector3& color )
+void Visual::Base::SetMixColor(const Vector3& color)
{
mImpl->mMixColor.r = color.r;
mImpl->mMixColor.g = color.g;
mImpl->mMixColor.b = color.b;
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- mImpl->mRenderer.SetProperty( mImpl->mMixColorIndex, color );
+ mImpl->mRenderer.SetProperty(mImpl->mMixColorIndex, color);
}
}
-void Visual::Base::AddEventObserver( Visual::EventObserver& observer)
+void Visual::Base::AddEventObserver(Visual::EventObserver& observer)
{
mImpl->mEventObserver = &observer;
}
-void Visual::Base::RemoveEventObserver( Visual::EventObserver& observer )
+void Visual::Base::RemoveEventObserver(Visual::EventObserver& observer)
{
mImpl->mEventObserver = NULL;
}
void Visual::Base::ResourceReady(Toolkit::Visual::ResourceStatus resourceStatus)
{
- if( mImpl->mResourceStatus != resourceStatus )
+ if(mImpl->mResourceStatus != resourceStatus)
{
mImpl->mResourceStatus = resourceStatus;
- if( mImpl->mEventObserver )
+ if(mImpl->mEventObserver)
{
// observer is currently a control impl
- mImpl->mEventObserver->ResourceReady( *this );
+ mImpl->mEventObserver->ResourceReady(*this);
}
}
}
bool Visual::Base::IsResourceReady() const
{
- return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY );
+ return (mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY);
}
bool Visual::Base::IsSynchronousLoadingRequired() const
{
- return ( mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING );
+ return (mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING);
}
Toolkit::Visual::Type Visual::Base::GetType() const
return mImpl->mRenderer;
}
-Property::Index Visual::Base::GetPropertyIndex( Property::Key key )
+Property::Index Visual::Base::GetPropertyIndex(Property::Key key)
{
- Property::Index index = mImpl->mRenderer.GetPropertyIndex( key );
+ Property::Index index = mImpl->mRenderer.GetPropertyIndex(key);
- if( index == Property::INVALID_INDEX )
+ if(index == Property::INVALID_INDEX)
{
// Is it a shader property?
Shader shader = mImpl->mRenderer.GetShader();
- index = shader.GetPropertyIndex( key );
- if( index != Property::INVALID_INDEX )
+ index = shader.GetPropertyIndex(key);
+ if(index != Property::INVALID_INDEX)
{
// Yes - we should register it in the Renderer so it can be set / animated
// independently, as shaders are shared across multiple renderers.
- std::string keyName;
- Property::Index keyIndex( Property::INVALID_KEY );
- if( key.type == Property::Key::INDEX )
+ std::string keyName;
+ Property::Index keyIndex(Property::INVALID_KEY);
+ if(key.type == Property::Key::INDEX)
{
- keyName = shader.GetPropertyName( index );
+ keyName = shader.GetPropertyName(index);
keyIndex = key.indexKey;
}
else
keyName = key.stringKey;
// Leave keyIndex as INVALID_KEY - it can still be registered against the string key.
}
- Property::Value value = shader.GetProperty( index );
- index = mImpl->mRenderer.RegisterProperty( keyIndex, keyName, value );
+ Property::Value value = shader.GetProperty(index);
+ index = mImpl->mRenderer.RegisterProperty(keyIndex, keyName, value);
}
}
return index;
}
void Visual::Base::SetupTransition(
- Dali::Animation& transition,
+ Dali::Animation& transition,
Internal::TransitionData::Animator& animator,
- Property::Index index,
- Property::Value& initialValue,
- Property::Value& targetValue )
+ Property::Index index,
+ Property::Value& initialValue,
+ Property::Value& targetValue)
{
- if( index != Property::INVALID_INDEX )
+ if(index != Property::INVALID_INDEX)
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
- if( animator.animate == false )
+ if(animator.animate == false)
{
- mImpl->mRenderer.SetProperty( index, targetValue );
+ mImpl->mRenderer.SetProperty(index, targetValue);
}
else
{
- if( animator.initialValue.GetType() != Property::NONE )
+ if(animator.initialValue.GetType() != Property::NONE)
{
- mImpl->mRenderer.SetProperty( index, initialValue );
+ mImpl->mRenderer.SetProperty(index, initialValue);
}
- if( ! transition )
+ if(!transition)
{
- transition = Dali::Animation::New( 0.1f );
+ transition = Dali::Animation::New(0.1f);
}
- transition.AnimateTo( Property( mImpl->mRenderer, index ),
- targetValue,
- animator.alphaFunction,
- TimePeriod( animator.timePeriodDelay,
- animator.timePeriodDuration ) );
+ transition.AnimateTo(Property(mImpl->mRenderer, index),
+ targetValue,
+ animator.alphaFunction,
+ TimePeriod(animator.timePeriodDelay,
+ animator.timePeriodDuration));
}
}
}
}
void Visual::Base::AnimateProperty(
- Dali::Animation& transition,
- Internal::TransitionData::Animator& animator )
+ Dali::Animation& transition,
+ Internal::TransitionData::Animator& animator)
{
#if defined(DEBUG_ENABLED)
{
std::ostringstream oss;
oss << "Visual::Base::AnimateProperty(Visual:" << mImpl->mName << " Property:" << animator.propertyKey << " Target: " << animator.targetValue << std::endl;
- DALI_LOG_INFO( gVisualBaseLogFilter, Debug::General, oss.str().c_str() );
+ DALI_LOG_INFO(gVisualBaseLogFilter, Debug::General, oss.str().c_str());
}
#endif
(mImpl->mType == Toolkit::Visual::PRIMITIVE &&
animator.propertyKey == PrimitiveVisual::Property::MIX_COLOR))
{
- AnimateMixColorProperty( transition, animator );
+ AnimateMixColorProperty(transition, animator);
}
else if(animator.propertyKey == Toolkit::Visual::Property::OPACITY ||
- animator.propertyKey == OPACITY )
+ animator.propertyKey == OPACITY)
{
- AnimateOpacityProperty( transition, animator );
+ AnimateOpacityProperty(transition, animator);
}
- else if( mImpl->mRenderer )
+ else if(mImpl->mRenderer)
{
- AnimateRendererProperty( transition, animator );
+ AnimateRendererProperty(transition, animator);
}
}
void Visual::Base::AnimateOpacityProperty(
- Dali::Animation& transition,
- Internal::TransitionData::Animator& animator )
+ Dali::Animation& transition,
+ Internal::TransitionData::Animator& animator)
{
float targetOpacity;
- if( animator.targetValue.Get( targetOpacity ) )
+ if(animator.targetValue.Get(targetOpacity))
{
mImpl->mMixColor.a = targetOpacity;
}
- SetupTransition( transition, animator, DevelRenderer::Property::OPACITY, animator.initialValue, animator.targetValue );
+ SetupTransition(transition, animator, DevelRenderer::Property::OPACITY, animator.initialValue, animator.targetValue);
}
void Visual::Base::AnimateRendererProperty(
- Dali::Animation& transition,
- Internal::TransitionData::Animator& animator )
+ Dali::Animation& transition,
+ Internal::TransitionData::Animator& animator)
{
- Property::Index index = GetPropertyIndex( animator.propertyKey );
- if( index != Property::INVALID_INDEX )
+ Property::Index index = GetPropertyIndex(animator.propertyKey);
+ if(index != Property::INVALID_INDEX)
{
- if( animator.targetValue.GetType() != Property::NONE )
+ if(animator.targetValue.GetType() != Property::NONE)
{
// Try writing target value into transform property map
// if it's not a valid key, then it won't alter mTransform
Property::Map map;
- if( animator.propertyKey.type == Property::Key::INDEX )
+ if(animator.propertyKey.type == Property::Key::INDEX)
{
- map.Add( animator.propertyKey.indexKey, animator.targetValue );
+ map.Add(animator.propertyKey.indexKey, animator.targetValue);
}
else
{
- map.Add( animator.propertyKey.stringKey, animator.targetValue );
+ map.Add(animator.propertyKey.stringKey, animator.targetValue);
}
- mImpl->mTransform.UpdatePropertyMap( map );
+ mImpl->mTransform.UpdatePropertyMap(map);
}
- SetupTransition( transition, animator, index, animator.initialValue, animator.targetValue );
+ SetupTransition(transition, animator, index, animator.initialValue, animator.targetValue);
}
}
void Visual::Base::AnimateMixColorProperty(
- Dali::Animation& transition,
- Internal::TransitionData::Animator& animator )
+ Dali::Animation& transition,
+ Internal::TransitionData::Animator& animator)
{
- Property::Index index = mImpl->mMixColorIndex;
- bool animateOpacity = false;
+ Property::Index index = mImpl->mMixColorIndex;
+ bool animateOpacity = false;
Property::Value initialOpacity;
Property::Value targetOpacity;
Property::Value initialMixColor;
Property::Value targetMixColor;
- if( index != Property::INVALID_INDEX )
+ if(index != Property::INVALID_INDEX)
{
Vector4 initialColor;
- if( animator.initialValue.Get(initialColor) )
+ if(animator.initialValue.Get(initialColor))
{
- if( animator.initialValue.GetType() == Property::VECTOR4 )
+ if(animator.initialValue.GetType() == Property::VECTOR4)
{
// if there is an initial color specifying alpha, test it
initialOpacity = initialColor.a;
}
- initialMixColor = Vector3( initialColor );
+ initialMixColor = Vector3(initialColor);
}
// Set target value into data store
- if( animator.targetValue.GetType() != Property::NONE )
+ if(animator.targetValue.GetType() != Property::NONE)
{
Vector4 mixColor;
animator.targetValue.Get(mixColor);
- if( animator.targetValue.GetType() == Property::VECTOR4 )
+ if(animator.targetValue.GetType() == Property::VECTOR4)
{
mImpl->mMixColor.a = mixColor.a;
- targetOpacity = mixColor.a;
- animateOpacity = true;
+ targetOpacity = mixColor.a;
+ animateOpacity = true;
}
mImpl->mMixColor.r = mixColor.r;
mImpl->mMixColor.g = mixColor.g;
mImpl->mMixColor.b = mixColor.b;
- targetMixColor = Vector3(mixColor);
+ targetMixColor = Vector3(mixColor);
}
- SetupTransition( transition, animator, index, initialMixColor, targetMixColor );
- if( animateOpacity )
+ SetupTransition(transition, animator, index, initialMixColor, targetMixColor);
+ if(animateOpacity)
{
- SetupTransition( transition, animator, DevelRenderer::Property::OPACITY, initialOpacity, targetOpacity );
+ SetupTransition(transition, animator, DevelRenderer::Property::OPACITY, initialOpacity, targetOpacity);
}
}
}
mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON);
- index = mImpl->mCornerRadiusIndex;
+ index = mImpl->mCornerRadiusIndex;
mImpl->mNeedCornerRadius = true;
// Change shader
- /*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "visual-factory-cache.h"
// EXTERNAL INCLUDES
-#include <dali/devel-api/common/hash.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
+#include <dali/devel-api/common/hash.h>
// INTERNAL INCLUDES
+#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
#include <dali-toolkit/internal/visuals/color/color-visual.h>
-#include <dali-toolkit/internal/visuals/svg/svg-visual.h>
#include <dali-toolkit/internal/visuals/image-atlas-manager.h>
-#include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
+#include <dali-toolkit/internal/visuals/svg/svg-visual.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-VisualFactoryCache::VisualFactoryCache( bool preMultiplyOnLoad )
-: mSvgRasterizeThread( NULL ),
+VisualFactoryCache::VisualFactoryCache(bool preMultiplyOnLoad)
+: mSvgRasterizeThread(NULL),
mVectorAnimationManager(),
mBrokenImageUrl(""),
- mPreMultiplyOnLoad( preMultiplyOnLoad )
+ mPreMultiplyOnLoad(preMultiplyOnLoad)
{
}
VisualFactoryCache::~VisualFactoryCache()
{
- SvgRasterizeThread::TerminateThread( mSvgRasterizeThread );
+ SvgRasterizeThread::TerminateThread(mSvgRasterizeThread);
}
-Geometry VisualFactoryCache::GetGeometry( GeometryType type )
+Geometry VisualFactoryCache::GetGeometry(GeometryType type)
{
- if( !mGeometry[type] && type == QUAD_GEOMETRY )
+ if(!mGeometry[type] && type == QUAD_GEOMETRY)
{
mGeometry[type] = CreateQuadGeometry();
}
return mGeometry[type];
}
-void VisualFactoryCache::SaveGeometry( GeometryType type, Geometry geometry )
+void VisualFactoryCache::SaveGeometry(GeometryType type, Geometry geometry)
{
mGeometry[type] = geometry;
}
-Shader VisualFactoryCache::GetShader( ShaderType type )
+Shader VisualFactoryCache::GetShader(ShaderType type)
{
return mShader[type];
}
-void VisualFactoryCache::SaveShader( ShaderType type, Shader shader )
+void VisualFactoryCache::SaveShader(ShaderType type, Shader shader)
{
mShader[type] = shader;
}
Geometry VisualFactoryCache::CreateQuadGeometry()
{
- const float halfWidth = 0.5f;
+ const float halfWidth = 0.5f;
const float halfHeight = 0.5f;
- struct QuadVertex { Vector2 position;};
- QuadVertex quadVertexData[4] =
+ struct QuadVertex
{
- { Vector2(-halfWidth, -halfHeight) },
- { Vector2(-halfWidth, halfHeight) },
- { Vector2( halfWidth, -halfHeight) },
- { Vector2( halfWidth, halfHeight) }
+ Vector2 position;
};
+ QuadVertex quadVertexData[4] =
+ {
+ {Vector2(-halfWidth, -halfHeight)},
+ {Vector2(-halfWidth, halfHeight)},
+ {Vector2(halfWidth, -halfHeight)},
+ {Vector2(halfWidth, halfHeight)}};
Property::Map quadVertexFormat;
quadVertexFormat["aPosition"] = Property::VECTOR2;
- VertexBuffer quadVertices = VertexBuffer::New( quadVertexFormat );
- quadVertices.SetData( quadVertexData, 4 );
+ VertexBuffer quadVertices = VertexBuffer::New(quadVertexFormat);
+ quadVertices.SetData(quadVertexData, 4);
// Create the geometry object
Geometry geometry = Geometry::New();
- geometry.AddVertexBuffer( quadVertices );
- geometry.SetType( Geometry::TRIANGLE_STRIP );
+ geometry.AddVertexBuffer(quadVertices);
+ geometry.SetType(Geometry::TRIANGLE_STRIP);
return geometry;
}
ImageAtlasManagerPtr VisualFactoryCache::GetAtlasManager()
{
- if( !mAtlasManager )
+ if(!mAtlasManager)
{
mAtlasManager = new ImageAtlasManager();
- mAtlasManager->SetBrokenImage( mBrokenImageUrl );
+ mAtlasManager->SetBrokenImage(mBrokenImageUrl);
}
return mAtlasManager;
SvgRasterizeThread* VisualFactoryCache::GetSVGRasterizationThread()
{
- if( !mSvgRasterizeThread )
+ if(!mSvgRasterizeThread)
{
mSvgRasterizeThread = new SvgRasterizeThread();
mSvgRasterizeThread->Start();
VectorAnimationManager& VisualFactoryCache::GetVectorAnimationManager()
{
- if( !mVectorAnimationManager )
+ if(!mVectorAnimationManager)
{
- mVectorAnimationManager = std::unique_ptr< VectorAnimationManager >( new VectorAnimationManager() );
+ mVectorAnimationManager = std::unique_ptr<VectorAnimationManager>(new VectorAnimationManager());
}
return *mVectorAnimationManager;
}
-Geometry VisualFactoryCache::CreateGridGeometry( Uint16Pair gridSize )
+Geometry VisualFactoryCache::CreateGridGeometry(Uint16Pair gridSize)
{
- uint16_t gridWidth = gridSize.GetWidth();
+ uint16_t gridWidth = gridSize.GetWidth();
uint16_t gridHeight = gridSize.GetHeight();
// Create vertices
- Vector< Vector2 > vertices;
- vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
+ Vector<Vector2> vertices;
+ vertices.Reserve((gridWidth + 1) * (gridHeight + 1));
- for( int y = 0; y < gridHeight + 1; ++y )
+ for(int y = 0; y < gridHeight + 1; ++y)
{
- for( int x = 0; x < gridWidth + 1; ++x )
+ for(int x = 0; x < gridWidth + 1; ++x)
{
- vertices.PushBack( Vector2( (float)x/gridWidth - 0.5f, (float)y/gridHeight - 0.5f) );
+ vertices.PushBack(Vector2((float)x / gridWidth - 0.5f, (float)y / gridHeight - 0.5f));
}
}
// Create indices
- Vector< unsigned short > indices;
- indices.Reserve( (gridWidth+2)*gridHeight*2 - 2);
+ Vector<unsigned short> indices;
+ indices.Reserve((gridWidth + 2) * gridHeight * 2 - 2);
- for( unsigned int row = 0u; row < gridHeight; ++row )
+ for(unsigned int row = 0u; row < gridHeight; ++row)
{
- unsigned int rowStartIndex = row*(gridWidth+1u);
- unsigned int nextRowStartIndex = rowStartIndex + gridWidth +1u;
+ unsigned int rowStartIndex = row * (gridWidth + 1u);
+ unsigned int nextRowStartIndex = rowStartIndex + gridWidth + 1u;
- if( row != 0u ) // degenerate index on non-first row
+ if(row != 0u) // degenerate index on non-first row
{
- indices.PushBack( rowStartIndex );
+ indices.PushBack(rowStartIndex);
}
- for( unsigned int column = 0u; column < gridWidth+1u; column++) // main strip
+ for(unsigned int column = 0u; column < gridWidth + 1u; column++) // main strip
{
- indices.PushBack( rowStartIndex + column);
- indices.PushBack( nextRowStartIndex + column);
+ indices.PushBack(rowStartIndex + column);
+ indices.PushBack(nextRowStartIndex + column);
}
- if( row != gridHeight-1u ) // degenerate index on non-last row
+ if(row != gridHeight - 1u) // degenerate index on non-last row
{
- indices.PushBack( nextRowStartIndex + gridWidth );
+ indices.PushBack(nextRowStartIndex + gridWidth);
}
}
Property::Map vertexFormat;
- vertexFormat[ "aPosition" ] = Property::VECTOR2;
- VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat );
- if( vertices.Size() > 0 )
+ vertexFormat["aPosition"] = Property::VECTOR2;
+ VertexBuffer vertexBuffer = VertexBuffer::New(vertexFormat);
+ if(vertices.Size() > 0)
{
- vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() );
+ vertexBuffer.SetData(&vertices[0], vertices.Size());
}
Property::Map indexFormat;
- indexFormat[ "indices" ] = Property::INTEGER;
- VertexBuffer indexVertexBuffer = VertexBuffer::New( indexFormat );
-
+ indexFormat["indices"] = Property::INTEGER;
+ VertexBuffer indexVertexBuffer = VertexBuffer::New(indexFormat);
// Create the geometry object
Geometry geometry = Geometry::New();
- geometry.AddVertexBuffer( vertexBuffer );
- if( indices.Size() > 0 )
+ geometry.AddVertexBuffer(vertexBuffer);
+ if(indices.Size() > 0)
{
- geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
+ geometry.SetIndexBuffer(&indices[0], indices.Size());
}
- geometry.SetType( Geometry::TRIANGLE_STRIP );
+ geometry.SetType(Geometry::TRIANGLE_STRIP);
return geometry;
}
{
if(!mBrokenImageTexture && mBrokenImageUrl.size())
{
- PixelData data;
- Devel::PixelBuffer pixelBuffer = LoadImageFromFile( mBrokenImageUrl );
- if( pixelBuffer )
+ PixelData data;
+ Devel::PixelBuffer pixelBuffer = LoadImageFromFile(mBrokenImageUrl);
+ if(pixelBuffer)
{
- data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
- mBrokenImageTexture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
- data.GetWidth(), data.GetHeight() );
- mBrokenImageTexture.Upload( data );
+ data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
+ mBrokenImageTexture = Texture::New(Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(), data.GetWidth(), data.GetHeight());
+ mBrokenImageTexture.Upload(data);
}
}
return mBrokenImageTexture;
}
-void VisualFactoryCache::SetPreMultiplyOnLoad( bool preMultiply )
+void VisualFactoryCache::SetPreMultiplyOnLoad(bool preMultiply)
{
mPreMultiplyOnLoad = preMultiply;
}
{
mBrokenImageUrl = brokenImageUrl;
- if( !mAtlasManager )
+ if(!mAtlasManager)
{
mAtlasManager = new ImageAtlasManager();
}
- mAtlasManager->SetBrokenImage( mBrokenImageUrl );
+ mAtlasManager->SetBrokenImage(mBrokenImageUrl);
}
} // namespace Internal
#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
// EXTERNAL INCLUDES
+#include <dali/devel-api/scripting/scripting.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/object/property-array.h>
-#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
-#include <dali/devel-api/scripting/scripting.h>
+#include <dali/public-api/object/type-registry.h>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
-#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
+#include <dali-toolkit/internal/visuals/animated-gradient/animated-gradient-visual.h>
+#include <dali-toolkit/internal/visuals/animated-image/animated-image-visual.h>
+#include <dali-toolkit/internal/visuals/animated-vector-image/animated-vector-image-visual.h>
+#include <dali-toolkit/internal/visuals/arc/arc-visual.h>
#include <dali-toolkit/internal/visuals/border/border-visual.h>
#include <dali-toolkit/internal/visuals/color/color-visual.h>
#include <dali-toolkit/internal/visuals/gradient/gradient-visual.h>
-#include <dali-toolkit/internal/visuals/animated-gradient/animated-gradient-visual.h>
+#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
#include <dali-toolkit/internal/visuals/image/image-visual.h>
#include <dali-toolkit/internal/visuals/mesh/mesh-visual.h>
#include <dali-toolkit/internal/visuals/npatch/npatch-visual.h>
#include <dali-toolkit/internal/visuals/primitive/primitive-visual.h>
#include <dali-toolkit/internal/visuals/svg/svg-visual.h>
#include <dali-toolkit/internal/visuals/text/text-visual.h>
-#include <dali-toolkit/internal/visuals/animated-image/animated-image-visual.h>
-#include <dali-toolkit/internal/visuals/animated-vector-image/animated-vector-image-visual.h>
-#include <dali-toolkit/internal/visuals/arc/arc-visual.h>
-#include <dali-toolkit/internal/visuals/wireframe/wireframe-visual.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
-#include <dali-toolkit/internal/visuals/visual-url.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
+#include <dali-toolkit/internal/visuals/visual-url.h>
+#include <dali-toolkit/internal/visuals/wireframe/wireframe-visual.h>
+#include <dali-toolkit/public-api/visuals/image-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-
#if defined(DEBUG_ENABLED)
-Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_CONTROL_VISUALS");
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_CONTROL_VISUALS");
#endif
BaseHandle Create()
return handle;
}
-DALI_TYPE_REGISTRATION_BEGIN_CREATE( Toolkit::VisualFactory, Dali::BaseHandle, Create, true )
+DALI_TYPE_REGISTRATION_BEGIN_CREATE(Toolkit::VisualFactory, Dali::BaseHandle, Create, true)
DALI_TYPE_REGISTRATION_END()
const char* const BROKEN_IMAGE_FILE_NAME = "broken.png"; ///< The file name of the broken image.
} // namespace
-VisualFactory::VisualFactory( bool debugEnabled )
+VisualFactory::VisualFactory(bool debugEnabled)
: mFactoryCache(),
mImageVisualShaderFactory(),
mSlotDelegate(this),
- mDebugEnabled( debugEnabled ),
- mPreMultiplyOnLoad( true )
+ mDebugEnabled(debugEnabled),
+ mPreMultiplyOnLoad(true)
{
}
{
}
-void VisualFactory::OnStyleChangedSignal( Toolkit::StyleManager styleManager, StyleChange::Type type)
+void VisualFactory::OnStyleChangedSignal(Toolkit::StyleManager styleManager, StyleChange::Type type)
{
- if( type == StyleChange::THEME_CHANGE )
+ if(type == StyleChange::THEME_CHANGE)
{
- const std::string imageDirPath = AssetManager::GetDaliImagePath();
- std::string brokenImageUrl = imageDirPath + BROKEN_IMAGE_FILE_NAME;
+ const std::string imageDirPath = AssetManager::GetDaliImagePath();
+ std::string brokenImageUrl = imageDirPath + BROKEN_IMAGE_FILE_NAME;
- Property::Map config = Toolkit::DevelStyleManager::GetConfigurations( styleManager );
- config["brokenImageUrl"].Get( brokenImageUrl );
+ Property::Map config = Toolkit::DevelStyleManager::GetConfigurations(styleManager);
+ config["brokenImageUrl"].Get(brokenImageUrl);
- if( mFactoryCache )
+ if(mFactoryCache)
{
mFactoryCache->SetBrokenImageUrl(brokenImageUrl);
}
}
}
-Toolkit::Visual::Base VisualFactory::CreateVisual( const Property::Map& propertyMap )
+Toolkit::Visual::Base VisualFactory::CreateVisual(const Property::Map& propertyMap)
{
Visual::BasePtr visualPtr;
- Property::Value* typeValue = propertyMap.Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE );
+ Property::Value* typeValue = propertyMap.Find(Toolkit::Visual::Property::TYPE, VISUAL_TYPE);
Toolkit::DevelVisual::Type visualType = Toolkit::DevelVisual::IMAGE; // Default to IMAGE type.
- if( typeValue )
+ if(typeValue)
{
- Scripting::GetEnumerationProperty( *typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, visualType );
+ Scripting::GetEnumerationProperty(*typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, visualType);
}
- switch( visualType )
+ switch(visualType)
{
case Toolkit::Visual::BORDER:
{
- visualPtr = BorderVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = BorderVisual::New(GetFactoryCache(), propertyMap);
break;
}
case Toolkit::Visual::COLOR:
{
- visualPtr = ColorVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = ColorVisual::New(GetFactoryCache(), propertyMap);
break;
}
case Toolkit::Visual::GRADIENT:
{
- visualPtr = GradientVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = GradientVisual::New(GetFactoryCache(), propertyMap);
break;
}
case Toolkit::Visual::IMAGE:
{
- Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
- std::string imageUrl;
- if( imageURLValue )
+ Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME);
+ std::string imageUrl;
+ if(imageURLValue)
{
- if( imageURLValue->Get( imageUrl ) )
+ if(imageURLValue->Get(imageUrl))
{
- if( !imageUrl.empty() )
+ if(!imageUrl.empty())
{
- VisualUrl visualUrl( imageUrl );
+ VisualUrl visualUrl(imageUrl);
- switch( visualUrl.GetType() )
+ switch(visualUrl.GetType())
{
case VisualUrl::N_PATCH:
{
}
case VisualUrl::SVG:
{
- visualPtr = SvgVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap );
+ visualPtr = SvgVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap);
break;
}
case VisualUrl::GIF:
case VisualUrl::WEBP:
{
- visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap );
+ visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap);
break;
}
case VisualUrl::JSON:
{
- visualPtr = AnimatedVectorImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap );
+ visualPtr = AnimatedVectorImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap);
break;
}
case VisualUrl::REGULAR_IMAGE:
{
- visualPtr = ImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap );
+ visualPtr = ImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap);
break;
}
}
else
{
Property::Array* array = imageURLValue->GetArray();
- if( array )
+ if(array)
{
- visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), *array, propertyMap );
+ visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), *array, propertyMap);
}
}
}
case Toolkit::Visual::MESH:
{
- visualPtr = MeshVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = MeshVisual::New(GetFactoryCache(), propertyMap);
break;
}
case Toolkit::Visual::PRIMITIVE:
{
- visualPtr = PrimitiveVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = PrimitiveVisual::New(GetFactoryCache(), propertyMap);
break;
}
case Toolkit::Visual::WIREFRAME:
{
- visualPtr = WireframeVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = WireframeVisual::New(GetFactoryCache(), propertyMap);
break;
}
case Toolkit::Visual::TEXT:
{
- visualPtr = TextVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = TextVisual::New(GetFactoryCache(), propertyMap);
break;
}
case Toolkit::Visual::N_PATCH:
{
- Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
- std::string imageUrl;
- if( imageURLValue && imageURLValue->Get( imageUrl ) )
+ Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME);
+ std::string imageUrl;
+ if(imageURLValue && imageURLValue->Get(imageUrl))
{
visualPtr = NPatchVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap);
}
case Toolkit::Visual::SVG:
{
- Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
- std::string imageUrl;
- if( imageURLValue && imageURLValue->Get( imageUrl ) )
+ Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME);
+ std::string imageUrl;
+ if(imageURLValue && imageURLValue->Get(imageUrl))
{
- visualPtr = SvgVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap );
+ visualPtr = SvgVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap);
}
break;
}
case Toolkit::Visual::ANIMATED_IMAGE:
{
- Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
- std::string imageUrl;
- if( imageURLValue )
+ Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME);
+ std::string imageUrl;
+ if(imageURLValue)
{
- if( imageURLValue->Get( imageUrl ) )
+ if(imageURLValue->Get(imageUrl))
{
- visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap );
+ visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap);
}
else
{
Property::Array* array = imageURLValue->GetArray();
- if( array )
+ if(array)
{
- visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), *array, propertyMap );
+ visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), *array, propertyMap);
}
}
}
case Toolkit::DevelVisual::ANIMATED_GRADIENT:
{
- visualPtr = AnimatedGradientVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = AnimatedGradientVisual::New(GetFactoryCache(), propertyMap);
break;
}
case Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE:
{
- Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
- std::string imageUrl;
- if( imageURLValue && imageURLValue->Get( imageUrl ) )
+ Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME);
+ std::string imageUrl;
+ if(imageURLValue && imageURLValue->Get(imageUrl))
{
- visualPtr = AnimatedVectorImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap );
+ visualPtr = AnimatedVectorImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap);
}
break;
}
case Toolkit::DevelVisual::ARC:
{
- visualPtr = ArcVisual::New( GetFactoryCache(), propertyMap );
+ visualPtr = ArcVisual::New(GetFactoryCache(), propertyMap);
break;
}
}
- DALI_LOG_INFO( gLogFilter, Debug::Concise, "VisualFactory::CreateVisual( VisualType:%s %s%s)\n",
- Scripting::GetEnumerationName<Toolkit::DevelVisual::Type>( visualType,
- VISUAL_TYPE_TABLE,
- VISUAL_TYPE_TABLE_COUNT ),
- ( visualType == Toolkit::DevelVisual::IMAGE ) ? "url:" : "",
- ( visualType == Toolkit::DevelVisual::IMAGE ) ?
- ( ([&] (){
- // Return URL if present in PropertyMap else return "not found message"
- Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
- return ( imageURLValue ) ? imageURLValue->Get<std::string>().c_str() : "url not found in PropertyMap";
- })()
- )
- : "" );
-
- if( !visualPtr )
+ DALI_LOG_INFO(gLogFilter, Debug::Concise, "VisualFactory::CreateVisual( VisualType:%s %s%s)\n", Scripting::GetEnumerationName<Toolkit::DevelVisual::Type>(visualType, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT), (visualType == Toolkit::DevelVisual::IMAGE) ? "url:" : "", (visualType == Toolkit::DevelVisual::IMAGE) ? (([&]() {
+ // Return URL if present in PropertyMap else return "not found message"
+ Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME);
+ return (imageURLValue) ? imageURLValue->Get<std::string>().c_str() : "url not found in PropertyMap";
+ })())
+ : "");
+
+ if(!visualPtr)
{
- DALI_LOG_ERROR( "VisualType unknown\n" );
+ DALI_LOG_ERROR("VisualType unknown\n");
}
- if( mDebugEnabled && visualType != Toolkit::DevelVisual::WIREFRAME )
+ if(mDebugEnabled && visualType != Toolkit::DevelVisual::WIREFRAME)
{
//Create a WireframeVisual if we have debug enabled
- visualPtr = WireframeVisual::New(GetFactoryCache(), visualPtr, propertyMap );
+ visualPtr = WireframeVisual::New(GetFactoryCache(), visualPtr, propertyMap);
}
- return Toolkit::Visual::Base( visualPtr.Get() );
+ return Toolkit::Visual::Base(visualPtr.Get());
}
-Toolkit::Visual::Base VisualFactory::CreateVisual( const std::string& url, ImageDimensions size )
+Toolkit::Visual::Base VisualFactory::CreateVisual(const std::string& url, ImageDimensions size)
{
Visual::BasePtr visualPtr;
- if( !url.empty() )
+ if(!url.empty())
{
// first resolve url type to know which visual to create
- VisualUrl visualUrl( url );
- switch( visualUrl.GetType() )
+ VisualUrl visualUrl(url);
+ switch(visualUrl.GetType())
{
case VisualUrl::N_PATCH:
{
}
case VisualUrl::SVG:
{
- visualPtr = SvgVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl );
+ visualPtr = SvgVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl);
break;
}
case VisualUrl::GIF:
case VisualUrl::WEBP:
{
- visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl );
+ visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl);
break;
}
case VisualUrl::JSON:
{
- visualPtr = AnimatedVectorImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl );
+ visualPtr = AnimatedVectorImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl);
break;
}
case VisualUrl::REGULAR_IMAGE:
{
- visualPtr = ImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, size );
+ visualPtr = ImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, size);
break;
}
}
}
- if( mDebugEnabled )
+ if(mDebugEnabled)
{
//Create a WireframeVisual if we have debug enabled
- visualPtr = WireframeVisual::New( GetFactoryCache(), visualPtr );
+ visualPtr = WireframeVisual::New(GetFactoryCache(), visualPtr);
}
- return Toolkit::Visual::Base( visualPtr.Get() );
+ return Toolkit::Visual::Base(visualPtr.Get());
}
-void VisualFactory::SetPreMultiplyOnLoad( bool preMultiply )
+void VisualFactory::SetPreMultiplyOnLoad(bool preMultiply)
{
- if( mPreMultiplyOnLoad != preMultiply )
+ if(mPreMultiplyOnLoad != preMultiply)
{
- GetFactoryCache().SetPreMultiplyOnLoad( preMultiply );
+ GetFactoryCache().SetPreMultiplyOnLoad(preMultiply);
}
mPreMultiplyOnLoad = preMultiply;
}
Internal::VisualFactoryCache& VisualFactory::GetFactoryCache()
{
- if( !mFactoryCache )
+ if(!mFactoryCache)
{
- mFactoryCache = std::unique_ptr<VisualFactoryCache>( new VisualFactoryCache( mPreMultiplyOnLoad ) );
+ mFactoryCache = std::unique_ptr<VisualFactoryCache>(new VisualFactoryCache(mPreMultiplyOnLoad));
- const std::string imageDirPath = AssetManager::GetDaliImagePath();
- std::string brokenImageUrl = imageDirPath + BROKEN_IMAGE_FILE_NAME;
+ const std::string imageDirPath = AssetManager::GetDaliImagePath();
+ std::string brokenImageUrl = imageDirPath + BROKEN_IMAGE_FILE_NAME;
Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
- if( styleManager )
+ if(styleManager)
{
- Property::Map config = Toolkit::DevelStyleManager::GetConfigurations( styleManager );
- config["brokenImageUrl"].Get( brokenImageUrl );
- styleManager.StyleChangedSignal().Connect( mSlotDelegate, &VisualFactory::OnStyleChangedSignal );
+ Property::Map config = Toolkit::DevelStyleManager::GetConfigurations(styleManager);
+ config["brokenImageUrl"].Get(brokenImageUrl);
+ styleManager.StyleChangedSignal().Connect(mSlotDelegate, &VisualFactory::OnStyleChangedSignal);
}
mFactoryCache->SetBrokenImageUrl(brokenImageUrl);
ImageVisualShaderFactory& VisualFactory::GetImageVisualShaderFactory()
{
- if( !mImageVisualShaderFactory )
+ if(!mImageVisualShaderFactory)
{
- mImageVisualShaderFactory = std::unique_ptr< ImageVisualShaderFactory >( new ImageVisualShaderFactory() );
+ mImageVisualShaderFactory = std::unique_ptr<ImageVisualShaderFactory>(new ImageVisualShaderFactory());
}
return *mImageVisualShaderFactory;
}
- /*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+/*
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include "visual-string-constants.h"
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN( VISUAL_TYPE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, BORDER )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, COLOR )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, GRADIENT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, IMAGE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, MESH )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, PRIMITIVE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, TEXT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, N_PATCH )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, SVG )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, ANIMATED_IMAGE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, WIREFRAME )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelVisual, ANIMATED_GRADIENT )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelVisual, ANIMATED_VECTOR_IMAGE )
-DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelVisual, ARC )
-DALI_ENUM_TO_STRING_TABLE_END( VISUAL_TYPE )
+DALI_ENUM_TO_STRING_TABLE_BEGIN(VISUAL_TYPE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, BORDER)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, COLOR)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, GRADIENT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, IMAGE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, MESH)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, PRIMITIVE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, TEXT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, N_PATCH)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, SVG)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, ANIMATED_IMAGE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, WIREFRAME)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelVisual, ANIMATED_GRADIENT)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelVisual, ANIMATED_VECTOR_IMAGE)
+ DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelVisual, ARC)
+DALI_ENUM_TO_STRING_TABLE_END(VISUAL_TYPE)
// Visual Type
-const char * const VISUAL_TYPE( "visualType" );
+const char* const VISUAL_TYPE("visualType");
// Custom shader
-const char * const CUSTOM_SHADER( "shader" );
-const char * const CUSTOM_VERTEX_SHADER( "vertexShader" );
-const char * const CUSTOM_FRAGMENT_SHADER( "fragmentShader" );
-const char * const CUSTOM_SUBDIVIDE_GRID_X( "subdivideGridX" );
-const char * const CUSTOM_SUBDIVIDE_GRID_Y( "subdivideGridY" );
-const char * const CUSTOM_SHADER_HINTS( "hints" );
+const char* const CUSTOM_SHADER("shader");
+const char* const CUSTOM_VERTEX_SHADER("vertexShader");
+const char* const CUSTOM_FRAGMENT_SHADER("fragmentShader");
+const char* const CUSTOM_SUBDIVIDE_GRID_X("subdivideGridX");
+const char* const CUSTOM_SUBDIVIDE_GRID_Y("subdivideGridY");
+const char* const CUSTOM_SHADER_HINTS("hints");
// Transform
-const char * const TRANSFORM( "transform" );
-const char * const SIZE( "size" );
-const char * const OFFSET( "offset" );
-const char * const OFFSET_SIZE_MODE( "offsetSizeMode" );
-const char * const ORIGIN( "origin" );
-const char * const ANCHOR_POINT( "anchorPoint" );
-const char * const EXTRA_SIZE( "extraSize" );
+const char* const TRANSFORM("transform");
+const char* const SIZE("size");
+const char* const OFFSET("offset");
+const char* const OFFSET_SIZE_MODE("offsetSizeMode");
+const char* const ORIGIN("origin");
+const char* const ANCHOR_POINT("anchorPoint");
+const char* const EXTRA_SIZE("extraSize");
// Premultipled alpha
-const char * const PREMULTIPLIED_ALPHA( "premultipliedAlpha" );
+const char* const PREMULTIPLIED_ALPHA("premultipliedAlpha");
// Mix color
-const char * const MIX_COLOR( "mixColor" );
-const char * const OPACITY( "opacity" );
+const char* const MIX_COLOR("mixColor");
+const char* const OPACITY("opacity");
// Fitting mode
-const char * const VISUAL_FITTING_MODE( "visualFittingMode" );
+const char* const VISUAL_FITTING_MODE("visualFittingMode");
// Corner radius
-const char * const CORNER_RADIUS( "cornerRadius" );
-const char * const CORNER_RADIUS_POLICY( "cornerRadiusPolicy" );
+const char* const CORNER_RADIUS("cornerRadius");
+const char* const CORNER_RADIUS_POLICY("cornerRadiusPolicy");
// Color visual
-const char * const RENDER_IF_TRANSPARENT_NAME( "renderIfTransparent" );
-const char * const BLUR_RADIUS_NAME( "blurRadius" );
+const char* const RENDER_IF_TRANSPARENT_NAME("renderIfTransparent");
+const char* const BLUR_RADIUS_NAME("blurRadius");
// Image visual
-const char * const IMAGE_URL_NAME( "url" );
-const char * const ATLAS_RECT_UNIFORM_NAME( "uAtlasRect" );
-const char * const PIXEL_AREA_UNIFORM_NAME( "pixelArea" );
-const char * const WRAP_MODE_UNIFORM_NAME( "wrapMode" );
-const char * const IMAGE_WRAP_MODE_U("wrapModeU");
-const char * const IMAGE_WRAP_MODE_V("wrapModeV");
-const char * const IMAGE_BORDER( "border" );
-const char * const PIXEL_ALIGNED_UNIFORM_NAME( "uPixelAligned" );
-const char * const ANIMATED_IMAGE_URLS_NAME("urls");
-const char * const BATCH_SIZE_NAME("batchSize");
-const char * const CACHE_SIZE_NAME("cacheSize");
-const char * const FRAME_DELAY_NAME("frameDelay");
-const char * const LOOP_COUNT_NAME("loopCount");
-const char * const MASK_CONTENT_SCALE_NAME("maskContentScale");
-const char * const CROP_TO_MASK_NAME("cropToMask");
-const char * const LOAD_POLICY_NAME("loadPolicy");
-const char * const RELEASE_POLICY_NAME("releasePolicy");
-const char * const ORIENTATION_CORRECTION_NAME("orientationCorrection");
-const char * const AUXILIARY_IMAGE_NAME("auxiliaryImage");
-const char * const AUXILIARY_IMAGE_ALPHA_NAME("auxiliaryImageAlpha");
-const char * const PLAY_RANGE_NAME( "playRange" );
-const char * const PLAY_STATE_NAME( "playState" );
-const char * const CURRENT_FRAME_NUMBER_NAME( "currentFrameNumber" );
-const char * const TOTAL_FRAME_NUMBER_NAME( "totalFrameNumber" );
-const char * const STOP_BEHAVIOR_NAME( "stopBehavior" );
-const char * const LOOPING_MODE_NAME( "loopingMode" );
-const char * const IMAGE_ATLASING( "atlasing" );
-const char * const SYNCHRONOUS_LOADING( "synchronousLoading" );
-const char * const IMAGE_FITTING_MODE( "fittingMode" );
-const char * const IMAGE_SAMPLING_MODE( "samplingMode" );
-const char * const IMAGE_DESIRED_WIDTH( "desiredWidth" );
-const char * const IMAGE_DESIRED_HEIGHT( "desiredHeight" );
-const char * const ALPHA_MASK_URL("alphaMaskUrl");
-const char * const REDRAW_IN_SCALING_DOWN_NAME("redrawInScalingDown");
+const char* const IMAGE_URL_NAME("url");
+const char* const ATLAS_RECT_UNIFORM_NAME("uAtlasRect");
+const char* const PIXEL_AREA_UNIFORM_NAME("pixelArea");
+const char* const WRAP_MODE_UNIFORM_NAME("wrapMode");
+const char* const IMAGE_WRAP_MODE_U("wrapModeU");
+const char* const IMAGE_WRAP_MODE_V("wrapModeV");
+const char* const IMAGE_BORDER("border");
+const char* const PIXEL_ALIGNED_UNIFORM_NAME("uPixelAligned");
+const char* const ANIMATED_IMAGE_URLS_NAME("urls");
+const char* const BATCH_SIZE_NAME("batchSize");
+const char* const CACHE_SIZE_NAME("cacheSize");
+const char* const FRAME_DELAY_NAME("frameDelay");
+const char* const LOOP_COUNT_NAME("loopCount");
+const char* const MASK_CONTENT_SCALE_NAME("maskContentScale");
+const char* const CROP_TO_MASK_NAME("cropToMask");
+const char* const LOAD_POLICY_NAME("loadPolicy");
+const char* const RELEASE_POLICY_NAME("releasePolicy");
+const char* const ORIENTATION_CORRECTION_NAME("orientationCorrection");
+const char* const AUXILIARY_IMAGE_NAME("auxiliaryImage");
+const char* const AUXILIARY_IMAGE_ALPHA_NAME("auxiliaryImageAlpha");
+const char* const PLAY_RANGE_NAME("playRange");
+const char* const PLAY_STATE_NAME("playState");
+const char* const CURRENT_FRAME_NUMBER_NAME("currentFrameNumber");
+const char* const TOTAL_FRAME_NUMBER_NAME("totalFrameNumber");
+const char* const STOP_BEHAVIOR_NAME("stopBehavior");
+const char* const LOOPING_MODE_NAME("loopingMode");
+const char* const IMAGE_ATLASING("atlasing");
+const char* const SYNCHRONOUS_LOADING("synchronousLoading");
+const char* const IMAGE_FITTING_MODE("fittingMode");
+const char* const IMAGE_SAMPLING_MODE("samplingMode");
+const char* const IMAGE_DESIRED_WIDTH("desiredWidth");
+const char* const IMAGE_DESIRED_HEIGHT("desiredHeight");
+const char* const ALPHA_MASK_URL("alphaMaskUrl");
+const char* const REDRAW_IN_SCALING_DOWN_NAME("redrawInScalingDown");
// Text visual
-const char * const TEXT_PROPERTY( "text" );
-const char * const FONT_FAMILY_PROPERTY( "fontFamily" );
-const char * const FONT_STYLE_PROPERTY( "fontStyle" );
-const char * const POINT_SIZE_PROPERTY( "pointSize" );
-const char * const MULTI_LINE_PROPERTY( "multiLine" );
-const char * const HORIZONTAL_ALIGNMENT_PROPERTY( "horizontalAlignment" );
-const char * const VERTICAL_ALIGNMENT_PROPERTY( "verticalAlignment" );
-const char * const TEXT_COLOR_PROPERTY( "textColor" );
-const char * const ENABLE_MARKUP_PROPERTY( "enableMarkup" );
-const char * const SHADOW_PROPERTY( "shadow" );
-const char * const UNDERLINE_PROPERTY( "underline" );
-const char * const OUTLINE_PROPERTY( "outline" );
-const char * const BACKGROUND_PROPERTY( "textBackground" );
-
+const char* const TEXT_PROPERTY("text");
+const char* const FONT_FAMILY_PROPERTY("fontFamily");
+const char* const FONT_STYLE_PROPERTY("fontStyle");
+const char* const POINT_SIZE_PROPERTY("pointSize");
+const char* const MULTI_LINE_PROPERTY("multiLine");
+const char* const HORIZONTAL_ALIGNMENT_PROPERTY("horizontalAlignment");
+const char* const VERTICAL_ALIGNMENT_PROPERTY("verticalAlignment");
+const char* const TEXT_COLOR_PROPERTY("textColor");
+const char* const ENABLE_MARKUP_PROPERTY("enableMarkup");
+const char* const SHADOW_PROPERTY("shadow");
+const char* const UNDERLINE_PROPERTY("underline");
+const char* const OUTLINE_PROPERTY("outline");
+const char* const BACKGROUND_PROPERTY("textBackground");
//NPatch visual
-const char * const BORDER_ONLY( "borderOnly" );
-const char * const BORDER( "border" );
+const char* const BORDER_ONLY("borderOnly");
+const char* const BORDER("border");
// non-animated property
const char* const GRADIENT_TYPE_NAME("gradientType");
const char* const UNIFORM_OFFSET_NAME("gradient_offset");
// Border visual
-const char * const COLOR_NAME("borderColor");
-const char * const SIZE_NAME("borderSize");
-const char * const ANTI_ALIASING("antiAliasing");
+const char* const COLOR_NAME("borderColor");
+const char* const SIZE_NAME("borderSize");
+const char* const ANTI_ALIASING("antiAliasing");
// properties: radial gradient
-const char * const CENTER_NAME("center"); // Property::VECTOR2
-const char * const RADIUS_NAME("radius"); // Property::FLOAT
+const char* const CENTER_NAME("center"); // Property::VECTOR2
+const char* const RADIUS_NAME("radius"); // Property::FLOAT
// properties: linear&radial gradient
-const char * const STOP_OFFSET_NAME("stopOffset"); // Property::Array FLOAT
-const char * const STOP_COLOR_NAME("stopColor"); // Property::Array VECTOR4
-const char * const UNITS_NAME("units"); // Property::String "userSpaceOnUse | objectBoundingBox"
-const char * const SPREAD_METHOD_NAME("spreadMethod"); // Property::String "pad | reflect | repeat"
+const char* const STOP_OFFSET_NAME("stopOffset"); // Property::Array FLOAT
+const char* const STOP_COLOR_NAME("stopColor"); // Property::Array VECTOR4
+const char* const UNITS_NAME("units"); // Property::String "userSpaceOnUse | objectBoundingBox"
+const char* const SPREAD_METHOD_NAME("spreadMethod"); // Property::String "pad | reflect | repeat"
//mesh visual
-const char * const OBJECT_URL_NAME( "objectUrl" );
-const char * const MATERIAL_URL_NAME( "materialUrl" );
-const char * const TEXTURES_PATH_NAME( "texturesPath" );
-const char * const SHADING_MODE_NAME( "shadingMode" );
-const char * const USE_MIPMAPPING_NAME( "useMipmapping" );
-const char * const USE_SOFT_NORMALS_NAME( "useSoftNormals" );
-const char * const LIGHT_POSITION_NAME( "lightPosition" );
-
+const char* const OBJECT_URL_NAME("objectUrl");
+const char* const MATERIAL_URL_NAME("materialUrl");
+const char* const TEXTURES_PATH_NAME("texturesPath");
+const char* const SHADING_MODE_NAME("shadingMode");
+const char* const USE_MIPMAPPING_NAME("useMipmapping");
+const char* const USE_SOFT_NORMALS_NAME("useSoftNormals");
+const char* const LIGHT_POSITION_NAME("lightPosition");
//Primitive properties
-const char * const PRIMITIVE_SHAPE( "shape" );
-const char * const SLICES( "slices" );
-const char * const STACKS( "stacks" );
-const char * const SCALE_TOP_RADIUS( "scaleTopRadius" );
-const char * const SCALE_BOTTOM_RADIUS( "scaleBottomRadius" );
-const char * const SCALE_HEIGHT( "scaleHeight" );
-const char * const SCALE_RADIUS( "scaleRadius" );
-const char * const SCALE_DIMENSIONS( "scaleDimensions" );
-const char * const BEVEL_PERCENTAGE( "bevelPercentage" );
-const char * const BEVEL_SMOOTHNESS( "bevelSmoothness" );
-const char * const LIGHT_POSITION_UNIFORM_NAME( "lightPosition" );
+const char* const PRIMITIVE_SHAPE("shape");
+const char* const SLICES("slices");
+const char* const STACKS("stacks");
+const char* const SCALE_TOP_RADIUS("scaleTopRadius");
+const char* const SCALE_BOTTOM_RADIUS("scaleBottomRadius");
+const char* const SCALE_HEIGHT("scaleHeight");
+const char* const SCALE_RADIUS("scaleRadius");
+const char* const SCALE_DIMENSIONS("scaleDimensions");
+const char* const BEVEL_PERCENTAGE("bevelPercentage");
+const char* const BEVEL_SMOOTHNESS("bevelSmoothness");
+const char* const LIGHT_POSITION_UNIFORM_NAME("lightPosition");
// Arc visual
-const char * const THICKNESS_NAME( "thickness" );
-const char * const START_ANGLE_NAME( "startAngle" );
-const char * const SWEEP_ANGLE_NAME( "sweepAngle" );
-const char * const CAP_NAME( "cap" );
+const char* const THICKNESS_NAME("thickness");
+const char* const START_ANGLE_NAME("startAngle");
+const char* const SWEEP_ANGLE_NAME("sweepAngle");
+const char* const CAP_NAME("cap");
} // namespace Internal
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{
namespace Internal
{
-
namespace
{
-
-VisualUrl::ProtocolType ResolveLocation( const std::string& url )
+VisualUrl::ProtocolType ResolveLocation(const std::string& url)
{
- const char* urlCStr = url.c_str();
- const uint32_t length = url.size();
- if( ( length > 7 ) && urlCStr[5] == ':' && urlCStr[6] == '/' && urlCStr[7] == '/' )
+ const char* urlCStr = url.c_str();
+ const uint32_t length = url.size();
+ if((length > 7) && urlCStr[5] == ':' && urlCStr[6] == '/' && urlCStr[7] == '/')
{
// https://
- if( ( 'h' == tolower( urlCStr[0] ) )&&
- ( 't' == tolower( urlCStr[1] ) )&&
- ( 't' == tolower( urlCStr[2] ) )&&
- ( 'p' == tolower( urlCStr[3] ) )&&
- ( 's' == tolower( urlCStr[4] ) ) )
+ if(('h' == tolower(urlCStr[0])) &&
+ ('t' == tolower(urlCStr[1])) &&
+ ('t' == tolower(urlCStr[2])) &&
+ ('p' == tolower(urlCStr[3])) &&
+ ('s' == tolower(urlCStr[4])))
{
return VisualUrl::REMOTE;
}
}
- else if( ( length > 6 ) && urlCStr[4] == ':' && urlCStr[5] == '/' && urlCStr[6] == '/' )
+ else if((length > 6) && urlCStr[4] == ':' && urlCStr[5] == '/' && urlCStr[6] == '/')
{
// http:// or dali://
- const char hOrd = tolower( urlCStr[0] );
- const char tOra = tolower( urlCStr[1] );
- const char tOrl = tolower( urlCStr[2] );
- const char pOri = tolower( urlCStr[3] );
- if( ( 'h' == hOrd )&&
- ( 't' == tOra )&&
- ( 't' == tOrl )&&
- ( 'p' == pOri ) )
+ const char hOrd = tolower(urlCStr[0]);
+ const char tOra = tolower(urlCStr[1]);
+ const char tOrl = tolower(urlCStr[2]);
+ const char pOri = tolower(urlCStr[3]);
+ if(('h' == hOrd) &&
+ ('t' == tOra) &&
+ ('t' == tOrl) &&
+ ('p' == pOri))
{
return VisualUrl::REMOTE;
}
- if( ( 'd' == hOrd )&&
- ( 'a' == tOra )&&
- ( 'l' == tOrl )&&
- ( 'i' == pOri ) )
+ if(('d' == hOrd) &&
+ ('a' == tOra) &&
+ ('l' == tOrl) &&
+ ('i' == pOri))
{
return VisualUrl::TEXTURE;
}
}
- else if( ( length > 5 ) && urlCStr[3] == ':' && urlCStr[4] == '/' && urlCStr[5] == '/' )
+ else if((length > 5) && urlCStr[3] == ':' && urlCStr[4] == '/' && urlCStr[5] == '/')
{
// ftp:// or ssh://
- const char fOrS = tolower( urlCStr[0] );
- if( ( 'f' == fOrS )||( 's' == fOrS ) )
+ const char fOrS = tolower(urlCStr[0]);
+ if(('f' == fOrS) || ('s' == fOrS))
{
- const char tOrs = tolower( urlCStr[1] );
- if( ( 't' == tOrs )||( 's' == tOrs ) )
+ const char tOrs = tolower(urlCStr[1]);
+ if(('t' == tOrs) || ('s' == tOrs))
{
- const char pOrh = tolower( urlCStr[2] );
- if( ( 'p' == pOrh )||( 'h' == pOrh ) )
+ const char pOrh = tolower(urlCStr[2]);
+ if(('p' == pOrh) || ('h' == pOrh))
{
return VisualUrl::REMOTE;
}
return VisualUrl::LOCAL;
}
-
-VisualUrl::Type ResolveType( const std::string& url )
+VisualUrl::Type ResolveType(const std::string& url)
{
// if only one char in string, can only be regular image
const std::size_t count = url.size();
- if( count > 0 )
+ if(count > 0)
{
// parsing from the end for better chance of early outs
- enum { SUFFIX, HASH, HASH_DOT } state = SUFFIX;
- char SVG[ 4 ] = { 'g', 'v', 's', '.' };
- char GIF[ 4 ] = { 'f', 'i', 'g', '.' };
- char WEBP[ 5 ] = { 'p', 'b', 'e', 'w', '.' };
- char JSON[ 5 ] = { 'n', 'o', 's', 'j', '.' };
- unsigned int svgScore = 0;
- unsigned int gifScore = 0;
+ enum
+ {
+ SUFFIX,
+ HASH,
+ HASH_DOT
+ } state = SUFFIX;
+ char SVG[4] = {'g', 'v', 's', '.'};
+ char GIF[4] = {'f', 'i', 'g', '.'};
+ char WEBP[5] = {'p', 'b', 'e', 'w', '.'};
+ char JSON[5] = {'n', 'o', 's', 'j', '.'};
+ unsigned int svgScore = 0;
+ unsigned int gifScore = 0;
unsigned int webpScore = 0;
unsigned int jsonScore = 0;
- int index = count;
- while( --index >= 0 )
+ int index = count;
+ while(--index >= 0)
{
- const char currentChar = tolower( url[ index ] );
+ const char currentChar = tolower(url[index]);
const std::size_t offsetFromEnd = count - index - 1u;
- if( ( offsetFromEnd < sizeof(SVG) )&&( currentChar == SVG[ offsetFromEnd ] ) )
+ if((offsetFromEnd < sizeof(SVG)) && (currentChar == SVG[offsetFromEnd]))
{
// early out if SVG as can't be used in N patch for now
- if( ++svgScore == sizeof(SVG) )
+ if(++svgScore == sizeof(SVG))
{
return VisualUrl::SVG;
}
}
- if( ( offsetFromEnd < sizeof(GIF) )&&( currentChar == GIF[ offsetFromEnd ] ) )
+ if((offsetFromEnd < sizeof(GIF)) && (currentChar == GIF[offsetFromEnd]))
{
// early out if GIF as can't be used in N patch for now
- if( ++gifScore == sizeof(GIF) )
+ if(++gifScore == sizeof(GIF))
{
return VisualUrl::GIF;
}
}
- if( ( offsetFromEnd < sizeof(WEBP) )&&( currentChar == WEBP[ offsetFromEnd ] ) )
+ if((offsetFromEnd < sizeof(WEBP)) && (currentChar == WEBP[offsetFromEnd]))
{
// early out if WEBP as can't be used in N patch for now
- if( ++webpScore == sizeof(WEBP) )
+ if(++webpScore == sizeof(WEBP))
{
return VisualUrl::WEBP;
}
}
- if( ( offsetFromEnd < sizeof(JSON) )&&( currentChar == JSON[ offsetFromEnd ] ) )
+ if((offsetFromEnd < sizeof(JSON)) && (currentChar == JSON[offsetFromEnd]))
{
// early out if JSON as can't be used in N patch for now
- if( ++jsonScore == sizeof(JSON) )
+ if(++jsonScore == sizeof(JSON))
{
return VisualUrl::JSON;
}
}
- switch( state )
+ switch(state)
{
case SUFFIX:
{
- if( '.' == currentChar )
+ if('.' == currentChar)
{
state = HASH;
}
}
case HASH:
{
- if( ( '#' == currentChar ) || ( '9' == currentChar ) )
+ if(('#' == currentChar) || ('9' == currentChar))
{
state = HASH_DOT;
}
}
case HASH_DOT:
{
- if( '.' == currentChar )
+ if('.' == currentChar)
{
return VisualUrl::N_PATCH;
}
return VisualUrl::REGULAR_IMAGE;
}
-}
-
+} // namespace
VisualUrl::VisualUrl()
: mUrl(),
- mType( VisualUrl::REGULAR_IMAGE ),
- mLocation( VisualUrl::LOCAL )
+ mType(VisualUrl::REGULAR_IMAGE),
+ mLocation(VisualUrl::LOCAL)
{
}
-VisualUrl::VisualUrl( const std::string& url )
-: mUrl( url ),
- mType( VisualUrl::REGULAR_IMAGE ),
- mLocation( VisualUrl::LOCAL )
+VisualUrl::VisualUrl(const std::string& url)
+: mUrl(url),
+ mType(VisualUrl::REGULAR_IMAGE),
+ mLocation(VisualUrl::LOCAL)
{
- if( ! url.empty() )
+ if(!url.empty())
{
- mLocation = ResolveLocation( url );
- if( VisualUrl::TEXTURE != mLocation )
+ mLocation = ResolveLocation(url);
+ if(VisualUrl::TEXTURE != mLocation)
{
// TEXTURE location url doesn't need type resolving, REGULAR_IMAGE is fine
- mType = ResolveType( url );
+ mType = ResolveType(url);
}
}
}
-VisualUrl::VisualUrl( const VisualUrl& url )
-: mUrl( url.mUrl ),
- mType( url.mType ),
- mLocation( url.mLocation )
+VisualUrl::VisualUrl(const VisualUrl& url)
+: mUrl(url.mUrl),
+ mType(url.mType),
+ mLocation(url.mLocation)
{
}
-VisualUrl& VisualUrl::operator=( const VisualUrl& url )
+VisualUrl& VisualUrl::operator=(const VisualUrl& url)
{
- if( &url != this )
+ if(&url != this)
{
- mUrl = url.mUrl;
- mType = url.mType;
+ mUrl = url.mUrl;
+ mType = url.mType;
mLocation = url.mLocation;
}
return *this;
std::string VisualUrl::GetLocation() const
{
- const auto location = mUrl.find( "://" );
- if( std::string::npos != location )
+ const auto location = mUrl.find("://");
+ if(std::string::npos != location)
{
- return mUrl.substr( location + 3u ); // 3 characters forwards from the start of ://
+ return mUrl.substr(location + 3u); // 3 characters forwards from the start of ://
}
return mUrl;
}
-std::string VisualUrl::CreateTextureUrl( const std::string& location )
+std::string VisualUrl::CreateTextureUrl(const std::string& location)
{
return "dali://" + location;
}
-} // Internal
+} // namespace Internal
-} // Toolkit
+} // namespace Toolkit
-} // Dali
+} // namespace Dali
#include "wireframe-visual.h"
// INTERNAL INCLUDES
-#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-factory-impl.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/public-api/visuals/visual-properties.h>
namespace Dali
{
-
namespace Toolkit
{
-
namespace Internal
{
-
namespace
{
-const char * const POSITION_ATTRIBUTE_NAME("aPosition");
-const char * const INDEX_NAME("indices");
-}
+const char* const POSITION_ATTRIBUTE_NAME("aPosition");
+const char* const INDEX_NAME("indices");
+} // namespace
-WireframeVisualPtr WireframeVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties )
+WireframeVisualPtr WireframeVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties)
{
Visual::BasePtr emtptyVisual;
return New(factoryCache, emtptyVisual, properties);
}
-WireframeVisualPtr WireframeVisual::New( VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual )
+WireframeVisualPtr WireframeVisual::New(VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual)
{
WireframeVisualPtr wireframeVisual(new WireframeVisual(factoryCache, actualVisual));
wireframeVisual->Initialize();
return wireframeVisual;
}
-WireframeVisualPtr WireframeVisual::New( VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual, const Property::Map& properties )
+WireframeVisualPtr WireframeVisual::New(VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual, const Property::Map& properties)
{
- WireframeVisualPtr wireframeVisual( new WireframeVisual( factoryCache, actualVisual ) );
+ WireframeVisualPtr wireframeVisual(new WireframeVisual(factoryCache, actualVisual));
// Instead of calling SetProperties, looking for the only valid property 'transform'
- Property::Value* transformValue = properties.Find( Toolkit::Visual::Property::TRANSFORM, TRANSFORM );
- Property::Map transformMap;
- if( transformValue && transformValue->Get( transformMap ) )
+ Property::Value* transformValue = properties.Find(Toolkit::Visual::Property::TRANSFORM, TRANSFORM);
+ Property::Map transformMap;
+ if(transformValue && transformValue->Get(transformMap))
{
- wireframeVisual->SetTransformAndSize( transformMap, Vector2::ZERO );
+ wireframeVisual->SetTransformAndSize(transformMap, Vector2::ZERO);
}
wireframeVisual->Initialize();
return wireframeVisual;
}
-WireframeVisual::WireframeVisual( VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual )
-: Visual::Base( factoryCache, Visual::FittingMode::FILL, actualVisual ? actualVisual->GetType() : Toolkit::Visual::WIREFRAME ),
- mActualVisual( actualVisual )
+WireframeVisual::WireframeVisual(VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual)
+: Visual::Base(factoryCache, Visual::FittingMode::FILL, actualVisual ? actualVisual->GetType() : Toolkit::Visual::WIREFRAME),
+ mActualVisual(actualVisual)
{
}
{
}
-float WireframeVisual::GetHeightForWidth( float width )
+float WireframeVisual::GetHeightForWidth(float width)
{
- if( mActualVisual )
+ if(mActualVisual)
{
- return mActualVisual->GetHeightForWidth( width );
+ return mActualVisual->GetHeightForWidth(width);
}
else
{
- return Visual::Base::GetHeightForWidth( width );
+ return Visual::Base::GetHeightForWidth(width);
}
}
-void WireframeVisual::GetNaturalSize( Vector2& naturalSize )
+void WireframeVisual::GetNaturalSize(Vector2& naturalSize)
{
- if( mActualVisual )
+ if(mActualVisual)
{
- mActualVisual->GetNaturalSize( naturalSize );
+ mActualVisual->GetNaturalSize(naturalSize);
}
else
{
- Visual::Base::GetNaturalSize( naturalSize );
+ Visual::Base::GetNaturalSize(naturalSize);
}
}
-void WireframeVisual::DoCreatePropertyMap( Property::Map& map ) const
+void WireframeVisual::DoCreatePropertyMap(Property::Map& map) const
{
- if( mActualVisual )
+ if(mActualVisual)
{
- mActualVisual->CreatePropertyMap( map );
+ mActualVisual->CreatePropertyMap(map);
}
else
{
map.Clear();
- map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::WIREFRAME );
+ map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::WIREFRAME);
}
}
-void WireframeVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
+void WireframeVisual::DoCreateInstancePropertyMap(Property::Map& map) const
{
// Do nothing
}
-void WireframeVisual::DoSetProperties( const Property::Map& propertyMap )
+void WireframeVisual::DoSetProperties(const Property::Map& propertyMap)
{
- Property::Value* mixValue = propertyMap.Find( Toolkit::Visual::Property::MIX_COLOR, MIX_COLOR );
- if( mixValue )
+ Property::Value* mixValue = propertyMap.Find(Toolkit::Visual::Property::MIX_COLOR, MIX_COLOR);
+ if(mixValue)
{
Vector4 mixColor;
- mixValue->Get( mixColor );
- SetMixColor( mixColor );
+ mixValue->Get(mixColor);
+ SetMixColor(mixColor);
}
}
-void WireframeVisual::DoSetOnScene( Actor& actor )
+void WireframeVisual::DoSetOnScene(Actor& actor)
{
- actor.AddRenderer( mImpl->mRenderer );
+ actor.AddRenderer(mImpl->mRenderer);
// Wireframe generated and ready to display
- ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+ ResourceReady(Toolkit::Visual::ResourceStatus::READY);
}
void WireframeVisual::OnInitialize()
{
- Shader shader = mFactoryCache.GetShader( VisualFactoryCache::WIREFRAME_SHADER );
- if( !shader )
+ Shader shader = mFactoryCache.GetShader(VisualFactoryCache::WIREFRAME_SHADER);
+ if(!shader)
{
- shader = Shader::New( SHADER_WIREFRAME_VISUAL_SHADER_VERT, SHADER_WIREFRAME_VISUAL_SHADER_FRAG );
- mFactoryCache.SaveShader( VisualFactoryCache::WIREFRAME_SHADER, shader );
+ shader = Shader::New(SHADER_WIREFRAME_VISUAL_SHADER_VERT, SHADER_WIREFRAME_VISUAL_SHADER_FRAG);
+ mFactoryCache.SaveShader(VisualFactoryCache::WIREFRAME_SHADER, shader);
}
- Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::WIREFRAME_GEOMETRY );
- if( !geometry )
+ Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::WIREFRAME_GEOMETRY);
+ if(!geometry)
{
geometry = CreateQuadWireframeGeometry();
- mFactoryCache.SaveGeometry( VisualFactoryCache::WIREFRAME_GEOMETRY, geometry );
+ mFactoryCache.SaveGeometry(VisualFactoryCache::WIREFRAME_GEOMETRY, geometry);
}
//Create the renderer
- mImpl->mRenderer = Renderer::New( geometry, shader);
+ mImpl->mRenderer = Renderer::New(geometry, shader);
//Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
Geometry WireframeVisual::CreateQuadWireframeGeometry()
{
- const float halfWidth = 0.5f;
+ const float halfWidth = 0.5f;
const float halfHeight = 0.5f;
- struct QuadVertex { Vector2 position;};
- QuadVertex quadVertexData[4] =
+ struct QuadVertex
{
- { Vector2(-halfWidth, -halfHeight) },
- { Vector2( halfWidth, -halfHeight) },
- { Vector2( halfWidth, halfHeight) },
- { Vector2(-halfWidth, halfHeight) }
+ Vector2 position;
};
+ QuadVertex quadVertexData[4] =
+ {
+ {Vector2(-halfWidth, -halfHeight)},
+ {Vector2(halfWidth, -halfHeight)},
+ {Vector2(halfWidth, halfHeight)},
+ {Vector2(-halfWidth, halfHeight)}};
Property::Map quadVertexFormat;
quadVertexFormat[POSITION_ATTRIBUTE_NAME] = Property::VECTOR2;
- VertexBuffer quadVertices = VertexBuffer::New( quadVertexFormat );
- quadVertices.SetData( quadVertexData, 4 );
+ VertexBuffer quadVertices = VertexBuffer::New(quadVertexFormat);
+ quadVertices.SetData(quadVertexData, 4);
// Create indices
- unsigned short indexData[10] = { 0, 1, 1, 2, 2, 3, 3, 0 };
+ unsigned short indexData[10] = {0, 1, 1, 2, 2, 3, 3, 0};
// Create the geometry object
Geometry geometry = Geometry::New();
- geometry.AddVertexBuffer( quadVertices );
- geometry.SetIndexBuffer( indexData, sizeof(indexData)/sizeof(indexData[0]) );
- geometry.SetType( Geometry::LINES );
+ geometry.AddVertexBuffer(quadVertices);
+ geometry.SetIndexBuffer(indexData, sizeof(indexData) / sizeof(indexData[0]));
+ geometry.SetType(Geometry::LINES);
return geometry;
}
void WireframeVisual::OnSetTransform()
{
- if( mImpl->mRenderer )
+ if(mImpl->mRenderer)
{
//Register transform properties
- mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
+ mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
}
}
Visual::Base& WireframeVisual::GetVisualObject()
{
- if( mActualVisual )
+ if(mActualVisual)
{
return *mActualVisual.Get();
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/public-api/controls/control-impl.h>
// EXTERNAL INCLUDES
+#include <dali/devel-api/actors/actor-devel.h>
+#include <dali/devel-api/common/stage.h>
#include <dali/devel-api/scripting/scripting.h>
#include <dali/integration-api/debug.h>
#include <dali/public-api/animation/constraint.h>
+#include <dali/public-api/object/type-info.h>
#include <dali/public-api/object/type-registry-helper.h>
#include <dali/public-api/size-negotiation/relayout-container.h>
#include <cstring> // for strcmp
#include <limits>
#include <stack>
#include <typeinfo>
-#include <dali/public-api/object/type-info.h>
-#include <dali/devel-api/common/stage.h>
-#include <dali/devel-api/actors/actor-devel.h>
// INTERNAL INCLUDES
+#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
#include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
#include <dali-toolkit/public-api/align-enumerations.h>
#include <dali-toolkit/public-api/controls/control.h>
+#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/public-api/focus-manager/keyboard-focus-manager.h>
#include <dali-toolkit/public-api/styling/style-manager.h>
#include <dali-toolkit/public-api/visuals/color-visual-properties.h>
#include <dali-toolkit/public-api/visuals/visual-properties.h>
-#include <dali-toolkit/internal/controls/control/control-data-impl.h>
-#include <dali-toolkit/public-api/controls/image-view/image-view.h>
-#include <dali-toolkit/dali-toolkit.h>
namespace Dali
{
bool Control::OnAccessibilityActivated()
{
- if( Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor( Self() ) )
+ if(Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor(Self()))
{
return OnKeyboardEnter();
}
}
Dali::TypeInfo type;
- Self().GetTypeInfo( type );
- if (type)
+ Self().GetTypeInfo(type);
+ if(type)
{
auto typeName = type.GetName();
- DevelControl::AppendAccessibilityAttribute( Self(), "t", typeName );
+ DevelControl::AppendAccessibilityAttribute(Self(), "t", typeName);
}
- if (Accessibility::IsUp())
+ if(Accessibility::IsUp())
mImpl->AccessibilityRegister();
}
{
Dali::Toolkit::Control handle(GetOwner());
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
- auto self = mImpl->GetAccessibilityObject( Self() );
- self->EmitFocused( focusGained );
+ auto self = mImpl->GetAccessibilityObject(Self());
+ self->EmitFocused(focusGained);
auto parent = self->GetParent();
- if( parent && !self->GetStates()[Dali::Accessibility::State::MANAGES_DESCENDANTS] )
+ if(parent && !self->GetStates()[Dali::Accessibility::State::MANAGES_DESCENDANTS])
{
- parent->EmitActiveDescendantChanged( parent, self );
+ parent->EmitActiveDescendantChanged(parent, self);
}
}
// Request to be laid out when the control is connected to the Scene.
// Signal that a Relayout may be needed
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
mImpl->AccessibilityRegister();
}
void Control::OnSceneDisconnection()
{
- if( Accessibility::IsUp() )
+ if(Accessibility::IsUp())
{
mImpl->AccessibilityDeregister();
}
{
// If the clipping mode has been set, we may need to create a renderer.
// Only do this if we are already on-stage as the OnSceneConnection will handle the off-stage clipping controls.
- switch( index )
+ switch(index)
{
case Actor::Property::CLIPPING_MODE:
{
- if( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ))
+ if(Self().GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
{
// Note: This method will handle whether creation of the renderer is required.
- CreateClippingRenderer( *this );
+ CreateClippingRenderer(*this);
}
break;
}
case Actor::Property::VISIBLE:
{
- if( Dali::Accessibility::IsUp() )
+ if(Dali::Accessibility::IsUp())
{
- Dali::Accessibility::Accessible::Get(Self())->EmitVisible( Self().GetProperty( Actor::Property::VISIBLE ).Get<bool>() );
+ Dali::Accessibility::Accessible::Get(Self())->EmitVisible(Self().GetProperty(Actor::Property::VISIBLE).Get<bool>());
}
break;
}
case Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE:
{
- if( Dali::Accessibility::IsUp() )
+ if(Dali::Accessibility::IsUp())
{
- Dali::Accessibility::Accessible::Get(Self())->Emit( Dali::Accessibility::ObjectPropertyChangeEvent::ROLE );
+ Dali::Accessibility::Accessible::Get(Self())->Emit(Dali::Accessibility::ObjectPropertyChangeEvent::ROLE);
}
break;
}
/*
- * Copyright (c) 2020 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
*/
-#include <dali/dali.h>
#include <dali-toolkit/dali-toolkit.h>
+#include <dali/dali.h>
#include <sstream>
using namespace Dali;
namespace
{
-
// The name we will use to register our custom property by.
const char* const TAG_PROPERTY_NAME = "tagIdentifier";
// The image for our image view
const char* const IMAGE_CARDS = "images/cards.jpg";
-} // namespace
+} // namespace
/**
* This example shows how to set properties in C++ and how to register and look-up custom properties.
* An image is added to the screen which changes and a custom property is added to the image-view.
* This value is incremented every time the image is touched and the text-label is updated.
*/
-class PropertyController: public ConnectionTracker
+class PropertyController : public ConnectionTracker
{
public:
-
- PropertyController( Application& application )
+ PropertyController(Application& application)
: mTagText(),
- mTagPropertyIndex( Property::INVALID_INDEX )
+ mTagPropertyIndex(Property::INVALID_INDEX)
{
// Connect to the Application's Init signal
- application.InitSignal().Connect( this, &PropertyController::Create );
+ application.InitSignal().Connect(this, &PropertyController::Create);
}
~PropertyController()
}
// C++ EXAMPLE
- void Create( Application& application )
+ void Create(Application& application)
{
// Get the window handle
Window window = application.GetWindow();
mImageView = ImageView::New();
// Set the property to move to the center
- mImageView.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
+ mImageView.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
// Set another property to set the image-map
Property::Map imageMap;
- imageMap[ Visual::Property::TYPE ] = Visual::IMAGE;
- imageMap[ ImageVisual::Property::URL ] = IMAGE_CARDS;
- imageMap[ ImageVisual::Property::DESIRED_WIDTH ] = 100;
- imageMap[ ImageVisual::Property::DESIRED_HEIGHT ] = 100;
- mImageView.SetProperty( ImageView::Property::IMAGE, imageMap );
+ imageMap[Visual::Property::TYPE] = Visual::IMAGE;
+ imageMap[ImageVisual::Property::URL] = IMAGE_CARDS;
+ imageMap[ImageVisual::Property::DESIRED_WIDTH] = 100;
+ imageMap[ImageVisual::Property::DESIRED_HEIGHT] = 100;
+ mImageView.SetProperty(ImageView::Property::IMAGE, imageMap);
// Add the image view to the window
- window.Add( mImageView );
+ window.Add(mImageView);
// Register a custom float property on mImageView and use it to store the number of times we are tapped
- mTagPropertyIndex = mImageView.RegisterProperty( TAG_PROPERTY_NAME, 0, Property::READ_WRITE /* Event-side only, i.e. not animatable */ );
+ mTagPropertyIndex = mImageView.RegisterProperty(TAG_PROPERTY_NAME, 0, Property::READ_WRITE /* Event-side only, i.e. not animatable */);
// Connect to the touch-event
- mImageView.TouchedSignal().Connect( this, &PropertyController::OnTouched );
+ mImageView.TouchedSignal().Connect(this, &PropertyController::OnTouched);
// Create text label
- mTagText = Toolkit::TextLabel::New( "0" );
- mTagText.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER );
- mTagText.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER );
- mTagText.SetProperty( TextLabel::Property::TEXT_COLOR, Color::WHITE );
- mTagText.SetProperty( TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" );
- window.Add( mTagText );
+ mTagText = Toolkit::TextLabel::New("0");
+ mTagText.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER);
+ mTagText.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER);
+ mTagText.SetProperty(TextLabel::Property::TEXT_COLOR, Color::WHITE);
+ mTagText.SetProperty(TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER");
+ window.Add(mTagText);
}
/**
* param[in] touch The touch-event
* return Set to true if the signal was consumed correctly
*/
- bool OnTouched( Actor actor, const TouchEvent& touch )
+ bool OnTouched(Actor actor, const TouchEvent& touch)
{
int touchedCount = 0;
// Look up the tag property by the cached property index.
// Note: If the property belongs to a control in another library, or we do not know the index, we can look the index up first with:
// Property::Index index = actor.GetPropertyIndex( TAG_PROPERTY_NAME );
- actor.GetProperty( mTagPropertyIndex ).Get( touchedCount );
+ actor.GetProperty(mTagPropertyIndex).Get(touchedCount);
// Increment and set back again
++touchedCount;
- actor.SetProperty( mTagPropertyIndex, touchedCount );
+ actor.SetProperty(mTagPropertyIndex, touchedCount);
// Set the text in the text-label
std::stringstream valueText;
valueText << touchedCount;
- mTagText.SetProperty( TextLabel::Property::TEXT, valueText.str() );
+ mTagText.SetProperty(TextLabel::Property::TEXT, valueText.str());
return true; // Consumed meaning any gestures will be cancelled
}
// C++ EXAMPLE END
private:
-
- ImageView mImageView; ///< An image view to show an image
- TextLabel mTagText; ///< A text label used to show the last button pressed.
- Property::Index mTagPropertyIndex; ///< A cached property index of our custom tag property.
+ ImageView mImageView; ///< An image view to show an image
+ TextLabel mTagText; ///< A text label used to show the last button pressed.
+ Property::Index mTagPropertyIndex; ///< A cached property index of our custom tag property.
};
// Entry point for applications.
-int main( int argc, char **argv )
+int main(int argc, char** argv)
{
- Application application = Application::New( &argc, &argv );
+ Application application = Application::New(&argc, &argv);
- PropertyController test( application );
+ PropertyController test(application);
application.MainLoop();
return 0;