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