Check NULL return value in builder-impl.cpp
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / builder / builder-impl.cpp
index f31bf5f..7f1b441 100644 (file)
 #include <sys/stat.h>
 #include <sstream>
 
-#include <dali/public-api/render-tasks/render-task-list.h>
+#include <dali/public-api/actors/camera-actor.h>
+#include <dali/public-api/actors/layer.h>
+#include <dali/public-api/object/property-array.h>
 #include <dali/public-api/object/type-info.h>
 #include <dali/public-api/object/type-registry.h>
-#include <dali/public-api/object/property-array.h>
-#include <dali/public-api/actors/layer.h>
-#include <dali/public-api/actors/image-actor.h>
-#include <dali/public-api/actors/camera-actor.h>
-#include <dali/devel-api/scripting/scripting.h>
+#include <dali/public-api/render-tasks/render-task-list.h>
 #include <dali/public-api/signals/functor-delegate.h>
+#include <dali/devel-api/scripting/scripting.h>
 #include <dali/integration-api/debug.h>
+#include <dali-toolkit/devel-api/controls/control-devel.h>
 
 // INTERNAL INCLUDES
 #include <dali-toolkit/public-api/controls/control.h>
 #include <dali-toolkit/devel-api/builder/json-parser.h>
 
-#include <dali-toolkit/internal/builder/builder-get-is.inl.h>
-#include <dali-toolkit/internal/builder/builder-filesystem.h>
 #include <dali-toolkit/internal/builder/builder-declarations.h>
+#include <dali-toolkit/internal/builder/builder-filesystem.h>
+#include <dali-toolkit/internal/builder/builder-get-is.inl.h>
+#include <dali-toolkit/internal/builder/builder-impl-debug.h>
 #include <dali-toolkit/internal/builder/builder-set-property.h>
 #include <dali-toolkit/internal/builder/replacement.h>
 #include <dali-toolkit/internal/builder/tree-node-manipulator.h>
 
-#include <dali-toolkit/internal/builder/builder-impl-debug.h>
-
 namespace Dali
 {
 
@@ -57,9 +56,11 @@ namespace Internal
 class Replacement;
 
 extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder );
+
 extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
+
 extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
-extern Actor SetupActor( const TreeNode& node, Actor& actor, const Replacement& constant );
+
 
 #if defined(DEBUG_ENABLED)
 Integration::Log::Filter* gFilterScript  = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT");
@@ -70,14 +71,20 @@ namespace
 
 #define TOKEN_STRING(x) #x
 
-const std::string KEYNAME_STYLES    = "styles";
-const std::string KEYNAME_TYPE      = "type";
-const std::string KEYNAME_ACTORS    = "actors";
-const std::string KEYNAME_SIGNALS   = "signals";
-const std::string KEYNAME_NAME      = "name";
-const std::string KEYNAME_TEMPLATES = "templates";
-const std::string KEYNAME_INCLUDES  = "includes";
-const std::string KEYNAME_MAPPINGS  = "mappings";
+const std::string KEYNAME_ACTORS           = "actors";
+const std::string KEYNAME_ENTRY_TRANSITION = "entryTransition";
+const std::string KEYNAME_EXIT_TRANSITION  = "exitTransition";
+const std::string KEYNAME_INCLUDES         = "includes";
+const std::string KEYNAME_INHERIT          = "inherit";
+const std::string KEYNAME_MAPPINGS         = "mappings";
+const std::string KEYNAME_NAME             = "name";
+const std::string KEYNAME_SIGNALS          = "signals";
+const std::string KEYNAME_STATES           = "states";
+const std::string KEYNAME_STYLES           = "styles";
+const std::string KEYNAME_TEMPLATES        = "templates";
+const std::string KEYNAME_TRANSITIONS      = "transitions";
+const std::string KEYNAME_TYPE             = "type";
+const std::string KEYNAME_VISUALS          = "visuals";
 
 const std::string PROPERTIES = "properties";
 const std::string ANIMATABLE_PROPERTIES = "animatableProperties";
