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