Fixed bug in SetIndexBuffer for v8 plugin
[platform/core/uifw/dali-toolkit.git] / plugins / dali-script-v8 / src / dali-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 "dali-wrapper.h"
20
21 // INTERNAL INCLUDES
22 #include <v8-utils.h>
23 #include <object/property-value-wrapper.h>
24 #include <dali/integration-api/debug.h>
25 #include <actors/actor-wrapper.h>
26 #include <controls/control-wrapper.h>
27 #include <stage/stage-wrapper.h>
28 #include <image/image-wrapper.h>
29 #include <animation/linear-constrainer-wrapper.h>
30 #include <animation/path-constrainer-wrapper.h>
31 #include <animation/path-wrapper.h>
32 #include <animation/animation-wrapper.h>
33 #include <controls/item-factory-wrapper.h>
34 #include <events/pan-gesture-detector-wrapper.h>
35 #include <object/property-buffer-wrapper.h>
36 #include <rendering/geometry-wrapper.h>
37 #include <rendering/texture-set-wrapper.h>
38 #include <rendering/renderer-wrapper.h>
39 #include <rendering/shader-wrapper.h>
40 #include <rendering/sampler-wrapper.h>
41 #include <shared/object-template-helper.h>
42 #include <constants/constants-wrapper.h>
43 #include <toolkit/builder/builder-wrapper.h>
44 #include <toolkit/focus-manager/keyboard-focus-manager-wrapper.h>
45
46
47 namespace Dali
48 {
49
50 namespace V8Plugin
51 {
52
53 namespace
54 {
55 /**
56  * This string defines how the global DALi object/namespace is used from JavaScript
57  * E.g. new dali.Image or dali.stage.add( )
58  */
59 const char* const DALI_API_NAME = "dali";
60
61 /**
62  * lookup table for setting up function calls for creating Dali objects
63  * e.g.  new dali.TextActor()
64  */
65 const ApiFunction ConstructorFunctionTable[]=
66 {
67     { "Rotation",           PropertyValueWrapper::NewRotation},
68     { "Matrix",             PropertyValueWrapper::NewMatrix},
69     { "Path",               PathWrapper::NewPath },
70     { "PathConstrainer",    PathConstrainerWrapper::NewPathConstrainer},
71     { "LinearConstrainer",  LinearConstrainerWrapper::NewLinearConstrainer},
72     { "Actor",              ActorWrapper::NewActor },
73     { "CameraActor",        ActorWrapper::NewActor },
74     { "Layer",              ActorWrapper::NewActor },
75     { "Control",            ControlWrapper::NewControl },
76     { "ResourceImage",      ImageWrapper::NewImage },
77     { "BufferImage",        ImageWrapper::NewImage },
78     { "FrameBufferImage",   ImageWrapper::NewImage },
79     { "Animation",          AnimationWrapper::NewAnimation},
80     { "ItemFactory",        ItemFactoryWrapper::NewItemFactory},
81     { "Shader",             ShaderWrapper::NewShader},
82     { "Sampler",            SamplerWrapper::NewSampler},
83     { "TextureSet",         TextureSetWrapper::NewTextureSet},
84     { "Geometry",           GeometryWrapper::NewGeometry},
85     { "Renderer",           RendererWrapper::NewRenderer},
86     { "PropertyBuffer",     PropertyBufferWrapper::NewPropertyBuffer},
87     { "Builder",            BuilderWrapper::NewBuilder},
88     { "PanGestureDetector", PanGestureDetectorWrapper::NewPanGestureDetector},
89
90 };
91
92 const unsigned int PropertyFunctionTableCount = sizeof(ConstructorFunctionTable)/sizeof(ConstructorFunctionTable[0]);
93
94 void FatalErrorCallback(const char* location, const char* message)
95 {
96   DALI_LOG_ERROR("%s, %s \n",location,message);
97   DALI_ASSERT_ALWAYS( 0 && "V8 fatal error");
98 }
99
100 #if defined(DEBUG_ENABLED)
101 // default to verbose logging
102 Integration::Log::Filter* gLogExecuteFilter( Integration::Log::Filter::New(Debug::Verbose, false, "EXECUTE_JAVASCRIPT") );
103 #endif
104 } // un-named name space
105
106
107
108 bool DaliWrapper::mInstanceCreated = false;
109 DaliWrapper* DaliWrapper::mWrapper = NULL;
110
111 DaliWrapper::DaliWrapper( RunMode runMode, v8::Isolate* isolate )
112 :mIsolate( isolate ),
113  mRunMode(runMode)
114 {
115 }
116
117 DaliWrapper::~DaliWrapper()
118 {
119   mInstanceCreated = false;
120 }
121
122 DaliWrapper& DaliWrapper::Get()
123 {
124   if( !mInstanceCreated )
125   {
126     mWrapper = new DaliWrapper( RUNNING_STANDALONE, NULL );
127
128     mInstanceCreated = true;
129
130     mWrapper->InitializeStandAlone();
131
132   }
133   return *mWrapper;
134 }
135
136 v8::Local<v8::Object> DaliWrapper::CreateWrapperForNodeJS( v8::Isolate* isolate )
137 {
138   v8::EscapableHandleScope handleScope( isolate);
139
140   mInstanceCreated = true;
141
142   mWrapper = new DaliWrapper( RUNNING_IN_NODE_JS, isolate );
143
144   v8::Local<v8::Object> dali = mWrapper->CreateDaliObject();
145
146   // As we running inside node, we already have an isolate and context
147   return handleScope.Escape( dali );
148 }
149
150 v8::Local<v8::Object>  DaliWrapper::CreateDaliObject()
151 {
152   v8::EscapableHandleScope handleScope( mIsolate  );
153
154   // Create dali object used for creating objects, and accessing constant values
155   // e.g. var x =  new dali.Actor(), or var col = dali.COLOR_RED;
156
157   v8::Local<v8::ObjectTemplate> daliObjectTemplate = NewDaliObjectTemplate( mIsolate );
158
159   // add dali.staqe
160   v8::Local<v8::Object> stageObject = StageWrapper::WrapStage( mIsolate, Stage::GetCurrent() );
161   daliObjectTemplate->Set( v8::String::NewFromUtf8( mIsolate, "stage") , stageObject );
162
163   v8::Local<v8::Object> keyboardObject = KeyboardFocusManagerWrapper::WrapKeyboardFocusManager( mIsolate,Toolkit::KeyboardFocusManager::Get() );
164   daliObjectTemplate->Set( v8::String::NewFromUtf8( mIsolate, "keyboardFocusManager") , keyboardObject );
165
166
167   //create an instance of the template
168   v8::Local<v8::Object> daliObject = daliObjectTemplate->NewInstance();
169
170   ConstantsWrapper::AddDaliConstants( mIsolate, daliObject);
171
172   daliObject->Set( v8::String::NewFromUtf8( mIsolate,  "V8_VERSION") ,v8::String::NewFromUtf8( mIsolate, v8::V8::GetVersion() ));
173
174   return handleScope.Escape( daliObject  );
175 }
176
177
178 void DaliWrapper::SetFlagsFromString(const std::string &flags)
179 {
180   v8::V8::SetFlagsFromString(flags.c_str(), flags.size());
181 }
182
183 void DaliWrapper::Shutdown()
184 {
185   // if we're running inside node then we don't have ownership of the context
186   if( mRunMode == RUNNING_IN_NODE_JS )
187   {
188     return;
189   }
190
191   DALI_LOG_WARNING("Destroying V8 DALi context\n");
192
193   if( !mContext.IsEmpty())
194   {
195     v8::HandleScope handleScope( mIsolate );
196     v8::Local<v8::Context> context = v8::Local<v8::Context>::New(mIsolate, mContext);
197     context->Exit();   // exit the context
198     mContext.Reset();  // destroys the context
199   }
200 }
201
202 bool DaliWrapper::ExecuteBuffer(const std::string &sourceCode, const std::string &sourceFileName)
203 {
204   return mModuleLoader.ExecuteScript( mIsolate,  sourceCode, sourceFileName );
205 }
206
207 bool DaliWrapper::ExecuteFile( const std::string& sourceFileName )
208 {
209   DALI_LOG_INFO( gLogExecuteFilter, Debug::Verbose, "Executing source file %s \n",sourceFileName.c_str() );
210
211   return mModuleLoader.ExecuteScriptFromFile( mIsolate,  sourceFileName );
212 }
213
214 GarbageCollectorInterface& DaliWrapper::GetDaliGarbageCollector()
215 {
216   return mGarbageCollector;
217 }
218
219 void DaliWrapper::ApplyGlobalObjectsToContext( v8::Local<v8::Context> context )
220 {
221   v8::HandleScope handleScope( mIsolate );
222
223   // Add global objects ( functions/ values ) e.g. log function
224   // create a console.log and console.error functions
225   v8::Local<v8::ObjectTemplate> consoleObjectTemplate = v8::ObjectTemplate::New( mIsolate );
226   consoleObjectTemplate->Set( v8::String::NewFromUtf8( mIsolate, "log"),   v8::FunctionTemplate::New( mIsolate, V8Utils::Log));
227   consoleObjectTemplate->Set( v8::String::NewFromUtf8( mIsolate, "error"), v8::FunctionTemplate::New( mIsolate, V8Utils::LogError));
228
229   context->Global()->Set( v8::String::NewFromUtf8( mIsolate, "console"), consoleObjectTemplate->NewInstance() );
230
231   // add require functionality
232   context->Global()->Set( v8::String::NewFromUtf8( mIsolate, "require"), v8::FunctionTemplate::New( mIsolate, DaliWrapper::Require)->GetFunction());
233
234   // Create the Dali object
235   // @todo consider forcing developers to perform require('dali') if we want to avoid polluting the global namespace
236   v8::Local<v8::Object> daliObject = CreateDaliObject();
237
238   // allow developers to require('dali'); // this is to maintain compatibility with node.js where dali is not part of the global namespace
239   mModuleLoader.StorePreBuiltModule( mIsolate, daliObject, DALI_API_NAME );
240
241   context->Global()->Set( v8::String::NewFromUtf8( mIsolate, DALI_API_NAME),daliObject );
242
243 }
244
245 void DaliWrapper::InitializeStandAlone()
246 {
247   if( !mIsolate )
248   {
249     v8::V8::InitializeICU();
250
251     v8::V8::Initialize();
252
253     // default isolate removed from V8 version 3.27.1 and beyond.
254     mIsolate = v8::Isolate::New();
255
256     mIsolate->Enter();
257
258     v8::V8::SetFatalErrorHandler( FatalErrorCallback );
259   }
260
261   // if context is null, create it and add dali object to the global object.
262   if( mContext.IsEmpty())
263   {
264      v8::HandleScope handleScope( mIsolate );
265
266      // create a new context.
267      // Isolate = isolated copy of the V8 including a heap manager, a garbage collector
268      // Only 1 thread can access a single Isolate at a given time. However, multiple Isolates can be run in parallel.
269      // Context = multiple contexts can exist in a given Isolate, and share data between contexts
270      v8::Local<v8::Context> context  = v8::Context::New( mIsolate );
271
272      context->Enter();
273
274      // Apply global objects like dali and console to the context
275      ApplyGlobalObjectsToContext(context);
276
277      mContext.Reset( mIsolate, context);
278   }
279
280   DALI_LOG_INFO( gLogExecuteFilter, Debug::Verbose, "V8 Library %s loaded \n", v8::V8::GetVersion() );
281 }
282
283
284 v8::Handle<v8::ObjectTemplate> DaliWrapper::NewDaliObjectTemplate( v8::Isolate* isolate )
285 {
286   v8::EscapableHandleScope handleScope( isolate );
287
288   // create the template
289   v8::Local< v8::ObjectTemplate > objTemplate = v8::ObjectTemplate::New( isolate );
290
291   // Add some value properties ( a property can be a primitive value, an object or a function).
292   objTemplate->Set( v8::String::NewFromUtf8( isolate, "BUILD"),
293                     v8::String::NewFromUtf8( isolate, "Dali binary built on:" __DATE__ ", at " __TIME__));
294
295 #ifdef DALI_DATA_READ_ONLY_DIR
296   // add the data data directory,
297   objTemplate->Set( v8::String::NewFromUtf8( isolate, "DALI_DATA_DIRECTORY"),
298                     v8::String::NewFromUtf8( isolate, DALI_DATA_READ_ONLY_DIR));
299 #endif
300   // add our constructor functions
301   ObjectTemplateHelper::InstallFunctions( isolate,
302                                           objTemplate,
303                                           ConstructorFunctionTable,
304                                           PropertyFunctionTableCount,
305                                           ObjectTemplateHelper::CONSTRUCTOR_FUNCTIONS);
306
307   return handleScope.Escape( objTemplate );
308 }
309
310 void DaliWrapper::Require(const v8::FunctionCallbackInfo< v8::Value >& args)
311 {
312   DaliWrapper& wrapper( DaliWrapper::Get() );
313   wrapper.mModuleLoader.Require( args );
314 }
315
316
317 } // namespace V8Plugin
318
319 } // namespace Dali