@@ -104,7 +111,7 @@ bool GetMappingKey( const std::string& str, std::string& key )
 }
 
 /*
- * Recursively collects all stylesin a node (An array of style names).
+ * Recursively collects all styles in a node (An array of style names).
  *
  * stylesCollection The set of styles from the json file (a json object of named styles)
  * style The style array to begin the collection from
@@ -119,11 +126,16 @@ void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style,
     {
       if( OptionalString styleName = IsString( (*iter).second ) )
       {
-        if( OptionalChild node = IsChild( stylesCollection, *styleName) )
+        if( OptionalChild node = IsChildIgnoreCase( stylesCollection, *styleName) )
         {
           styleList.push_back( &(*node) );
 
-          if( OptionalChild subStyle = IsChild( *node, KEYNAME_STYLES ) )
+          OptionalChild subStyle = IsChild( *node, KEYNAME_INHERIT );
+          if( ! subStyle )
+          {
+            subStyle = IsChild( *node, KEYNAME_STYLES );
+          }
+          if( subStyle )
           {
             CollectAllStyles( stylesCollection, *subStyle, styleList );
           }
@@ -136,381 +148,267 @@ void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style,
 
 } // namespace anon
 
-/*
- * Sets the handle properties found in the tree node
- */
-void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
+
+Builder::Builder()
+: mSlotDelegate( this )
 {
-  if( handle )
-  {
+  mParser = Dali::Toolkit::JsonParser::New();
 
-    for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
-    {
-      const TreeNode::KeyNodePair& keyChild = *iter;
+  Property::Map defaultDirs;
+  defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ]       = DALI_IMAGE_DIR;
+  defaultDirs[ TOKEN_STRING(DALI_SOUND_DIR) ]       = DALI_SOUND_DIR;
+  defaultDirs[ TOKEN_STRING(DALI_STYLE_DIR) ]       = DALI_STYLE_DIR;
+  defaultDirs[ TOKEN_STRING(DALI_STYLE_IMAGE_DIR) ] = DALI_STYLE_IMAGE_DIR;
 
-      std::string key( keyChild.first );
+  AddConstants( defaultDirs );
+}
 
-      // ignore special fields; type,actors,signals,styles
-      if(key == KEYNAME_TYPE || key == KEYNAME_ACTORS || key == KEYNAME_SIGNALS || key == KEYNAME_STYLES || key == KEYNAME_MAPPINGS )
-      {
-        continue;
-      }
+void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format )
+{
+  // parser to get constants and includes only
+  Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New();
 
-      Handle propertyObject( handle );
+  if( !parser.Parse( data ) )
+  {
+    DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
+                      parser.GetErrorLineNumber(),
+                      parser.GetErrorColumn(),
+                      parser.GetErrorDescription().c_str() );
 
-      Dali::Property::Index index = propertyObject.GetPropertyIndex( key );
+    DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
+  }
+  else
+  {
+    // load configuration map
+    LoadConfiguration( *parser.GetRoot(), mConfigurationMap );
+    // load constant map (allows the user to override the constants in the json after loading)
+    LoadConstants( *parser.GetRoot(), mReplacementMap );
+    // merge includes
+    if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) )
+    {
+      Replacement replacer( mReplacementMap );
 
-      if( Property::INVALID_INDEX != index )
+      for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter)
       {
-        Property::Type type = propertyObject.GetPropertyType(index);
-        Property::Value value;
-        bool mapped = false;
+        OptionalString filename = replacer.IsString( (*iter).second );
 
-        // if node.value is a mapping, get the property value from the "mappings" table
-        if( keyChild.second.GetType() == TreeNode::STRING )
-        {
-          std::string mappingKey;
-          if( GetMappingKey(keyChild.second.GetString(), mappingKey) )
-          {
-            OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
-            mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
-          }
-        }
-        if( ! mapped )
-        {
-          mapped = DeterminePropertyFromNode( keyChild.second, type, value, constant );
-          if( ! mapped )
-          {
-            // verbose as this might not be a problem
-            // eg parentOrigin can be a string which is picked up later
-            DALI_SCRIPT_VERBOSE("Could not convert property:%s\n", key.c_str());
-          }
-        }
-        if( mapped )
+        if( filename )
         {
-          DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
-
-          propertyObject.SetProperty( index, value );
+#if defined(DEBUG_ENABLED)
+          DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str());
+#endif
+          LoadFromString( GetFileContents(*filename) );
         }
       }
-      else
-      {
-        DALI_SCRIPT_VERBOSE("SetProperty INVALID '%s' Index=:%d\n", key.c_str(), index);
-      }
+    }
 
-      // Add custom properties
-      SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
-      SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
+    if( mParser.Parse( data ) )
+    {
+      // Drop the styles and get them to be rebuilt against the new parse tree as required.
+      mStyles.Clear();
+    }
+    else
+    {
+      DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
+                        mParser.GetErrorLineNumber(),
+                        mParser.GetErrorColumn(),
+                        mParser.GetErrorDescription().c_str() );
 
-    } // for property nodes
-  }
-  else
-  {
-    DALI_SCRIPT_WARNING("Style applied to empty handle\n");
+      DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
+    }
   }
+
+  DUMP_PARSE_TREE(mParser); // This macro only writes out if DEBUG is enabled and the "DUMP_TREE" constant is defined in the stylesheet.
+  DUMP_TEST_MAPPINGS(mParser);
+
+  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
 }
 
-void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
-                          const std::string& childName, Property::AccessMode accessMode )
+void Builder::AddConstants( const Property::Map& map )
 {
-  // Add custom properties
-  if( OptionalChild customPropertiesChild = IsChild(node, childName) )
-  {
-    const TreeNode& customPropertiesNode = *customPropertiesChild;
-    const TreeConstIter endIter = customPropertiesNode.CEnd();
-    for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
-    {
-      const TreeNode::KeyNodePair& keyChild = *iter;
-      std::string key( keyChild.first );
+  mReplacementMap.Merge( map );
+}
 
-      Property::Value value;
-      DeterminePropertyFromNode( keyChild.second, value, constant );
-      // Register/Set property.
-      handle.RegisterProperty( key, value, accessMode );
-    }
-  }
+void Builder::AddConstant( const std::string& key, const Property::Value& value )
+{
+  mReplacementMap[key] = value;
 }
 
-// Set properties from node on handle.
-void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
-                               Dali::Handle& handle, const Replacement& constant )
+const Property::Map& Builder::GetConfigurations() const
 {
-  if( Actor actor = Actor::DownCast(handle) )
-  {
-    SetProperties( node, actor, constant );
+  return mConfigurationMap;
+}
 
-    if( actor )
-    {
-      SetupActor( node, actor, constant );
+const Property::Map& Builder::GetConstants() const
+{
+  return mReplacementMap;
+}
 
-      // add signals
-      SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
-      SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
-   }
+const Property::Value& Builder::GetConstant( const std::string& key ) const
+{
+  Property::Value* match = mReplacementMap.Find( key );
+  if( match )
+  {
+    return (*match);
   }
   else
   {
-    SetProperties( node, handle, constant );
+    static Property::Value invalid;
+    return invalid;
   }
 }
 
-// Appling by style helper
-// use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
-void Builder::ApplyStylesByActor(  const TreeNode& root, const TreeNode& node,
-                                   Dali::Handle& handle, const Replacement& constant )
+Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
 {
-  if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
-  {
-    if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
-    {
-      // in a style the actor subtree properties referenced by actor name
-      for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
-      {
-        Dali::Actor foundActor;
-
-        if( (*iter).first )
-        {
-          foundActor = actor.FindChildByName( (*iter).first );
-        }
-
-        if( !foundActor )
-        {
-          // debug log cannot find searched for actor
-#if defined(DEBUG_ENABLED)
-          DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
-#endif
-        }
-        else
-        {
-#if defined(DEBUG_ENABLED)
-          DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
-#endif
-          ApplyProperties( root, (*iter).second, foundActor, constant );
-        }
-      }
-    }
-  }
+  Replacement replacement(map, mReplacementMap);
+  return CreateAnimation( animationName, replacement, sourceActor);
 }
 
+Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
+{
+  Replacement replacement(map, mReplacementMap);
+  return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
+}
 
-void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
-                                       Dali::Handle& handle, const Replacement& constant )
+Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
 {
-  OptionalChild styles = IsChild(root, KEYNAME_STYLES);
-  OptionalChild style  = IsChild(node, KEYNAME_STYLES);
+  Replacement replacement( mReplacementMap );
 
-  if( styles && style )
-  {
-    TreeNodeList additionalStyles;
+  return CreateAnimation( animationName, replacement, sourceActor );
+}
 
-    CollectAllStyles( *styles, *style, additionalStyles );
+Animation Builder::CreateAnimation( const std::string& animationName )
+{
+  Replacement replacement( mReplacementMap );
 
-#if defined(DEBUG_ENABLED)
-    for(TreeNode::ConstIterator iter = (*style).CBegin(); iter != (*style).CEnd(); ++iter)
-    {
-      if( OptionalString styleName = IsString( (*iter).second ) )
-      {
-        DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
-      }
-    }
-#endif
+  return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
+}
 
-    // a style may have other styles, which has other styles etc so we apply in reverse by convention.
-    for(TreeNodeList::reverse_iterator iter = additionalStyles.rbegin(); iter != additionalStyles.rend(); ++iter)
-    {
-      ApplyProperties( root, *(*iter), handle, constant );
+BaseHandle Builder::Create( const std::string& templateName )
+{
+  Replacement replacement( mReplacementMap );
+  return Create( templateName, replacement );
+}
 
-      ApplyStylesByActor( root, *(*iter), handle, constant );
-    }
-  }
+BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
+{
+  Replacement replacement( map, mReplacementMap );
+  return Create( templateName, replacement );
+}
 
