2 * Copyright (c) 2016 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 FrameBufferImage Builder::GetFrameBufferImage( const std::string &name )
463 Replacement constant( mReplacementMap );
464 return GetFrameBufferImage(name, constant);
467 FrameBufferImage Builder::GetFrameBufferImage( const std::string &name, const Replacement& constant )
469 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
471 FrameBufferImage ret;
473 ImageLut::const_iterator iter( mFrameBufferImageLut.find( name ) );
474 if( iter != mFrameBufferImageLut.end() )
480 if( OptionalChild images = IsChild( *mParser.GetRoot(), "frameBufferImages") )
482 if( OptionalChild image = IsChild( *images, name ) )
484 Dali::Property::Value property(Property::MAP);
485 if( DeterminePropertyFromNode( *image, Property::MAP, property, constant ) )
487 Property::Map* map = property.GetMap();
491 (*map)[ KEYNAME_TYPE ] = Property::Value(std::string("FrameBufferImage") );
492 ret = FrameBufferImage::DownCast( Dali::Scripting::NewImage( property ) );
493 mFrameBufferImageLut[ name ] = ret;
503 Path Builder::GetPath( const std::string& name )
505 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
509 PathLut::const_iterator iter( mPathLut.find( name ) );
510 if( iter != mPathLut.end() )
516 if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") )
518 if( OptionalChild path = IsChild( *paths, name ) )
521 if( OptionalChild pointsProperty = IsChild( *path, "points") )
523 Dali::Property::Value points(Property::ARRAY);
524 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
527 ret.SetProperty( Path::Property::POINTS, points);
529 //controlPoints property
530 if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") )
532 Dali::Property::Value points(Property::ARRAY);
533 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
535 ret.SetProperty( Path::Property::CONTROL_POINTS, points);
541 float curvature(0.25f);
542 if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") )
544 curvature = *pointsProperty;
546 ret.GenerateControlPoints(curvature);
549 //Add the new path to the hash table for paths
550 mPathLut[ name ] = ret;
555 //Interpolation points not specified
556 DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() );
566 PathConstrainer Builder::GetPathConstrainer( const std::string& name )
568 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
570 //Search the pathConstrainer in the LUT
571 size_t count( mPathConstrainerLut.size() );
572 for( size_t i(0); i!=count; ++i )
574 if( mPathConstrainerLut[i].name == name )
576 //PathConstrainer has already been created
577 return mPathConstrainerLut[i].pathConstrainer;
581 //Create a new PathConstrainer
583 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
585 if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) )
587 OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type")));
590 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
592 else if( *constrainerType == "PathConstrainer")
595 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") )
597 Dali::Property::Value points(Property::ARRAY);
598 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
600 ret = PathConstrainer::New();
601 ret.SetProperty( PathConstrainer::Property::POINTS, points);
603 //controlPoints property
604 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") )
606 Dali::Property::Value points(Property::ARRAY);
607 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
609 ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points);
613 OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) );
616 ret.SetProperty( PathConstrainer::Property::FORWARD, *forward);
619 //Add the new constrainer to the vector of PathConstrainer
620 PathConstrainerEntry entry = {name,ret};
621 mPathConstrainerLut.push_back( entry );
625 //Control points not specified
626 DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() );
632 //Interpolation points not specified
633 DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() );
638 DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() );
647 bool Builder::IsPathConstrainer( const std::string& name )
649 size_t count( mPathConstrainerLut.size() );
650 for( size_t i(0); i!=count; ++i )
652 if( mPathConstrainerLut[i].name == name )
658 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
660 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
662 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
669 return *constrainerType == "PathConstrainer";
676 Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name )
678 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
680 //Search the LinearConstrainer in the LUT
681 size_t count( mLinearConstrainerLut.size() );
682 for( size_t i(0); i!=count; ++i )
684 if( mLinearConstrainerLut[i].name == name )
686 //LinearConstrainer has already been created
687 return mLinearConstrainerLut[i].linearConstrainer;
691 //Create a new LinearConstrainer
692 LinearConstrainer ret;
693 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
695 if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) )
697 OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type")));
700 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
702 else if( *constrainerType == "LinearConstrainer")
705 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") )
707 Dali::Property::Value points(Property::ARRAY);
708 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
710 ret = Dali::LinearConstrainer::New();
711 ret.SetProperty( LinearConstrainer::Property::VALUE, points);
713 //controlPoints property
714 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") )
716 Dali::Property::Value points(Property::ARRAY);
717 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
719 ret.SetProperty( LinearConstrainer::Property::PROGRESS, points);
722 //Add the new constrainer to vector of LinearConstrainer
723 LinearConstrainerEntry entry = {name,ret};
724 mLinearConstrainerLut.push_back( entry );
729 //Interpolation points not specified
730 DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() );
735 DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() );
743 bool Builder::IsLinearConstrainer( const std::string& name )
745 // Search the LinearConstrainer in the LUT
746 size_t count( mLinearConstrainerLut.size() );
747 for( size_t i(0); i!=count; ++i )
749 if( mLinearConstrainerLut[i].name == name )
755 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
757 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
759 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
766 return *constrainerType == "LinearConstrainer";
773 Toolkit::Builder::BuilderSignalType& Builder::QuitSignal()
778 void Builder::EmitQuitSignal()
787 void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap )
789 Replacement replacer(intoMap);
791 if( OptionalChild constants = IsChild(root, "config") )
793 for(TreeNode::ConstIterator iter = (*constants).CBegin();
794 iter != (*constants).CEnd(); ++iter)
796 Dali::Property::Value property;
797 if( (*iter).second.GetName() )
799 DeterminePropertyFromNode( (*iter).second, property, replacer );
801 // If config is string, find constant and replace it to original value.
802 if( (*iter).second.GetType() == TreeNode::STRING )
804 std::string stringConfigValue;
805 if( property.Get( stringConfigValue ) )
809 while( pos < stringConfigValue.size() )
811 // If we can't find "{","}" pair in stringConfigValue, will out loop.
812 std::size_t leftPos = stringConfigValue.find( "{", pos );
813 if( leftPos != std::string::npos )
815 std::size_t rightPos = stringConfigValue.find( "}", pos+1 );
817 if( rightPos != std::string::npos )
819 // If we find "{","}" pair but can't find matched constant
820 // try to find other "{","}" pair after current left position.
823 for( unsigned int i = 0; i < mReplacementMap.Count() ; i++ )
825 std::string constant = mReplacementMap.GetKey(i);
827 // Compare string which is between "{" and "}" with constant string
828 // If they are same, change string in stringConfigValue to mapped constant value.
829 if ( stringConfigValue.compare( leftPos+1, rightPos-leftPos-1,constant) == 0 )
831 std::string replaceString;
832 mReplacementMap.GetValue(i).Get( replaceString );
834 stringConfigValue.replace( leftPos, rightPos-leftPos+1, replaceString );
835 pos = leftPos + replaceString.size();
842 // If we cannot find constant in const value, will out loop.
843 pos = stringConfigValue.size();
848 // If we cannot find constant in const value, will out loop.
849 pos = stringConfigValue.size();
852 property = Property::Value( stringConfigValue );
855 intoMap[ (*iter).second.GetName() ] = property;
861 void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
863 Replacement replacer(intoMap);
865 if( OptionalChild constants = IsChild(root, "constants") )
867 for(TreeNode::ConstIterator iter = (*constants).CBegin();
868 iter != (*constants).CEnd(); ++iter)
870 Dali::Property::Value property;
871 if( (*iter).second.GetName() )
873 #if defined(DEBUG_ENABLED)
874 DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
876 DeterminePropertyFromNode( (*iter).second, property, replacer );
877 intoMap[ (*iter).second.GetName() ] = property;
882 #if defined(DEBUG_ENABLED)
883 Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
884 if( iter && iter->GetType() == Property::STRING )
886 std::string logLevel( iter->Get< std::string >() );
887 if( logLevel == "NoLogging" )
889 gFilterScript->SetLogLevel( Integration::Log::NoLogging );
891 else if( logLevel == "Concise" )
893 gFilterScript->SetLogLevel( Integration::Log::Concise );
895 else if( logLevel == "General" )
897 gFilterScript->SetLogLevel( Integration::Log::General );
899 else if( logLevel == "Verbose" )
901 gFilterScript->SetLogLevel( Integration::Log::Verbose );
907 Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
909 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
913 if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
915 if( OptionalChild animation = IsChild(*animations, animationName) )
917 anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
921 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
926 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
932 BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
934 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
936 BaseHandle baseHandle;
938 OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
942 DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
946 OptionalChild childTemplate = IsChild(*templates, templateName);
949 DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
953 OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
957 DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
961 baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
970 * Create a dali type from a node.
971 * If parent given and an actor type was created then add it to the parent and
972 * recursively add nodes children.
974 BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
975 Actor parent, const Replacement& replacements )
977 BaseHandle baseHandle;
979 const TreeNode* templateNode = NULL;
981 if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
983 typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
987 // a template name is also allowed inplace of the type name
988 OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
992 if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
994 templateNode = &(*isTemplate);
996 if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
998 typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
1007 DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
1011 baseHandle = typeInfo.CreateInstance();
1012 Handle handle = Handle::DownCast(baseHandle);
1013 Actor actor = Actor::DownCast(handle);
1018 DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
1020 #if defined(DEBUG_ENABLED)
1023 DALI_SCRIPT_VERBOSE(" Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
1024 DALI_SCRIPT_VERBOSE(" Is Handle Property Count=%d\n", handle.GetPropertyCount());
1029 DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetId());
1032 Toolkit::Control control = Toolkit::Control::DownCast(handle);
1035 DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetId());
1037 #endif // DEBUG_ENABLED
1041 ApplyProperties( root, *templateNode, handle, replacements );
1043 if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
1045 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1047 DoCreate( root, (*iter).second, actor, replacements );
1054 // add children of all the styles
1055 if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
1057 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1059 DoCreate( root, (*iter).second, actor, replacements );
1063 // apply style on top as they need the children to exist
1064 ApplyAllStyleProperties( root, node, actor, replacements );
1066 // then add to parent
1069 parent.Add( actor );
1074 ApplyProperties( root, node, handle, replacements );
1079 DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
1086 void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
1088 const Stage& stage = Stage::GetCurrent();
1089 Layer root = stage.GetRootLayer();
1091 if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
1093 Actor actor = root.FindChildByName(*s);
1096 task.SetSourceActor( actor );
1100 DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
1104 if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
1106 CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
1109 task.SetCameraActor( actor );
1113 DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
1117 if( OptionalString s = constant.IsString( IsChild(node, "targetFrameBuffer") ) )
1119 FrameBufferImage fb = GetFrameBufferImage( *s, constant );
1122 task.SetTargetFrameBuffer( fb );
1126 DALI_SCRIPT_WARNING("Cannot find target frame buffer '%s'\n", (*s).c_str() );
1130 if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
1132 if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
1134 task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
1136 else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
1138 task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
1142 DALI_SCRIPT_WARNING("todo");
1146 // other setup is via the property system
1147 SetProperties( node, task, constant );
1150 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
1152 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
1154 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
1156 std::string styleNameLower(styleName);
1157 OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower );
1159 if( styles && style )
1161 ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
1170 void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
1171 Dali::Handle& handle, const Replacement& constant )
1173 const char* styleName = node.GetName();
1175 StylePtr style = Style::New();
1177 StylePtr* matchedStyle = NULL;
1180 matchedStyle = mStyles.Find( styleName );
1181 if( ! matchedStyle )
1183 OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
1184 OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
1185 if( !inheritFromNode )
1187 inheritFromNode = IsChild( node, KEYNAME_STYLES );
1192 if( inheritFromNode )
1194 TreeNodeList additionalStyleNodes;
1196 CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
1198 #if defined(DEBUG_ENABLED)
1199 for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
1201 if( OptionalString styleName = IsString( (*iter).second ) )
1203 DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
1208 // a style may have other styles, which has other styles etc so we apply in reverse by convention.
1209 for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
1211 RecordStyle( style, *(*iter), handle, constant );
1212 ApplySignals( root, *(*iter), handle );
1213 ApplyStylesByActor( root, *(*iter), handle, constant );
1217 RecordStyle( style, node, handle, constant );
1218 mStyles.Add( styleName, style ); // shallow copy
1219 matchedStyle = &style;
1226 StylePtr style( *matchedStyle );
1227 Dictionary<Property::Map> instancedProperties;
1228 style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties );
1230 else // If there were no styles, instead set properties
1232 SetProperties( node, handle, constant );
1234 ApplySignals( root, node, handle );
1235 ApplyStylesByActor( root, node, handle, constant );
1238 void Builder::RecordStyle( StylePtr style,
1239 const TreeNode& node,
1240 Dali::Handle& handle,
1241 const Replacement& replacements )
1243 // With repeated calls, accumulate inherited states, visuals and properties
1244 // but override any with same name
1246 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1248 const TreeNode::KeyNodePair& keyValue = *iter;
1249 std::string key( keyValue.first );
1250 if( key == KEYNAME_STATES )
1252 const TreeNode& states = keyValue.second;
1253 if( states.GetType() != TreeNode::OBJECT )
1255 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
1259 for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
1261 const TreeNode& stateNode = (*iter).second;
1262 const char* stateName = stateNode.GetName();
1263 if( stateNode.GetType() != TreeNode::OBJECT )
1265 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
1269 StylePtr* stylePtr = style->subStates.Find( stateName );
1272 StylePtr style(*stylePtr);
1273 RecordStyle( style, stateNode, handle, replacements );
1277 StylePtr subState = Style::New();
1278 RecordStyle( subState, stateNode, handle, replacements );
1279 style->subStates.Add( stateName, subState );
1283 else if( key == KEYNAME_VISUALS )
1285 for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
1287 // Each key in this table should be a property name matching a visual.
1288 const TreeNode::KeyNodePair& visual = *iter;
1289 Dali::Property::Value property(Property::MAP);
1290 if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
1292 Property::Map* mapPtr = style->visuals.Find( visual.first );
1295 // Override existing visuals
1297 mapPtr->Merge( *property.GetMap() );
1301 Property::Map* map = property.GetMap();
1304 style->visuals.Add( visual.first, *map );
1310 else if( key == KEYNAME_ENTRY_TRANSITION )
1312 RecordTransitionData( keyValue, style->entryTransition, replacements );
1314 else if( key == KEYNAME_EXIT_TRANSITION )
1316 RecordTransitionData( keyValue, style->exitTransition, replacements );
1318 else if( key == KEYNAME_TRANSITIONS )
1320 RecordTransitions( keyValue, style->transitions, replacements );
1322 else if( key == KEYNAME_TYPE ||
1323 key == KEYNAME_ACTORS ||
1324 key == KEYNAME_SIGNALS ||
1325 key == KEYNAME_STYLES ||
1326 key == KEYNAME_MAPPINGS ||
1327 key == KEYNAME_INHERIT )
1331 else // It's a property
1333 Property::Index index;
1334 Property::Value value;
1335 if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
1337 Property::Value* existingValuePtr = style->properties.Find( index );
1338 if( existingValuePtr != NULL )
1340 *existingValuePtr = value; // Overwrite existing property.
1344 style->properties.Add( index, value );
1351 void Builder::RecordTransitions(
1352 const TreeNode::KeyNodePair& keyValue,
1353 Property::Array& value,
1354 const Replacement& replacements )
1356 //@todo add new transitions to style.transitions
1357 // override existing transitions. A transition matches on target & property name
1358 const TreeNode& node = keyValue.second;
1359 if( node.GetType() == TreeNode::ARRAY )
1361 Dali::Property::Value property(Property::ARRAY);
1362 if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
1364 value = *property.GetArray();
1367 else if( node.GetType() == TreeNode::OBJECT )
1369 Dali::Property::Value property(Property::MAP);
1370 if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
1372 Property::Array propertyArray;
1373 propertyArray.Add( property );
1374 value = propertyArray;
1379 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first );
1383 void Builder::RecordTransitionData(
1384 const TreeNode::KeyNodePair& keyValue,
1385 Toolkit::TransitionData& transitionData,
1386 const Replacement& replacements )
1388 const TreeNode& node = keyValue.second;
1389 if( node.GetType() == TreeNode::ARRAY )
1391 Dali::Property::Value property(Property::ARRAY);
1392 if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) )
1394 transitionData = Toolkit::TransitionData::New( *property.GetArray() );
1397 else if( node.GetType() == TreeNode::OBJECT )
1399 Dali::Property::Value property(Property::MAP);
1400 if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
1402 transitionData = Toolkit::TransitionData::New( *property.GetMap() );
1408 // Set properties from node on handle.
1409 void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
1410 Dali::Handle& handle, const Replacement& constant )
1412 SetProperties( node, handle, constant );
1413 ApplySignals( root, node, handle );
1416 void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
1418 Actor actor = Actor::DownCast(handle);
1422 SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1423 SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1428 // Appling by style helper
1429 // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
1430 void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node,
1431 Dali::Handle& handle, const Replacement& constant )
1433 if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
1435 if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
1437 // in a style the actor subtree properties referenced by actor name
1438 for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
1440 Dali::Actor foundActor;
1444 foundActor = actor.FindChildByName( (*iter).first );
1449 DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
1453 DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
1454 ApplyProperties( root, (*iter).second, foundActor, constant );
1462 * Sets the handle properties found in the tree node
1464 void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
1468 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1470 const TreeNode::KeyNodePair& keyChild = *iter;
1472 std::string key( keyChild.first );
1474 // ignore special fields;
1475 if( key == KEYNAME_TYPE ||
1476 key == KEYNAME_ACTORS ||
1477 key == KEYNAME_SIGNALS ||
1478 key == KEYNAME_STYLES ||
1479 key == KEYNAME_MAPPINGS ||
1480 key == KEYNAME_INHERIT ||
1481 key == KEYNAME_STATES ||
1482 key == KEYNAME_VISUALS ||
1483 key == KEYNAME_ENTRY_TRANSITION ||
1484 key == KEYNAME_EXIT_TRANSITION ||
1485 key == KEYNAME_TRANSITIONS )
1490 Property::Index index;
1491 Property::Value value;
1493 bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
1496 DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
1498 handle.SetProperty( index, value );
1501 // Add custom properties
1502 SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
1503 SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
1505 } // for property nodes
1509 DALI_SCRIPT_WARNING("Style applied to empty handle\n");
1513 bool Builder::MapToTargetProperty(
1514 Handle& propertyObject,
1515 const std::string& key,
1516 const TreeNode& node,
1517 const Replacement& constant,
1518 Property::Index& index,
1519 Property::Value& value )
1521 bool mapped = false;
1523 index = propertyObject.GetPropertyIndex( key );
1524 if( Property::INVALID_INDEX != index )
1526 Property::Type type = propertyObject.GetPropertyType(index);
1528 // if node.value is a mapping, get the property value from the "mappings" table
1529 if( node.GetType() == TreeNode::STRING )
1531 std::string mappingKey;
1532 if( GetMappingKey( node.GetString(), mappingKey) )
1534 OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
1535 mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
1540 mapped = DeterminePropertyFromNode( node, type, value, constant );
1543 // Just determine the property from the node and if it's valid, let the property object handle it
1544 DeterminePropertyFromNode( node, value, constant );
1545 mapped = ( value.GetType() != Property::NONE );
1551 DALI_LOG_ERROR("Key '%s' not found.\n", key.c_str());
1556 bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
1559 return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
1562 bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
1564 Replacement replacer( mReplacementMap );
1565 bool result = false;
1567 keyStack.push_back( theKey );
1569 for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
1571 std::string aKey( (*iter).first );
1572 if( aKey.compare( theKey ) == 0 )
1574 if( propertyType == Property::NONE )
1576 DeterminePropertyFromNode( (*iter).second, value, replacer );
1581 result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
1586 ConvertChildValue(mappingRoot, keyStack, value);
1591 keyStack.pop_back();
1596 bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
1598 bool result = false;
1600 switch( child.GetType() )
1602 case Property::STRING:
1605 if( child.Get( value ) )
1608 if( GetMappingKey( value, key ) )
1610 // Check key for cycles:
1612 for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
1614 if( key.compare(*iter) == 0 )
1616 // key is already in stack; stop.
1617 DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
1618 child = Property::Value("");
1626 // The following call will overwrite the child with the value
1627 // from the mapping.
1628 RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
1638 Property::Map* map = child.GetMap();
1641 for( Property::Map::SizeType i=0; i < map->Count(); ++i )
1643 Property::Value& child = map->GetValue(i);
1644 ConvertChildValue(mappingRoot, keyStack, child);
1650 case Property::ARRAY:
1652 Property::Array* array = child.GetArray();
1655 for( Property::Array::SizeType i=0; i < array->Count(); ++i )
1657 Property::Value& child = array->GetElementAt(i);
1658 ConvertChildValue(mappingRoot, keyStack, child);
1665 // Ignore other types.
1672 void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
1673 const std::string& childName, Property::AccessMode accessMode )
1675 // Add custom properties
1676 if( OptionalChild customPropertiesChild = IsChild(node, childName) )
1678 const TreeNode& customPropertiesNode = *customPropertiesChild;
1679 const TreeConstIter endIter = customPropertiesNode.CEnd();
1680 for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
1682 const TreeNode::KeyNodePair& keyChild = *iter;
1683 std::string key( keyChild.first );
1684 Property::Value value;
1685 DeterminePropertyFromNode( keyChild.second, value, constant );
1687 // Register/Set property.
1688 handle.RegisterProperty( key, value, accessMode );
1694 } // namespace Internal
1696 } // namespace Toolkit