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