-  // applying given node last
-  ApplyProperties( root, node, handle, constant );
+BaseHandle Builder::CreateFromJson( const std::string& json )
+{
+  BaseHandle ret;
 
-  ApplyStylesByActor( root, node, handle, constant );
+  // merge in new template, hoping no one else has one named '@temp@'
+  std::string newTemplate =
+    std::string("{\"templates\":{\"@temp@\":") +                      \
+    json +                                                            \
+    std::string("}}");
 
-}
+  if( mParser.Parse(newTemplate) )
+  {
+    Replacement replacement( mReplacementMap );
+    ret = Create( "@temp@", replacement );
+  }
 
+  return ret;
+}
 
-/*
- * Create a dali type from a node.
- * If parent given and an actor type was created then add it to the parent and
- * recursively add nodes children.
- */
-BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
-                              Actor parent, const Replacement& replacements )
+bool Builder::ApplyFromJson(  Handle& handle, const std::string& json )
 {
-  BaseHandle baseHandle;
-  TypeInfo typeInfo;
-  const TreeNode* templateNode = NULL;
+  bool ret = false;
 
-  if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
-  {
-    typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
-
-    if( !typeInfo )
-    {
-      // a template name is also allowed inplace of the type name
-      OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
-
-      if( templates )
-      {
-        if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
-        {
-          templateNode = &(*isTemplate);
-
-          if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
-          {
-            typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
-          }
-        }
-      }
-    }
-  }
+  // merge new style, hoping no one else has one named '@temp@'
+  std::string newStyle =
+    std::string("{\"styles\":{\"@temp@\":") +                           \
+    json +                                                              \
+    std::string("}}");
 
-  if(!typeInfo)
+  if( mParser.Parse(newStyle) )
   {
-    DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
+    Replacement replacement( mReplacementMap );
+    ret = ApplyStyle( "@temp@", handle, replacement );
   }
-  else
-  {
-    baseHandle       = typeInfo.CreateInstance();
-    Handle handle    = Handle::DownCast(baseHandle);
-    Actor actor      = Actor::DownCast(handle);
-
-    if(handle)
-    {
-
-      DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
-
-#if defined(DEBUG_ENABLED)
-      if(handle)
-      {
-        DALI_SCRIPT_VERBOSE("  Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
-        DALI_SCRIPT_VERBOSE("  Is Handle Property Count=%d\n", handle.GetPropertyCount());
-      }
-
-      if(actor)
-      {
-        DALI_SCRIPT_VERBOSE("  Is Actor id=%d\n", actor.GetId());
-      }
-
-      Toolkit::Control control  = Toolkit::Control::DownCast(handle);
-      if(control)
-      {
-        DALI_SCRIPT_VERBOSE("  Is Control id=%d\n", actor.GetId());
-      }
-#endif // DEBUG_ENABLED
 
-      if( templateNode )
-      {
-        ApplyProperties( root, *templateNode, handle, replacements );
+  return ret;
+}
 
-        if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
-        {
-          for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
-          {
-            DoCreate( root, (*iter).second, actor, replacements );
-          }
-        }
-      }
+bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
+{
+  Replacement replacer( mReplacementMap );
+  return ApplyStyle( styleName, handle, replacer );
+}
 
-      if( actor )
-      {
-        // add children of all the styles
-        if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
-        {
-          for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
-          {
-            DoCreate( root, (*iter).second, actor, replacements );
-          }
-        }
+bool Builder::LookupStyleName( const std::string& styleName )
+{
+  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
 
-        // apply style on top as they need the children to exist
-        ApplyAllStyleProperties( root, node, actor, replacements );
+  OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
+  OptionalChild style  = IsChildIgnoreCase( *styles, styleName );
 
-        // then add to parent
-        if( parent )
-        {
-          parent.Add( actor );
-        }
-      }
-      else
-      {
-        ApplyProperties( root, node, handle, replacements );
-      }
-    }
-    else
-    {
-      DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
-    }
+  if( styles && style )
+  {
+    return true;
   }
-
-  return baseHandle;
+  return false;
 }
 
-void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
+const StylePtr Builder::GetStyle( const std::string& styleName )
 {
-  const Stage& stage = Stage::GetCurrent();
-  Layer root  = stage.GetRootLayer();
+  const StylePtr* style = mStyles.FindConst( styleName );
 
-  if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
+  if( style==NULL )
   {
-    Actor actor = root.FindChildByName(*s);
-    if(actor)
-    {
-      task.SetSourceActor( actor );
-    }
-    else
-    {
-      DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
-    }
+    return StylePtr(NULL);
   }
-
-  if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
+  else
   {
-    CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
-    if(actor)
-    {
-      task.SetCameraActor( actor );
-    }
-    else
-    {
-      DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
-    }
+    return *style;
   }
+}
 
-  if( OptionalString s = constant.IsString( IsChild(node, "targetFrameBuffer") ) )
-  {
-    FrameBufferImage fb = GetFrameBufferImage( *s, constant );
-    if(fb)
-    {
-      task.SetTargetFrameBuffer( fb );
-    }
-    else
-    {
-      DALI_SCRIPT_WARNING("Cannot find target frame buffer '%s'\n", (*s).c_str() );
-    }
-  }
+void Builder::AddActors( Actor toActor )
+{
+  // 'stage' is the default/by convention section to add from
+  AddActors( "stage", toActor );
+}
 
-  if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
+void Builder::AddActors( const std::string &sectionName, Actor toActor )
+{
+  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
+
+  Property::Map overrideMap;
+  Replacement replacements(overrideMap, mReplacementMap);
+
+  OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
+
+  if( add )
   {
-    if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
-    {
-      task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
-    }
-    else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
+    for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
     {
-      task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
+      // empty actor adds directly to the stage
+      BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
+      Actor actor = Actor::DownCast(baseHandle);
+      if(actor)
+      {
+        toActor.Add( actor );
+      }
     }
-    else
+
+    // if were adding the 'stage' section then also check for a render task called stage
+    // to add automatically
+    if( "stage" == sectionName )
     {
-      DALI_SCRIPT_WARNING("todo");
+      if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
+      {
+        if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
+        {
+          CreateRenderTask( "stage" );
+        }
+      }
     }
   }
-
-  // other setup is via the property system
-  SetProperties( node, task, constant );
 }
 
 void Builder::CreateRenderTask( const std::string &name )
@@ -745,6 +643,7 @@ PathConstrainer Builder::GetPathConstrainer( const std::string& name )
   return ret;
 }
 
+
 bool Builder::IsPathConstrainer( const std::string& name )
 {
   size_t count( mPathConstrainerLut.size() );
@@ -881,472 +780,861 @@ void Builder::EmitQuitSignal()
   mQuitSignal.Emit();
 }
 
-void Builder::AddActors( Actor toActor )
+Builder::~Builder()
 {
-  // 'stage' is the default/by convention section to add from
-  AddActors( "stage", toActor );
 }
 
-void Builder::AddActors( const std::string &sectionName, Actor toActor )
+void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap )
 {
-  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
-
-  Property::Map overrideMap;
-  Replacement replacements(overrideMap, mReplacementMap);
-
-  OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
+  Replacement replacer(intoMap);
 
-  if( add )
+  if( OptionalChild constants = IsChild(root, "config") )
   {
-    for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
-    {
-      // empty actor adds directly to the stage
-      BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
-      Actor actor = Actor::DownCast(baseHandle);
-      if(actor)
-      {
-        toActor.Add( actor );
-      }
-    }
-
-    // if were adding the 'stage' section then also check for a render task called stage
-    // to add automatically
-    if( "stage" == sectionName )
+    for(TreeNode::ConstIterator iter = (*constants).CBegin();
+        iter != (*constants).CEnd(); ++iter)
     {
-      if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
+      Dali::Property::Value property;
+      if( (*iter).second.GetName() )
       {
-        if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
-        {
-          CreateRenderTask( "stage" );
-        }
+        DeterminePropertyFromNode( (*iter).second, property, replacer );
+        intoMap[ (*iter).second.GetName() ] = property;
       }
     }
   }
 }
 
-Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
+void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
 {
-  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
-
-  Animation anim;
+  Replacement replacer(intoMap);
 
-  if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
+  if( OptionalChild constants = IsChild(root, "constants") )
   {
-    if( OptionalChild animation = IsChild(*animations, animationName) )
-    {
-      anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
-    }
-    else
+    for(TreeNode::ConstIterator iter = (*constants).CBegin();
+        iter != (*constants).CEnd(); ++iter)
     {
-      DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
-    }
-  }
-  else
-  {
-    DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
+      Dali::Property::Value property;
+      if( (*iter).second.GetName() )
+      {
+#if defined(DEBUG_ENABLED)
+        DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
+#endif
+        DeterminePropertyFromNode( (*iter).second, property, replacer );
+        intoMap[ (*iter).second.GetName() ] = property;
+      }
+    }
   }
 
-  return anim;
+#if defined(DEBUG_ENABLED)
+  Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
+  if( iter && iter->GetType() == Property::STRING )
+  {
+    std::string logLevel( iter->Get< std::string >() );
+    if( logLevel == "NoLogging" )
+    {
+      gFilterScript->SetLogLevel( Integration::Log::NoLogging );
+    }
+    else if( logLevel == "Concise" )
+    {
+      gFilterScript->SetLogLevel( Integration::Log::Concise );
+    }
+    else if( logLevel == "General" )
+    {
+      gFilterScript->SetLogLevel( Integration::Log::General );
+    }
+    else if( logLevel == "Verbose" )
+    {
+      gFilterScript->SetLogLevel( Integration::Log::Verbose );
+    }
+  }
+#endif
 }
 
-Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
+Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
 {
-  Replacement replacement(map, mReplacementMap);
-  return CreateAnimation( animationName, replacement, sourceActor);
-}
+  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
 
-Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
-{
-  Replacement replacement(map, mReplacementMap);
-  return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
-}
+  Animation anim;
 
-Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
-{
-  Replacement replacement( mReplacementMap );
+  if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
+  {
+    if( OptionalChild animation = IsChild(*animations, animationName) )
+    {
+      anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
+    }
+    else
+    {
+      DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
+    }
+  }
+  else
+  {
+    DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
+  }
 
-  return CreateAnimation( animationName, replacement, sourceActor );
+  return anim;
 }
 
-Animation Builder::CreateAnimation( const std::string& animationName )
+BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
 {
-  Replacement replacement( mReplacementMap );
+  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
 
-  return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
+  BaseHandle baseHandle;
+
+  OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
+
+  if( !templates )
+  {
+    DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
+  }
+  else
+  {
+    OptionalChild childTemplate = IsChild(*templates, templateName);
+    if(!childTemplate)
+    {
+      DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
+    }
+    else
+    {
+      OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
+
+      if(!type)
+      {
+        DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
+      }
+      else
+      {
+        baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
+      }
+    }
+  }
+
+  return baseHandle;
 }
 
-bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
+/*
+ * Create a dali type from a node.
+ * If parent given and an actor type was created then add it to the parent and
+ * recursively add nodes children.
+ */
+BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
+                              Actor parent, const Replacement& replacements )
 {
-  bool result = false;
+  BaseHandle baseHandle;
+  TypeInfo typeInfo;
+  const TreeNode* templateNode = NULL;
 
-  switch( child.GetType() )
+  if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
   {
-    case Property::STRING:
+    typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
+
+    if( !typeInfo )
     {
-      std::string value;
-      if( child.Get( value ) )
+      // a template name is also allowed inplace of the type name
+      OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
+
+      if( templates )
       {
-        std::string key;
-        if( GetMappingKey( value, key ) )
+        if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
         {
-          // Check key for cycles:
-          result=true;
-          for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
-          {
-            if( key.compare(*iter) == 0 )
-            {
-              // key is already in stack; stop.
-              DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
-              child = Property::Value("");
-              result=false;
-              break;
-            }
-          }
+          templateNode = &(*isTemplate);
 
-          if( result )
+          if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
           {
-            // The following call will overwrite the child with the value
-            // from the mapping.
-            RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
-            result = true;
+            typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
           }
         }
       }
-      break;
     }
+  }
 
-    case Property::MAP:
+  if(!typeInfo)
+  {
+    DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
+  }
+  else
+  {
+    baseHandle       = typeInfo.CreateInstance();
+    Handle handle    = Handle::DownCast(baseHandle);
+    Actor actor      = Actor::DownCast(handle);
+
+    if(handle)
     {
-      Property::Map* map = child.GetMap();
-      for( Property::Map::SizeType i=0; i < map->Count(); ++i )
+
+      DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
+
+#if defined(DEBUG_ENABLED)
+      if(handle)
       {
-        Property::Value& child = map->GetValue(i);
-        ConvertChildValue(mappingRoot, keyStack, child);
+        DALI_SCRIPT_VERBOSE("  Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
+        DALI_SCRIPT_VERBOSE("  Is Handle Property Count=%d\n", handle.GetPropertyCount());
       }
-      break;
-    }
 
-    case Property::ARRAY:
-    {
-      Property::Array* array = child.GetArray();
-      for( Property::Array::SizeType i=0; i < array->Count(); ++i )
+      if(actor)
       {
-        Property::Value& child = array->GetElementAt(i);
-        ConvertChildValue(mappingRoot, keyStack, child);
+        DALI_SCRIPT_VERBOSE("  Is Actor id=%d\n", actor.GetId());
       }
-      break;
+
+      Toolkit::Control control  = Toolkit::Control::DownCast(handle);
+      if(control)
+      {
+        DALI_SCRIPT_VERBOSE("  Is Control id=%d\n", actor.GetId());
+      }
+#endif // DEBUG_ENABLED
+
+      if( templateNode )
+      {
+        ApplyProperties( root, *templateNode, handle, replacements );
+
+        if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
+        {
+          for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
+          {
+            DoCreate( root, (*iter).second, actor, replacements );
+          }
+        }
+      }
+
+      if( actor )
+      {
+        // add children of all the styles
+        if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
+        {
+          for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
+          {
+            DoCreate( root, (*iter).second, actor, replacements );
+          }
+        }
+
+        // apply style on top as they need the children to exist
+        ApplyAllStyleProperties( root, node, actor, replacements );
+
+        // then add to parent
+        if( parent )
+        {
+          parent.Add( actor );
+        }
+      }
+      else
+      {
+        ApplyProperties( root, node, handle, replacements );
+      }
+    }
+    else
+    {
+      DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
     }
+  }
 
-    default:
-      // Ignore other types.
-      break;
+  return baseHandle;
+}
+
+void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
+{
+  const Stage& stage = Stage::GetCurrent();
+  Layer root  = stage.GetRootLayer();
+
+  if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
+  {
+    Actor actor = root.FindChildByName(*s);
+    if(actor)
+    {
+      task.SetSourceActor( actor );
+    }
+    else
+    {
+      DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
+    }
   }
 
-  return result;
+  if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
+  {
+    CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
+    if(actor)
+    {
+      task.SetCameraActor( actor );
+    }
+    else
+    {
+      DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
+    }
+  }
+
+  if( OptionalString s = constant.IsString( IsChild(node, "targetFrameBuffer") ) )
+  {
+    FrameBufferImage fb = GetFrameBufferImage( *s, constant );
+    if(fb)
+    {
+      task.SetTargetFrameBuffer( fb );
+    }
+    else
+    {
+      DALI_SCRIPT_WARNING("Cannot find target frame buffer '%s'\n", (*s).c_str() );
+    }
+  }
+
+  if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
+  {
+    if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
+    {
+      task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
+    }
+    else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
+    {
+      task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
+    }
+    else
+    {
+      DALI_SCRIPT_WARNING("todo");
+    }
+  }
+
+  // other setup is via the property system
+  SetProperties( node, task, constant );
 }
 
-bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
+bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
 {
-  Replacement replacer( mReplacementMap );
-  bool result = false;
+  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
 
-  keyStack.push_back( theKey );
+  OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
 
-  for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
+  std::string styleNameLower(styleName);
+  OptionalChild style  = IsChildIgnoreCase( *styles, styleNameLower );
+
+  if( styles && style )
   {
-    std::string aKey( (*iter).first );
-    if( aKey.compare( theKey ) == 0 )
+    ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
+    return true;
+  }
+  else
+  {
+    return false;
+  }
+}
+
+void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
+                                       Dali::Handle& handle, const Replacement& constant )
+{
+  const char* styleName = node.GetName();
+
+  StylePtr style = Style::New();
+
+  StylePtr* matchedStyle = NULL;
+  if( styleName )
+  {
+    matchedStyle = mStyles.Find( styleName );
+    if( ! matchedStyle )
     {
-      if( propertyType == Property::NONE )
+      OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
+      OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
+      if( !inheritFromNode )
       {
-        DeterminePropertyFromNode( (*iter).second, value, replacer );
-        result = true;
+        inheritFromNode = IsChild( node, KEYNAME_STYLES );
       }
-      else
+
+      if( styleNodes )
       {
-        result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
+        if( inheritFromNode )
+        {
+          TreeNodeList additionalStyleNodes;
+
+          CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
+
+#if defined(DEBUG_ENABLED)
+          for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
+          {
+            if( OptionalString styleName = IsString( (*iter).second ) )
+            {
+              DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
+            }
+          }
+#endif
+
+          // a style may have other styles, which has other styles etc so we apply in reverse by convention.
+          for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
+          {
+            RecordStyle( style, *(*iter), handle, constant );
+            ApplySignals( root, *(*iter), handle );
+            ApplyStylesByActor( root, *(*iter), handle, constant );
+          }
+        }
+
+        RecordStyle( style, node, handle, constant );
+        mStyles.Add( styleName, style ); // shallow copy
+        matchedStyle = &style;
       }
+    }
+  }
 
-      if( result )
+  if( matchedStyle )
+  {
+    StylePtr style( *matchedStyle );
+    Dictionary<Property::Map> instancedProperties;
+    style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties );
+  }
+  else // If there were no styles, instead set properties
+  {
+    SetProperties( node, handle, constant );
+  }
+  ApplySignals( root, node, handle );
+  ApplyStylesByActor( root, node, handle, constant );
+}
+
+void Builder::RecordStyle( StylePtr           style,
+                           const TreeNode&    node,
+                           Dali::Handle&      handle,
+                           const Replacement& replacements )
+{
+  // With repeated calls, accumulate inherited states, visuals and properties
+  // but override any with same name
+
+  for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
+  {
+    const TreeNode::KeyNodePair& keyValue = *iter;
+    std::string key( keyValue.first );
+    if( key == KEYNAME_STATES )
+    {
+      const TreeNode& states = keyValue.second;
+      if( states.GetType() != TreeNode::OBJECT )
       {
-        ConvertChildValue(mappingRoot, keyStack, value);
+        DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
+        continue;
+      }
+
+      for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
+      {
+        const TreeNode& stateNode = (*iter).second;
+        const char* stateName = stateNode.GetName();
+        if( stateNode.GetType() != TreeNode::OBJECT )
+        {
+          DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
+          continue;
+        }
+
+        StylePtr* stylePtr = style->subStates.Find( stateName );
+        if( stylePtr )
+        {
+          StylePtr style(*stylePtr);
+          RecordStyle( style, stateNode, handle, replacements );
+        }
+        else
+        {
+          StylePtr subState = Style::New();
+          RecordStyle( subState, stateNode, handle, replacements );
+          style->subStates.Add( stateName, subState );
+        }
+      }
+    }
+    else if( key == KEYNAME_VISUALS )
+    {
+      for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
+      {
+        // Each key in this table should be a property name matching a visual.
+        const TreeNode::KeyNodePair& visual = *iter;
+        Dali::Property::Value property(Property::MAP);
+        if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
+        {
+          Property::Map* mapPtr = style->visuals.Find( visual.first );
+          if( mapPtr )
+          {
+            // Override existing visuals
+            mapPtr->Clear();
+            mapPtr->Merge( *property.GetMap() );
+          }
+          else
+          {
+            Property::Map* map = property.GetMap();
+            if( map )
+            {
+              style->visuals.Add( visual.first, *map );
+            }
+          }
+        }
+      }
+    }
+    else if( key == KEYNAME_ENTRY_TRANSITION )
+    {
+      RecordTransitionData( keyValue, style->entryTransition, replacements );
+    }
+    else if( key == KEYNAME_EXIT_TRANSITION )
+    {
+      RecordTransitionData( keyValue, style->exitTransition, replacements );
+    }
+    else if( key == KEYNAME_TRANSITIONS )
+    {
+      RecordTransitions( keyValue, style->transitions, replacements );
+    }
+    else if( key == KEYNAME_TYPE ||
+             key == KEYNAME_ACTORS ||
+             key == KEYNAME_SIGNALS ||
+             key == KEYNAME_STYLES ||
+             key == KEYNAME_MAPPINGS ||
+             key == KEYNAME_INHERIT )
+    {
+      continue;
+    }
+    else // It's a property
+    {
+      Property::Index index;
+      Property::Value value;
+      if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
+      {
+        Property::Value* existingValuePtr = style->properties.Find( index );
+        if( existingValuePtr != NULL )
+        {
+          *existingValuePtr = value; // Overwrite existing property.
+        }
+        else
+        {
+          style->properties.Add( index, value );
+        }
       }
-      break;
     }
   }
-  keyStack.pop_back();
-
-  return result;
 }
 
