5165a09798f5333da62aec4ab3d13ff16f3c1821
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / builder / builder-impl.cpp
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/builder/builder-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <sys/stat.h>
23 #include <sstream>
24
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>
35
36 // INTERNAL INCLUDES
37 #include <dali-toolkit/public-api/controls/control.h>
38 #include <dali-toolkit/devel-api/asset-manager/asset-manager.h>
39 #include <dali-toolkit/devel-api/builder/json-parser.h>
40
41 #include <dali-toolkit/internal/builder/builder-declarations.h>
42 #include <dali-toolkit/internal/builder/builder-filesystem.h>
43 #include <dali-toolkit/internal/builder/builder-get-is.inl.h>
44 #include <dali-toolkit/internal/builder/builder-impl-debug.h>
45 #include <dali-toolkit/internal/builder/builder-set-property.h>
46 #include <dali-toolkit/internal/builder/replacement.h>
47 #include <dali-toolkit/internal/builder/tree-node-manipulator.h>
48
49 namespace Dali
50 {
51
52 namespace Toolkit
53 {
54
55 namespace Internal
56 {
57 class Replacement;
58
59 extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder );
60
61 extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
62
63 extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder);
64
65
66 #if defined(DEBUG_ENABLED)
67 Integration::Log::Filter* gFilterScript  = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT");
68 #endif
69
70 namespace
71 {
72
73 #define TOKEN_STRING(x) #x
74
75 const std::string KEYNAME_ACTORS           = "actors";
76 const std::string KEYNAME_ENTRY_TRANSITION = "entryTransition";
77 const std::string KEYNAME_EXIT_TRANSITION  = "exitTransition";
78 const std::string KEYNAME_INCLUDES         = "includes";
79 const std::string KEYNAME_INHERIT          = "inherit";
80 const std::string KEYNAME_MAPPINGS         = "mappings";
81 const std::string KEYNAME_NAME             = "name";
82 const std::string KEYNAME_SIGNALS          = "signals";
83 const std::string KEYNAME_STATES           = "states";
84 const std::string KEYNAME_STYLES           = "styles";
85 const std::string KEYNAME_TEMPLATES        = "templates";
86 const std::string KEYNAME_TRANSITIONS      = "transitions";
87 const std::string KEYNAME_TYPE             = "type";
88 const std::string KEYNAME_VISUALS          = "visuals";
89
90 const std::string PROPERTIES = "properties";
91 const std::string ANIMATABLE_PROPERTIES = "animatableProperties";
92
93 typedef std::vector<const TreeNode*> TreeNodeList;
94
95
96 bool GetMappingKey( const std::string& str, std::string& key )
97 {
98   bool result = false;
99   std::string test( str );
100   if( ! test.empty() )
101   {
102     if( test.at(0) == '<' )
103     {
104       if( test.at(test.length()-1) == '>' )
105       {
106         key = test.substr( 1, test.length()-2 );
107         result = true;
108       }
109     }
110   }
111   return result;
112 }
113
114 /*
115  * Recursively collects all styles in a node (An array of style names).
116  *
117  * stylesCollection The set of styles from the json file (a json object of named styles)
118  * style The style array to begin the collection from
119  * styleList The style list to add nodes to apply
120  */
121 void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList )
122 {
123   // style is an array of style names
124   if( TreeNode::ARRAY == style.GetType() )
125   {
126     for(TreeNode::ConstIterator iter = style.CBegin(); iter != style.CEnd(); ++iter)
127     {
128       if( OptionalString styleName = IsString( (*iter).second ) )
129       {
130         if( OptionalChild node = IsChildIgnoreCase( stylesCollection, *styleName) )
131         {
132           styleList.push_back( &(*node) );
133
134           OptionalChild subStyle = IsChild( *node, KEYNAME_INHERIT );
135           if( ! subStyle )
136           {
137             subStyle = IsChild( *node, KEYNAME_STYLES );
138           }
139           if( subStyle )
140           {
141             CollectAllStyles( stylesCollection, *subStyle, styleList );
142           }
143         }
144       }
145     }
146   }
147 }
148
149
150 } // namespace anon
151
152
153 Builder::Builder()
154 : mSlotDelegate( this )
155 {
156   mParser = Dali::Toolkit::JsonParser::New();
157
158   Property::Map defaultDirs;
159   defaultDirs[TOKEN_STRING(DALI_IMAGE_DIR)]       = AssetManager::GetDaliImagePath();
160   defaultDirs[TOKEN_STRING(DALI_SOUND_DIR)]       = AssetManager::GetDaliSoundPath();
161   defaultDirs[TOKEN_STRING(DALI_STYLE_DIR)]       = AssetManager::GetDaliStylePath();
162   defaultDirs[TOKEN_STRING(DALI_STYLE_IMAGE_DIR)] = AssetManager::GetDaliStyleImagePath();
163
164   AddConstants( defaultDirs );
165 }
166
167 void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format )
168 {
169   // parser to get constants and includes only
170   Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New();
171
172   if( !parser.Parse( data ) )
173   {
174     DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
175                       parser.GetErrorLineNumber(),
176                       parser.GetErrorColumn(),
177                       parser.GetErrorDescription().c_str() );
178
179     DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
180   }
181   else
182   {
183     // load constant map (allows the user to override the constants in the json after loading)
184     LoadConstants( *parser.GetRoot(), mReplacementMap );
185     // load configuration map
186     LoadConfiguration( *parser.GetRoot(), mConfigurationMap );
187     // merge includes
188     if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) )
189     {
190       Replacement replacer( mReplacementMap );
191
192       for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter)
193       {
194         OptionalString filename = replacer.IsString( (*iter).second );
195
196         if( filename )
197         {
198 #if defined(DEBUG_ENABLED)
199           DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str());
200 #endif
201           LoadFromString( GetFileContents(*filename) );
202         }
203       }
204     }
205
206     if( mParser.Parse( data ) )
207     {
208       // Drop the styles and get them to be rebuilt against the new parse tree as required.
209       mStyles.Clear();
210     }
211     else
212     {
213       DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n",
214                         mParser.GetErrorLineNumber(),
215                         mParser.GetErrorColumn(),
216                         mParser.GetErrorDescription().c_str() );
217
218       DALI_ASSERT_ALWAYS(!"Cannot parse JSON");
219     }
220   }
221
222   DUMP_PARSE_TREE(mParser); // This macro only writes out if DEBUG is enabled and the "DUMP_TREE" constant is defined in the stylesheet.
223   DUMP_TEST_MAPPINGS(mParser);
224
225   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON");
226 }
227
228 void Builder::AddConstants( const Property::Map& map )
229 {
230   mReplacementMap.Merge( map );
231 }
232
233 void Builder::AddConstant( const std::string& key, const Property::Value& value )
234 {
235   mReplacementMap[key] = value;
236 }
237
238 const Property::Map& Builder::GetConfigurations() const
239 {
240   return mConfigurationMap;
241 }
242
243 const Property::Map& Builder::GetConstants() const
244 {
245   return mReplacementMap;
246 }
247
248 const Property::Value& Builder::GetConstant( const std::string& key ) const
249 {
250   Property::Value* match = mReplacementMap.Find( key );
251   if( match )
252   {
253     return (*match);
254   }
255   else
256   {
257     static Property::Value invalid;
258     return invalid;
259   }
260 }
261
262 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor )
263 {
264   Replacement replacement(map, mReplacementMap);
265   return CreateAnimation( animationName, replacement, sourceActor);
266 }
267
268 Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map )
269 {
270   Replacement replacement(map, mReplacementMap);
271   return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() );
272 }
273
274 Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor )
275 {
276   Replacement replacement( mReplacementMap );
277
278   return CreateAnimation( animationName, replacement, sourceActor );
279 }
280
281 Animation Builder::CreateAnimation( const std::string& animationName )
282 {
283   Replacement replacement( mReplacementMap );
284
285   return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() );
286 }
287
288 BaseHandle Builder::Create( const std::string& templateName )
289 {
290   Replacement replacement( mReplacementMap );
291   return Create( templateName, replacement );
292 }
293
294 BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map )
295 {
296   Replacement replacement( map, mReplacementMap );
297   return Create( templateName, replacement );
298 }
299
300 BaseHandle Builder::CreateFromJson( const std::string& json )
301 {
302   BaseHandle ret;
303
304   // merge in new template, hoping no one else has one named '@temp@'
305   std::string newTemplate =
306     std::string("{\"templates\":{\"@temp@\":") +                      \
307     json +                                                            \
308     std::string("}}");
309
310   if( mParser.Parse(newTemplate) )
311   {
312     Replacement replacement( mReplacementMap );
313     ret = Create( "@temp@", replacement );
314   }
315
316   return ret;
317 }
318
319 bool Builder::ApplyFromJson(  Handle& handle, const std::string& json )
320 {
321   bool ret = false;
322
323   // merge new style, hoping no one else has one named '@temp@'
324   std::string newStyle =
325     std::string("{\"styles\":{\"@temp@\":") +                           \
326     json +                                                              \
327     std::string("}}");
328
329   if( mParser.Parse(newStyle) )
330   {
331     Replacement replacement( mReplacementMap );
332     ret = ApplyStyle( "@temp@", handle, replacement );
333   }
334
335   return ret;
336 }
337
338 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle )
339 {
340   Replacement replacer( mReplacementMap );
341   return ApplyStyle( styleName, handle, replacer );
342 }
343
344 bool Builder::LookupStyleName( const std::string& styleName )
345 {
346   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
347
348   OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
349   OptionalChild style  = IsChildIgnoreCase( *styles, styleName );
350
351   if( styles && style )
352   {
353     return true;
354   }
355   return false;
356 }
357
358 const StylePtr Builder::GetStyle( const std::string& styleName )
359 {
360   const StylePtr* style = mStyles.FindConst( styleName );
361
362   if( style==NULL )
363   {
364     return StylePtr(NULL);
365   }
366   else
367   {
368     return *style;
369   }
370 }
371
372 void Builder::AddActors( Actor toActor )
373 {
374   // 'stage' is the default/by convention section to add from
375   AddActors( "stage", toActor );
376 }
377
378 void Builder::AddActors( const std::string &sectionName, Actor toActor )
379 {
380   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
381
382   Property::Map overrideMap;
383   Replacement replacements(overrideMap, mReplacementMap);
384
385   OptionalChild add = IsChild(*mParser.GetRoot(), sectionName);
386
387   if( add )
388   {
389     for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter )
390     {
391       // empty actor adds directly to the stage
392       BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements );
393       Actor actor = Actor::DownCast(baseHandle);
394       if(actor)
395       {
396         toActor.Add( actor );
397       }
398     }
399
400     // if were adding the 'stage' section then also check for a render task called stage
401     // to add automatically
402     if( "stage" == sectionName )
403     {
404       if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") )
405       {
406         if( OptionalChild tasks = IsChild(*renderTasks, "stage") )
407         {
408           CreateRenderTask( "stage" );
409         }
410       }
411     }
412   }
413 }
414
415 void Builder::CreateRenderTask( const std::string &name )
416 {
417   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
418
419   Replacement constant(mReplacementMap);
420
421   const Stage& stage = Stage::GetCurrent();
422
423   OptionalChild tasks = IsChild(*mParser.GetRoot(), "renderTasks");
424
425   if(tasks)
426   {
427     //
428     // Create the tasks from the current task as generally we want
429     // to setup task zero and onwards. Although this does overwrite
430     // the properties of the current task.
431     //
432     if( OptionalChild renderTask = IsChild(*tasks, name ) )
433     {
434       RenderTaskList list = stage.GetRenderTaskList();
435       unsigned int start = list.GetTaskCount();
436
437       RenderTask task;
438       if(0 == start)
439       {
440         // zero should have already been created by the stage so really
441         // this case should never happen
442         task = list.CreateTask();
443         start++;
444       }
445
446       TreeNode::ConstIterator iter = (*renderTask).CBegin();
447       task = list.GetTask( start - 1 );
448
449       SetupTask( task, (*iter).second, constant  );
450
451       ++iter;
452
453       for(; iter != (*renderTask).CEnd(); ++iter )
454       {
455         task = list.CreateTask();
456         SetupTask( task, (*iter).second, constant );
457       }
458     }
459   }
460 }
461
462 Path Builder::GetPath( const std::string& name )
463 {
464   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
465
466   Path ret;
467
468   PathLut::const_iterator iter( mPathLut.find( name ) );
469   if( iter != mPathLut.end() )
470   {
471     ret = iter->second;
472   }
473   else
474   {
475     if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") )
476     {
477       if( OptionalChild path = IsChild( *paths, name ) )
478       {
479         //points property
480         if( OptionalChild pointsProperty = IsChild( *path, "points") )
481         {
482           Dali::Property::Value points(Property::ARRAY);
483           if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
484           {
485             ret = Path::New();
486             ret.SetProperty( Path::Property::POINTS, points);
487
488             //controlPoints property
489             if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") )
490             {
491               Dali::Property::Value points(Property::ARRAY);
492               if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
493               {
494                 ret.SetProperty( Path::Property::CONTROL_POINTS, points);
495               }
496             }
497             else
498             {
499               //Curvature
500               float curvature(0.25f);
501               if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") )
502               {
503                 curvature = *pointsProperty;
504               }
505               ret.GenerateControlPoints(curvature);
506             }
507
508             //Add the new path to the hash table for paths
509             mPathLut[ name ] = ret;
510           }
511         }
512         else
513         {
514           //Interpolation points not specified
515           DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() );
516         }
517       }
518
519     }
520   }
521
522   return ret;
523 }
524
525 PathConstrainer Builder::GetPathConstrainer( const std::string& name )
526 {
527   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
528
529   //Search the pathConstrainer in the LUT
530   size_t count( mPathConstrainerLut.size() );
531   for( size_t i(0); i!=count; ++i )
532   {
533     if( mPathConstrainerLut[i].name == name )
534     {
535       //PathConstrainer has already been created
536       return mPathConstrainerLut[i].pathConstrainer;
537     }
538   }
539
540   //Create a new PathConstrainer
541   PathConstrainer ret;
542   if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
543   {
544     if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) )
545     {
546       OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type")));
547       if(!constrainerType)
548       {
549         DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
550       }
551       else if( *constrainerType == "PathConstrainer")
552       {
553         //points property
554         if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") )
555         {
556           Dali::Property::Value points(Property::ARRAY);
557           if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
558           {
559             ret = PathConstrainer::New();
560             ret.SetProperty( PathConstrainer::Property::POINTS, points);
561
562             //controlPoints property
563             if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") )
564             {
565               Dali::Property::Value points(Property::ARRAY);
566               if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
567               {
568                 ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points);
569               }
570
571               //Forward vector
572               OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) );
573               if( forward )
574               {
575                 ret.SetProperty( PathConstrainer::Property::FORWARD, *forward);
576               }
577
578               //Add the new constrainer to the vector of PathConstrainer
579               PathConstrainerEntry entry = {name,ret};
580               mPathConstrainerLut.push_back( entry );
581             }
582             else
583             {
584               //Control points not specified
585               DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() );
586             }
587           }
588         }
589         else
590         {
591           //Interpolation points not specified
592           DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() );
593         }
594       }
595       else
596       {
597         DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() );
598       }
599     }
600   }
601
602   return ret;
603 }
604
605
606 bool Builder::IsPathConstrainer( const std::string& name )
607 {
608   size_t count( mPathConstrainerLut.size() );
609   for( size_t i(0); i!=count; ++i )
610   {
611     if( mPathConstrainerLut[i].name == name )
612     {
613       return true;
614     }
615   }
616
617   if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
618   {
619     if( OptionalChild constrainer = IsChild( *constrainers, name ) )
620     {
621       OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
622       if(!constrainerType)
623       {
624         return false;
625       }
626       else
627       {
628          return *constrainerType == "PathConstrainer";
629       }
630     }
631   }
632   return false;
633 }
634
635 Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name )
636 {
637   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
638
639   //Search the LinearConstrainer in the LUT
640   size_t count( mLinearConstrainerLut.size() );
641   for( size_t i(0); i!=count; ++i )
642   {
643     if( mLinearConstrainerLut[i].name == name )
644     {
645       //LinearConstrainer has already been created
646       return mLinearConstrainerLut[i].linearConstrainer;
647     }
648   }
649
650   //Create a new LinearConstrainer
651   LinearConstrainer ret;
652   if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
653   {
654     if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) )
655     {
656       OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type")));
657       if(!constrainerType)
658       {
659         DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() );
660       }
661       else if( *constrainerType == "LinearConstrainer")
662       {
663         //points property
664         if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") )
665         {
666           Dali::Property::Value points(Property::ARRAY);
667           if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
668           {
669             ret = Dali::LinearConstrainer::New();
670             ret.SetProperty( LinearConstrainer::Property::VALUE, points);
671
672             //controlPoints property
673             if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") )
674             {
675               Dali::Property::Value points(Property::ARRAY);
676               if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) )
677               {
678                 ret.SetProperty( LinearConstrainer::Property::PROGRESS, points);
679               }
680             }
681             //Add the new constrainer to vector of LinearConstrainer
682             LinearConstrainerEntry entry = {name,ret};
683             mLinearConstrainerLut.push_back( entry );
684           }
685         }
686         else
687         {
688           //Interpolation points not specified
689           DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() );
690         }
691       }
692       else
693       {
694         DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() );
695       }
696     }
697   }
698
699   return ret;
700 }
701
702 bool Builder::IsLinearConstrainer( const std::string& name )
703 {
704   // Search the LinearConstrainer in the LUT
705   size_t count( mLinearConstrainerLut.size() );
706   for( size_t i(0); i!=count; ++i )
707   {
708     if( mLinearConstrainerLut[i].name == name )
709     {
710       return true;
711     }
712   }
713
714   if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") )
715   {
716     if( OptionalChild constrainer = IsChild( *constrainers, name ) )
717     {
718       OptionalString constrainerType(IsString(IsChild(*constrainer, "type")));
719       if(!constrainerType)
720       {
721         return false;
722       }
723       else
724       {
725          return *constrainerType == "LinearConstrainer";
726       }
727     }
728   }
729   return false;
730 }
731
732 Toolkit::Builder::BuilderSignalType& Builder::QuitSignal()
733 {
734   return mQuitSignal;
735 }
736
737 void Builder::EmitQuitSignal()
738 {
739   mQuitSignal.Emit();
740 }
741
742 Builder::~Builder()
743 {
744 }
745
746 void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap )
747 {
748   Replacement replacer(intoMap);
749
750   if( OptionalChild constants = IsChild(root, "config") )
751   {
752     for(TreeNode::ConstIterator iter = (*constants).CBegin();
753         iter != (*constants).CEnd(); ++iter)
754     {
755       Dali::Property::Value property;
756       if( (*iter).second.GetName() )
757       {
758         DeterminePropertyFromNode( (*iter).second, property, replacer );
759
760         // If config is string, find constant and replace it to original value.
761         if( (*iter).second.GetType() == TreeNode::STRING )
762         {
763           std::string stringConfigValue;
764           if( property.Get( stringConfigValue ) )
765           {
766             std::size_t pos = 0;
767
768             while( pos < stringConfigValue.size() )
769             {
770               // If we can't find "{","}" pair in stringConfigValue, will out loop.
771               std::size_t leftPos = stringConfigValue.find( "{", pos );
772               if( leftPos != std::string::npos )
773               {
774                 std::size_t rightPos = stringConfigValue.find( "}", pos+1 );
775
776                 if( rightPos != std::string::npos )
777                 {
778                   // If we find "{","}" pair but can't find matched constant
779                   // try to find other "{","}" pair after current left position.
780                   pos = leftPos+1;
781
782                   for( uint32_t i = 0; i < mReplacementMap.Count() ; i++ )
783                   {
784                     Property::Key constant = mReplacementMap.GetKeyAt(i);
785
786                     // Compare string which is between "{" and "}" with constant string
787                     // If they are same, change string in stringConfigValue to mapped constant value.
788                     if ( 0 == stringConfigValue.compare( leftPos+1, rightPos-leftPos-1, constant.stringKey ) )
789                     {
790                       std::string replaceString;
791                       mReplacementMap.GetValue(i).Get( replaceString );
792
793                       stringConfigValue.replace( leftPos, rightPos-leftPos+1, replaceString );
794                       pos = leftPos + replaceString.size();
795                       break;
796                     }
797                   }
798                 }
799                 else
800                 {
801                   // If we cannot find constant in const value, will out loop.
802                   pos = stringConfigValue.size();
803                 }
804               }
805               else
806               {
807                 // If we cannot find constant in const value, will out loop.
808                 pos = stringConfigValue.size();
809               }
810             }
811             property = Property::Value( stringConfigValue );
812           }
813         }
814         intoMap[ (*iter).second.GetName() ] = property;
815       }
816     }
817   }
818 }
819
820 void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap )
821 {
822   Replacement replacer(intoMap);
823
824   if( OptionalChild constants = IsChild(root, "constants") )
825   {
826     for(TreeNode::ConstIterator iter = (*constants).CBegin();
827         iter != (*constants).CEnd(); ++iter)
828     {
829       Dali::Property::Value property;
830       if( (*iter).second.GetName() )
831       {
832 #if defined(DEBUG_ENABLED)
833         DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName());
834 #endif
835         DeterminePropertyFromNode( (*iter).second, property, replacer );
836         intoMap[ (*iter).second.GetName() ] = property;
837       }
838     }
839   }
840
841 #if defined(DEBUG_ENABLED)
842   Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" );
843   if( iter && iter->GetType() == Property::STRING )
844   {
845     std::string logLevel( iter->Get< std::string >() );
846     if( logLevel == "NoLogging" )
847     {
848       gFilterScript->SetLogLevel( Integration::Log::NoLogging );
849     }
850     else if( logLevel == "Concise" )
851     {
852       gFilterScript->SetLogLevel( Integration::Log::Concise );
853     }
854     else if( logLevel == "General" )
855     {
856       gFilterScript->SetLogLevel( Integration::Log::General );
857     }
858     else if( logLevel == "Verbose" )
859     {
860       gFilterScript->SetLogLevel( Integration::Log::Verbose );
861     }
862   }
863 #endif
864 }
865
866 Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor )
867 {
868   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
869
870   Animation anim;
871
872   if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") )
873   {
874     if( OptionalChild animation = IsChild(*animations, animationName) )
875     {
876       anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this );
877     }
878     else
879     {
880       DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() );
881     }
882   }
883   else
884   {
885     DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() );
886   }
887
888   return anim;
889 }
890
891 BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant )
892 {
893   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
894
895   BaseHandle baseHandle;
896
897   OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES);
898
899   if( !templates )
900   {
901     DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n");
902   }
903   else
904   {
905     OptionalChild childTemplate = IsChild(*templates, templateName);
906     if(!childTemplate)
907     {
908       DALI_SCRIPT_WARNING("Template '%s' does not exist in template section\n", templateName.c_str());
909     }
910     else
911     {
912       OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) );
913
914       if(!type)
915       {
916         DALI_SCRIPT_WARNING("Cannot create template '%s' as template section is missing 'type'\n", templateName.c_str());
917       }
918       else
919       {
920         baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant );
921       }
922     }
923   }
924
925   return baseHandle;
926 }
927
928 /*
929  * Create a dali type from a node.
930  * If parent given and an actor type was created then add it to the parent and
931  * recursively add nodes children.
932  */
933 BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node,
934                               Actor parent, const Replacement& replacements )
935 {
936   BaseHandle baseHandle;
937   TypeInfo typeInfo;
938   const TreeNode* templateNode = NULL;
939
940   if( OptionalString typeName = IsString(node, KEYNAME_TYPE) )
941   {
942     typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName );
943
944     if( !typeInfo )
945     {
946       // a template name is also allowed inplace of the type name
947       OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES);
948
949       if( templates )
950       {
951         if( OptionalChild isTemplate = IsChild( *templates, *typeName ) )
952         {
953           templateNode = &(*isTemplate);
954
955           if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) )
956           {
957             typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName );
958           }
959         }
960       }
961     }
962   }
963
964   if(!typeInfo)
965   {
966     DALI_SCRIPT_WARNING("Cannot create Dali type from node '%s'\n", node.GetName());
967   }
968   else
969   {
970     baseHandle       = typeInfo.CreateInstance();
971     Handle handle    = Handle::DownCast(baseHandle);
972     Actor actor      = Actor::DownCast(handle);
973
974     if(handle)
975     {
976
977       DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str());
978
979 #if defined(DEBUG_ENABLED)
980       if(handle)
981       {
982         DALI_SCRIPT_VERBOSE("  Is Handle Object=%d\n", (long*)handle.GetObjectPtr());
983         DALI_SCRIPT_VERBOSE("  Is Handle Property Count=%d\n", handle.GetPropertyCount());
984       }
985
986       if(actor)
987       {
988         DALI_SCRIPT_VERBOSE("  Is Actor id=%d\n", actor.GetId());
989       }
990
991       Toolkit::Control control  = Toolkit::Control::DownCast(handle);
992       if(control)
993       {
994         DALI_SCRIPT_VERBOSE("  Is Control id=%d\n", actor.GetId());
995       }
996 #endif // DEBUG_ENABLED
997
998       if( templateNode )
999       {
1000         ApplyProperties( root, *templateNode, handle, replacements );
1001
1002         if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) )
1003         {
1004           for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1005           {
1006             DoCreate( root, (*iter).second, actor, replacements );
1007           }
1008         }
1009       }
1010
1011       if( actor )
1012       {
1013         // add children of all the styles
1014         if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) )
1015         {
1016           for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter )
1017           {
1018             DoCreate( root, (*iter).second, actor, replacements );
1019           }
1020         }
1021
1022         // apply style on top as they need the children to exist
1023         ApplyAllStyleProperties( root, node, actor, replacements );
1024
1025         // then add to parent
1026         if( parent )
1027         {
1028           parent.Add( actor );
1029         }
1030       }
1031       else
1032       {
1033         ApplyProperties( root, node, handle, replacements );
1034       }
1035     }
1036     else
1037     {
1038       DALI_SCRIPT_WARNING("Cannot create handle from type '%s'\n", typeInfo.GetName().c_str());
1039     }
1040   }
1041
1042   return baseHandle;
1043 }
1044
1045 void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant )
1046 {
1047   const Stage& stage = Stage::GetCurrent();
1048   Layer root  = stage.GetRootLayer();
1049
1050   if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) )
1051   {
1052     Actor actor = root.FindChildByName(*s);
1053     if(actor)
1054     {
1055       task.SetSourceActor( actor );
1056     }
1057     else
1058     {
1059       DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() );
1060     }
1061   }
1062
1063   if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) )
1064   {
1065     CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) );
1066     if(actor)
1067     {
1068       task.SetCameraActor( actor );
1069     }
1070     else
1071     {
1072       DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() );
1073     }
1074   }
1075
1076   if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) )
1077   {
1078     if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s)
1079     {
1080       task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION );
1081     }
1082     else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s)
1083     {
1084       task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION );
1085     }
1086     else
1087     {
1088       DALI_SCRIPT_WARNING("todo");
1089     }
1090   }
1091
1092   // other setup is via the property system
1093   SetProperties( node, task, constant );
1094 }
1095
1096 bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement )
1097 {
1098   DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded");
1099
1100   OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES );
1101
1102   std::string styleNameLower(styleName);
1103   OptionalChild style  = IsChildIgnoreCase( *styles, styleNameLower );
1104
1105   if( styles && style )
1106   {
1107     ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement );
1108     return true;
1109   }
1110   else
1111   {
1112     return false;
1113   }
1114 }
1115
1116 void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node,
1117                                        Dali::Handle& handle, const Replacement& constant )
1118 {
1119   const char* styleName = node.GetName();
1120
1121   StylePtr style = Style::New();
1122
1123   StylePtr* matchedStyle = NULL;
1124   if( styleName )
1125   {
1126     matchedStyle = mStyles.Find( styleName );
1127     if( ! matchedStyle )
1128     {
1129       OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES);
1130       OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT);
1131       if( !inheritFromNode )
1132       {
1133         inheritFromNode = IsChild( node, KEYNAME_STYLES );
1134       }
1135
1136       if( styleNodes )
1137       {
1138         if( inheritFromNode )
1139         {
1140           TreeNodeList additionalStyleNodes;
1141
1142           CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes );
1143
1144 #if defined(DEBUG_ENABLED)
1145           for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter)
1146           {
1147             if( OptionalString styleName = IsString( (*iter).second ) )
1148             {
1149               DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str());
1150             }
1151           }
1152 #endif
1153
1154           // a style may have other styles, which has other styles etc so we apply in reverse by convention.
1155           for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter)
1156           {
1157             RecordStyle( style, *(*iter), handle, constant );
1158             ApplySignals( root, *(*iter), handle );
1159             ApplyStylesByActor( root, *(*iter), handle, constant );
1160           }
1161         }
1162
1163         RecordStyle( style, node, handle, constant );
1164         mStyles.Add( styleName, style ); // shallow copy
1165         matchedStyle = &style;
1166       }
1167     }
1168   }
1169
1170   if( matchedStyle )
1171   {
1172     StylePtr style( *matchedStyle );
1173     Dictionary<Property::Map> instancedProperties;
1174     style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties );
1175   }
1176   else // If there were no styles, instead set properties
1177   {
1178     SetProperties( node, handle, constant );
1179   }
1180   ApplySignals( root, node, handle );
1181   ApplyStylesByActor( root, node, handle, constant );
1182 }
1183
1184 void Builder::RecordStyle( StylePtr           style,
1185                            const TreeNode&    node,
1186                            Dali::Handle&      handle,
1187                            const Replacement& replacements )
1188 {
1189   // With repeated calls, accumulate inherited states, visuals and properties
1190   // but override any with same name
1191
1192   for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1193   {
1194     const TreeNode::KeyNodePair& keyValue = *iter;
1195     std::string key( keyValue.first );
1196     if( key == KEYNAME_STATES )
1197     {
1198       const TreeNode& states = keyValue.second;
1199       if( states.GetType() != TreeNode::OBJECT )
1200       {
1201         DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() );
1202         continue;
1203       }
1204
1205       for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter )
1206       {
1207         const TreeNode& stateNode = (*iter).second;
1208         const char* stateName = stateNode.GetName();
1209         if( stateNode.GetType() != TreeNode::OBJECT )
1210         {
1211           DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName );
1212           continue;
1213         }
1214
1215         StylePtr* stylePtr = style->subStates.Find( stateName );
1216         if( stylePtr )
1217         {
1218           StylePtr style(*stylePtr);
1219           RecordStyle( style, stateNode, handle, replacements );
1220         }
1221         else
1222         {
1223           StylePtr subState = Style::New();
1224           RecordStyle( subState, stateNode, handle, replacements );
1225           style->subStates.Add( stateName, subState );
1226         }
1227       }
1228     }
1229     else if( key == KEYNAME_VISUALS )
1230     {
1231       for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter )
1232       {
1233         // Each key in this table should be a property name matching a visual.
1234         const TreeNode::KeyNodePair& visual = *iter;
1235         Dali::Property::Value property(Property::MAP);
1236         if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) )
1237         {
1238           Property::Map* mapPtr = style->visuals.Find( visual.first );
1239           if( mapPtr )
1240           {
1241             // Override existing visuals
1242             mapPtr->Clear();
1243             mapPtr->Merge( *property.GetMap() );
1244           }
1245           else
1246           {
1247             Property::Map* map = property.GetMap();
1248             if( map )
1249             {
1250               style->visuals.Add( visual.first, *map );
1251             }
1252           }
1253         }
1254       }
1255     }
1256     else if( key == KEYNAME_ENTRY_TRANSITION )
1257     {
1258       RecordTransitionData( keyValue, style->entryTransition, replacements );
1259     }
1260     else if( key == KEYNAME_EXIT_TRANSITION )
1261     {
1262       RecordTransitionData( keyValue, style->exitTransition, replacements );
1263     }
1264     else if( key == KEYNAME_TRANSITIONS )
1265     {
1266       RecordTransitions( keyValue, style->transitions, replacements );
1267     }
1268     else if( key == KEYNAME_TYPE ||
1269              key == KEYNAME_ACTORS ||
1270              key == KEYNAME_SIGNALS ||
1271              key == KEYNAME_STYLES ||
1272              key == KEYNAME_MAPPINGS ||
1273              key == KEYNAME_INHERIT )
1274     {
1275       continue;
1276     }
1277     else // It's a property
1278     {
1279       Property::Index index;
1280       Property::Value value;
1281       if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) )
1282       {
1283         Property::Value* existingValuePtr = style->properties.Find( index );
1284         if( existingValuePtr != NULL )
1285         {
1286           *existingValuePtr = value; // Overwrite existing property.
1287         }
1288         else
1289         {
1290           style->properties.Add( index, value );
1291         }
1292       }
1293     }
1294   }
1295 }
1296
1297 void Builder::RecordTransitions(
1298   const TreeNode::KeyNodePair& keyValue,
1299   Property::Array& value,
1300   const Replacement& replacements )
1301 {
1302   //@todo add new transitions to style.transitions
1303   //      override existing transitions. A transition matches on target & property name
1304   const TreeNode& node = keyValue.second;
1305   if( node.GetType() == TreeNode::ARRAY )
1306   {
1307     Dali::Property::Value property(Property::ARRAY);
1308     if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) )
1309     {
1310       value = *property.GetArray();
1311     }
1312   }
1313   else if( node.GetType() == TreeNode::OBJECT )
1314   {
1315     Dali::Property::Value property(Property::MAP);
1316     if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) )
1317     {
1318       Property::Array propertyArray;
1319       propertyArray.Add( property );
1320       value = propertyArray;
1321     }
1322   }
1323   else
1324   {
1325     DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first );
1326   }
1327 }
1328
1329 void Builder::RecordTransitionData(
1330   const TreeNode::KeyNodePair& keyValue,
1331   Toolkit::TransitionData& transitionData,
1332   const Replacement& replacements )
1333 {
1334   const TreeNode& node = keyValue.second;
1335   if( node.GetType() == TreeNode::ARRAY )
1336   {
1337     Dali::Property::Value property(Property::ARRAY);
1338     if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) )
1339     {
1340       transitionData = Toolkit::TransitionData::New( *property.GetArray() );
1341     }
1342   }
1343   else if( node.GetType() == TreeNode::OBJECT )
1344   {
1345     Dali::Property::Value property(Property::MAP);
1346     if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) )
1347     {
1348       transitionData = Toolkit::TransitionData::New( *property.GetMap() );
1349     }
1350   }
1351 }
1352
1353
1354 // Set properties from node on handle.
1355 void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node,
1356                                Dali::Handle& handle, const Replacement& constant )
1357 {
1358   SetProperties( node, handle, constant );
1359   ApplySignals( root, node, handle );
1360 }
1361
1362 void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle )
1363 {
1364   Actor actor = Actor::DownCast(handle);
1365   if( actor )
1366   {
1367     // add signals
1368     SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1369     SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this );
1370   }
1371 }
1372
1373
1374 // Appling by style helper
1375 // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node
1376 void Builder::ApplyStylesByActor(  const TreeNode& root, const TreeNode& node,
1377                                    Dali::Handle& handle, const Replacement& constant )
1378 {
1379   if( Dali::Actor actor = Dali::Actor::DownCast( handle ) )
1380   {
1381     if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) )
1382     {
1383       // in a style the actor subtree properties referenced by actor name
1384       for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter )
1385       {
1386         Dali::Actor foundActor;
1387
1388         if( (*iter).first )
1389         {
1390           foundActor = actor.FindChildByName( (*iter).first );
1391         }
1392
1393         if( !foundActor )
1394         {
1395           DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first);
1396         }
1397         else
1398         {
1399           DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first);
1400           ApplyProperties( root, (*iter).second, foundActor, constant );
1401         }
1402       }
1403     }
1404   }
1405 }
1406
1407 /*
1408  * Sets the handle properties found in the tree node
1409  */
1410 void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant )
1411 {
1412   if( handle )
1413   {
1414     for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter )
1415     {
1416       const TreeNode::KeyNodePair& keyChild = *iter;
1417
1418       std::string key( keyChild.first );
1419
1420       // ignore special fields;
1421       if( key == KEYNAME_TYPE ||
1422           key == KEYNAME_ACTORS ||
1423           key == KEYNAME_SIGNALS ||
1424           key == KEYNAME_STYLES ||
1425           key == KEYNAME_MAPPINGS ||
1426           key == KEYNAME_INHERIT ||
1427           key == KEYNAME_STATES ||
1428           key == KEYNAME_VISUALS ||
1429           key == KEYNAME_ENTRY_TRANSITION ||
1430           key == KEYNAME_EXIT_TRANSITION ||
1431           key == KEYNAME_TRANSITIONS )
1432       {
1433         continue;
1434       }
1435
1436       Property::Index index;
1437       Property::Value value;
1438
1439       bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value );
1440       if( mapped )
1441       {
1442         DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() );
1443
1444         handle.SetProperty( index, value );
1445       }
1446
1447       // Add custom properties
1448       SetCustomProperties(node, handle, constant, PROPERTIES, Property::READ_WRITE);
1449       SetCustomProperties(node, handle, constant, ANIMATABLE_PROPERTIES, Property::ANIMATABLE);
1450
1451     } // for property nodes
1452   }
1453   else
1454   {
1455     DALI_SCRIPT_WARNING("Style applied to empty handle\n");
1456   }
1457 }
1458
1459 bool Builder::MapToTargetProperty(
1460   Handle&            propertyObject,
1461   const std::string& key,
1462   const TreeNode&    node,
1463   const Replacement& constant,
1464   Property::Index&   index,
1465   Property::Value&   value )
1466 {
1467   bool mapped = false;
1468
1469   index = propertyObject.GetPropertyIndex( key );
1470   if( Property::INVALID_INDEX != index )
1471   {
1472     Property::Type type = propertyObject.GetPropertyType(index);
1473
1474     // if node.value is a mapping, get the property value from the "mappings" table
1475     if( node.GetType() == TreeNode::STRING )
1476     {
1477       std::string mappingKey;
1478       if( GetMappingKey( node.GetString(), mappingKey) )
1479       {
1480         OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS );
1481         mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value );
1482       }
1483     }
1484     if( ! mapped )
1485     {
1486       mapped = DeterminePropertyFromNode( node, type, value, constant );
1487       if( ! mapped )
1488       {
1489         // Just determine the property from the node and if it's valid, let the property object handle it
1490         DeterminePropertyFromNode( node, value, constant );
1491         mapped = ( value.GetType() != Property::NONE );
1492       }
1493     }
1494   }
1495   else
1496   {
1497     DALI_LOG_ERROR("Key '%s' not found.\n", key.c_str());
1498   }
1499   return mapped;
1500 }
1501
1502 bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value )
1503 {
1504   KeyStack keyStack;
1505   return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value );
1506 }
1507
1508 bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value )
1509 {
1510   Replacement replacer( mReplacementMap );
1511   bool result = false;
1512
1513   keyStack.push_back( theKey );
1514
1515   for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter )
1516   {
1517     std::string aKey( (*iter).first );
1518     if( aKey.compare( theKey ) == 0 )
1519     {
1520       if( propertyType == Property::NONE )
1521       {
1522         DeterminePropertyFromNode( (*iter).second, value, replacer );
1523         result = true;
1524       }
1525       else
1526       {
1527         result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer );
1528       }
1529
1530       if( result )
1531       {
1532         ConvertChildValue(mappingRoot, keyStack, value);
1533       }
1534       break;
1535     }
1536   }
1537   keyStack.pop_back();
1538
1539   return result;
1540 }
1541
1542 bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child )
1543 {
1544   bool result = false;
1545
1546   switch( child.GetType() )
1547   {
1548     case Property::STRING:
1549     {
1550       std::string value;
1551       if( child.Get( value ) )
1552       {
1553         std::string key;
1554         if( GetMappingKey( value, key ) )
1555         {
1556           // Check key for cycles:
1557           result=true;
1558           for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter )
1559           {
1560             if( key.compare(*iter) == 0 )
1561             {
1562               // key is already in stack; stop.
1563               DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str());
1564               child = Property::Value("");
1565               result=false;
1566               break;
1567             }
1568           }
1569
1570           if( result )
1571           {
1572             // The following call will overwrite the child with the value
1573             // from the mapping.
1574             RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child );
1575             result = true;
1576           }
1577         }
1578       }
1579       break;
1580     }
1581
1582     case Property::MAP:
1583     {
1584       Property::Map* map = child.GetMap();
1585       if( map )
1586       {
1587         for( Property::Map::SizeType i=0; i < map->Count(); ++i )
1588         {
1589           Property::Value& child = map->GetValue(i);
1590           ConvertChildValue(mappingRoot, keyStack, child);
1591         }
1592       }
1593       break;
1594     }
1595
1596     case Property::ARRAY:
1597     {
1598       Property::Array* array = child.GetArray();
1599       if( array )
1600       {
1601         for( Property::Array::SizeType i=0; i < array->Count(); ++i )
1602         {
1603           Property::Value& child = array->GetElementAt(i);
1604           ConvertChildValue(mappingRoot, keyStack, child);
1605         }
1606       }
1607       break;
1608     }
1609
1610     default:
1611       // Ignore other types.
1612       break;
1613   }
1614
1615   return result;
1616 }
1617
1618 void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant,
1619                           const std::string& childName, Property::AccessMode accessMode )
1620 {
1621   // Add custom properties
1622   if( OptionalChild customPropertiesChild = IsChild(node, childName) )
1623   {
1624     const TreeNode& customPropertiesNode = *customPropertiesChild;
1625     const TreeConstIter endIter = customPropertiesNode.CEnd();
1626     for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter )
1627     {
1628       const TreeNode::KeyNodePair& keyChild = *iter;
1629       std::string key( keyChild.first );
1630       Property::Value value;
1631       DeterminePropertyFromNode( keyChild.second, value, constant );
1632
1633       // Register/Set property.
1634       handle.RegisterProperty( key, value, accessMode );
1635     }
1636   }
1637 }
1638
1639
1640 } // namespace Internal
1641
1642 } // namespace Toolkit
1643
1644 } // namespace Dali