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/asset-manager/asset-manager.h>
39 #include <dali-toolkit/devel-api/builder/json-parser.h>
41 #include <dali-toolkit/internal/builder/builder-declarations.h>
42 #include <dali-toolkit/internal/builder/builder-filesystem.h>
43 #include <dali-toolkit/internal/builder/builder-get-is.inl.h>
44 #include <dali-toolkit/internal/builder/builder-impl-debug.h>
45 #include <dali-toolkit/internal/builder/builder-set-property.h>
46 #include <dali-toolkit/internal/builder/replacement.h>
47 #include <dali-toolkit/internal/builder/tree-node-manipulator.h>
59 extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder );
61 extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
63 extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
66 #if defined(DEBUG_ENABLED)
67 Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT");
73 #define TOKEN_STRING(x) #x
75 const std::string KEYNAME_ACTORS = "actors";
76 const std::string KEYNAME_ENTRY_TRANSITION = "entryTransition";
77 const std::string KEYNAME_EXIT_TRANSITION = "exitTransition";
78 const std::string KEYNAME_INCLUDES = "includes";
79 const std::string KEYNAME_INHERIT = "inherit";
80 const std::string KEYNAME_MAPPINGS = "mappings";
81 const std::string KEYNAME_NAME = "name";
82 const std::string KEYNAME_SIGNALS = "signals";
83 const std::string KEYNAME_STATES = "states";
84 const std::string KEYNAME_STYLES = "styles";
85 const std::string KEYNAME_TEMPLATES = "templates";
86 const std::string KEYNAME_TRANSITIONS = "transitions";
87 const std::string KEYNAME_TYPE = "type";
88 const std::string KEYNAME_VISUALS = "visuals";
90 const std::string PROPERTIES = "properties";
91 const std::string ANIMATABLE_PROPERTIES = "animatableProperties";
93 typedef std::vector<const TreeNode*> TreeNodeList;
96 bool GetMappingKey( const std::string& str, std::string& key )
99 std::string test( str );
102 if( test.at(0) == '<' )
104 if( test.at(test.length()-1) == '>' )
106 key = test.substr( 1, test.length()-2 );
115 * Recursively collects all styles in a node (An array of style names).
117 * stylesCollection The set of styles from the json file (a json object of named styles)
118 * style The style array to begin the collection from
119 * styleList The style list to add nodes to apply
121 void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList )
123 // style is an array of style names
124 if( TreeNode::ARRAY == style.GetType() )
126 for(TreeNode::ConstIterator iter = style.CBegin(); iter != style.CEnd(); ++iter)
128 if( OptionalString styleName = IsString( (*iter).second ) )
130 if( OptionalChild node = IsChildIgnoreCase( stylesCollection, *styleName) )
132 styleList.push_back( &(*node) );
134 OptionalChild subStyle = IsChild( *node, KEYNAME_INHERIT );
137 subStyle = IsChild( *node, KEYNAME_STYLES );
141 CollectAllStyles( stylesCollection, *subStyle, styleList );
154 : mSlotDelegate( this )
156 mParser = Dali::Toolkit::JsonParser::New();
158 Property::Map defaultDirs;
159 defaultDirs[TOKEN_STRING(DALI_IMAGE_DIR)] = AssetManager::GetDaliImagePath();
160 defaultDirs[TOKEN_STRING(DALI_SOUND_DIR)] = AssetManager::GetDaliSoundPath();
161 defaultDirs[TOKEN_STRING(DALI_STYLE_DIR)] = AssetManager::GetDaliStylePath();
162 defaultDirs[TOKEN_STRING(DALI_STYLE_IMAGE_DIR)] = AssetManager::GetDaliStyleImagePath();
164 AddConstants( defaultDirs );
167 void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format )
169 // parser to get constants and includes only
170 Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New();
172 if( !parser.Parse( data ) )
174 DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
175 parser.GetErrorLineNumber(),
176 parser.GetErrorColumn(),
177 parser.GetErrorDescription().c_str() );
179 DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
183 // load constant map (allows the user to override the constants in the json after loading)
184 LoadConstants( *parser.GetRoot(), mReplacementMap );
185 // load configuration map
186 LoadConfiguration( *parser.GetRoot(), mConfigurationMap );
188 if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) )
190 Replacement replacer( mReplacementMap );
192 for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter)
194 OptionalString filename = replacer.IsString( (*iter).second );
198 #if defined(DEBUG_ENABLED)
199 DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str());
201 LoadFromString( GetFileContents(*filename) );
206 if( mParser.Parse( data ) )
208 // Drop the styles and get them to be rebuilt against the new parse tree as required.
213 DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
214 mParser.GetErrorLineNumber(),
215 mParser.GetErrorColumn(),
216 mParser.GetErrorDescription().c_str() );
218 DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
222 DUMP_PARSE_TREE(mParser); // This macro only writes out if DEBUG is enabled and the "DUMP_TREE" constant is defined in the stylesheet.
223 DUMP_TEST_MAPPINGS(mParser);
225 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
228 void Builder::AddConstants( const Property::Map& map )
230 mReplacementMap.Merge( map );
233 void Builder::AddConstant( const std::string& key, const Property::Value& value )
235 mReplacementMap[key] = value;
238 const Property::Map& Builder::GetConfigurations() const
240 return mConfigurationMap;
243 const Property::Map& Builder::GetConstants() const
245 return mReplacementMap;
248 const Property::Value& Builder::GetConstant( const std::string& key ) const
250 Property::Value* match = mReplacementMap.Find( key );
257 static Property::Value invalid;
262 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
264 Replacement replacement(map, mReplacementMap);
265 return CreateAnimation( animationName, replacement, sourceActor);
268 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
270 Replacement replacement(map, mReplacementMap);
271 return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
274 Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
276 Replacement replacement( mReplacementMap );
278 return CreateAnimation( animationName, replacement, sourceActor );
281 Animation Builder::CreateAnimation( const std::string& animationName )
283 Replacement replacement( mReplacementMap );
285 return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
288 BaseHandle Builder::Create( const std::string& templateName )
290 Replacement replacement( mReplacementMap );
291 return Create( templateName, replacement );
294 BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
296 Replacement replacement( map, mReplacementMap );
297 return Create( templateName, replacement );
300 BaseHandle Builder::CreateFromJson( const std::string& json )
304 // merge in new template, hoping no one else has one named '@temp@'
305 std::string newTemplate =
306 std::string("{\"templates\":{\"@temp@\":") + \
310 if( mParser.Parse(newTemplate) )
312 Replacement replacement( mReplacementMap );
313 ret = Create( "@temp@", replacement );
319 bool Builder::ApplyFromJson( Handle& handle, const std::string& json )
323 // merge new style, hoping no one else has one named '@temp@'
324 std::string newStyle =
325 std::string("{\"styles\":{\"@temp@\":") + \
329 if( mParser.Parse(newStyle) )
331 Replacement replacement( mReplacementMap );
332 ret = ApplyStyle( "@temp@", handle, replacement );
338 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
340 Replacement replacer( mReplacementMap );
341 return ApplyStyle( styleName, handle, replacer );
344 bool Builder::LookupStyleName( const std::string& styleName )
346 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
348 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
349 OptionalChild style = IsChildIgnoreCase( *styles, styleName );
351 if( styles && style )
358 const StylePtr Builder::GetStyle( const std::string& styleName )
360 const StylePtr* style = mStyles.FindConst( styleName );
364 return StylePtr(NULL);
372 void Builder::AddActors( Actor toActor )
374 // 'stage' is the default/by convention section to add from
375 AddActors( "stage", toActor );
378 void Builder::AddActors( const std::string §ionName, Actor toActor )
380 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
382 Property::Map overrideMap;
383 Replacement replacements(overrideMap, mReplacementMap);
385 OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
389 for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
391 // empty actor adds directly to the stage
392 BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
393 Actor actor = Actor::DownCast(baseHandle);
396 toActor.Add( actor );
400 // if were adding the 'stage' section then also check for a render task called stage
401 // to add automatically
402 if( "stage" == sectionName )
404 if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
406 if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
408 CreateRenderTask( "stage" );
415 void Builder::CreateRenderTask( const std::string &name )
417 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
419 Replacement constant(mReplacementMap);
421 const Stage& stage = Stage::GetCurrent();
423 OptionalChild tasks = IsChild(*mParser.GetRoot(), "renderTasks");
428 // Create the tasks from the current task as generally we want
429 // to setup task zero and onwards. Although this does overwrite
430 // the properties of the current task.
432 if( OptionalChild renderTask = IsChild(*tasks, name ) )
434 RenderTaskList list = stage.GetRenderTaskList();
435 unsigned int start = list.GetTaskCount();
440 // zero should have already been created by the stage so really
441 // this case should never happen
442 task = list.CreateTask();
446 TreeNode::ConstIterator iter = (*renderTask).CBegin();
447 task = list.GetTask( start - 1 );
449 SetupTask( task, (*iter).second, constant );
453 for(; iter != (*renderTask).CEnd(); ++iter )
455 task = list.CreateTask();
456 SetupTask( task, (*iter).second, constant );
462 Path Builder::GetPath( const std::string& name )
464 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
468 PathLut::const_iterator iter( mPathLut.find( name ) );
469 if( iter != mPathLut.end() )
475 if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") )
477 if( OptionalChild path = IsChild( *paths, name ) )
480 if( OptionalChild pointsProperty = IsChild( *path, "points") )
482 Dali::Property::Value points(Property::ARRAY);
483 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
486 ret.SetProperty( Path::Property::POINTS, points);
488 //controlPoints property
489 if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") )
491 Dali::Property::Value points(Property::ARRAY);
492 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
494 ret.SetProperty( Path::Property::CONTROL_POINTS, points);
500 float curvature(0.25f);
501 if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") )
503 curvature = *pointsProperty;
505 ret.GenerateControlPoints(curvature);
508 //Add the new path to the hash table for paths
509 mPathLut[ name ] = ret;
514 //Interpolation points not specified
515 DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() );
525 PathConstrainer Builder::GetPathConstrainer( const std::string& name )
527 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
529 //Search the pathConstrainer in the LUT
530 size_t count( mPathConstrainerLut.size() );
531 for( size_t i(0); i!=count; ++i )
533 if( mPathConstrainerLut[i].name == name )
535 //PathConstrainer has already been created
536 return mPathConstrainerLut[i].pathConstrainer;
540 //Create a new PathConstrainer
542 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
544 if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) )
546 OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type")));
549 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
551 else if( *constrainerType == "PathConstrainer")
554 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") )
556 Dali::Property::Value points(Property::ARRAY);
557 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
559 ret = PathConstrainer::New();
560 ret.SetProperty( PathConstrainer::Property::POINTS, points);
562 //controlPoints property
563 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") )
565 Dali::Property::Value points(Property::ARRAY);
566 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
568 ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points);
572 OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) );
575 ret.SetProperty( PathConstrainer::Property::FORWARD, *forward);
578 //Add the new constrainer to the vector of PathConstrainer
579 PathConstrainerEntry entry = {name,ret};
580 mPathConstrainerLut.push_back( entry );
584 //Control points not specified
585 DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() );
591 //Interpolation points not specified
592 DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() );
597 DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() );
606 bool Builder::IsPathConstrainer( const std::string& name )
608 size_t count( mPathConstrainerLut.size() );
609 for( size_t i(0); i!=count; ++i )
611 if( mPathConstrainerLut[i].name == name )
617 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
619 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
621 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
628 return *constrainerType == "PathConstrainer";
635 Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name )
637 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
639 //Search the LinearConstrainer in the LUT
640 size_t count( mLinearConstrainerLut.size() );
641 for( size_t i(0); i!=count; ++i )
643 if( mLinearConstrainerLut[i].name == name )
645 //LinearConstrainer has already been created
646 return mLinearConstrainerLut[i].linearConstrainer;
650 //Create a new LinearConstrainer
651 LinearConstrainer ret;
652 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
654 if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) )
656 OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type")));
659 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
661 else if( *constrainerType == "LinearConstrainer")
664 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") )
666 Dali::Property::Value points(Property::ARRAY);
667 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
669 ret = Dali::LinearConstrainer::New();
670 ret.SetProperty( LinearConstrainer::Property::VALUE, points);
672 //controlPoints property
673 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") )
675 Dali::Property::Value points(Property::ARRAY);
676 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
678 ret.SetProperty( LinearConstrainer::Property::PROGRESS, points);
681 //Add the new constrainer to vector of LinearConstrainer
682 LinearConstrainerEntry entry = {name,ret};
683 mLinearConstrainerLut.push_back( entry );
688 //Interpolation points not specified
689 DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() );
694 DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() );
702 bool Builder::IsLinearConstrainer( const std::string& name )
704 // Search the LinearConstrainer in the LUT
705 size_t count( mLinearConstrainerLut.size() );
706 for( size_t i(0); i!=count; ++i )
708 if( mLinearConstrainerLut[i].name == name )
714 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
716 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
718 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
725 return *constrainerType == "LinearConstrainer";
732 Toolkit::Builder::BuilderSignalType& Builder::QuitSignal()
737 void Builder::EmitQuitSignal()
746 void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap )
748 Replacement replacer(intoMap);
750 if( OptionalChild constants = IsChild(root, "config") )
752 for(TreeNode::ConstIterator iter = (*constants).CBegin();
753 iter != (*constants).CEnd(); ++iter)
755 Dali::Property::Value property;
756 if( (*iter).second.GetName() )
758 DeterminePropertyFromNode( (*iter).second, property, replacer );
760 // If config is string, find constant and replace it to original value.
761 if( (*iter).second.GetType() == TreeNode::STRING )
763 std::string stringConfigValue;
764 if( property.Get( stringConfigValue ) )
768 while( pos < stringConfigValue.size() )
770 // If we can't find "{","}" pair in stringConfigValue, will out loop.
771 std::size_t leftPos = stringConfigValue.find( "{", pos );
772 if( leftPos != std::string::npos )
774 std::size_t rightPos = stringConfigValue.find( "}", pos+1 );
776 if( rightPos != std::string::npos )
778 // If we find "{","}" pair but can't find matched constant
779 // try to find other "{","}" pair after current left position.
782 for( uint32_t i = 0; i < mReplacementMap.Count() ; i++ )
784 Property::Key constant = mReplacementMap.GetKeyAt(i);
786 // Compare string which is between "{" and "}" with constant string
787 // If they are same, change string in stringConfigValue to mapped constant value.
788 if ( 0 == stringConfigValue.compare( leftPos+1, rightPos-leftPos-1, constant.stringKey ) )
790 std::string replaceString;
791 mReplacementMap.GetValue(i).Get( replaceString );
793 stringConfigValue.replace( leftPos, rightPos-leftPos+1, replaceString );
794 pos = leftPos + replaceString.size();
801 // If we cannot find constant in const value, will out loop.
802 pos = stringConfigValue.size();
807 // If we cannot find constant in const value, will out loop.
808 pos = stringConfigValue.size();
811 property = Property::Value( stringConfigValue );
814 intoMap[ (*iter).second.GetName() ] = property;
820 void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
822 Replacement replacer(intoMap);
824 if( OptionalChild constants = IsChild(root, "constants") )
826 for(TreeNode::ConstIterator iter = (*constants).CBegin();
827 iter != (*constants).CEnd(); ++iter)
829 Dali::Property::Value property;
830 if( (*iter).second.GetName() )
832 #if defined(DEBUG_ENABLED)
833 DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
835 DeterminePropertyFromNode( (*iter).second, property, replacer );
836 intoMap[ (*iter).second.GetName() ] = property;
841 #if defined(DEBUG_ENABLED)
842 Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
843 if( iter && iter->GetType() == Property::STRING )
845 std::string logLevel( iter->Get< std::string >() );
846 if( logLevel == "NoLogging" )
848 gFilterScript->SetLogLevel( Integration::Log::NoLogging );
850 else if( logLevel == "Concise" )
852 gFilterScript->SetLogLevel( Integration::Log::Concise );
854 else if( logLevel == "General" )
856 gFilterScript->SetLogLevel( Integration::Log::General );
858 else if( logLevel == "Verbose" )
860 gFilterScript->SetLogLevel( Integration::Log::Verbose );
866 Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
868 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
872 if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
874 if( OptionalChild animation = IsChild(*animations, animationName) )
876 anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
880 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
885 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
891 BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
893 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
895 BaseHandle baseHandle;
897 OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
901 DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
905 OptionalChild childTemplate = IsChild(*templates, templateName);
908 DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
912 OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
916 DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
920 baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
929 * Create a dali type from a node.
930 * If parent given and an actor type was created then add it to the parent and
931 * recursively add nodes children.
933 BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
934 Actor parent, const Replacement& replacements )
936 BaseHandle baseHandle;
938 const TreeNode* templateNode = NULL;
940 if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
942 typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
946 // a template name is also allowed inplace of the type name
947 OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
951 if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
953 templateNode = &(*isTemplate);
955 if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
957 typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
966 DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
970 baseHandle = typeInfo.CreateInstance();
971 Handle handle = Handle::DownCast(baseHandle);
972 Actor actor = Actor::DownCast(handle);
977 DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
979 #if defined(DEBUG_ENABLED)
982 DALI_SCRIPT_VERBOSE(" Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
983 DALI_SCRIPT_VERBOSE(" Is Handle Property Count=%d\n", handle.GetPropertyCount());
988 DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetId());
991 Toolkit::Control control = Toolkit::Control::DownCast(handle);
994 DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetId());
996 #endif // DEBUG_ENABLED
1000 ApplyProperties( root, *templateNode, handle, replacements );
1002 if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
1004 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1006 DoCreate( root, (*iter).second, actor, replacements );
1013 // add children of all the styles
1014 if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
1016 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1018 DoCreate( root, (*iter).second, actor, replacements );
1022 // apply style on top as they need the children to exist
1023 ApplyAllStyleProperties( root, node, actor, replacements );
1025 // then add to parent
1028 parent.Add( actor );
1033 ApplyProperties( root, node, handle, replacements );
1038 DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
1045 void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
1047 const Stage& stage = Stage::GetCurrent();
1048 Layer root = stage.GetRootLayer();
1050 if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
1052 Actor actor = root.FindChildByName(*s);
1055 task.SetSourceActor( actor );
1059 DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
1063 if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
1065 CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
1068 task.SetCameraActor( actor );
1072 DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
1076 if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
1078 if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
1080 task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
1082 else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
1084 task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
1088 DALI_SCRIPT_WARNING("todo");
1092 // other setup is via the property system
1093 SetProperties( node, task, constant );
1096 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
1098 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
1100 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
1102 std::string styleNameLower(styleName);
1103 OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower );
1105 if( styles && style )
1107 ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
1116 void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
1117 Dali::Handle& handle, const Replacement& constant )
1119 const char* styleName = node.GetName();
1121 StylePtr style = Style::New();
1123 StylePtr* matchedStyle = NULL;
1126 matchedStyle = mStyles.Find( styleName );
1127 if( ! matchedStyle )
1129 OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
1130 OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
1131 if( !inheritFromNode )
1133 inheritFromNode = IsChild( node, KEYNAME_STYLES );
1138 if( inheritFromNode )
1140 TreeNodeList additionalStyleNodes;
1142 CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
1144 #if defined(DEBUG_ENABLED)
1145 for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
1147 if( OptionalString styleName = IsString( (*iter).second ) )
1149 DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
1154 // a style may have other styles, which has other styles etc so we apply in reverse by convention.
1155 for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
1157 RecordStyle( style, *(*iter), handle, constant );
1158 ApplySignals( root, *(*iter), handle );
1159 ApplyStylesByActor( root, *(*iter), handle, constant );
1163 RecordStyle( style, node, handle, constant );
1164 mStyles.Add( styleName, style ); // shallow copy
1165 matchedStyle = &style;
1172 StylePtr style( *matchedStyle );
1173 Dictionary<Property::Map> instancedProperties;
1174 style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties );
1176 else // If there were no styles, instead set properties
1178 SetProperties( node, handle, constant );
1180 ApplySignals( root, node, handle );
1181 ApplyStylesByActor( root, node, handle, constant );
1184 void Builder::RecordStyle( StylePtr style,
1185 const TreeNode& node,
1186 Dali::Handle& handle,
1187 const Replacement& replacements )
1189 // With repeated calls, accumulate inherited states, visuals and properties
1190 // but override any with same name
1192 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1194 const TreeNode::KeyNodePair& keyValue = *iter;
1195 std::string key( keyValue.first );
1196 if( key == KEYNAME_STATES )
1198 const TreeNode& states = keyValue.second;
1199 if( states.GetType() != TreeNode::OBJECT )
1201 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
1205 for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
1207 const TreeNode& stateNode = (*iter).second;
1208 const char* stateName = stateNode.GetName();
1209 if( stateNode.GetType() != TreeNode::OBJECT )
1211 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
1215 StylePtr* stylePtr = style->subStates.Find( stateName );
1218 StylePtr style(*stylePtr);
1219 RecordStyle( style, stateNode, handle, replacements );
1223 StylePtr subState = Style::New();
1224 RecordStyle( subState, stateNode, handle, replacements );
1225 style->subStates.Add( stateName, subState );
1229 else if( key == KEYNAME_VISUALS )
1231 for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
1233 // Each key in this table should be a property name matching a visual.
1234 const TreeNode::KeyNodePair& visual = *iter;
1235 Dali::Property::Value property(Property::MAP);
1236 if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
1238 Property::Map* mapPtr = style->visuals.Find( visual.first );
1241 // Override existing visuals
1243 mapPtr->Merge( *property.GetMap() );
1247 Property::Map* map = property.GetMap();
1250 style->visuals.Add( visual.first, *map );
1256 else if( key == KEYNAME_ENTRY_TRANSITION )
1258 RecordTransitionData( keyValue, style->entryTransition, replacements );
1260 else if( key == KEYNAME_EXIT_TRANSITION )
1262 RecordTransitionData( keyValue, style->exitTransition, replacements );
1264 else if( key == KEYNAME_TRANSITIONS )
1266 RecordTransitions( keyValue, style->transitions, replacements );
1268 else if( key == KEYNAME_TYPE ||
1269 key == KEYNAME_ACTORS ||
1270 key == KEYNAME_SIGNALS ||
1271 key == KEYNAME_STYLES ||
1272 key == KEYNAME_MAPPINGS ||
1273 key == KEYNAME_INHERIT )
1277 else // It's a property
1279 Property::Index index;
1280 Property::Value value;
1281 if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
1283 Property::Value* existingValuePtr = style->properties.Find( index );
1284 if( existingValuePtr != NULL )
1286 *existingValuePtr = value; // Overwrite existing property.
1290 style->properties.Add( index, value );
1297 void Builder::RecordTransitions(
1298 const TreeNode::KeyNodePair& keyValue,
1299 Property::Array& value,
1300 const Replacement& replacements )
1302 //@todo add new transitions to style.transitions
1303 // override existing transitions. A transition matches on target & property name
1304 const TreeNode& node = keyValue.second;
1305 if( node.GetType() == TreeNode::ARRAY )
1307 Dali::Property::Value property(Property::ARRAY);
1308 if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
1310 value = *property.GetArray();
1313 else if( node.GetType() == TreeNode::OBJECT )
1315 Dali::Property::Value property(Property::MAP);
1316 if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
1318 Property::Array propertyArray;
1319 propertyArray.Add( property );
1320 value = propertyArray;
1325 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first );
1329 void Builder::RecordTransitionData(
1330 const TreeNode::KeyNodePair& keyValue,
1331 Toolkit::TransitionData& transitionData,
1332 const Replacement& replacements )
1334 const TreeNode& node = keyValue.second;
1335 if( node.GetType() == TreeNode::ARRAY )
1337 Dali::Property::Value property(Property::ARRAY);
1338 if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) )
1340 transitionData = Toolkit::TransitionData::New( *property.GetArray() );
1343 else if( node.GetType() == TreeNode::OBJECT )
1345 Dali::Property::Value property(Property::MAP);
1346 if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
1348 transitionData = Toolkit::TransitionData::New( *property.GetMap() );
1354 // Set properties from node on handle.
1355 void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
1356 Dali::Handle& handle, const Replacement& constant )
1358 SetProperties( node, handle, constant );
1359 ApplySignals( root, node, handle );
1362 void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
1364 Actor actor = Actor::DownCast(handle);
1368 SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1369 SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1374 // Appling by style helper
1375 // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
1376 void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node,
1377 Dali::Handle& handle, const Replacement& constant )
1379 if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
1381 if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
1383 // in a style the actor subtree properties referenced by actor name
1384 for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
1386 Dali::Actor foundActor;
1390 foundActor = actor.FindChildByName( (*iter).first );
1395 DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
1399 DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
1400 ApplyProperties( root, (*iter).second, foundActor, constant );
1408 * Sets the handle properties found in the tree node
1410 void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
1414 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1416 const TreeNode::KeyNodePair& keyChild = *iter;
1418 std::string key( keyChild.first );
1420 // ignore special fields;
1421 if( key == KEYNAME_TYPE ||
1422 key == KEYNAME_ACTORS ||
1423 key == KEYNAME_SIGNALS ||
1424 key == KEYNAME_STYLES ||
1425 key == KEYNAME_MAPPINGS ||
1426 key == KEYNAME_INHERIT ||
1427 key == KEYNAME_STATES ||
1428 key == KEYNAME_VISUALS ||
1429 key == KEYNAME_ENTRY_TRANSITION ||
1430 key == KEYNAME_EXIT_TRANSITION ||
1431 key == KEYNAME_TRANSITIONS )
1436 Property::Index index;
1437 Property::Value value;
1439 bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
1442 DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
1444 handle.SetProperty( index, value );
1447 // Add custom properties
1448 SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
1449 SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
1451 } // for property nodes
1455 DALI_SCRIPT_WARNING("Style applied to empty handle\n");
1459 bool Builder::MapToTargetProperty(
1460 Handle& propertyObject,
1461 const std::string& key,
1462 const TreeNode& node,
1463 const Replacement& constant,
1464 Property::Index& index,
1465 Property::Value& value )
1467 bool mapped = false;
1469 index = propertyObject.GetPropertyIndex( key );
1470 if( Property::INVALID_INDEX != index )
1472 Property::Type type = propertyObject.GetPropertyType(index);
1474 // if node.value is a mapping, get the property value from the "mappings" table
1475 if( node.GetType() == TreeNode::STRING )
1477 std::string mappingKey;
1478 if( GetMappingKey( node.GetString(), mappingKey) )
1480 OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
1481 mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
1486 mapped = DeterminePropertyFromNode( node, type, value, constant );
1489 // Just determine the property from the node and if it's valid, let the property object handle it
1490 DeterminePropertyFromNode( node, value, constant );
1491 mapped = ( value.GetType() != Property::NONE );
1497 DALI_LOG_ERROR("Key '%s' not found.\n", key.c_str());
1502 bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
1505 return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
1508 bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
1510 Replacement replacer( mReplacementMap );
1511 bool result = false;
1513 keyStack.push_back( theKey );
1515 for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
1517 std::string aKey( (*iter).first );
1518 if( aKey.compare( theKey ) == 0 )
1520 if( propertyType == Property::NONE )
1522 DeterminePropertyFromNode( (*iter).second, value, replacer );
1527 result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
1532 ConvertChildValue(mappingRoot, keyStack, value);
1537 keyStack.pop_back();
1542 bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
1544 bool result = false;
1546 switch( child.GetType() )
1548 case Property::STRING:
1551 if( child.Get( value ) )
1554 if( GetMappingKey( value, key ) )
1556 // Check key for cycles:
1558 for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
1560 if( key.compare(*iter) == 0 )
1562 // key is already in stack; stop.
1563 DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
1564 child = Property::Value("");
1572 // The following call will overwrite the child with the value
1573 // from the mapping.
1574 RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
1584 Property::Map* map = child.GetMap();
1587 for( Property::Map::SizeType i=0; i < map->Count(); ++i )
1589 Property::Value& child = map->GetValue(i);
1590 ConvertChildValue(mappingRoot, keyStack, child);
1596 case Property::ARRAY:
1598 Property::Array* array = child.GetArray();
1601 for( Property::Array::SizeType i=0; i < array->Count(); ++i )
1603 Property::Value& child = array->GetElementAt(i);
1604 ConvertChildValue(mappingRoot, keyStack, child);
1611 // Ignore other types.
1618 void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
1619 const std::string& childName, Property::AccessMode accessMode )
1621 // Add custom properties
1622 if( OptionalChild customPropertiesChild = IsChild(node, childName) )
1624 const TreeNode& customPropertiesNode = *customPropertiesChild;
1625 const TreeConstIter endIter = customPropertiesNode.CEnd();
1626 for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
1628 const TreeNode::KeyNodePair& keyChild = *iter;
1629 std::string key( keyChild.first );
1630 Property::Value value;
1631 DeterminePropertyFromNode( keyChild.second, value, constant );
1633 // Register/Set property.
1634 handle.RegisterProperty( key, value, accessMode );
1640 } // namespace Internal
1642 } // namespace Toolkit