+void Builder::RecordTransitions(
+  const TreeNode::KeyNodePair& keyValue,
+  Property::Array& value,
+  const Replacement& replacements )
+{
+  //@todo add new transitions to style.transitions
+  //      override existing transitions. A transition matches on target & property name
+  const TreeNode& node = keyValue.second;
+  if( node.GetType() == TreeNode::ARRAY )
+  {
+    Dali::Property::Value property(Property::ARRAY);
+    if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
+    {
+      value = *property.GetArray();
+    }
+  }
+  else if( node.GetType() == TreeNode::OBJECT )
+  {
+    Dali::Property::Value property(Property::MAP);
+    if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
+    {
+      Property::Array propertyArray;
+      propertyArray.Add( property );
+      value = propertyArray;
+    }
+  }
+  else
+  {
+    DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first );
+  }
+}
 
-bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
+void Builder::RecordTransitionData(
+  const TreeNode::KeyNodePair& keyValue,
+  Toolkit::TransitionData& transitionData,
+  const Replacement& replacements )
 {
-  KeyStack keyStack;
-  return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
+  const TreeNode& node = keyValue.second;
+  if( node.GetType() == TreeNode::ARRAY )
+  {
+    Dali::Property::Value property(Property::ARRAY);
+    if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) )
+    {
+      transitionData = Toolkit::TransitionData::New( *property.GetArray() );
+    }
+  }
+  else if( node.GetType() == TreeNode::OBJECT )
+  {
+    Dali::Property::Value property(Property::MAP);
+    if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
+    {
+      transitionData = Toolkit::TransitionData::New( *property.GetMap() );
+    }
+  }
 }
 
 
