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 configuration map
183 LoadConfiguration( *parser.GetRoot(), mConfigurationMap );
184 // load constant map (allows the user to override the constants in the json after loading)
185 LoadConstants( *parser.GetRoot(), mReplacementMap );
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 DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
208 mParser.GetErrorLineNumber(),
209 mParser.GetErrorColumn(),
210 mParser.GetErrorDescription().c_str() );
212 DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
216 DUMP_PARSE_TREE(parser); // This macro only writes out if DEBUG is enabled and the "DUMP_TREE" constant is defined in the stylesheet.
217 DUMP_TEST_MAPPINGS(parser);
219 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
222 void Builder::AddConstants( const Property::Map& map )
224 mReplacementMap.Merge( map );
227 void Builder::AddConstant( const std::string& key, const Property::Value& value )
229 mReplacementMap[key] = value;
232 const Property::Map& Builder::GetConfigurations() const
234 return mConfigurationMap;
237 const Property::Map& Builder::GetConstants() const
239 return mReplacementMap;
242 const Property::Value& Builder::GetConstant( const std::string& key ) const
244 Property::Value* match = mReplacementMap.Find( key );
251 static Property::Value invalid;
256 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
258 Replacement replacement(map, mReplacementMap);
259 return CreateAnimation( animationName, replacement, sourceActor);
262 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
264 Replacement replacement(map, mReplacementMap);
265 return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
268 Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
270 Replacement replacement( mReplacementMap );
272 return CreateAnimation( animationName, replacement, sourceActor );
275 Animation Builder::CreateAnimation( const std::string& animationName )
277 Replacement replacement( mReplacementMap );
279 return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
282 BaseHandle Builder::Create( const std::string& templateName )
284 Replacement replacement( mReplacementMap );
285 return Create( templateName, replacement );
288 BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
290 Replacement replacement( map, mReplacementMap );
291 return Create( templateName, replacement );
294 BaseHandle Builder::CreateFromJson( const std::string& json )
298 // merge in new template, hoping no one else has one named '@temp@'
299 std::string newTemplate =
300 std::string("{\"templates\":{\"@temp@\":") + \
304 if( mParser.Parse(newTemplate) )
306 Replacement replacement( mReplacementMap );
307 ret = Create( "@temp@", replacement );
313 bool Builder::ApplyFromJson( Handle& handle, const std::string& json )
317 // merge new style, hoping no one else has one named '@temp@'
318 std::string newStyle =
319 std::string("{\"styles\":{\"@temp@\":") + \
323 if( mParser.Parse(newStyle) )
325 Replacement replacement( mReplacementMap );
326 ret = ApplyStyle( "@temp@", handle, replacement );
332 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
334 Replacement replacer( mReplacementMap );
335 return ApplyStyle( styleName, handle, replacer );
338 bool Builder::LookupStyleName( const std::string& styleName )
340 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
342 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
343 OptionalChild style = IsChildIgnoreCase( *styles, styleName );
345 if( styles && style )
352 const StylePtr Builder::GetStyle( const std::string& styleName )
354 const StylePtr* style = mStyles.FindConst( styleName );
358 return StylePtr(NULL);
366 void Builder::AddActors( Actor toActor )
368 // 'stage' is the default/by convention section to add from
369 AddActors( "stage", toActor );
372 void Builder::AddActors( const std::string §ionName, Actor toActor )
374 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
376 Property::Map overrideMap;
377 Replacement replacements(overrideMap, mReplacementMap);
379 OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
383 for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
385 // empty actor adds directly to the stage
386 BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
387 Actor actor = Actor::DownCast(baseHandle);
390 toActor.Add( actor );
394 // if were adding the 'stage' section then also check for a render task called stage
395 // to add automatically
396 if( "stage" == sectionName )
398 if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
400 if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
402 CreateRenderTask( "stage" );
409 void Builder::CreateRenderTask( const std::string &name )
411 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
413 Replacement constant(mReplacementMap);
415 const Stage& stage = Stage::GetCurrent();
417 OptionalChild tasks = IsChild(*mParser.GetRoot(), "renderTasks");
422 // Create the tasks from the current task as generally we want
423 // to setup task zero and onwards. Although this does overwrite
424 // the properties of the current task.
426 if( OptionalChild renderTask = IsChild(*tasks, name ) )
428 RenderTaskList list = stage.GetRenderTaskList();
429 unsigned int start = list.GetTaskCount();
434 // zero should have already been created by the stage so really
435 // this case should never happen
436 task = list.CreateTask();
440 TreeNode::ConstIterator iter = (*renderTask).CBegin();
441 task = list.GetTask( start - 1 );
443 SetupTask( task, (*iter).second, constant );
447 for(; iter != (*renderTask).CEnd(); ++iter )
449 task = list.CreateTask();
450 SetupTask( task, (*iter).second, constant );
456 FrameBufferImage Builder::GetFrameBufferImage( const std::string &name )
458 Replacement constant( mReplacementMap );
459 return GetFrameBufferImage(name, constant);
462 FrameBufferImage Builder::GetFrameBufferImage( const std::string &name, const Replacement& constant )
464 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
466 FrameBufferImage ret;
468 ImageLut::const_iterator iter( mFrameBufferImageLut.find( name ) );
469 if( iter != mFrameBufferImageLut.end() )
475 if( OptionalChild images = IsChild( *mParser.GetRoot(), "frameBufferImages") )
477 if( OptionalChild image = IsChild( *images, name ) )
479 Dali::Property::Value property(Property::MAP);
480 if( DeterminePropertyFromNode( *image, Property::MAP, property, constant ) )
482 Property::Map* map = property.GetMap();
486 (*map)[ KEYNAME_TYPE ] = Property::Value(std::string("FrameBufferImage") );
487 ret = FrameBufferImage::DownCast( Dali::Scripting::NewImage( property ) );
488 mFrameBufferImageLut[ name ] = ret;
498 Path Builder::GetPath( const std::string& name )
500 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
504 PathLut::const_iterator iter( mPathLut.find( name ) );
505 if( iter != mPathLut.end() )
511 if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") )
513 if( OptionalChild path = IsChild( *paths, name ) )
516 if( OptionalChild pointsProperty = IsChild( *path, "points") )
518 Dali::Property::Value points(Property::ARRAY);
519 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
522 ret.SetProperty( Path::Property::POINTS, points);
524 //controlPoints property
525 if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") )
527 Dali::Property::Value points(Property::ARRAY);
528 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
530 ret.SetProperty( Path::Property::CONTROL_POINTS, points);
536 float curvature(0.25f);
537 if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") )
539 curvature = *pointsProperty;
541 ret.GenerateControlPoints(curvature);
544 //Add the new path to the hash table for paths
545 mPathLut[ name ] = ret;
550 //Interpolation points not specified
551 DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() );
561 PathConstrainer Builder::GetPathConstrainer( const std::string& name )
563 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
565 //Search the pathConstrainer in the LUT
566 size_t count( mPathConstrainerLut.size() );
567 for( size_t i(0); i!=count; ++i )
569 if( mPathConstrainerLut[i].name == name )
571 //PathConstrainer has already been created
572 return mPathConstrainerLut[i].pathConstrainer;
576 //Create a new PathConstrainer
578 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
580 if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) )
582 OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type")));
585 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
587 else if( *constrainerType == "PathConstrainer")
590 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") )
592 Dali::Property::Value points(Property::ARRAY);
593 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
595 ret = PathConstrainer::New();
596 ret.SetProperty( PathConstrainer::Property::POINTS, points);
598 //controlPoints property
599 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") )
601 Dali::Property::Value points(Property::ARRAY);
602 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
604 ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points);
608 OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) );
611 ret.SetProperty( PathConstrainer::Property::FORWARD, *forward);
614 //Add the new constrainer to the vector of PathConstrainer
615 PathConstrainerEntry entry = {name,ret};
616 mPathConstrainerLut.push_back( entry );
620 //Control points not specified
621 DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() );
627 //Interpolation points not specified
628 DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() );
633 DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() );
642 bool Builder::IsPathConstrainer( const std::string& name )
644 size_t count( mPathConstrainerLut.size() );
645 for( size_t i(0); i!=count; ++i )
647 if( mPathConstrainerLut[i].name == name )
653 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
655 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
657 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
664 return *constrainerType == "PathConstrainer";
671 Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name )
673 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
675 //Search the LinearConstrainer in the LUT
676 size_t count( mLinearConstrainerLut.size() );
677 for( size_t i(0); i!=count; ++i )
679 if( mLinearConstrainerLut[i].name == name )
681 //LinearConstrainer has already been created
682 return mLinearConstrainerLut[i].linearConstrainer;
686 //Create a new LinearConstrainer
687 LinearConstrainer ret;
688 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
690 if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) )
692 OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type")));
695 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
697 else if( *constrainerType == "LinearConstrainer")
700 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") )
702 Dali::Property::Value points(Property::ARRAY);
703 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
705 ret = Dali::LinearConstrainer::New();
706 ret.SetProperty( LinearConstrainer::Property::VALUE, points);
708 //controlPoints property
709 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") )
711 Dali::Property::Value points(Property::ARRAY);
712 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
714 ret.SetProperty( LinearConstrainer::Property::PROGRESS, points);
717 //Add the new constrainer to vector of LinearConstrainer
718 LinearConstrainerEntry entry = {name,ret};
719 mLinearConstrainerLut.push_back( entry );
724 //Interpolation points not specified
725 DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() );
730 DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() );
738 bool Builder::IsLinearConstrainer( const std::string& name )
740 // Search the LinearConstrainer in the LUT
741 size_t count( mLinearConstrainerLut.size() );
742 for( size_t i(0); i!=count; ++i )
744 if( mLinearConstrainerLut[i].name == name )
750 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
752 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
754 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
761 return *constrainerType == "LinearConstrainer";
768 Toolkit::Builder::BuilderSignalType& Builder::QuitSignal()
773 void Builder::EmitQuitSignal()
782 void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap )
784 Replacement replacer(intoMap);
786 if( OptionalChild constants = IsChild(root, "config") )
788 for(TreeNode::ConstIterator iter = (*constants).CBegin();
789 iter != (*constants).CEnd(); ++iter)
791 Dali::Property::Value property;
792 if( (*iter).second.GetName() )
794 DeterminePropertyFromNode( (*iter).second, property, replacer );
795 intoMap[ (*iter).second.GetName() ] = property;
801 void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
803 Replacement replacer(intoMap);
805 if( OptionalChild constants = IsChild(root, "constants") )
807 for(TreeNode::ConstIterator iter = (*constants).CBegin();
808 iter != (*constants).CEnd(); ++iter)
810 Dali::Property::Value property;
811 if( (*iter).second.GetName() )
813 #if defined(DEBUG_ENABLED)
814 DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
816 DeterminePropertyFromNode( (*iter).second, property, replacer );
817 intoMap[ (*iter).second.GetName() ] = property;
822 #if defined(DEBUG_ENABLED)
823 Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
824 if( iter && iter->GetType() == Property::STRING )
826 std::string logLevel( iter->Get< std::string >() );
827 if( logLevel == "NoLogging" )
829 gFilterScript->SetLogLevel( Integration::Log::NoLogging );
831 else if( logLevel == "Concise" )
833 gFilterScript->SetLogLevel( Integration::Log::Concise );
835 else if( logLevel == "General" )
837 gFilterScript->SetLogLevel( Integration::Log::General );
839 else if( logLevel == "Verbose" )
841 gFilterScript->SetLogLevel( Integration::Log::Verbose );
847 Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
849 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
853 if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
855 if( OptionalChild animation = IsChild(*animations, animationName) )
857 anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
861 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
866 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
872 BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
874 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
876 BaseHandle baseHandle;
878 OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
882 DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
886 OptionalChild childTemplate = IsChild(*templates, templateName);
889 DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
893 OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
897 DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
901 baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
910 * Create a dali type from a node.
911 * If parent given and an actor type was created then add it to the parent and
912 * recursively add nodes children.
914 BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
915 Actor parent, const Replacement& replacements )
917 BaseHandle baseHandle;
919 const TreeNode* templateNode = NULL;
921 if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
923 typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
927 // a template name is also allowed inplace of the type name
928 OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
932 if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
934 templateNode = &(*isTemplate);
936 if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
938 typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
947 DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
951 baseHandle = typeInfo.CreateInstance();
952 Handle handle = Handle::DownCast(baseHandle);
953 Actor actor = Actor::DownCast(handle);
958 DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
960 #if defined(DEBUG_ENABLED)
963 DALI_SCRIPT_VERBOSE(" Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
964 DALI_SCRIPT_VERBOSE(" Is Handle Property Count=%d\n", handle.GetPropertyCount());
969 DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetId());
972 Toolkit::Control control = Toolkit::Control::DownCast(handle);
975 DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetId());
977 #endif // DEBUG_ENABLED
981 ApplyProperties( root, *templateNode, handle, replacements );
983 if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
985 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
987 DoCreate( root, (*iter).second, actor, replacements );
994 // add children of all the styles
995 if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
997 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
999 DoCreate( root, (*iter).second, actor, replacements );
1003 // apply style on top as they need the children to exist
1004 ApplyAllStyleProperties( root, node, actor, replacements );
1006 // then add to parent
1009 parent.Add( actor );
1014 ApplyProperties( root, node, handle, replacements );
1019 DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
1026 void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
1028 const Stage& stage = Stage::GetCurrent();
1029 Layer root = stage.GetRootLayer();
1031 if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
1033 Actor actor = root.FindChildByName(*s);
1036 task.SetSourceActor( actor );
1040 DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
1044 if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
1046 CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
1049 task.SetCameraActor( actor );
1053 DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
1057 if( OptionalString s = constant.IsString( IsChild(node, "targetFrameBuffer") ) )
1059 FrameBufferImage fb = GetFrameBufferImage( *s, constant );
1062 task.SetTargetFrameBuffer( fb );
1066 DALI_SCRIPT_WARNING("Cannot find target frame buffer '%s'\n", (*s).c_str() );
1070 if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
1072 if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
1074 task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
1076 else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
1078 task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
1082 DALI_SCRIPT_WARNING("todo");
1086 // other setup is via the property system
1087 SetProperties( node, task, constant );
1090 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
1092 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
1094 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
1096 std::string styleNameLower(styleName);
1097 OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower );
1099 if( styles && style )
1101 ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
1110 void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
1111 Dali::Handle& handle, const Replacement& constant )
1113 const char* styleName = node.GetName();
1115 StylePtr style = Style::New();
1117 StylePtr* matchedStyle = NULL;
1120 matchedStyle = mStyles.Find( styleName );
1121 if( ! matchedStyle )
1123 OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
1124 OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
1125 if( !inheritFromNode )
1127 inheritFromNode = IsChild( node, KEYNAME_STYLES );
1132 if( inheritFromNode )
1134 TreeNodeList additionalStyleNodes;
1136 CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
1138 #if defined(DEBUG_ENABLED)
1139 for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
1141 if( OptionalString styleName = IsString( (*iter).second ) )
1143 DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
1148 // a style may have other styles, which has other styles etc so we apply in reverse by convention.
1149 for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
1151 RecordStyle( style, *(*iter), handle, constant );
1152 ApplySignals( root, *(*iter), handle );
1153 ApplyStylesByActor( root, *(*iter), handle, constant );
1157 RecordStyle( style, node, handle, constant );
1158 mStyles.Add( styleName, style ); // shallow copy
1159 matchedStyle = &style;
1166 StylePtr style( *matchedStyle );
1167 Dictionary<Property::Map> instancedProperties;
1168 style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties );
1170 else // If there were no styles, instead set properties
1172 SetProperties( node, handle, constant );
1174 ApplySignals( root, node, handle );
1175 ApplyStylesByActor( root, node, handle, constant );
1178 void Builder::RecordStyle( StylePtr style,
1179 const TreeNode& node,
1180 Dali::Handle& handle,
1181 const Replacement& replacements )
1183 // With repeated calls, accumulate inherited states, visuals and properties
1184 // but override any with same name
1186 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1188 const TreeNode::KeyNodePair& keyValue = *iter;
1189 std::string key( keyValue.first );
1190 if( key == KEYNAME_STATES )
1192 const TreeNode& states = keyValue.second;
1193 if( states.GetType() != TreeNode::OBJECT )
1195 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
1199 for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
1201 const TreeNode& stateNode = (*iter).second;
1202 const char* stateName = stateNode.GetName();
1203 if( stateNode.GetType() != TreeNode::OBJECT )
1205 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
1209 StylePtr* stylePtr = style->subStates.Find( stateName );
1212 StylePtr style(*stylePtr);
1213 RecordStyle( style, stateNode, handle, replacements );
1217 StylePtr subState = Style::New();
1218 RecordStyle( subState, stateNode, handle, replacements );
1219 style->subStates.Add( stateName, subState );
1223 else if( key == KEYNAME_VISUALS )
1225 for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
1227 // Each key in this table should be a property name matching a visual.
1228 const TreeNode::KeyNodePair& visual = *iter;
1229 Dali::Property::Value property(Property::MAP);
1230 if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
1232 Property::Map* mapPtr = style->visuals.Find( visual.first );
1235 // Override existing visuals
1237 mapPtr->Merge( *property.GetMap() );
1241 style->visuals.Add(visual.first, *property.GetMap());
1246 else if( key == KEYNAME_ENTRY_TRANSITION )
1248 RecordTransitionData( keyValue, style->entryTransition, replacements );
1250 else if( key == KEYNAME_EXIT_TRANSITION )
1252 RecordTransitionData( keyValue, style->exitTransition, replacements );
1254 else if( key == KEYNAME_TRANSITIONS )
1256 RecordTransitions( keyValue, style->transitions, replacements );
1258 else if( key == KEYNAME_TYPE ||
1259 key == KEYNAME_ACTORS ||
1260 key == KEYNAME_SIGNALS ||
1261 key == KEYNAME_STYLES ||
1262 key == KEYNAME_MAPPINGS ||
1263 key == KEYNAME_INHERIT )
1267 else // It's a property
1269 Property::Index index;
1270 Property::Value value;
1271 if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
1273 Property::Value* existingValuePtr = style->properties.Find( index );
1274 if( existingValuePtr != NULL )
1276 *existingValuePtr = value; // Overwrite existing property.
1280 style->properties.Add( index, value );
1287 void Builder::RecordTransitions(
1288 const TreeNode::KeyNodePair& keyValue,
1289 Property::Array& value,
1290 const Replacement& replacements )
1292 //@todo add new transitions to style.transitions
1293 // override existing transitions. A transition matches on target & property name
1294 const TreeNode& node = keyValue.second;
1295 if( node.GetType() == TreeNode::ARRAY )
1297 Dali::Property::Value property(Property::ARRAY);
1298 if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
1300 value = *property.GetArray();
1303 else if( node.GetType() == TreeNode::OBJECT )
1305 Dali::Property::Value property(Property::MAP);
1306 if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
1308 Property::Array propertyArray;
1309 propertyArray.Add( property );
1310 value = propertyArray;
1315 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first );
1319 void Builder::RecordTransitionData(
1320 const TreeNode::KeyNodePair& keyValue,
1321 Toolkit::TransitionData& transitionData,
1322 const Replacement& replacements )
1324 const TreeNode& node = keyValue.second;
1325 if( node.GetType() == TreeNode::ARRAY )
1327 Dali::Property::Value property(Property::ARRAY);
1328 if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) )
1330 transitionData = Toolkit::TransitionData::New( *property.GetArray() );
1333 else if( node.GetType() == TreeNode::OBJECT )
1335 Dali::Property::Value property(Property::MAP);
1336 if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
1338 transitionData = Toolkit::TransitionData::New( *property.GetMap() );
1344 // Set properties from node on handle.
1345 void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
1346 Dali::Handle& handle, const Replacement& constant )
1348 SetProperties( node, handle, constant );
1349 ApplySignals( root, node, handle );
1352 void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
1354 Actor actor = Actor::DownCast(handle);
1358 SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1359 SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1364 // Appling by style helper
1365 // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
1366 void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node,
1367 Dali::Handle& handle, const Replacement& constant )
1369 if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
1371 if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
1373 // in a style the actor subtree properties referenced by actor name
1374 for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
1376 Dali::Actor foundActor;
1380 foundActor = actor.FindChildByName( (*iter).first );
1385 DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
1389 DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
1390 ApplyProperties( root, (*iter).second, foundActor, constant );
1398 * Sets the handle properties found in the tree node
1400 void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
1404 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1406 const TreeNode::KeyNodePair& keyChild = *iter;
1408 std::string key( keyChild.first );
1410 // ignore special fields;
1411 if( key == KEYNAME_TYPE ||
1412 key == KEYNAME_ACTORS ||
1413 key == KEYNAME_SIGNALS ||
1414 key == KEYNAME_STYLES ||
1415 key == KEYNAME_MAPPINGS ||
1416 key == KEYNAME_INHERIT ||
1417 key == KEYNAME_STATES ||
1418 key == KEYNAME_VISUALS ||
1419 key == KEYNAME_ENTRY_TRANSITION ||
1420 key == KEYNAME_EXIT_TRANSITION ||
1421 key == KEYNAME_TRANSITIONS )
1426 Property::Index index;
1427 Property::Value value;
1429 bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
1432 DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
1434 handle.SetProperty( index, value );
1437 // Add custom properties
1438 SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
1439 SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
1441 } // for property nodes
1445 DALI_SCRIPT_WARNING("Style applied to empty handle\n");
1449 bool Builder::MapToTargetProperty(
1450 Handle& propertyObject,
1451 const std::string& key,
1452 const TreeNode& node,
1453 const Replacement& constant,
1454 Property::Index& index,
1455 Property::Value& value )
1457 bool mapped = false;
1459 index = propertyObject.GetPropertyIndex( key );
1460 if( Property::INVALID_INDEX != index )
1462 Property::Type type = propertyObject.GetPropertyType(index);
1464 // if node.value is a mapping, get the property value from the "mappings" table
1465 if( node.GetType() == TreeNode::STRING )
1467 std::string mappingKey;
1468 if( GetMappingKey( node.GetString(), mappingKey) )
1470 OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
1471 mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
1476 mapped = DeterminePropertyFromNode( node, type, value, constant );
1479 // Just determine the property from the node and if it's valid, let the property object handle it
1480 DeterminePropertyFromNode( node, value, constant );
1481 mapped = ( value.GetType() != Property::NONE );
1487 DALI_LOG_ERROR("Key '%s' not found.\n", key.c_str());
1492 bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
1495 return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
1498 bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
1500 Replacement replacer( mReplacementMap );
1501 bool result = false;
1503 keyStack.push_back( theKey );
1505 for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
1507 std::string aKey( (*iter).first );
1508 if( aKey.compare( theKey ) == 0 )
1510 if( propertyType == Property::NONE )
1512 DeterminePropertyFromNode( (*iter).second, value, replacer );
1517 result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
1522 ConvertChildValue(mappingRoot, keyStack, value);
1527 keyStack.pop_back();
1532 bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
1534 bool result = false;
1536 switch( child.GetType() )
1538 case Property::STRING:
1541 if( child.Get( value ) )
1544 if( GetMappingKey( value, key ) )
1546 // Check key for cycles:
1548 for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
1550 if( key.compare(*iter) == 0 )
1552 // key is already in stack; stop.
1553 DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
1554 child = Property::Value("");
1562 // The following call will overwrite the child with the value
1563 // from the mapping.
1564 RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
1574 Property::Map* map = child.GetMap();
1577 for( Property::Map::SizeType i=0; i < map->Count(); ++i )
1579 Property::Value& child = map->GetValue(i);
1580 ConvertChildValue(mappingRoot, keyStack, child);
1586 case Property::ARRAY:
1588 Property::Array* array = child.GetArray();
1591 for( Property::Array::SizeType i=0; i < array->Count(); ++i )
1593 Property::Value& child = array->GetElementAt(i);
1594 ConvertChildValue(mappingRoot, keyStack, child);
1601 // Ignore other types.
1608 void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
1609 const std::string& childName, Property::AccessMode accessMode )
1611 // Add custom properties
1612 if( OptionalChild customPropertiesChild = IsChild(node, childName) )
1614 const TreeNode& customPropertiesNode = *customPropertiesChild;
1615 const TreeConstIter endIter = customPropertiesNode.CEnd();
1616 for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
1618 const TreeNode::KeyNodePair& keyChild = *iter;
1619 std::string key( keyChild.first );
1620 Property::Value value;
1621 DeterminePropertyFromNode( keyChild.second, value, constant );
1623 // Register/Set property.
1624 handle.RegisterProperty( key, value, accessMode );
1630 } // namespace Internal
1632 } // namespace Toolkit