2 * Copyright (c) 2020 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali-toolkit/internal/builder/builder-impl.h>
25 #include <dali/public-api/actors/camera-actor.h>
26 #include <dali/public-api/actors/layer.h>
27 #include <dali/public-api/object/property-array.h>
28 #include <dali/public-api/object/type-info.h>
29 #include <dali/public-api/object/type-registry.h>
30 #include <dali/public-api/render-tasks/render-task-list.h>
31 #include <dali/public-api/signals/functor-delegate.h>
32 #include <dali/devel-api/common/stage.h>
33 #include <dali/devel-api/scripting/scripting.h>
34 #include <dali/integration-api/debug.h>
35 #include <dali-toolkit/devel-api/controls/control-devel.h>
38 #include <dali-toolkit/public-api/controls/control.h>
39 #include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
40 #include <dali-toolkit/devel-api/builder/json-parser.h>
42 #include <dali-toolkit/internal/builder/builder-declarations.h>
43 #include <dali-toolkit/internal/builder/builder-filesystem.h>
44 #include <dali-toolkit/internal/builder/builder-get-is.inl.h>
45 #include <dali-toolkit/internal/builder/builder-impl-debug.h>
46 #include <dali-toolkit/internal/builder/builder-set-property.h>
47 #include <dali-toolkit/internal/builder/replacement.h>
48 #include <dali-toolkit/internal/builder/tree-node-manipulator.h>
60 extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder );
62 extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
64 extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
67 #if defined(DEBUG_ENABLED)
68 Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT");
74 #define TOKEN_STRING(x) #x
76 const std::string KEYNAME_ACTORS = "actors";
77 const std::string KEYNAME_ENTRY_TRANSITION = "entryTransition";
78 const std::string KEYNAME_EXIT_TRANSITION = "exitTransition";
79 const std::string KEYNAME_INCLUDES = "includes";
80 const std::string KEYNAME_INHERIT = "inherit";
81 const std::string KEYNAME_MAPPINGS = "mappings";
82 const std::string KEYNAME_NAME = "name";
83 const std::string KEYNAME_SIGNALS = "signals";
84 const std::string KEYNAME_STATES = "states";
85 const std::string KEYNAME_STYLES = "styles";
86 const std::string KEYNAME_TEMPLATES = "templates";
87 const std::string KEYNAME_TRANSITIONS = "transitions";
88 const std::string KEYNAME_TYPE = "type";
89 const std::string KEYNAME_VISUALS = "visuals";
91 const std::string PROPERTIES = "properties";
92 const std::string ANIMATABLE_PROPERTIES = "animatableProperties";
94 typedef std::vector<const TreeNode*> TreeNodeList;
97 bool GetMappingKey( const std::string& str, std::string& key )
100 std::string test( str );
103 if( test.at(0) == '<' )
105 if( test.at(test.length()-1) == '>' )
107 key = test.substr( 1, test.length()-2 );
116 * Recursively collects all styles in a node (An array of style names).
118 * stylesCollection The set of styles from the json file (a json object of named styles)
119 * style The style array to begin the collection from
120 * styleList The style list to add nodes to apply
122 void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList )
124 // style is an array of style names
125 if( TreeNode::ARRAY == style.GetType() )
127 for(TreeNode::ConstIterator iter = style.CBegin(); iter != style.CEnd(); ++iter)
129 if( OptionalString styleName = IsString( (*iter).second ) )
131 if( OptionalChild node = IsChildIgnoreCase( stylesCollection, *styleName) )
133 styleList.push_back( &(*node) );
135 OptionalChild subStyle = IsChild( *node, KEYNAME_INHERIT );
138 subStyle = IsChild( *node, KEYNAME_STYLES );
142 CollectAllStyles( stylesCollection, *subStyle, styleList );
155 : mSlotDelegate( this )
157 mParser = Dali::Toolkit::JsonParser::New();
159 Property::Map defaultDirs;
160 defaultDirs[TOKEN_STRING(DALI_IMAGE_DIR)] = AssetManager::GetDaliImagePath();
161 defaultDirs[TOKEN_STRING(DALI_SOUND_DIR)] = AssetManager::GetDaliSoundPath();
162 defaultDirs[TOKEN_STRING(DALI_STYLE_DIR)] = AssetManager::GetDaliStylePath();
163 defaultDirs[TOKEN_STRING(DALI_STYLE_IMAGE_DIR)] = AssetManager::GetDaliStyleImagePath();
165 AddConstants( defaultDirs );
168 void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format )
170 // parser to get constants and includes only
171 Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New();
173 if( !parser.Parse( data ) )
175 DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
176 parser.GetErrorLineNumber(),
177 parser.GetErrorColumn(),
178 parser.GetErrorDescription().c_str() );
180 DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
184 // load constant map (allows the user to override the constants in the json after loading)
185 LoadConstants( *parser.GetRoot(), mReplacementMap );
186 // load configuration map
187 LoadConfiguration( *parser.GetRoot(), mConfigurationMap );
189 if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) )
191 Replacement replacer( mReplacementMap );
193 for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter)
195 OptionalString filename = replacer.IsString( (*iter).second );
199 #if defined(DEBUG_ENABLED)
200 DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str());
202 LoadFromString( GetFileContents(*filename) );
207 if( mParser.Parse( data ) )
209 // Drop the styles and get them to be rebuilt against the new parse tree as required.
214 DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
215 mParser.GetErrorLineNumber(),
216 mParser.GetErrorColumn(),
217 mParser.GetErrorDescription().c_str() );
219 DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
223 DUMP_PARSE_TREE(mParser); // This macro only writes out if DEBUG is enabled and the "DUMP_TREE" constant is defined in the stylesheet.
224 DUMP_TEST_MAPPINGS(mParser);
226 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
229 void Builder::AddConstants( const Property::Map& map )
231 mReplacementMap.Merge( map );
234 void Builder::AddConstant( const std::string& key, const Property::Value& value )
236 mReplacementMap[key] = value;
239 const Property::Map& Builder::GetConfigurations() const
241 return mConfigurationMap;
244 const Property::Map& Builder::GetConstants() const
246 return mReplacementMap;
249 const Property::Value& Builder::GetConstant( const std::string& key ) const
251 Property::Value* match = mReplacementMap.Find( key );
258 static Property::Value invalid;
263 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
265 Replacement replacement(map, mReplacementMap);
266 return CreateAnimation( animationName, replacement, sourceActor);
269 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
271 Replacement replacement(map, mReplacementMap);
272 return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
275 Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
277 Replacement replacement( mReplacementMap );
279 return CreateAnimation( animationName, replacement, sourceActor );
282 Animation Builder::CreateAnimation( const std::string& animationName )
284 Replacement replacement( mReplacementMap );
286 return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
289 BaseHandle Builder::Create( const std::string& templateName )
291 Replacement replacement( mReplacementMap );
292 return Create( templateName, replacement );
295 BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
297 Replacement replacement( map, mReplacementMap );
298 return Create( templateName, replacement );
301 BaseHandle Builder::CreateFromJson( const std::string& json )
305 // merge in new template, hoping no one else has one named '@temp@'
306 std::string newTemplate =
307 std::string("{\"templates\":{\"@temp@\":") + \
311 if( mParser.Parse(newTemplate) )
313 Replacement replacement( mReplacementMap );
314 ret = Create( "@temp@", replacement );
320 bool Builder::ApplyFromJson( Handle& handle, const std::string& json )
324 // merge new style, hoping no one else has one named '@temp@'
325 std::string newStyle =
326 std::string("{\"styles\":{\"@temp@\":") + \
330 if( mParser.Parse(newStyle) )
332 Replacement replacement( mReplacementMap );
333 ret = ApplyStyle( "@temp@", handle, replacement );
339 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
341 Replacement replacer( mReplacementMap );
342 return ApplyStyle( styleName, handle, replacer );
345 bool Builder::LookupStyleName( const std::string& styleName )
347 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
349 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
350 OptionalChild style = IsChildIgnoreCase( *styles, styleName );
352 if( styles && style )
359 const StylePtr Builder::GetStyle( const std::string& styleName )
361 const StylePtr* style = mStyles.FindConst( styleName );
365 return StylePtr(NULL);
373 void Builder::AddActors( Actor toActor )
375 // 'stage' is the default/by convention section to add from
376 AddActors( "stage", toActor );
379 void Builder::AddActors( const std::string §ionName, Actor toActor )
381 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
383 Property::Map overrideMap;
384 Replacement replacements(overrideMap, mReplacementMap);
386 OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
390 for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
392 // empty actor adds directly to the stage
393 BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
394 Actor actor = Actor::DownCast(baseHandle);
397 toActor.Add( actor );
401 // if were adding the 'stage' section then also check for a render task called stage
402 // to add automatically
403 if( "stage" == sectionName )
405 if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
407 if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
409 CreateRenderTask( "stage" );
416 void Builder::CreateRenderTask( const std::string &name )
418 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
420 Replacement constant(mReplacementMap);
422 const Stage& stage = Stage::GetCurrent();
424 OptionalChild tasks = IsChild(*mParser.GetRoot(), "renderTasks");
429 // Create the tasks from the current task as generally we want
430 // to setup task zero and onwards. Although this does overwrite
431 // the properties of the current task.
433 if( OptionalChild renderTask = IsChild(*tasks, name ) )
435 RenderTaskList list = stage.GetRenderTaskList();
436 unsigned int start = list.GetTaskCount();
441 // zero should have already been created by the stage so really
442 // this case should never happen
443 task = list.CreateTask();
447 TreeNode::ConstIterator iter = (*renderTask).CBegin();
448 task = list.GetTask( start - 1 );
450 SetupTask( task, (*iter).second, constant );
454 for(; iter != (*renderTask).CEnd(); ++iter )
456 task = list.CreateTask();
457 SetupTask( task, (*iter).second, constant );
463 Path Builder::GetPath( const std::string& name )
465 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
469 PathLut::const_iterator iter( mPathLut.find( name ) );
470 if( iter != mPathLut.end() )
476 if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") )
478 if( OptionalChild path = IsChild( *paths, name ) )
481 if( OptionalChild pointsProperty = IsChild( *path, "points") )
483 Dali::Property::Value points(Property::ARRAY);
484 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
487 ret.SetProperty( Path::Property::POINTS, points);
489 //controlPoints property
490 if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") )
492 Dali::Property::Value points(Property::ARRAY);
493 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
495 ret.SetProperty( Path::Property::CONTROL_POINTS, points);
501 float curvature(0.25f);
502 if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") )
504 curvature = *pointsProperty;
506 ret.GenerateControlPoints(curvature);
509 //Add the new path to the hash table for paths
510 mPathLut[ name ] = ret;
515 //Interpolation points not specified
516 DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() );
526 PathConstrainer Builder::GetPathConstrainer( const std::string& name )
528 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
530 //Search the pathConstrainer in the LUT
531 size_t count( mPathConstrainerLut.size() );
532 for( size_t i(0); i!=count; ++i )
534 if( mPathConstrainerLut[i].name == name )
536 //PathConstrainer has already been created
537 return mPathConstrainerLut[i].pathConstrainer;
541 //Create a new PathConstrainer
543 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
545 if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) )
547 OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type")));
550 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
552 else if( *constrainerType == "PathConstrainer")
555 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") )
557 Dali::Property::Value points(Property::ARRAY);
558 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
560 ret = PathConstrainer::New();
561 ret.SetProperty( PathConstrainer::Property::POINTS, points);
563 //controlPoints property
564 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") )
566 Dali::Property::Value points(Property::ARRAY);
567 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
569 ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points);
573 OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) );
576 ret.SetProperty( PathConstrainer::Property::FORWARD, *forward);
579 //Add the new constrainer to the vector of PathConstrainer
580 PathConstrainerEntry entry = {name,ret};
581 mPathConstrainerLut.push_back( entry );
585 //Control points not specified
586 DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() );
592 //Interpolation points not specified
593 DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() );
598 DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() );
607 bool Builder::IsPathConstrainer( const std::string& name )
609 size_t count( mPathConstrainerLut.size() );
610 for( size_t i(0); i!=count; ++i )
612 if( mPathConstrainerLut[i].name == name )
618 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
620 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
622 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
629 return *constrainerType == "PathConstrainer";
636 Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name )
638 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
640 //Search the LinearConstrainer in the LUT
641 size_t count( mLinearConstrainerLut.size() );
642 for( size_t i(0); i!=count; ++i )
644 if( mLinearConstrainerLut[i].name == name )
646 //LinearConstrainer has already been created
647 return mLinearConstrainerLut[i].linearConstrainer;
651 //Create a new LinearConstrainer
652 LinearConstrainer ret;
653 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
655 if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) )
657 OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type")));
660 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
662 else if( *constrainerType == "LinearConstrainer")
665 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") )
667 Dali::Property::Value points(Property::ARRAY);
668 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
670 ret = Dali::LinearConstrainer::New();
671 ret.SetProperty( LinearConstrainer::Property::VALUE, points);
673 //controlPoints property
674 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") )
676 Dali::Property::Value points(Property::ARRAY);
677 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
679 ret.SetProperty( LinearConstrainer::Property::PROGRESS, points);
682 //Add the new constrainer to vector of LinearConstrainer
683 LinearConstrainerEntry entry = {name,ret};
684 mLinearConstrainerLut.push_back( entry );
689 //Interpolation points not specified
690 DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() );
695 DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() );
703 bool Builder::IsLinearConstrainer( const std::string& name )
705 // Search the LinearConstrainer in the LUT
706 size_t count( mLinearConstrainerLut.size() );
707 for( size_t i(0); i!=count; ++i )
709 if( mLinearConstrainerLut[i].name == name )
715 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
717 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
719 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
726 return *constrainerType == "LinearConstrainer";
733 Toolkit::Builder::BuilderSignalType& Builder::QuitSignal()
738 void Builder::EmitQuitSignal()
747 void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap )
749 Replacement replacer(intoMap);
751 if( OptionalChild constants = IsChild(root, "config") )
753 for(TreeNode::ConstIterator iter = (*constants).CBegin();
754 iter != (*constants).CEnd(); ++iter)
756 Dali::Property::Value property;
757 if( (*iter).second.GetName() )
759 DeterminePropertyFromNode( (*iter).second, property, replacer );
761 // If config is string, find constant and replace it to original value.
762 if( (*iter).second.GetType() == TreeNode::STRING )
764 std::string stringConfigValue;
765 if( property.Get( stringConfigValue ) )
769 while( pos < stringConfigValue.size() )
771 // If we can't find "{","}" pair in stringConfigValue, will out loop.
772 std::size_t leftPos = stringConfigValue.find( "{", pos );
773 if( leftPos != std::string::npos )
775 std::size_t rightPos = stringConfigValue.find( "}", pos+1 );
777 if( rightPos != std::string::npos )
779 // If we find "{","}" pair but can't find matched constant
780 // try to find other "{","}" pair after current left position.
783 for( uint32_t i = 0; i < mReplacementMap.Count() ; i++ )
785 Property::Key constant = mReplacementMap.GetKeyAt(i);
787 // Compare string which is between "{" and "}" with constant string
788 // If they are same, change string in stringConfigValue to mapped constant value.
789 if ( 0 == stringConfigValue.compare( leftPos+1, rightPos-leftPos-1, constant.stringKey ) )
791 std::string replaceString;
792 mReplacementMap.GetValue(i).Get( replaceString );
794 stringConfigValue.replace( leftPos, rightPos-leftPos+1, replaceString );
795 pos = leftPos + replaceString.size();
802 // If we cannot find constant in const value, will out loop.
803 pos = stringConfigValue.size();
808 // If we cannot find constant in const value, will out loop.
809 pos = stringConfigValue.size();
812 property = Property::Value( stringConfigValue );
815 intoMap[ (*iter).second.GetName() ] = property;
821 void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
823 Replacement replacer(intoMap);
825 if( OptionalChild constants = IsChild(root, "constants") )
827 for(TreeNode::ConstIterator iter = (*constants).CBegin();
828 iter != (*constants).CEnd(); ++iter)
830 Dali::Property::Value property;
831 if( (*iter).second.GetName() )
833 #if defined(DEBUG_ENABLED)
834 DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
836 DeterminePropertyFromNode( (*iter).second, property, replacer );
837 intoMap[ (*iter).second.GetName() ] = property;
842 #if defined(DEBUG_ENABLED)
843 Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
844 if( iter && iter->GetType() == Property::STRING )
846 std::string logLevel( iter->Get< std::string >() );
847 if( logLevel == "NoLogging" )
849 gFilterScript->SetLogLevel( Integration::Log::NoLogging );
851 else if( logLevel == "Concise" )
853 gFilterScript->SetLogLevel( Integration::Log::Concise );
855 else if( logLevel == "General" )
857 gFilterScript->SetLogLevel( Integration::Log::General );
859 else if( logLevel == "Verbose" )
861 gFilterScript->SetLogLevel( Integration::Log::Verbose );
867 Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
869 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
873 if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
875 if( OptionalChild animation = IsChild(*animations, animationName) )
877 anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
881 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
886 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
892 BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
894 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
896 BaseHandle baseHandle;
898 OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
902 DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
906 OptionalChild childTemplate = IsChild(*templates, templateName);
909 DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
913 OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
917 DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
921 baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
930 * Create a dali type from a node.
931 * If parent given and an actor type was created then add it to the parent and
932 * recursively add nodes children.
934 BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
935 Actor parent, const Replacement& replacements )
937 BaseHandle baseHandle;
939 const TreeNode* templateNode = NULL;
941 if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
943 typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
947 // a template name is also allowed inplace of the type name
948 OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
952 if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
954 templateNode = &(*isTemplate);
956 if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
958 typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
967 DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
971 baseHandle = typeInfo.CreateInstance();
972 Handle handle = Handle::DownCast(baseHandle);
973 Actor actor = Actor::DownCast(handle);
978 DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
980 #if defined(DEBUG_ENABLED)
983 DALI_SCRIPT_VERBOSE(" Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
984 DALI_SCRIPT_VERBOSE(" Is Handle Property Count=%d\n", handle.GetPropertyCount());
989 DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetProperty< int >( Actor::Property::ID ));
992 Toolkit::Control control = Toolkit::Control::DownCast(handle);
995 DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetProperty< int >( Actor::Property::ID ));
997 #endif // DEBUG_ENABLED
1001 ApplyProperties( root, *templateNode, handle, replacements );
1003 if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
1005 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1007 DoCreate( root, (*iter).second, actor, replacements );
1014 // add children of all the styles
1015 if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
1017 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1019 DoCreate( root, (*iter).second, actor, replacements );
1023 // apply style on top as they need the children to exist
1024 ApplyAllStyleProperties( root, node, actor, replacements );
1026 // then add to parent
1029 parent.Add( actor );
1034 ApplyProperties( root, node, handle, replacements );
1039 DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
1046 void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
1048 const Stage& stage = Stage::GetCurrent();
1049 Layer root = stage.GetRootLayer();
1051 if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
1053 Actor actor = root.FindChildByName(*s);
1056 task.SetSourceActor( actor );
1060 DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
1064 if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
1066 CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
1069 task.SetCameraActor( actor );
1073 DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
1077 if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
1079 if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
1081 task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
1083 else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
1085 task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
1089 DALI_SCRIPT_WARNING("todo");
1093 // other setup is via the property system
1094 SetProperties( node, task, constant );
1097 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
1099 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
1101 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
1103 std::string styleNameLower(styleName);
1104 OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower );
1106 if( styles && style )
1108 ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
1117 void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
1118 Dali::Handle& handle, const Replacement& constant )
1120 const char* styleName = node.GetName();
1122 StylePtr style = Style::New();
1124 StylePtr* matchedStyle = NULL;
1127 matchedStyle = mStyles.Find( styleName );
1128 if( ! matchedStyle )
1130 OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
1131 OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
1132 if( !inheritFromNode )
1134 inheritFromNode = IsChild( node, KEYNAME_STYLES );
1139 if( inheritFromNode )
1141 TreeNodeList additionalStyleNodes;
1143 CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
1145 #if defined(DEBUG_ENABLED)
1146 for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
1148 if( OptionalString styleName = IsString( (*iter).second ) )
1150 DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
1155 // a style may have other styles, which has other styles etc so we apply in reverse by convention.
1156 for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
1158 RecordStyle( style, *(*iter), handle, constant );
1159 ApplySignals( root, *(*iter), handle );
1160 ApplyStylesByActor( root, *(*iter), handle, constant );
1164 RecordStyle( style, node, handle, constant );
1165 mStyles.Add( styleName, style ); // shallow copy
1166 matchedStyle = &style;
1173 StylePtr style( *matchedStyle );
1174 Dictionary<Property::Map> instancedProperties;
1175 style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties );
1177 else // If there were no styles, instead set properties
1179 SetProperties( node, handle, constant );
1181 ApplySignals( root, node, handle );
1182 ApplyStylesByActor( root, node, handle, constant );
1185 void Builder::RecordStyle( StylePtr style,
1186 const TreeNode& node,
1187 Dali::Handle& handle,
1188 const Replacement& replacements )
1190 // With repeated calls, accumulate inherited states, visuals and properties
1191 // but override any with same name
1193 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1195 const TreeNode::KeyNodePair& keyValue = *iter;
1196 std::string key( keyValue.first );
1197 if( key == KEYNAME_STATES )
1199 const TreeNode& states = keyValue.second;
1200 if( states.GetType() != TreeNode::OBJECT )
1202 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
1206 for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
1208 const TreeNode& stateNode = (*iter).second;
1209 const char* stateName = stateNode.GetName();
1210 if( stateNode.GetType() != TreeNode::OBJECT )
1212 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
1216 StylePtr* stylePtr = style->subStates.Find( stateName );
1219 StylePtr style(*stylePtr);
1220 RecordStyle( style, stateNode, handle, replacements );
1224 StylePtr subState = Style::New();
1225 RecordStyle( subState, stateNode, handle, replacements );
1226 style->subStates.Add( stateName, subState );
1230 else if( key == KEYNAME_VISUALS )
1232 for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
1234 // Each key in this table should be a property name matching a visual.
1235 const TreeNode::KeyNodePair& visual = *iter;
1236 Dali::Property::Value property(Property::MAP);
1237 if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
1239 Property::Map* mapPtr = style->visuals.Find( visual.first );
1242 // Override existing visuals
1244 mapPtr->Merge( *property.GetMap() );
1248 Property::Map* map = property.GetMap();
1251 style->visuals.Add( visual.first, *map );
1257 else if( key == KEYNAME_ENTRY_TRANSITION )
1259 RecordTransitionData( keyValue, style->entryTransition, replacements );
1261 else if( key == KEYNAME_EXIT_TRANSITION )
1263 RecordTransitionData( keyValue, style->exitTransition, replacements );
1265 else if( key == KEYNAME_TRANSITIONS )
1267 RecordTransitions( keyValue, style->transitions, replacements );
1269 else if( key == KEYNAME_TYPE ||
1270 key == KEYNAME_ACTORS ||
1271 key == KEYNAME_SIGNALS ||
1272 key == KEYNAME_STYLES ||
1273 key == KEYNAME_MAPPINGS ||
1274 key == KEYNAME_INHERIT )
1278 else // It's a property
1280 Property::Index index;
1281 Property::Value value;
1282 if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
1284 Property::Value* existingValuePtr = style->properties.Find( index );
1285 if( existingValuePtr != NULL )
1287 *existingValuePtr = value; // Overwrite existing property.
1291 style->properties.Add( index, value );
1298 void Builder::RecordTransitions(
1299 const TreeNode::KeyNodePair& keyValue,
1300 Property::Array& value,
1301 const Replacement& replacements )
1303 //@todo add new transitions to style.transitions
1304 // override existing transitions. A transition matches on target & property name
1305 const TreeNode& node = keyValue.second;
1306 if( node.GetType() == TreeNode::ARRAY )
1308 Dali::Property::Value property(Property::ARRAY);
1309 if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
1311 value = *property.GetArray();
1314 else if( node.GetType() == TreeNode::OBJECT )
1316 Dali::Property::Value property(Property::MAP);
1317 if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
1319 Property::Array propertyArray;
1320 propertyArray.Add( property );
1321 value = propertyArray;
1326 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first );
1330 void Builder::RecordTransitionData(
1331 const TreeNode::KeyNodePair& keyValue,
1332 Toolkit::TransitionData& transitionData,
1333 const Replacement& replacements )
1335 const TreeNode& node = keyValue.second;
1336 if( node.GetType() == TreeNode::ARRAY )
1338 Dali::Property::Value property(Property::ARRAY);
1339 if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) )
1341 transitionData = Toolkit::TransitionData::New( *property.GetArray() );
1344 else if( node.GetType() == TreeNode::OBJECT )
1346 Dali::Property::Value property(Property::MAP);
1347 if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
1349 transitionData = Toolkit::TransitionData::New( *property.GetMap() );
1355 // Set properties from node on handle.
1356 void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
1357 Dali::Handle& handle, const Replacement& constant )
1359 SetProperties( node, handle, constant );
1360 ApplySignals( root, node, handle );
1363 void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
1365 Actor actor = Actor::DownCast(handle);
1369 SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1370 SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1375 // Appling by style helper
1376 // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
1377 void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node,
1378 Dali::Handle& handle, const Replacement& constant )
1380 if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
1382 if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
1384 // in a style the actor subtree properties referenced by actor name
1385 for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
1387 Dali::Actor foundActor;
1391 foundActor = actor.FindChildByName( (*iter).first );
1396 DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
1400 DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
1401 ApplyProperties( root, (*iter).second, foundActor, constant );
1409 * Sets the handle properties found in the tree node
1411 void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
1415 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1417 const TreeNode::KeyNodePair& keyChild = *iter;
1419 std::string key( keyChild.first );
1421 // ignore special fields;
1422 if( key == KEYNAME_TYPE ||
1423 key == KEYNAME_ACTORS ||
1424 key == KEYNAME_SIGNALS ||
1425 key == KEYNAME_STYLES ||
1426 key == KEYNAME_MAPPINGS ||
1427 key == KEYNAME_INHERIT ||
1428 key == KEYNAME_STATES ||
1429 key == KEYNAME_VISUALS ||
1430 key == KEYNAME_ENTRY_TRANSITION ||
1431 key == KEYNAME_EXIT_TRANSITION ||
1432 key == KEYNAME_TRANSITIONS )
1437 Property::Index index;
1438 Property::Value value;
1440 bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
1443 DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
1445 handle.SetProperty( index, value );
1448 // Add custom properties
1449 SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
1450 SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
1452 } // for property nodes
1456 DALI_SCRIPT_WARNING("Style applied to empty handle\n");
1460 bool Builder::MapToTargetProperty(
1461 Handle& propertyObject,
1462 const std::string& key,
1463 const TreeNode& node,
1464 const Replacement& constant,
1465 Property::Index& index,
1466 Property::Value& value )
1468 bool mapped = false;
1470 index = propertyObject.GetPropertyIndex( key );
1471 if( Property::INVALID_INDEX != index )
1473 Property::Type type = propertyObject.GetPropertyType(index);
1475 // if node.value is a mapping, get the property value from the "mappings" table
1476 if( node.GetType() == TreeNode::STRING )
1478 std::string mappingKey;
1479 if( GetMappingKey( node.GetString(), mappingKey) )
1481 OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
1482 mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
1487 mapped = DeterminePropertyFromNode( node, type, value, constant );
1490 // Just determine the property from the node and if it's valid, let the property object handle it
1491 DeterminePropertyFromNode( node, value, constant );
1492 mapped = ( value.GetType() != Property::NONE );
1498 DALI_LOG_ERROR("Key '%s' not found.\n", key.c_str());
1503 bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
1506 return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
1509 bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
1511 Replacement replacer( mReplacementMap );
1512 bool result = false;
1514 keyStack.push_back( theKey );
1516 for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
1518 std::string aKey( (*iter).first );
1519 if( aKey.compare( theKey ) == 0 )
1521 if( propertyType == Property::NONE )
1523 DeterminePropertyFromNode( (*iter).second, value, replacer );
1528 result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
1533 ConvertChildValue(mappingRoot, keyStack, value);
1538 keyStack.pop_back();
1543 bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
1545 bool result = false;
1547 switch( child.GetType() )
1549 case Property::STRING:
1552 if( child.Get( value ) )
1555 if( GetMappingKey( value, key ) )
1557 // Check key for cycles:
1559 for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
1561 if( key.compare(*iter) == 0 )
1563 // key is already in stack; stop.
1564 DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
1565 child = Property::Value("");
1573 // The following call will overwrite the child with the value
1574 // from the mapping.
1575 RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
1585 Property::Map* map = child.GetMap();
1588 for( Property::Map::SizeType i=0; i < map->Count(); ++i )
1590 Property::Value& child = map->GetValue(i);
1591 ConvertChildValue(mappingRoot, keyStack, child);
1597 case Property::ARRAY:
1599 Property::Array* array = child.GetArray();
1602 for( Property::Array::SizeType i=0; i < array->Count(); ++i )
1604 Property::Value& child = array->GetElementAt(i);
1605 ConvertChildValue(mappingRoot, keyStack, child);
1612 // Ignore other types.
1619 void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
1620 const std::string& childName, Property::AccessMode accessMode )
1622 // Add custom properties
1623 if( OptionalChild customPropertiesChild = IsChild(node, childName) )
1625 const TreeNode& customPropertiesNode = *customPropertiesChild;
1626 const TreeConstIter endIter = customPropertiesNode.CEnd();
1627 for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
1629 const TreeNode::KeyNodePair& keyChild = *iter;
1630 std::string key( keyChild.first );
1631 Property::Value value;
1632 DeterminePropertyFromNode( keyChild.second, value, constant );
1634 // Register/Set property.
1635 handle.RegisterProperty( key, value, accessMode );
1641 } // namespace Internal
1643 } // namespace Toolkit