-void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format )
+// Set properties from node on handle.
+void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
+                               Dali::Handle& handle, const Replacement& constant )
 {
-  // parser to get constants and includes only
-  Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New();
+  SetProperties( node, handle, constant );
+  ApplySignals( root, node, handle );
+}
 
-  if( !parser.Parse( data ) )
+void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
+{
+  Actor actor = Actor::DownCast(handle);
+  if( actor )
   {
-    DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
-                      parser.GetErrorLineNumber(),
-                      parser.GetErrorColumn(),
-                      parser.GetErrorDescription().c_str() );
-
-    DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
+    // add signals
+    SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
+    SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
   }
-  else
-  {
-    // load constant map (allows the user to override the constants in the json after loading)
-    LoadConstants( *parser.GetRoot(), mReplacementMap );
+}
 
-    // merge includes
-    if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) )
-    {
-      Replacement replacer( mReplacementMap );
 
-      for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter)
+// Appling by style helper
+// use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
+void Builder::ApplyStylesByActor(  const TreeNode& root, const TreeNode& node,
+                                   Dali::Handle& handle, const Replacement& constant )
+{
+  if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
+  {
+    if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
+    {
+      // in a style the actor subtree properties referenced by actor name
+      for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
       {
-        OptionalString filename = replacer.IsString( (*iter).second );
+        Dali::Actor foundActor;
 
-        if( filename )
+        if( (*iter).first )
         {
-#if defined(DEBUG_ENABLED)
-          DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str());
-#endif
-          LoadFromString( GetFileContents(*filename) );
+          foundActor = actor.FindChildByName( (*iter).first );
+        }
+
+        if( !foundActor )
+        {
+          DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
+        }
+        else
+        {
+          DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
+          ApplyProperties( root, (*iter).second, foundActor, constant );
         }
       }
     }
+  }
+}
 
-    if( !mParser.Parse( data ) )
+/*
+ * Sets the handle properties found in the tree node
+ */
+void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
+{
+  if( handle )
+  {
+    for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
     {
-      DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
-                        mParser.GetErrorLineNumber(),
-                        mParser.GetErrorColumn(),
-                        mParser.GetErrorDescription().c_str() );
+      const TreeNode::KeyNodePair& keyChild = *iter;
 
-      DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
-    }
-  }
+      std::string key( keyChild.first );
 
-  DUMP_PARSE_TREE(parser); // This macro only writes out if DEBUG is enabled and the "DUMP_TREE" constant is defined in the stylesheet.
-  DUMP_TEST_MAPPINGS(parser);
+      // ignore special fields;
+      if( key == KEYNAME_TYPE ||
+          key == KEYNAME_ACTORS ||
+          key == KEYNAME_SIGNALS ||
+          key == KEYNAME_STYLES ||
+          key == KEYNAME_MAPPINGS ||
+          key == KEYNAME_INHERIT ||
+          key == KEYNAME_STATES ||
+          key == KEYNAME_VISUALS ||
+          key == KEYNAME_ENTRY_TRANSITION ||
+          key == KEYNAME_EXIT_TRANSITION ||
+          key == KEYNAME_TRANSITIONS )
+      {
+        continue;
+      }
 
-  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
-}
+      Property::Index index;
+      Property::Value value;
 
-void Builder::AddConstants( const Property::Map& map )
-{
-  mReplacementMap.Merge( map );
-}
+      bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
+      if( mapped )
+      {
+        DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
 
-void Builder::AddConstant( const std::string& key, const Property::Value& value )
-{
-  mReplacementMap[key] = value;
-}
+        handle.SetProperty( index, value );
+      }
 
-const Property::Map& Builder::GetConstants() const
-{
-  return mReplacementMap;
-}
+      // Add custom properties
+      SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
+      SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
 
-const Property::Value& Builder::GetConstant( const std::string& key ) const
-{
-  Property::Value* match = mReplacementMap.Find( key );
-  if( match )
-  {
-    return (*match);
+    } // for property nodes
   }
   else
   {
-    static Property::Value invalid;
-    return invalid;
+    DALI_SCRIPT_WARNING("Style applied to empty handle\n");
   }
 }
 
-void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
+bool Builder::MapToTargetProperty(
+  Handle&            propertyObject,
+  const std::string& key,
+  const TreeNode&    node,
+  const Replacement& constant,
+  Property::Index&   index,
+  Property::Value&   value )
 {
-  Replacement replacer(intoMap);
+  bool mapped = false;
 
-  if( OptionalChild constants = IsChild(root, "constants") )
+  index = propertyObject.GetPropertyIndex( key );
+  if( Property::INVALID_INDEX != index )
   {
-    for(TreeNode::ConstIterator iter = (*constants).CBegin();
-        iter != (*constants).CEnd(); ++iter)
+    Property::Type type = propertyObject.GetPropertyType(index);
+
+    // if node.value is a mapping, get the property value from the "mappings" table
+    if( node.GetType() == TreeNode::STRING )
     {
-      Dali::Property::Value property;
-      if( (*iter).second.GetName() )
+      std::string mappingKey;
+      if( GetMappingKey( node.GetString(), mappingKey) )
       {
-#if defined(DEBUG_ENABLED)
-        DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
-#endif
-        DeterminePropertyFromNode( (*iter).second, property, replacer );
-        intoMap[ (*iter).second.GetName() ] = property;
+        OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
+        mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
       }
     }
-  }
-
-#if defined(DEBUG_ENABLED)
-  Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
-  if( iter && iter->GetType() == Property::STRING )
-  {
-    std::string logLevel( iter->Get< std::string >() );
-    if( logLevel == "NoLogging" )
-    {
-      gFilterScript->SetLogLevel( Integration::Log::NoLogging );
-    }
-    else if( logLevel == "Concise" )
-    {
-      gFilterScript->SetLogLevel( Integration::Log::Concise );
-    }
-    else if( logLevel == "General" )
-    {
-      gFilterScript->SetLogLevel( Integration::Log::General );
-    }
-    else if( logLevel == "Verbose" )
+    if( ! mapped )
     {
-      gFilterScript->SetLogLevel( Integration::Log::Verbose );
+      mapped = DeterminePropertyFromNode( node, type, value, constant );
+      if( ! mapped )
+      {
+        // Just determine the property from the node and if it's valid, let the property object handle it
+        DeterminePropertyFromNode( node, value, constant );
+        mapped = ( value.GetType() != Property::NONE );
+      }
     }
   }
-#endif
-
-}
-
-bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
-{
-  Replacement replacer( mReplacementMap );
-  return ApplyStyle( styleName, handle, replacer );
-}
-
-bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
-{
-  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
-
-  OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
-  OptionalChild style  = IsChild( *styles, styleName );
-
-  if( styles && style )
-  {
-    ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
-    return true;
-  }
   else
   {
-    return false;
+    DALI_LOG_ERROR("Key '%s' not found.\n", key.c_str());
   }
+  return mapped;
 }
 
-BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
+bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
 {
-  Replacement replacement( map, mReplacementMap );
-  return Create( templateName, replacement );
+  KeyStack keyStack;
+  return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
 }
 
-BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
+bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
 {
-  DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
-
-  BaseHandle baseHandle;
+  Replacement replacer( mReplacementMap );
+  bool result = false;
 
-  OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
+  keyStack.push_back( theKey );
 
-  if( !templates )
-  {
-    DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
-  }
-  else
+  for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
   {
-    OptionalChild childTemplate = IsChild(*templates, templateName);
-    if(!childTemplate)
-    {
-      DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
-    }
-    else
+    std::string aKey( (*iter).first );
+    if( aKey.compare( theKey ) == 0 )
     {
-      OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
-
-      if(!type)
+      if( propertyType == Property::NONE )
       {
-        DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
+        DeterminePropertyFromNode( (*iter).second, value, replacer );
+        result = true;
       }
       else
       {
-        baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
+        result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
+      }
+
+      if( result )
+      {
+        ConvertChildValue(mappingRoot, keyStack, value);
       }
+      break;
     }
   }
+  keyStack.pop_back();
 
-  return baseHandle;
+  return result;
 }
 
-BaseHandle Builder::CreateFromJson( const std::string& json )
+bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
 {
-  BaseHandle ret;
-
-  // merge in new template, hoping no one else has one named '@temp@'
-  std::string newTemplate =
-    std::string("{\"templates\":{\"@temp@\":") +                      \
-    json +                                                            \
-    std::string("}}");
+  bool result = false;
 
-  if( mParser.Parse(newTemplate) )
+  switch( child.GetType() )
   {
-    Replacement replacement( mReplacementMap );
-    ret = Create( "@temp@", replacement );
-  }
+    case Property::STRING:
+    {
+      std::string value;
+      if( child.Get( value ) )
+      {
+        std::string key;
+        if( GetMappingKey( value, key ) )
+        {
+          // Check key for cycles:
+          result=true;
+          for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
+          {
+            if( key.compare(*iter) == 0 )
+            {
+              // key is already in stack; stop.
+              DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
+              child = Property::Value("");
+              result=false;
+              break;
+            }
+          }
 
-  return ret;
-}
+          if( result )
+          {
+            // The following call will overwrite the child with the value
+            // from the mapping.
+            RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
+            result = true;
+          }
+        }
+      }
+      break;
+    }
 
-bool Builder::ApplyFromJson(  Handle& handle, const std::string& json )
-{
-  bool ret = false;
+    case Property::MAP:
+    {
+      Property::Map* map = child.GetMap();
+      if( map )
+      {
+        for( Property::Map::SizeType i=0; i < map->Count(); ++i )
+        {
+          Property::Value& child = map->GetValue(i);
+          ConvertChildValue(mappingRoot, keyStack, child);
+        }
+      }
+      break;
+    }
 
-  // merge new style, hoping no one else has one named '@temp@'
-  std::string newStyle =
-    std::string("{\"styles\":{\"@temp@\":") +                           \
-    json +                                                              \
-    std::string("}}");
+    case Property::ARRAY:
+    {
+      Property::Array* array = child.GetArray();
+      if( array )
+      {
+        for( Property::Array::SizeType i=0; i < array->Count(); ++i )
+        {
+          Property::Value& child = array->GetElementAt(i);
+          ConvertChildValue(mappingRoot, keyStack, child);
+        }
+      }
+      break;
+    }
 
-  if( mParser.Parse(newStyle) )
-  {
-    Replacement replacement( mReplacementMap );
-    ret = ApplyStyle( "@temp@", handle, replacement );
+    default:
+      // Ignore other types.
+      break;
   }
 
-  return ret;
-}
-
-
-BaseHandle Builder::Create( const std::string& templateName )
-{
-  Replacement replacement( mReplacementMap );
-  return Create( templateName, replacement );
+  return result;
 }
 
-Builder::Builder()
-: mSlotDelegate( this )
+void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
+                          const std::string& childName, Property::AccessMode accessMode )
 {
-  mParser = Dali::Toolkit::JsonParser::New();
-
-  Property::Map defaultDirs;
-  defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ]       = DALI_IMAGE_DIR;
-  defaultDirs[ TOKEN_STRING(DALI_SOUND_DIR) ]       = DALI_SOUND_DIR;
-  defaultDirs[ TOKEN_STRING(DALI_STYLE_DIR) ]       = DALI_STYLE_DIR;
-  defaultDirs[ TOKEN_STRING(DALI_STYLE_IMAGE_DIR) ] = DALI_STYLE_IMAGE_DIR;
+  // Add custom properties
+  if( OptionalChild customPropertiesChild = IsChild(node, childName) )
+  {
+    const TreeNode& customPropertiesNode = *customPropertiesChild;
+    const TreeConstIter endIter = customPropertiesNode.CEnd();
+    for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
+    {
+      const TreeNode::KeyNodePair& keyChild = *iter;
+      std::string key( keyChild.first );
+      Property::Value value;
+      DeterminePropertyFromNode( keyChild.second, value, constant );
 
-  AddConstants( defaultDirs );
+      // Register/Set property.
+      handle.RegisterProperty( key, value, accessMode );
+    }
+  }
 }
 
-Builder::~Builder()
-{
-}
 
 } // namespace Internal