Merge "Remove de-funct dynamics support" into devel/master
[platform/core/uifw/dali-toolkit.git] / plugins / dali-script-v8 / src / actors / actor-wrapper.cpp
1 /*
2  * Copyright (c) 2015 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 "actor-wrapper.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/object/type-registry.h>
23 #include <dali-toolkit/public-api/controls/control.h>
24
25 // INTERNAL INCLUDES
26 #include <actors/layer-api.h>
27 #include <actors/actor-api.h>
28 #include <actors/image-actor-api.h>
29 #include <actors/camera-actor-api.h>
30 #include <v8-utils.h>
31 #include <dali-wrapper.h>
32
33 namespace Dali
34 {
35
36 namespace V8Plugin
37 {
38
39 v8::Persistent<v8::ObjectTemplate> ActorWrapper::mActorTemplate;
40 v8::Persistent<v8::ObjectTemplate> ActorWrapper::mImageActorTemplate;
41 v8::Persistent<v8::ObjectTemplate> ActorWrapper::mCameraActorTemplate;
42 v8::Persistent<v8::ObjectTemplate> ActorWrapper::mLayerActorTemplate;
43
44 namespace
45 {
46
47
48 /**
49  * pointer to a persistent template handle
50  */
51 struct ActorTemplate
52 {
53   v8::Persistent<v8::ObjectTemplate>* actorTemplate;
54 };
55
56 /**
57  * array of templates for each type of actor
58  */
59 const ActorTemplate ActorTemplateLookup[]=
60 {
61     { &ActorWrapper::mActorTemplate },        // ACTOR
62     { &ActorWrapper::mImageActorTemplate },   // IMAGE_ACTOR
63     { &ActorWrapper::mLayerActorTemplate },   // LAYER_ACTOR
64     { &ActorWrapper::mCameraActorTemplate}    // CAMERA_ACTOR
65 };
66
67 /**
68  * Bitmask of API's that an actor can support
69  */
70 enum ActorApiBitMask
71 {
72   ACTOR_API              = 1 << 0,
73   IMAGE_ACTOR_API        = 1 << 1,
74   LAYER_API              = 1 << 2,
75   CAMERA_ACTOR_API       = 1 << 3,
76 };
77
78 /**
79  * structure used for the ActorApiLookup.
80  */
81 struct ActorApiStruct
82 {
83   const char* actorName;
84   ActorWrapper::ActorType actorType;
85   Actor (*constructor)( const v8::FunctionCallbackInfo< v8::Value >& args);
86   int supportApis;
87 };
88
89 /**
90  * Lookup table to match a actor type with a constructor and supported API's.
91  * HandleWrapper::ActorType is used to index this table
92  */
93 const ActorApiStruct ActorApiLookup[]=
94 {
95   {"Actor",      ActorWrapper::ACTOR,        ActorApi::New,       ACTOR_API },
96   {"ImageActor", ActorWrapper::IMAGE_ACTOR,  ImageActorApi::New,  ACTOR_API | IMAGE_ACTOR_API   },
97   {"Layer",      ActorWrapper::LAYER_ACTOR,  LayerApi::New,       ACTOR_API | LAYER_API                                },
98   {"CameraActor",ActorWrapper::CAMERA_ACTOR, CameraActorApi::New, ACTOR_API | CAMERA_ACTOR_API                         },
99 };
100
101 const unsigned int ActorApiLookupCount = sizeof(ActorApiLookup)/sizeof(ActorApiLookup[0]);
102
103
104
105 /**
106  * Creates an actor given a type name
107  * Uses the type registry to create an actor of the correct type
108  */
109 Actor CreateActor( const v8::FunctionCallbackInfo< v8::Value >& args,
110                         const std::string& typeName )
111 {
112   Actor actor;
113
114   ActorWrapper::ActorType actorType = ActorWrapper::GetActorType( typeName );
115
116   // if we don't currently support the actor type, then use type registry to create it
117   if( actorType == ActorWrapper::UNKNOWN_ACTOR )
118   {
119       DALI_SCRIPT_EXCEPTION( args.GetIsolate(), "Unknown actor type" );
120       return Actor();
121   }
122   else
123   {
124     // run the constructor for this type of actor so it can pull out
125     // custom parameters, e.g. new ImageActor( MyImage );
126     actor = (ActorApiLookup[actorType].constructor)( args );
127   }
128   return actor;
129 }
130
131
132
133 /**
134  * given an actor type return what api's it supports
135  */
136 int GetActorSupportedApis( ActorWrapper::ActorType type )
137 {
138   return ActorApiLookup[ type].supportApis;
139 }
140
141 /**
142  * Used for the ActorFunctionTable to map function names to functions
143  * with for a specific API
144  */
145 struct ActorFunctions
146 {
147   const char* name;               ///< function name
148   void (*function)( const v8::FunctionCallbackInfo< v8::Value >& args);
149   ActorApiBitMask api;
150 };
151
152 /**
153  * Contains a list of all functions that can be called an
154  * actor / image-actor / layer / camera-actor
155  */
156 const ActorFunctions ActorFunctionTable[]=
157 {
158     /**************************************
159     * Actor API (in order of actor.h)
160     * Any properties that have accessor functions are ignored to avoid duplication
161     **************************************/
162     // ignore. GetName()  use Actor.name
163     // ignore. SetName()  use Actor.name
164     { "GetId",             ActorApi::GetId,            ACTOR_API },
165     { "IsRoot",            ActorApi::IsRoot,           ACTOR_API },
166     { "OnStage",           ActorApi::OnStage,          ACTOR_API },
167     { "IsLayer",           ActorApi::IsLayer,          ACTOR_API },
168     { "GetLayer",          ActorApi::GetLayer,         ACTOR_API },
169     { "Add",               ActorApi::AddActor,         ACTOR_API },
170     { "Remove",            ActorApi::RemoveActor,      ACTOR_API },
171     { "IsEqualTo" ,        ActorApi::IsEqualTo,        ACTOR_API },
172     { "Unparent",          ActorApi::Unparent,         ACTOR_API },
173     { "GetChildCount",     ActorApi::GetChildCount,    ACTOR_API },
174     { "GetChildAt"   ,     ActorApi::GetChildAt,       ACTOR_API },
175     { "FindChildByName",   ActorApi::FindChildByName,  ACTOR_API },
176     { "FindChildById",     ActorApi::FindChildById,    ACTOR_API },
177     { "GetParent" ,        ActorApi::GetParent,        ACTOR_API },
178     { "GetActorType" ,     ActorApi::GetActorType,     ACTOR_API }, // custom for javascript
179
180     // ignore. SetParentOrigin() use Actor.parentOrigin
181     // ignore. GetCurrentParentOrigin()  use Actor.parentOrigin
182     // ignore. SetAnchorPoint()  use Actor.anchorPoint
183     // ignore. GetCurrentAnchorPoint()  use Actor.anchorPoint
184     // ignore. SetSize() use Actor.size
185     // ignore. GetCurrentSize() use Actor.size
186     // ignore. SetPosition(....) use Actor.position
187     // ignore. SetX, SetY, SetZ,  use Actor.position.x, Actor.position.y, Actor.position.z
188     { "TranslateBy",         ActorApi::TranslateBy,              ACTOR_API },
189     // ignore GetCurrentPosition(). use Actor.position
190     // ignore GetCurrentWorldPosition() use Actor.worldPosition
191     // ignore SetPositionInheritanceMode() use Actor.positionInheritance
192     // ignore GetPositionInheritanceMode()  use Actor.positionInheritance
193     // ignore SetOrientation() use Actor.orientation
194     { "RotateBy",         ActorApi::RotateBy,          ACTOR_API },
195     // ignore GetCurrentOrientation() use Actor.orientation
196     // ignore SetInheritOrientation() use Actor.inheritOrientation
197     // ignore IsOrientationInherited() use Actor.inheritOrientation
198     // ignore GetCurrentWorldOrientation() use Actor.worldOrientation
199     // ignore SetScale() use Actor.scale
200     { "ScaleBy",         ActorApi::ScaleBy,            ACTOR_API },
201     // ignore GetCurrentScale() use Actor.scale
202     // ignore GetCurrentWorldScale() use Actor.worldScale
203     // ignore SetInheritScale() use Actor.inheritScale
204     // ignore IsScaleInherited() use Actor.inheritScale
205     // ignore GetCurrentWorldMatrix() use Actor.worldMatrix
206     // ignore SetVisible() use Actor.visible
207     // ignore IsVisible() use Actor.visible
208     // ignore SetOpacity() use Actor.opacity
209     // ignore GetCurrentOpacity() use Actor.opacity
210     // ignore SetColor() use Actor.color
211     // ignore GetCurrentColor() use Actor.color
212     // ignore SetColorMode() use Actor.colorMode
213     // ignore GetColorMode() use Actor.colorMode
214     // ignore GetCurrentWorldColor() use Actor.worldColor
215     // ignore SetInheritShaderEffect() use Actor.inheritShaderEffect
216     // ignore GetInheritShaderEffect() use Actor.inheritShaderEffect
217     // ignore SetDrawMode() use Actor.drawMode
218     // ignore GetDrawMode() use Actor.drawMode
219     // ignore SetSensitive() use Actor.sensitve
220     // ignore IsSensitive() use Actor.sensitive
221     { "ScreenToLocal"       , ActorApi::ScreenToLocal,         ACTOR_API},
222     // ignore SetLeaveRequired() use Actor.leaveRequired
223     // ignore GetLeaveRequired() use Actor.leaveRequired
224     { "SetKeyboardFocusable", ActorApi::SetKeyboardFocusable,  ACTOR_API }, //-- should this be a property???
225     { "IsKeyboardFocusable" , ActorApi::IsKeyboardFocusable,   ACTOR_API }, //-- should this be a property???
226
227     /**************************************
228      * Layer  API (in order of layer.h)
229      **************************************/
230     { "GetDepth",           LayerApi::GetDepth,                 LAYER_API  },
231     { "Raise",              LayerApi::Raise,                    LAYER_API  },
232     { "Lower",              LayerApi::Lower,                    LAYER_API  },
233     { "RaiseAbove",         LayerApi::RaiseAbove,               LAYER_API  },
234     { "RaiseBelow",         LayerApi::LowerBelow,               LAYER_API  },
235     { "RaiseToTop",         LayerApi::RaiseToTop,               LAYER_API  },
236     { "LowerToBottom",      LayerApi::ToBottom,                 LAYER_API  },
237     { "MoveAbove",          LayerApi::MoveAbove,                LAYER_API  },
238     { "MoveBelow",          LayerApi::MoveBelow,                LAYER_API  },
239     // ignore SetClipping, use layer.clippingEnable
240     // ignore IsClipping, use layer.clippingEnable
241     // ignore SetClippingBox, use layer.clippingBox
242     { "SetDepthTestDisabled", LayerApi::SetDepthTestDisabled,   LAYER_API },
243     { "IsDepthTestDisabled",  LayerApi::IsDepthTestDisabled,    LAYER_API },
244     // @todo SetSortFunction
245
246     /**************************************
247      * Image Actor API (in order of image-actor.h)
248      **************************************/
249
250     { "SetImage",           ImageActorApi::SetImage,              IMAGE_ACTOR_API },
251     { "GetImage",           ImageActorApi::GetImage,              IMAGE_ACTOR_API },
252     // ignore SetPixelArea, use imageActor.pixelArea
253     // ignore GetPixelArea, use imageActor.pixelArea
254     // ignore SetStyle, use imageActor.style
255     // ignore GetStyle, use imageActor.style
256     // ignore SetNinePatchBorder use imageActor.border
257     // ignore GetNinePatchBorder use imageActor.border
258     { "SetSortModifier",    ImageActorApi::SetSortModifier,   IMAGE_ACTOR_API  },
259     { "GetSortModifier",    ImageActorApi::GetSortModifier,   IMAGE_ACTOR_API  },
260     { "SetCullFace",        ImageActorApi::SetCullFace,       IMAGE_ACTOR_API  },
261     { "GetCullFace",        ImageActorApi::GetCullFace,       IMAGE_ACTOR_API  },
262     { "SetBlendMode",       ImageActorApi::SetBlendMode,      IMAGE_ACTOR_API  },
263     { "GetBlendMode",       ImageActorApi::GetBlendMode,      IMAGE_ACTOR_API  },
264     { "SetBlendFunc",       ImageActorApi::SetBlendFunc,      IMAGE_ACTOR_API  },
265     { "GetBlendFunc",       ImageActorApi::GetBlendFunc,      IMAGE_ACTOR_API  },
266     { "SetShaderEffect",    ImageActorApi::SetShaderEffect,   IMAGE_ACTOR_API  },
267     { "GetShaderEffect",    ImageActorApi::GetShaderEffect,   IMAGE_ACTOR_API  },
268     { "RemoveShaderEffect", ImageActorApi::RemoveShaderEffect,IMAGE_ACTOR_API  },
269     // ignore SetFadeIn use imageActor.fadeIn
270     // ignore GetFadeIn use imageActor.fadeIn
271     // ignore SetFadeInDuration use imageActor.fadeInDuration
272     // ignore GetFadeInDuration use imageActor.fadeInDuration
273     //{ "GetCurrentImageSize", ImageActorApi::GetCurrentImageSize,  IMAGE_ACTOR_API },
274
275     /**************************************
276      * Mesh Actor API (in order of mesh-actor.h)
277      **************************************/
278     // @todo a version of MeshActor::New( mesh )
279     // @todo a version of MeshActor::New( AnimatableMesh )
280     // @todo SetMaterial
281     // @todo GetMaterial
282     // @todo BindBonesToMesh
283
284     /**************************************
285      * Camera Actor API (in order of camera.h)
286      **************************************/
287     // ignore SetType use camera.type
288     // ignore GetType use camera.type
289     // ignore SetProjectionMode use camera.projectionMode
290     // ignore GetProjectionMode use camera.projectionMode
291     // ignore SetFieldOfView use camera.fieldOfView
292     // ignore GetFieldOfView use camera.fieldOfView
293     // ignore SetAspectRatio use camera.aspectRatio
294     // ignore GetAspectRatio use camera.aspectRatio
295     // ignore SetNearClippingPlane use camera.nearPlaneDistance
296     // ignore GetNearClippingPlane use camera.nearPlaneDistance
297     // ignore SetFarClippingPlane use camera.farPlaneDistance
298     // ignore GetFarClippingPlane use camera.farPlaneDistance
299     // ignore GetTargetPosition use camera.targetPosition
300     // ignore SetInvertYAxis use camera.invertYAxis
301     // ignore GetInvertYAxis use camera.invertYAxis
302     { "SetPerspectiveProjection",   CameraActorApi::SetPerspectiveProjection,   CAMERA_ACTOR_API },
303     { "SetOrthographicProjection",  CameraActorApi::SetOrthographicProjection,  CAMERA_ACTOR_API },
304
305 };
306
307 const unsigned int ActorFunctionTableCount = sizeof(ActorFunctionTable)/sizeof(ActorFunctionTable[0]);
308 } //un-named space
309
310
311 ActorWrapper::ActorWrapper( Actor actor,
312               GarbageCollectorInterface& gc )
313 : HandleWrapper( BaseWrappedObject::ACTOR , actor, gc ),
314   mActor( actor )
315
316 {
317 }
318
319 v8::Handle<v8::Object> ActorWrapper::WrapActor(v8::Isolate* isolate, Actor actor )
320 {
321   v8::EscapableHandleScope handleScope( isolate );
322
323   // Check whether the actor is a Control
324   ActorWrapper::ActorType type = Toolkit::Control::DownCast(actor) ? ACTOR : GetActorType( actor.GetTypeName() );
325   v8::Local<v8::Object> object = WrapActor( isolate, actor, type );
326
327   return handleScope.Escape( object );
328 }
329
330 Actor ActorWrapper::GetActor()
331 {
332   return mActor;
333 }
334
335 v8::Handle<v8::Object> ActorWrapper::WrapActor( v8::Isolate* isolate, Actor actor, ActorType actorType )
336 {
337   v8::EscapableHandleScope handleScope( isolate );
338   v8::Local<v8::ObjectTemplate> objectTemplate;
339
340   objectTemplate = GetActorTemplate( isolate, actorType );
341
342   // create an instance of the template
343   v8::Local<v8::Object> localObject = objectTemplate->NewInstance();
344
345   // create teh actor object
346   ActorWrapper* pointer = new ActorWrapper( actor, Dali::V8Plugin::DaliWrapper::Get().GetDaliGarbageCollector() );
347
348   // assign the JavaScript object to the wrapper.
349   // This also stores Dali object, in an internal field inside the JavaScript object.
350   pointer->SetJavascriptObject( isolate, localObject );
351
352   return handleScope.Escape( localObject );
353 }
354
355 v8::Local<v8::ObjectTemplate> ActorWrapper::GetActorTemplate( v8::Isolate* isolate, ActorWrapper::ActorType type )
356 {
357   v8::EscapableHandleScope handleScope( isolate );
358   v8::Local<v8::ObjectTemplate> objectTemplate;
359
360   if( ActorTemplateLookup[type].actorTemplate->IsEmpty() )
361   {
362     objectTemplate = MakeDaliActorTemplate( isolate, type );
363     ActorTemplateLookup[type].actorTemplate->Reset( isolate, objectTemplate );
364   }
365   else
366   {
367     // get the object template
368     objectTemplate = v8::Local<v8::ObjectTemplate>::New( isolate, *ActorTemplateLookup[type].actorTemplate );
369   }
370
371   return handleScope.Escape( objectTemplate );
372 }
373
374 v8::Handle<v8::ObjectTemplate> ActorWrapper::MakeDaliActorTemplate( v8::Isolate* isolate, ActorType actorType )
375 {
376   v8::EscapableHandleScope handleScope( isolate );
377
378   v8::Local<v8::ObjectTemplate> objTemplate = v8::ObjectTemplate::New();
379
380   objTemplate->SetInternalFieldCount( BaseWrappedObject::FIELD_COUNT );
381
382   // find out what API's this actor supports
383   int supportApis = GetActorSupportedApis( actorType );
384
385   // add our function properties
386   for( unsigned int i = 0; i < ActorFunctionTableCount; ++i )
387   {
388     const ActorFunctions property =  ActorFunctionTable[i];
389
390     // check to see if the actor supports a certain type of API
391     // e.g. ImageActor will support ACTOR_API, RENDERABLE_API and IMAGE_ACTOR_API
392     if( supportApis &  property.api )
393     {
394       std::string funcName = V8Utils::GetJavaScriptFunctionName( property.name);
395
396       objTemplate->Set( v8::String::NewFromUtf8(   isolate, funcName.c_str() ),
397                       v8::FunctionTemplate::New( isolate, property.function ) );
398     }
399   }
400
401   // property handle intercepts property getters and setters and signals
402   HandleWrapper::AddInterceptsToTemplate( isolate, objTemplate );
403
404
405   return handleScope.Escape( objTemplate );
406 }
407
408 void ActorWrapper::NewActor( const v8::FunctionCallbackInfo< v8::Value >& args)
409 {
410   v8::Isolate* isolate = args.GetIsolate();
411   v8::HandleScope handleScope( isolate );
412
413   if( !args.IsConstructCall() )
414   {
415     DALI_SCRIPT_EXCEPTION( isolate, "constructor called without 'new" );
416     return;
417   }
418
419   // find out the callee function name...e.g. ImageActor, MeshActor
420   v8::Local<v8::Function> callee = args.Callee();
421   v8::Local<v8::Value> v8String = callee->GetName();
422   std::string typeName = V8Utils::v8StringToStdString( v8String );
423
424   // create a new actor based on type, using the type registry.
425   Actor actor = CreateActor( args, typeName );
426
427   v8::Local<v8::Object> localObject = WrapActor( isolate, actor );
428
429   args.GetReturnValue().Set( localObject );
430 }
431
432 void ActorWrapper::NewControl( const v8::FunctionCallbackInfo< v8::Value >& args)
433 {
434   v8::Isolate* isolate = args.GetIsolate();
435   v8::HandleScope handleScope( isolate );
436
437   if( !args.IsConstructCall() )
438   {
439     DALI_SCRIPT_EXCEPTION( isolate, "constructor called without 'new" );
440     return;
441   }
442
443   bool found( false );
444   std::string controlName = V8Utils::GetStringParameter( PARAMETER_0, found, isolate,  args );
445
446   if( !found )
447   {
448     DALI_SCRIPT_EXCEPTION( isolate, "missing control name" );
449     return;
450   }
451   Actor control;
452   Dali::TypeInfo typeInfo = Dali::TypeRegistry::Get().GetTypeInfo( controlName );
453   if( typeInfo ) // handle, check if it has a value
454   {
455     Dali::BaseHandle handle = typeInfo.CreateInstance();
456     if( handle )
457     {
458       control = Actor::DownCast( handle );
459     }
460   }
461
462   v8::Local<v8::Object> localObject = WrapActor( isolate, control, ACTOR );
463
464   args.GetReturnValue().Set( localObject );
465 }
466
467
468 /**
469  * given an actor type name, e.g. ImageActor returns the type, e.g. ActorWrapper::IMAGE_ACTOR
470  */
471 ActorWrapper::ActorType ActorWrapper::GetActorType( const std::string& name )
472 {
473   for( unsigned int i = 0 ; i < ActorApiLookupCount ; i++ )
474   {
475     if( ActorApiLookup[i].actorName == name )
476     {
477       return ActorApiLookup[i].actorType;
478     }
479   }
480   return ActorWrapper::UNKNOWN_ACTOR;
481 }
482
483
484
485 } // namespace V8Plugin
486
487 } // namespace Dali