2 * Copyright (c) 2018 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/scripting/scripting.h>
33 #include <dali/integration-api/debug.h>
34 #include <dali-toolkit/devel-api/controls/control-devel.h>
37 #include <dali-toolkit/public-api/controls/control.h>
38 #include <dali-toolkit/devel-api/builder/json-parser.h>
40 #include <dali-toolkit/internal/builder/builder-declarations.h>
41 #include <dali-toolkit/internal/builder/builder-filesystem.h>
42 #include <dali-toolkit/internal/builder/builder-get-is.inl.h>
43 #include <dali-toolkit/internal/builder/builder-impl-debug.h>
44 #include <dali-toolkit/internal/builder/builder-set-property.h>
45 #include <dali-toolkit/internal/builder/replacement.h>
46 #include <dali-toolkit/internal/builder/tree-node-manipulator.h>
58 extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder );
60 extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
62 extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
65 #if defined(DEBUG_ENABLED)
66 Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT");
72 #define TOKEN_STRING(x) #x
74 const std::string KEYNAME_ACTORS = "actors";
75 const std::string KEYNAME_ENTRY_TRANSITION = "entryTransition";
76 const std::string KEYNAME_EXIT_TRANSITION = "exitTransition";
77 const std::string KEYNAME_INCLUDES = "includes";
78 const std::string KEYNAME_INHERIT = "inherit";
79 const std::string KEYNAME_MAPPINGS = "mappings";
80 const std::string KEYNAME_NAME = "name";
81 const std::string KEYNAME_SIGNALS = "signals";
82 const std::string KEYNAME_STATES = "states";
83 const std::string KEYNAME_STYLES = "styles";
84 const std::string KEYNAME_TEMPLATES = "templates";
85 const std::string KEYNAME_TRANSITIONS = "transitions";
86 const std::string KEYNAME_TYPE = "type";
87 const std::string KEYNAME_VISUALS = "visuals";
89 const std::string PROPERTIES = "properties";
90 const std::string ANIMATABLE_PROPERTIES = "animatableProperties";
92 typedef std::vector<const TreeNode*> TreeNodeList;
95 bool GetMappingKey( const std::string& str, std::string& key )
98 std::string test( str );
101 if( test.at(0) == '<' )
103 if( test.at(test.length()-1) == '>' )
105 key = test.substr( 1, test.length()-2 );
114 * Recursively collects all styles in a node (An array of style names).
116 * stylesCollection The set of styles from the json file (a json object of named styles)
117 * style The style array to begin the collection from
118 * styleList The style list to add nodes to apply
120 void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList )
122 // style is an array of style names
123 if( TreeNode::ARRAY == style.GetType() )
125 for(TreeNode::ConstIterator iter = style.CBegin(); iter != style.CEnd(); ++iter)
127 if( OptionalString styleName = IsString( (*iter).second ) )
129 if( OptionalChild node = IsChildIgnoreCase( stylesCollection, *styleName) )
131 styleList.push_back( &(*node) );
133 OptionalChild subStyle = IsChild( *node, KEYNAME_INHERIT );
136 subStyle = IsChild( *node, KEYNAME_STYLES );
140 CollectAllStyles( stylesCollection, *subStyle, styleList );
153 : mSlotDelegate( this )
155 mParser = Dali::Toolkit::JsonParser::New();
157 Property::Map defaultDirs;
158 defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;
159 defaultDirs[ TOKEN_STRING(DALI_SOUND_DIR) ] = DALI_SOUND_DIR;
160 defaultDirs[ TOKEN_STRING(DALI_STYLE_DIR) ] = DALI_STYLE_DIR;
161 defaultDirs[ TOKEN_STRING(DALI_STYLE_IMAGE_DIR) ] = DALI_STYLE_IMAGE_DIR;
163 AddConstants( defaultDirs );
166 void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format )
168 // parser to get constants and includes only
169 Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New();
171 if( !parser.Parse( data ) )
173 DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
174 parser.GetErrorLineNumber(),
175 parser.GetErrorColumn(),
176 parser.GetErrorDescription().c_str() );
178 DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
182 // load constant map (allows the user to override the constants in the json after loading)
183 LoadConstants( *parser.GetRoot(), mReplacementMap );
184 // load configuration map
185 LoadConfiguration( *parser.GetRoot(), mConfigurationMap );
187 if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) )
189 Replacement replacer( mReplacementMap );
191 for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter)
193 OptionalString filename = replacer.IsString( (*iter).second );
197 #if defined(DEBUG_ENABLED)
198 DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str());
200 LoadFromString( GetFileContents(*filename) );
205 if( mParser.Parse( data ) )
207 // Drop the styles and get them to be rebuilt against the new parse tree as required.
212 DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
213 mParser.GetErrorLineNumber(),
214 mParser.GetErrorColumn(),
215 mParser.GetErrorDescription().c_str() );
217 DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
221 DUMP_PARSE_TREE(mParser); // This macro only writes out if DEBUG is enabled and the "DUMP_TREE" constant is defined in the stylesheet.
222 DUMP_TEST_MAPPINGS(mParser);
224 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
227 void Builder::AddConstants( const Property::Map& map )
229 mReplacementMap.Merge( map );
232 void Builder::AddConstant( const std::string& key, const Property::Value& value )
234 mReplacementMap[key] = value;
237 const Property::Map& Builder::GetConfigurations() const
239 return mConfigurationMap;
242 const Property::Map& Builder::GetConstants() const
244 return mReplacementMap;
247 const Property::Value& Builder::GetConstant( const std::string& key ) const
249 Property::Value* match = mReplacementMap.Find( key );
256 static Property::Value invalid;
261 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
263 Replacement replacement(map, mReplacementMap);
264 return CreateAnimation( animationName, replacement, sourceActor);
267 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
269 Replacement replacement(map, mReplacementMap);
270 return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
273 Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
275 Replacement replacement( mReplacementMap );
277 return CreateAnimation( animationName, replacement, sourceActor );
280 Animation Builder::CreateAnimation( const std::string& animationName )
282 Replacement replacement( mReplacementMap );
284 return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
287 BaseHandle Builder::Create( const std::string& templateName )
289 Replacement replacement( mReplacementMap );
290 return Create( templateName, replacement );
293 BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
295 Replacement replacement( map, mReplacementMap );
296 return Create( templateName, replacement );
299 BaseHandle Builder::CreateFromJson( const std::string& json )
303 // merge in new template, hoping no one else has one named '@temp@'
304 std::string newTemplate =
305 std::string("{\"templates\":{\"@temp@\":") + \
309 if( mParser.Parse(newTemplate) )
311 Replacement replacement( mReplacementMap );
312 ret = Create( "@temp@", replacement );
318 bool Builder::ApplyFromJson( Handle& handle, const std::string& json )
322 // merge new style, hoping no one else has one named '@temp@'
323 std::string newStyle =
324 std::string("{\"styles\":{\"@temp@\":") + \
328 if( mParser.Parse(newStyle) )
330 Replacement replacement( mReplacementMap );
331 ret = ApplyStyle( "@temp@", handle, replacement );
337 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
339 Replacement replacer( mReplacementMap );
340 return ApplyStyle( styleName, handle, replacer );
343 bool Builder::LookupStyleName( const std::string& styleName )
345 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
347 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
348 OptionalChild style = IsChildIgnoreCase( *styles, styleName );
350 if( styles && style )
357 const StylePtr Builder::GetStyle( const std::string& styleName )
359 const StylePtr* style = mStyles.FindConst( styleName );
363 return StylePtr(NULL);
371 void Builder::AddActors( Actor toActor )
373 // 'stage' is the default/by convention section to add from
374 AddActors( "stage", toActor );
377 void Builder::AddActors( const std::string §ionName, Actor toActor )
379 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
381 Property::Map overrideMap;
382 Replacement replacements(overrideMap, mReplacementMap);
384 OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
388 for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
390 // empty actor adds directly to the stage
391 BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
392 Actor actor = Actor::DownCast(baseHandle);
395 toActor.Add( actor );
399 // if were adding the 'stage' section then also check for a render task called stage
400 // to add automatically
401 if( "stage" == sectionName )
403 if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
405 if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
407 CreateRenderTask( "stage" );
414 void Builder::CreateRenderTask( const std::string &name )
416 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
418 Replacement constant(mReplacementMap);
420 const Stage& stage = Stage::GetCurrent();
422 OptionalChild tasks = IsChild(*mParser.GetRoot(), "renderTasks");
427 // Create the tasks from the current task as generally we want
428 // to setup task zero and onwards. Although this does overwrite
429 // the properties of the current task.
431 if( OptionalChild renderTask = IsChild(*tasks, name ) )
433 RenderTaskList list = stage.GetRenderTaskList();
434 unsigned int start = list.GetTaskCount();
439 // zero should have already been created by the stage so really
440 // this case should never happen
441 task = list.CreateTask();
445 TreeNode::ConstIterator iter = (*renderTask).CBegin();
446 task = list.GetTask( start - 1 );
448 SetupTask( task, (*iter).second, constant );
452 for(; iter != (*renderTask).CEnd(); ++iter )
454 task = list.CreateTask();
455 SetupTask( task, (*iter).second, constant );
461 Path Builder::GetPath( const std::string& name )
463 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
467 PathLut::const_iterator iter( mPathLut.find( name ) );
468 if( iter != mPathLut.end() )
474 if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") )
476 if( OptionalChild path = IsChild( *paths, name ) )
479 if( OptionalChild pointsProperty = IsChild( *path, "points") )
481 Dali::Property::Value points(Property::ARRAY);
482 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
485 ret.SetProperty( Path::Property::POINTS, points);
487 //controlPoints property
488 if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") )
490 Dali::Property::Value points(Property::ARRAY);
491 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
493 ret.SetProperty( Path::Property::CONTROL_POINTS, points);
499 float curvature(0.25f);
500 if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") )
502 curvature = *pointsProperty;
504 ret.GenerateControlPoints(curvature);
507 //Add the new path to the hash table for paths
508 mPathLut[ name ] = ret;
513 //Interpolation points not specified
514 DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() );
524 PathConstrainer Builder::GetPathConstrainer( const std::string& name )
526 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
528 //Search the pathConstrainer in the LUT
529 size_t count( mPathConstrainerLut.size() );
530 for( size_t i(0); i!=count; ++i )
532 if( mPathConstrainerLut[i].name == name )
534 //PathConstrainer has already been created
535 return mPathConstrainerLut[i].pathConstrainer;
539 //Create a new PathConstrainer
541 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
543 if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) )
545 OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type")));
548 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
550 else if( *constrainerType == "PathConstrainer")
553 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") )
555 Dali::Property::Value points(Property::ARRAY);
556 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
558 ret = PathConstrainer::New();
559 ret.SetProperty( PathConstrainer::Property::POINTS, points);
561 //controlPoints property
562 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") )
564 Dali::Property::Value points(Property::ARRAY);
565 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
567 ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points);
571 OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) );
574 ret.SetProperty( PathConstrainer::Property::FORWARD, *forward);
577 //Add the new constrainer to the vector of PathConstrainer
578 PathConstrainerEntry entry = {name,ret};
579 mPathConstrainerLut.push_back( entry );
583 //Control points not specified
584 DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() );
590 //Interpolation points not specified
591 DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() );
596 DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() );
605 bool Builder::IsPathConstrainer( const std::string& name )
607 size_t count( mPathConstrainerLut.size() );
608 for( size_t i(0); i!=count; ++i )
610 if( mPathConstrainerLut[i].name == name )
616 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
618 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
620 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
627 return *constrainerType == "PathConstrainer";
634 Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name )
636 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
638 //Search the LinearConstrainer in the LUT
639 size_t count( mLinearConstrainerLut.size() );
640 for( size_t i(0); i!=count; ++i )
642 if( mLinearConstrainerLut[i].name == name )
644 //LinearConstrainer has already been created
645 return mLinearConstrainerLut[i].linearConstrainer;
649 //Create a new LinearConstrainer
650 LinearConstrainer ret;
651 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
653 if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) )
655 OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type")));
658 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
660 else if( *constrainerType == "LinearConstrainer")
663 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") )
665 Dali::Property::Value points(Property::ARRAY);
666 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
668 ret = Dali::LinearConstrainer::New();
669 ret.SetProperty( LinearConstrainer::Property::VALUE, points);
671 //controlPoints property
672 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") )
674 Dali::Property::Value points(Property::ARRAY);
675 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
677 ret.SetProperty( LinearConstrainer::Property::PROGRESS, points);
680 //Add the new constrainer to vector of LinearConstrainer
681 LinearConstrainerEntry entry = {name,ret};
682 mLinearConstrainerLut.push_back( entry );
687 //Interpolation points not specified
688 DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() );
693 DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() );
701 bool Builder::IsLinearConstrainer( const std::string& name )
703 // Search the LinearConstrainer in the LUT
704 size_t count( mLinearConstrainerLut.size() );
705 for( size_t i(0); i!=count; ++i )
707 if( mLinearConstrainerLut[i].name == name )
713 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
715 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
717 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
724 return *constrainerType == "LinearConstrainer";
731 Toolkit::Builder::BuilderSignalType& Builder::QuitSignal()
736 void Builder::EmitQuitSignal()
745 void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap )
747 Replacement replacer(intoMap);
749 if( OptionalChild constants = IsChild(root, "config") )
751 for(TreeNode::ConstIterator iter = (*constants).CBegin();
752 iter != (*constants).CEnd(); ++iter)
754 Dali::Property::Value property;
755 if( (*iter).second.GetName() )
757 DeterminePropertyFromNode( (*iter).second, property, replacer );
759 // If config is string, find constant and replace it to original value.
760 if( (*iter).second.GetType() == TreeNode::STRING )
762 std::string stringConfigValue;
763 if( property.Get( stringConfigValue ) )
767 while( pos < stringConfigValue.size() )
769 // If we can't find "{","}" pair in stringConfigValue, will out loop.
770 std::size_t leftPos = stringConfigValue.find( "{", pos );
771 if( leftPos != std::string::npos )
773 std::size_t rightPos = stringConfigValue.find( "}", pos+1 );
775 if( rightPos != std::string::npos )
777 // If we find "{","}" pair but can't find matched constant
778 // try to find other "{","}" pair after current left position.
781 for( uint32_t i = 0; i < mReplacementMap.Count() ; i++ )
783 Property::Key constant = mReplacementMap.GetKeyAt(i);
785 // Compare string which is between "{" and "}" with constant string
786 // If they are same, change string in stringConfigValue to mapped constant value.
787 if ( 0 == stringConfigValue.compare( leftPos+1, rightPos-leftPos-1, constant.stringKey ) )
789 std::string replaceString;
790 mReplacementMap.GetValue(i).Get( replaceString );
792 stringConfigValue.replace( leftPos, rightPos-leftPos+1, replaceString );
793 pos = leftPos + replaceString.size();
800 // If we cannot find constant in const value, will out loop.
801 pos = stringConfigValue.size();
806 // If we cannot find constant in const value, will out loop.
807 pos = stringConfigValue.size();
810 property = Property::Value( stringConfigValue );
813 intoMap[ (*iter).second.GetName() ] = property;
819 void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
821 Replacement replacer(intoMap);
823 if( OptionalChild constants = IsChild(root, "constants") )
825 for(TreeNode::ConstIterator iter = (*constants).CBegin();
826 iter != (*constants).CEnd(); ++iter)
828 Dali::Property::Value property;
829 if( (*iter).second.GetName() )
831 #if defined(DEBUG_ENABLED)
832 DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
834 DeterminePropertyFromNode( (*iter).second, property, replacer );
835 intoMap[ (*iter).second.GetName() ] = property;
840 #if defined(DEBUG_ENABLED)
841 Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
842 if( iter && iter->GetType() == Property::STRING )
844 std::string logLevel( iter->Get< std::string >() );
845 if( logLevel == "NoLogging" )
847 gFilterScript->SetLogLevel( Integration::Log::NoLogging );
849 else if( logLevel == "Concise" )
851 gFilterScript->SetLogLevel( Integration::Log::Concise );
853 else if( logLevel == "General" )
855 gFilterScript->SetLogLevel( Integration::Log::General );
857 else if( logLevel == "Verbose" )
859 gFilterScript->SetLogLevel( Integration::Log::Verbose );
865 Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
867 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
871 if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
873 if( OptionalChild animation = IsChild(*animations, animationName) )
875 anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
879 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
884 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
890 BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
892 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
894 BaseHandle baseHandle;
896 OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
900 DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
904 OptionalChild childTemplate = IsChild(*templates, templateName);
907 DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
911 OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
915 DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
919 baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
928 * Create a dali type from a node.
929 * If parent given and an actor type was created then add it to the parent and
930 * recursively add nodes children.
932 BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
933 Actor parent, const Replacement& replacements )
935 BaseHandle baseHandle;
937 const TreeNode* templateNode = NULL;
939 if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
941 typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
945 // a template name is also allowed inplace of the type name
946 OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
950 if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
952 templateNode = &(*isTemplate);
954 if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
956 typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
965 DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
969 baseHandle = typeInfo.CreateInstance();
970 Handle handle = Handle::DownCast(baseHandle);
971 Actor actor = Actor::DownCast(handle);
976 DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
978 #if defined(DEBUG_ENABLED)
981 DALI_SCRIPT_VERBOSE(" Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
982 DALI_SCRIPT_VERBOSE(" Is Handle Property Count=%d\n", handle.GetPropertyCount());
987 DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetId());
990 Toolkit::Control control = Toolkit::Control::DownCast(handle);
993 DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetId());
995 #endif // DEBUG_ENABLED
999 ApplyProperties( root, *templateNode, handle, replacements );
1001 if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
1003 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1005 DoCreate( root, (*iter).second, actor, replacements );
1012 // add children of all the styles
1013 if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
1015 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1017 DoCreate( root, (*iter).second, actor, replacements );
1021 // apply style on top as they need the children to exist
1022 ApplyAllStyleProperties( root, node, actor, replacements );
1024 // then add to parent
1027 parent.Add( actor );
1032 ApplyProperties( root, node, handle, replacements );
1037 DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
1044 void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
1046 const Stage& stage = Stage::GetCurrent();
1047 Layer root = stage.GetRootLayer();
1049 if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
1051 Actor actor = root.FindChildByName(*s);
1054 task.SetSourceActor( actor );
1058 DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
1062 if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
1064 CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
1067 task.SetCameraActor( actor );
1071 DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
1075 if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
1077 if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
1079 task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
1081 else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
1083 task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
1087 DALI_SCRIPT_WARNING("todo");
1091 // other setup is via the property system
1092 SetProperties( node, task, constant );
1095 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
1097 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
1099 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
1101 std::string styleNameLower(styleName);
1102 OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower );
1104 if( styles && style )
1106 ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
1115 void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
1116 Dali::Handle& handle, const Replacement& constant )
1118 const char* styleName = node.GetName();
1120 StylePtr style = Style::New();
1122 StylePtr* matchedStyle = NULL;
1125 matchedStyle = mStyles.Find( styleName );
1126 if( ! matchedStyle )
1128 OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
1129 OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
1130 if( !inheritFromNode )
1132 inheritFromNode = IsChild( node, KEYNAME_STYLES );
1137 if( inheritFromNode )
1139 TreeNodeList additionalStyleNodes;
1141 CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
1143 #if defined(DEBUG_ENABLED)
1144 for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
1146 if( OptionalString styleName = IsString( (*iter).second ) )
1148 DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
1153 // a style may have other styles, which has other styles etc so we apply in reverse by convention.
1154 for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
1156 RecordStyle( style, *(*iter), handle, constant );
1157 ApplySignals( root, *(*iter), handle );
1158 ApplyStylesByActor( root, *(*iter), handle, constant );
1162 RecordStyle( style, node, handle, constant );
1163 mStyles.Add( styleName, style ); // shallow copy
1164 matchedStyle = &style;
1171 StylePtr style( *matchedStyle );
1172 Dictionary<Property::Map> instancedProperties;
1173 style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties );
1175 else // If there were no styles, instead set properties
1177 SetProperties( node, handle, constant );
1179 ApplySignals( root, node, handle );
1180 ApplyStylesByActor( root, node, handle, constant );
1183 void Builder::RecordStyle( StylePtr style,
1184 const TreeNode& node,
1185 Dali::Handle& handle,
1186 const Replacement& replacements )
1188 // With repeated calls, accumulate inherited states, visuals and properties
1189 // but override any with same name
1191 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1193 const TreeNode::KeyNodePair& keyValue = *iter;
1194 std::string key( keyValue.first );
1195 if( key == KEYNAME_STATES )
1197 const TreeNode& states = keyValue.second;
1198 if( states.GetType() != TreeNode::OBJECT )
1200 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
1204 for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
1206 const TreeNode& stateNode = (*iter).second;
1207 const char* stateName = stateNode.GetName();
1208 if( stateNode.GetType() != TreeNode::OBJECT )
1210 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
1214 StylePtr* stylePtr = style->subStates.Find( stateName );
1217 StylePtr style(*stylePtr);
1218 RecordStyle( style, stateNode, handle, replacements );
1222 StylePtr subState = Style::New();
1223 RecordStyle( subState, stateNode, handle, replacements );
1224 style->subStates.Add( stateName, subState );
1228 else if( key == KEYNAME_VISUALS )
1230 for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
1232 // Each key in this table should be a property name matching a visual.
1233 const TreeNode::KeyNodePair& visual = *iter;
1234 Dali::Property::Value property(Property::MAP);
1235 if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
1237 Property::Map* mapPtr = style->visuals.Find( visual.first );
1240 // Override existing visuals
1242 mapPtr->Merge( *property.GetMap() );
1246 Property::Map* map = property.GetMap();
1249 style->visuals.Add( visual.first, *map );
1255 else if( key == KEYNAME_ENTRY_TRANSITION )
1257 RecordTransitionData( keyValue, style->entryTransition, replacements );
1259 else if( key == KEYNAME_EXIT_TRANSITION )
1261 RecordTransitionData( keyValue, style->exitTransition, replacements );
1263 else if( key == KEYNAME_TRANSITIONS )
1265 RecordTransitions( keyValue, style->transitions, replacements );
1267 else if( key == KEYNAME_TYPE ||
1268 key == KEYNAME_ACTORS ||
1269 key == KEYNAME_SIGNALS ||
1270 key == KEYNAME_STYLES ||
1271 key == KEYNAME_MAPPINGS ||
1272 key == KEYNAME_INHERIT )
1276 else // It's a property
1278 Property::Index index;
1279 Property::Value value;
1280 if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
1282 Property::Value* existingValuePtr = style->properties.Find( index );
1283 if( existingValuePtr != NULL )
1285 *existingValuePtr = value; // Overwrite existing property.
1289 style->properties.Add( index, value );
1296 void Builder::RecordTransitions(
1297 const TreeNode::KeyNodePair& keyValue,
1298 Property::Array& value,
1299 const Replacement& replacements )
1301 //@todo add new transitions to style.transitions
1302 // override existing transitions. A transition matches on target & property name
1303 const TreeNode& node = keyValue.second;
1304 if( node.GetType() == TreeNode::ARRAY )
1306 Dali::Property::Value property(Property::ARRAY);
1307 if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
1309 value = *property.GetArray();
1312 else if( node.GetType() == TreeNode::OBJECT )
1314 Dali::Property::Value property(Property::MAP);
1315 if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
1317 Property::Array propertyArray;
1318 propertyArray.Add( property );
1319 value = propertyArray;
1324 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first );
1328 void Builder::RecordTransitionData(
1329 const TreeNode::KeyNodePair& keyValue,
1330 Toolkit::TransitionData& transitionData,
1331 const Replacement& replacements )
1333 const TreeNode& node = keyValue.second;
1334 if( node.GetType() == TreeNode::ARRAY )
1336 Dali::Property::Value property(Property::ARRAY);
1337 if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) )
1339 transitionData = Toolkit::TransitionData::New( *property.GetArray() );
1342 else if( node.GetType() == TreeNode::OBJECT )
1344 Dali::Property::Value property(Property::MAP);
1345 if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
1347 transitionData = Toolkit::TransitionData::New( *property.GetMap() );
1353 // Set properties from node on handle.
1354 void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
1355 Dali::Handle& handle, const Replacement& constant )
1357 SetProperties( node, handle, constant );
1358 ApplySignals( root, node, handle );
1361 void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
1363 Actor actor = Actor::DownCast(handle);
1367 SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1368 SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1373 // Appling by style helper
1374 // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
1375 void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node,
1376 Dali::Handle& handle, const Replacement& constant )
1378 if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
1380 if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
1382 // in a style the actor subtree properties referenced by actor name
1383 for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
1385 Dali::Actor foundActor;
1389 foundActor = actor.FindChildByName( (*iter).first );
1394 DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
1398 DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
1399 ApplyProperties( root, (*iter).second, foundActor, constant );
1407 * Sets the handle properties found in the tree node
1409 void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
1413 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1415 const TreeNode::KeyNodePair& keyChild = *iter;
1417 std::string key( keyChild.first );
1419 // ignore special fields;
1420 if( key == KEYNAME_TYPE ||
1421 key == KEYNAME_ACTORS ||
1422 key == KEYNAME_SIGNALS ||
1423 key == KEYNAME_STYLES ||
1424 key == KEYNAME_MAPPINGS ||
1425 key == KEYNAME_INHERIT ||
1426 key == KEYNAME_STATES ||
1427 key == KEYNAME_VISUALS ||
1428 key == KEYNAME_ENTRY_TRANSITION ||
1429 key == KEYNAME_EXIT_TRANSITION ||
1430 key == KEYNAME_TRANSITIONS )
1435 Property::Index index;
1436 Property::Value value;
1438 bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
1441 DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
1443 handle.SetProperty( index, value );
1446 // Add custom properties
1447 SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
1448 SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
1450 } // for property nodes
1454 DALI_SCRIPT_WARNING("Style applied to empty handle\n");
1458 bool Builder::MapToTargetProperty(
1459 Handle& propertyObject,
1460 const std::string& key,
1461 const TreeNode& node,
1462 const Replacement& constant,
1463 Property::Index& index,
1464 Property::Value& value )
1466 bool mapped = false;
1468 index = propertyObject.GetPropertyIndex( key );
1469 if( Property::INVALID_INDEX != index )
1471 Property::Type type = propertyObject.GetPropertyType(index);
1473 // if node.value is a mapping, get the property value from the "mappings" table
1474 if( node.GetType() == TreeNode::STRING )
1476 std::string mappingKey;
1477 if( GetMappingKey( node.GetString(), mappingKey) )
1479 OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
1480 mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
1485 mapped = DeterminePropertyFromNode( node, type, value, constant );
1488 // Just determine the property from the node and if it's valid, let the property object handle it
1489 DeterminePropertyFromNode( node, value, constant );
1490 mapped = ( value.GetType() != Property::NONE );
1496 DALI_LOG_ERROR("Key '%s' not found.\n", key.c_str());
1501 bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
1504 return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
1507 bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
1509 Replacement replacer( mReplacementMap );
1510 bool result = false;
1512 keyStack.push_back( theKey );
1514 for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
1516 std::string aKey( (*iter).first );
1517 if( aKey.compare( theKey ) == 0 )
1519 if( propertyType == Property::NONE )
1521 DeterminePropertyFromNode( (*iter).second, value, replacer );
1526 result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
1531 ConvertChildValue(mappingRoot, keyStack, value);
1536 keyStack.pop_back();
1541 bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
1543 bool result = false;
1545 switch( child.GetType() )
1547 case Property::STRING:
1550 if( child.Get( value ) )
1553 if( GetMappingKey( value, key ) )
1555 // Check key for cycles:
1557 for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
1559 if( key.compare(*iter) == 0 )
1561 // key is already in stack; stop.
1562 DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
1563 child = Property::Value("");
1571 // The following call will overwrite the child with the value
1572 // from the mapping.
1573 RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
1583 Property::Map* map = child.GetMap();
1586 for( Property::Map::SizeType i=0; i < map->Count(); ++i )
1588 Property::Value& child = map->GetValue(i);
1589 ConvertChildValue(mappingRoot, keyStack, child);
1595 case Property::ARRAY:
1597 Property::Array* array = child.GetArray();
1600 for( Property::Array::SizeType i=0; i < array->Count(); ++i )
1602 Property::Value& child = array->GetElementAt(i);
1603 ConvertChildValue(mappingRoot, keyStack, child);
1610 // Ignore other types.
1617 void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
1618 const std::string& childName, Property::AccessMode accessMode )
1620 // Add custom properties
1621 if( OptionalChild customPropertiesChild = IsChild(node, childName) )
1623 const TreeNode& customPropertiesNode = *customPropertiesChild;
1624 const TreeConstIter endIter = customPropertiesNode.CEnd();
1625 for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
1627 const TreeNode::KeyNodePair& keyChild = *iter;
1628 std::string key( keyChild.first );
1629 Property::Value value;
1630 DeterminePropertyFromNode( keyChild.second, value, constant );
1632 // Register/Set property.
1633 handle.RegisterProperty( key, value, accessMode );
1639 } // namespace Internal
1641 } // namespace Toolkit