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 );
186 if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) )
188 Replacement replacer( mReplacementMap );
190 for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter)
192 OptionalString filename = replacer.IsString( (*iter).second );
196 #if defined(DEBUG_ENABLED)
197 DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str());
199 LoadFromString( GetFileContents(*filename) );
204 if( !mParser.Parse( data ) )
206 DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
207 mParser.GetErrorLineNumber(),
208 mParser.GetErrorColumn(),
209 mParser.GetErrorDescription().c_str() );
211 DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
215 DUMP_PARSE_TREE(parser); // This macro only writes out if DEBUG is enabled and the "DUMP_TREE" constant is defined in the stylesheet.
216 DUMP_TEST_MAPPINGS(parser);
218 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
221 void Builder::AddConstants( const Property::Map& map )
223 mReplacementMap.Merge( map );
226 void Builder::AddConstant( const std::string& key, const Property::Value& value )
228 mReplacementMap[key] = value;
231 const Property::Map& Builder::GetConstants() const
233 return mReplacementMap;
236 const Property::Value& Builder::GetConstant( const std::string& key ) const
238 Property::Value* match = mReplacementMap.Find( key );
245 static Property::Value invalid;
250 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
252 Replacement replacement(map, mReplacementMap);
253 return CreateAnimation( animationName, replacement, sourceActor);
256 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
258 Replacement replacement(map, mReplacementMap);
259 return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
262 Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
264 Replacement replacement( mReplacementMap );
266 return CreateAnimation( animationName, replacement, sourceActor );
269 Animation Builder::CreateAnimation( const std::string& animationName )
271 Replacement replacement( mReplacementMap );
273 return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
276 BaseHandle Builder::Create( const std::string& templateName )
278 Replacement replacement( mReplacementMap );
279 return Create( templateName, replacement );
282 BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
284 Replacement replacement( map, mReplacementMap );
285 return Create( templateName, replacement );
288 BaseHandle Builder::CreateFromJson( const std::string& json )
292 // merge in new template, hoping no one else has one named '@temp@'
293 std::string newTemplate =
294 std::string("{\"templates\":{\"@temp@\":") + \
298 if( mParser.Parse(newTemplate) )
300 Replacement replacement( mReplacementMap );
301 ret = Create( "@temp@", replacement );
307 bool Builder::ApplyFromJson( Handle& handle, const std::string& json )
311 // merge new style, hoping no one else has one named '@temp@'
312 std::string newStyle =
313 std::string("{\"styles\":{\"@temp@\":") + \
317 if( mParser.Parse(newStyle) )
319 Replacement replacement( mReplacementMap );
320 ret = ApplyStyle( "@temp@", handle, replacement );
326 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
328 Replacement replacer( mReplacementMap );
329 return ApplyStyle( styleName, handle, replacer );
332 bool Builder::LookupStyleName( const std::string& styleName )
334 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
336 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
337 OptionalChild style = IsChildIgnoreCase( *styles, styleName );
339 if( styles && style )
346 const StylePtr Builder::GetStyle( const std::string& styleName )
348 const StylePtr* style = mStyles.FindCaseInsensitiveC( styleName );
352 return StylePtr(NULL);
360 void Builder::AddActors( Actor toActor )
362 // 'stage' is the default/by convention section to add from
363 AddActors( "stage", toActor );
366 void Builder::AddActors( const std::string §ionName, Actor toActor )
368 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
370 Property::Map overrideMap;
371 Replacement replacements(overrideMap, mReplacementMap);
373 OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
377 for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
379 // empty actor adds directly to the stage
380 BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
381 Actor actor = Actor::DownCast(baseHandle);
384 toActor.Add( actor );
388 // if were adding the 'stage' section then also check for a render task called stage
389 // to add automatically
390 if( "stage" == sectionName )
392 if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
394 if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
396 CreateRenderTask( "stage" );
403 void Builder::CreateRenderTask( const std::string &name )
405 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
407 Replacement constant(mReplacementMap);
409 const Stage& stage = Stage::GetCurrent();
411 OptionalChild tasks = IsChild(*mParser.GetRoot(), "renderTasks");
416 // Create the tasks from the current task as generally we want
417 // to setup task zero and onwards. Although this does overwrite
418 // the properties of the current task.
420 if( OptionalChild renderTask = IsChild(*tasks, name ) )
422 RenderTaskList list = stage.GetRenderTaskList();
423 unsigned int start = list.GetTaskCount();
428 // zero should have already been created by the stage so really
429 // this case should never happen
430 task = list.CreateTask();
434 TreeNode::ConstIterator iter = (*renderTask).CBegin();
435 task = list.GetTask( start - 1 );
437 SetupTask( task, (*iter).second, constant );
441 for(; iter != (*renderTask).CEnd(); ++iter )
443 task = list.CreateTask();
444 SetupTask( task, (*iter).second, constant );
450 FrameBufferImage Builder::GetFrameBufferImage( const std::string &name )
452 Replacement constant( mReplacementMap );
453 return GetFrameBufferImage(name, constant);
456 FrameBufferImage Builder::GetFrameBufferImage( const std::string &name, const Replacement& constant )
458 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
460 FrameBufferImage ret;
462 ImageLut::const_iterator iter( mFrameBufferImageLut.find( name ) );
463 if( iter != mFrameBufferImageLut.end() )
469 if( OptionalChild images = IsChild( *mParser.GetRoot(), "frameBufferImages") )
471 if( OptionalChild image = IsChild( *images, name ) )
473 Dali::Property::Value property(Property::MAP);
474 if( DeterminePropertyFromNode( *image, Property::MAP, property, constant ) )
476 Property::Map* map = property.GetMap();
480 (*map)[ KEYNAME_TYPE ] = Property::Value(std::string("FrameBufferImage") );
481 ret = FrameBufferImage::DownCast( Dali::Scripting::NewImage( property ) );
482 mFrameBufferImageLut[ name ] = ret;
492 Path Builder::GetPath( const std::string& name )
494 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
498 PathLut::const_iterator iter( mPathLut.find( name ) );
499 if( iter != mPathLut.end() )
505 if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") )
507 if( OptionalChild path = IsChild( *paths, name ) )
510 if( OptionalChild pointsProperty = IsChild( *path, "points") )
512 Dali::Property::Value points(Property::ARRAY);
513 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
516 ret.SetProperty( Path::Property::POINTS, points);
518 //controlPoints property
519 if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") )
521 Dali::Property::Value points(Property::ARRAY);
522 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
524 ret.SetProperty( Path::Property::CONTROL_POINTS, points);
530 float curvature(0.25f);
531 if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") )
533 curvature = *pointsProperty;
535 ret.GenerateControlPoints(curvature);
538 //Add the new path to the hash table for paths
539 mPathLut[ name ] = ret;
544 //Interpolation points not specified
545 DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() );
555 PathConstrainer Builder::GetPathConstrainer( const std::string& name )
557 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
559 //Search the pathConstrainer in the LUT
560 size_t count( mPathConstrainerLut.size() );
561 for( size_t i(0); i!=count; ++i )
563 if( mPathConstrainerLut[i].name == name )
565 //PathConstrainer has already been created
566 return mPathConstrainerLut[i].pathConstrainer;
570 //Create a new PathConstrainer
572 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
574 if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) )
576 OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type")));
579 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
581 else if( *constrainerType == "PathConstrainer")
584 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") )
586 Dali::Property::Value points(Property::ARRAY);
587 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
589 ret = PathConstrainer::New();
590 ret.SetProperty( PathConstrainer::Property::POINTS, points);
592 //controlPoints property
593 if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") )
595 Dali::Property::Value points(Property::ARRAY);
596 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
598 ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points);
602 OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) );
605 ret.SetProperty( PathConstrainer::Property::FORWARD, *forward);
608 //Add the new constrainer to the vector of PathConstrainer
609 PathConstrainerEntry entry = {name,ret};
610 mPathConstrainerLut.push_back( entry );
614 //Control points not specified
615 DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() );
621 //Interpolation points not specified
622 DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() );
627 DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() );
636 bool Builder::IsPathConstrainer( const std::string& name )
638 size_t count( mPathConstrainerLut.size() );
639 for( size_t i(0); i!=count; ++i )
641 if( mPathConstrainerLut[i].name == name )
647 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
649 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
651 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
658 return *constrainerType == "PathConstrainer";
665 Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name )
667 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
669 //Search the LinearConstrainer in the LUT
670 size_t count( mLinearConstrainerLut.size() );
671 for( size_t i(0); i!=count; ++i )
673 if( mLinearConstrainerLut[i].name == name )
675 //LinearConstrainer has already been created
676 return mLinearConstrainerLut[i].linearConstrainer;
680 //Create a new LinearConstrainer
681 LinearConstrainer ret;
682 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
684 if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) )
686 OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type")));
689 DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
691 else if( *constrainerType == "LinearConstrainer")
694 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") )
696 Dali::Property::Value points(Property::ARRAY);
697 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
699 ret = Dali::LinearConstrainer::New();
700 ret.SetProperty( LinearConstrainer::Property::VALUE, points);
702 //controlPoints property
703 if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") )
705 Dali::Property::Value points(Property::ARRAY);
706 if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
708 ret.SetProperty( LinearConstrainer::Property::PROGRESS, points);
711 //Add the new constrainer to vector of LinearConstrainer
712 LinearConstrainerEntry entry = {name,ret};
713 mLinearConstrainerLut.push_back( entry );
718 //Interpolation points not specified
719 DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() );
724 DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() );
732 bool Builder::IsLinearConstrainer( const std::string& name )
734 // Search the LinearConstrainer in the LUT
735 size_t count( mLinearConstrainerLut.size() );
736 for( size_t i(0); i!=count; ++i )
738 if( mLinearConstrainerLut[i].name == name )
744 if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
746 if( OptionalChild constrainer = IsChild( *constrainers, name ) )
748 OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
755 return *constrainerType == "LinearConstrainer";
762 Toolkit::Builder::BuilderSignalType& Builder::QuitSignal()
767 void Builder::EmitQuitSignal()
776 void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
778 Replacement replacer(intoMap);
780 if( OptionalChild constants = IsChild(root, "constants") )
782 for(TreeNode::ConstIterator iter = (*constants).CBegin();
783 iter != (*constants).CEnd(); ++iter)
785 Dali::Property::Value property;
786 if( (*iter).second.GetName() )
788 #if defined(DEBUG_ENABLED)
789 DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
791 DeterminePropertyFromNode( (*iter).second, property, replacer );
792 intoMap[ (*iter).second.GetName() ] = property;
797 #if defined(DEBUG_ENABLED)
798 Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
799 if( iter && iter->GetType() == Property::STRING )
801 std::string logLevel( iter->Get< std::string >() );
802 if( logLevel == "NoLogging" )
804 gFilterScript->SetLogLevel( Integration::Log::NoLogging );
806 else if( logLevel == "Concise" )
808 gFilterScript->SetLogLevel( Integration::Log::Concise );
810 else if( logLevel == "General" )
812 gFilterScript->SetLogLevel( Integration::Log::General );
814 else if( logLevel == "Verbose" )
816 gFilterScript->SetLogLevel( Integration::Log::Verbose );
822 Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
824 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
828 if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
830 if( OptionalChild animation = IsChild(*animations, animationName) )
832 anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
836 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
841 DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
847 BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
849 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
851 BaseHandle baseHandle;
853 OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
857 DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
861 OptionalChild childTemplate = IsChild(*templates, templateName);
864 DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
868 OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
872 DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
876 baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
885 * Create a dali type from a node.
886 * If parent given and an actor type was created then add it to the parent and
887 * recursively add nodes children.
889 BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
890 Actor parent, const Replacement& replacements )
892 BaseHandle baseHandle;
894 const TreeNode* templateNode = NULL;
896 if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
898 typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
902 // a template name is also allowed inplace of the type name
903 OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
907 if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
909 templateNode = &(*isTemplate);
911 if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
913 typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
922 DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
926 baseHandle = typeInfo.CreateInstance();
927 Handle handle = Handle::DownCast(baseHandle);
928 Actor actor = Actor::DownCast(handle);
933 DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
935 #if defined(DEBUG_ENABLED)
938 DALI_SCRIPT_VERBOSE(" Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
939 DALI_SCRIPT_VERBOSE(" Is Handle Property Count=%d\n", handle.GetPropertyCount());
944 DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetId());
947 Toolkit::Control control = Toolkit::Control::DownCast(handle);
950 DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetId());
952 #endif // DEBUG_ENABLED
956 ApplyProperties( root, *templateNode, handle, replacements );
958 if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
960 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
962 DoCreate( root, (*iter).second, actor, replacements );
969 // add children of all the styles
970 if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
972 for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
974 DoCreate( root, (*iter).second, actor, replacements );
978 // apply style on top as they need the children to exist
979 ApplyAllStyleProperties( root, node, actor, replacements );
981 // then add to parent
989 ApplyProperties( root, node, handle, replacements );
994 DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
1001 void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
1003 const Stage& stage = Stage::GetCurrent();
1004 Layer root = stage.GetRootLayer();
1006 if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
1008 Actor actor = root.FindChildByName(*s);
1011 task.SetSourceActor( actor );
1015 DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
1019 if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
1021 CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
1024 task.SetCameraActor( actor );
1028 DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
1032 if( OptionalString s = constant.IsString( IsChild(node, "targetFrameBuffer") ) )
1034 FrameBufferImage fb = GetFrameBufferImage( *s, constant );
1037 task.SetTargetFrameBuffer( fb );
1041 DALI_SCRIPT_WARNING("Cannot find target frame buffer '%s'\n", (*s).c_str() );
1045 if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
1047 if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
1049 task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
1051 else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
1053 task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
1057 DALI_SCRIPT_WARNING("todo");
1061 // other setup is via the property system
1062 SetProperties( node, task, constant );
1065 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
1067 DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
1069 OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
1071 std::string styleNameLower(styleName);
1072 OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower );
1074 if( styles && style )
1076 ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
1085 void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
1086 Dali::Handle& handle, const Replacement& constant )
1088 const char* styleName = node.GetName();
1090 StylePtr style = Style::New();
1092 StylePtr* matchedStyle = NULL;
1095 matchedStyle = mStyles.FindCaseInsensitive( styleName );
1096 if( ! matchedStyle )
1098 OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
1099 OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
1100 if( !inheritFromNode )
1102 inheritFromNode = IsChild( node, KEYNAME_STYLES );
1107 if( inheritFromNode )
1109 TreeNodeList additionalStyleNodes;
1111 CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
1113 #if defined(DEBUG_ENABLED)
1114 for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
1116 if( OptionalString styleName = IsString( (*iter).second ) )
1118 DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
1123 // a style may have other styles, which has other styles etc so we apply in reverse by convention.
1124 for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
1126 RecordStyle( style, *(*iter), handle, constant );
1127 ApplySignals( root, *(*iter), handle );
1128 ApplyStylesByActor( root, *(*iter), handle, constant );
1132 RecordStyle( style, node, handle, constant );
1133 mStyles.Add( styleName, style ); // shallow copy
1134 matchedStyle = &style;
1141 StylePtr style( *matchedStyle );
1142 style->ApplyVisualsAndPropertiesRecursively( handle ); // (recurses through states)
1144 else // If there were no styles, instead set properties
1146 SetProperties( node, handle, constant );
1148 ApplySignals( root, node, handle );
1149 ApplyStylesByActor( root, node, handle, constant );
1152 void Builder::RecordStyle( StylePtr style,
1153 const TreeNode& node,
1154 Dali::Handle& handle,
1155 const Replacement& replacements )
1157 // With repeated calls, accumulate inherited states, visuals and properties
1158 // but override any with same name
1160 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1162 const TreeNode::KeyNodePair& keyValue = *iter;
1163 std::string key( keyValue.first );
1164 if( key == KEYNAME_STATES )
1166 const TreeNode& states = keyValue.second;
1167 if( states.GetType() != TreeNode::OBJECT )
1169 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
1173 for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
1175 const TreeNode& stateNode = (*iter).second;
1176 const char* stateName = stateNode.GetName();
1177 if( stateNode.GetType() != TreeNode::OBJECT )
1179 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
1183 StylePtr* stylePtr = style->subStates.FindCaseInsensitive( stateName );
1186 StylePtr style(*stylePtr);
1187 RecordStyle( style, stateNode, handle, replacements );
1191 StylePtr subState = Style::New();
1192 RecordStyle( subState, stateNode, handle, replacements );
1193 style->subStates.Add( stateName, subState );
1197 else if( key == KEYNAME_VISUALS )
1199 for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
1201 // Each key in this table should be a property name matching a visual.
1202 const TreeNode::KeyNodePair& visual = *iter;
1203 Dali::Property::Value property(Property::MAP);
1204 if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
1206 Property::Map* mapPtr = style->visuals.FindCaseInsensitive( visual.first );
1209 // Override existing visuals
1211 mapPtr->Merge(*property.GetMap());
1215 style->visuals.Add(visual.first, *property.GetMap());
1220 else if( key == KEYNAME_ENTRY_TRANSITION )
1222 Dali::Property::Value property(Property::MAP);
1223 if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
1225 style->entryTransition = Toolkit::TransitionData::New( *property.GetMap() );
1228 else if( key == KEYNAME_EXIT_TRANSITION )
1230 Dali::Property::Value property(Property::MAP);
1231 if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
1233 style->exitTransition = Toolkit::TransitionData::New( *property.GetMap() );
1236 else if( key == KEYNAME_TRANSITIONS )
1238 //@todo add new transitions to style.transitions
1239 // override existing transitions. A transition matches on target & property name
1240 const TreeNode& node = keyValue.second;
1241 if( node.GetType() == TreeNode::ARRAY )
1243 Dali::Property::Value property(Property::ARRAY);
1244 if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
1246 style->transitions = *property.GetArray();
1249 else if( node.GetType() == TreeNode::OBJECT )
1251 Dali::Property::Value property(Property::MAP);
1252 if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
1254 Property::Array propertyArray;
1255 propertyArray.Add( property );
1256 style->transitions = propertyArray;
1261 DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", key.c_str() );
1264 else if( key == KEYNAME_TYPE ||
1265 key == KEYNAME_ACTORS ||
1266 key == KEYNAME_SIGNALS ||
1267 key == KEYNAME_STYLES ||
1268 key == KEYNAME_MAPPINGS ||
1269 key == KEYNAME_INHERIT )
1273 else // It's a property
1275 Property::Index index;
1276 Property::Value value;
1277 if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
1279 Property::Value* existingValuePtr = style->properties.Find( index );
1280 if( existingValuePtr != NULL )
1282 *existingValuePtr = value; // Overwrite existing property.
1286 style->properties.Add( index, value );
1293 // Set properties from node on handle.
1294 void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
1295 Dali::Handle& handle, const Replacement& constant )
1297 SetProperties( node, handle, constant );
1298 ApplySignals( root, node, handle );
1301 void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
1303 Actor actor = Actor::DownCast(handle);
1307 SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1308 SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1313 // Appling by style helper
1314 // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
1315 void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node,
1316 Dali::Handle& handle, const Replacement& constant )
1318 if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
1320 if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
1322 // in a style the actor subtree properties referenced by actor name
1323 for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
1325 Dali::Actor foundActor;
1329 foundActor = actor.FindChildByName( (*iter).first );
1334 DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
1338 DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
1339 ApplyProperties( root, (*iter).second, foundActor, constant );
1347 * Sets the handle properties found in the tree node
1349 void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
1353 for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1355 const TreeNode::KeyNodePair& keyChild = *iter;
1357 std::string key( keyChild.first );
1359 // ignore special fields;
1360 if( key == KEYNAME_TYPE ||
1361 key == KEYNAME_ACTORS ||
1362 key == KEYNAME_SIGNALS ||
1363 key == KEYNAME_STYLES ||
1364 key == KEYNAME_MAPPINGS ||
1365 key == KEYNAME_INHERIT ||
1366 key == KEYNAME_STATES ||
1367 key == KEYNAME_VISUALS ||
1368 key == KEYNAME_ENTRY_TRANSITION ||
1369 key == KEYNAME_EXIT_TRANSITION ||
1370 key == KEYNAME_TRANSITIONS )
1375 Property::Index index;
1376 Property::Value value;
1378 bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
1381 DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
1383 handle.SetProperty( index, value );
1386 // Add custom properties
1387 SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
1388 SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
1390 } // for property nodes
1394 DALI_SCRIPT_WARNING("Style applied to empty handle\n");
1398 bool Builder::MapToTargetProperty(
1399 Handle& propertyObject,
1400 const std::string& key,
1401 const TreeNode& node,
1402 const Replacement& constant,
1403 Property::Index& index,
1404 Property::Value& value )
1406 bool mapped = false;
1408 index = propertyObject.GetPropertyIndex( key );
1409 if( Property::INVALID_INDEX != index )
1411 Property::Type type = propertyObject.GetPropertyType(index);
1413 // if node.value is a mapping, get the property value from the "mappings" table
1414 if( node.GetType() == TreeNode::STRING )
1416 std::string mappingKey;
1417 if( GetMappingKey( node.GetString(), mappingKey) )
1419 OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
1420 mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
1425 mapped = DeterminePropertyFromNode( node, type, value, constant );
1428 // Just determine the property from the node and if it's valid, let the property object handle it
1429 DeterminePropertyFromNode( node, value, constant );
1430 mapped = ( value.GetType() != Property::NONE );
1436 DALI_LOG_ERROR("Key '%s' not found.\n", key.c_str());
1441 bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
1444 return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
1447 bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
1449 Replacement replacer( mReplacementMap );
1450 bool result = false;
1452 keyStack.push_back( theKey );
1454 for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
1456 std::string aKey( (*iter).first );
1457 if( aKey.compare( theKey ) == 0 )
1459 if( propertyType == Property::NONE )
1461 DeterminePropertyFromNode( (*iter).second, value, replacer );
1466 result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
1471 ConvertChildValue(mappingRoot, keyStack, value);
1476 keyStack.pop_back();
1481 bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
1483 bool result = false;
1485 switch( child.GetType() )
1487 case Property::STRING:
1490 if( child.Get( value ) )
1493 if( GetMappingKey( value, key ) )
1495 // Check key for cycles:
1497 for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
1499 if( key.compare(*iter) == 0 )
1501 // key is already in stack; stop.
1502 DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
1503 child = Property::Value("");
1511 // The following call will overwrite the child with the value
1512 // from the mapping.
1513 RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
1523 Property::Map* map = child.GetMap();
1526 for( Property::Map::SizeType i=0; i < map->Count(); ++i )
1528 Property::Value& child = map->GetValue(i);
1529 ConvertChildValue(mappingRoot, keyStack, child);
1535 case Property::ARRAY:
1537 Property::Array* array = child.GetArray();
1540 for( Property::Array::SizeType i=0; i < array->Count(); ++i )
1542 Property::Value& child = array->GetElementAt(i);
1543 ConvertChildValue(mappingRoot, keyStack, child);
1550 // Ignore other types.
1557 void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
1558 const std::string& childName, Property::AccessMode accessMode )
1560 // Add custom properties
1561 if( OptionalChild customPropertiesChild = IsChild(node, childName) )
1563 const TreeNode& customPropertiesNode = *customPropertiesChild;
1564 const TreeConstIter endIter = customPropertiesNode.CEnd();
1565 for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
1567 const TreeNode::KeyNodePair& keyChild = *iter;
1568 std::string key( keyChild.first );
1569 Property::Value value;
1570 DeterminePropertyFromNode( keyChild.second, value, constant );
1572 // Register/Set property.
1573 handle.RegisterProperty( key, value, accessMode );
1579 } // namespace Internal
1581 } // namespace Toolkit