Cleanup for removal of ImageAttributes from public API
[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 <stage/stage-wrapper.h>
27 #include <image/image-wrapper.h>
28 #include <animation/path-wrapper.h>
29 #include <animation/path-constraint-wrapper.h>
30 #include <animation/animation-wrapper.h>
31 #include <events/pan-gesture-detector-wrapper.h>
32 #include <shader-effects/shader-effect-wrapper.h>
33 #include <shared/object-template-helper.h>
34 #include <constants/constants-wrapper.h>
35 #include <toolkit/builder/builder-wrapper.h>
36 #include <toolkit/focus-manager/keyboard-focus-manager-wrapper.h>
37
38
39 namespace Dali
40 {
41
42 namespace V8Plugin
43 {
44
45 namespace
46 {
47 /**
48  * This string defines how the global DALi object/namespace is used from JavaScript
49  * E.g. new dali.Image or dali.stage.add( )
50  */
51 const char* const DALI_API_NAME = "dali";
52
53 /**
54  * lookup table for setting up function calls for creating Dali objects
55  * e.g.  new dali.TextActor()
56  */
57 const ApiFunction ConstructorFunctionTable[]=
58 {
59     { "Rotation",           PropertyValueWrapper::NewRotation},
60     { "Matrix",             PropertyValueWrapper::NewMatrix},
61     { "Path",               PathWrapper::NewPath },
62     { "PathConstraint",     PathConstraintWrapper::NewPathConstraint },
63     { "Actor",              ActorWrapper::NewActor },
64     { "TextActor",          ActorWrapper::NewActor },
65     { "ImageActor",         ActorWrapper::NewActor },
66     { "MeshActor",          ActorWrapper::NewActor },
67     { "CameraActor",        ActorWrapper::NewActor },
68     { "Layer",              ActorWrapper::NewActor },
69     { "TextView",           ActorWrapper::NewActor },
70     { "ResourceImage",      ImageWrapper::NewImage },
71     { "BufferImage",        ImageWrapper::NewImage },
72     { "NinePatchImage",     ImageWrapper::NewImage },
73     { "FrameBufferImage",   ImageWrapper::NewImage },
74     { "Animation",          AnimationWrapper::NewAnimation},
75     { "ShaderEffect",       ShaderEffectWrapper::NewShaderEffect},
76     { "Builder",            BuilderWrapper::NewBuilder},
77     { "PanGestureDetector", PanGestureDetectorWrapper::NewPanGestureDetector},
78
79 };
80
81 const unsigned int PropertyFunctionTableCount = sizeof(ConstructorFunctionTable)/sizeof(ConstructorFunctionTable[0]);
82
83 void FatalErrorCallback(const char* location, const char* message)
84 {
85   DALI_LOG_ERROR("%s, %s \n",location,message);
86   DALI_ASSERT_ALWAYS( 0 && "V8 fatal error");
87 }
88
89 #if defined(DEBUG_ENABLED)
90 // default to verbose logging
91 Integration::Log::Filter* gLogExecuteFilter( Integration::Log::Filter::New(Debug::Verbose, false, "EXECUTE_JAVASCRIPT") );
92 #endif
93 } // un-named name space
94
95
96
97 bool DaliWrapper::mInstanceCreated = false;
98 DaliWrapper* DaliWrapper::mWrapper = NULL;
99
100 DaliWrapper::DaliWrapper()
101 :mIsolate( NULL )
102 {
103 }
104
105 DaliWrapper::~DaliWrapper()
106 {
107   mInstanceCreated = false;
108 }
109
110 DaliWrapper& DaliWrapper::Get()
111 {
112   if(!mInstanceCreated)
113   {
114     mWrapper = new DaliWrapper();
115     mInstanceCreated = true;
116
117     if(mWrapper)
118     {
119       mWrapper->Initialize();
120     }
121   }
122
123   return *mWrapper;
124 }
125
126 void DaliWrapper::SetFlagsFromString(const std::string &flags)
127 {
128   v8::V8::SetFlagsFromString(flags.c_str(), flags.size());
129 }
130
131 void DaliWrapper::Shutdown()
132 {
133   DALI_LOG_WARNING("Destroying V8 DALi context\n");
134
135   if( !mContext.IsEmpty())
136   {
137     v8::HandleScope handleScope( mIsolate );
138     v8::Local<v8::Context> context = v8::Local<v8::Context>::New(mIsolate, mContext);
139     context->Exit();   // exit the context
140     mContext.Reset();  // destroys the context
141   }
142 }
143
144 void DaliWrapper::ExecuteBuffer(const std::string &sourceCode, const std::string &sourceFileName)
145 {
146   mModuleLoader.ExecuteScript( mIsolate,  sourceCode, sourceFileName );
147 }
148
149 void DaliWrapper::ExecuteFile( const std::string& sourceFileName )
150 {
151   DALI_LOG_INFO( gLogExecuteFilter, Debug::Verbose, "Executing source file %s \n",sourceFileName.c_str() );
152
153   mModuleLoader.ExecuteScriptFromFile( mIsolate,  sourceFileName );
154 }
155
156 GarbageCollectorInterface& DaliWrapper::GetDaliGarbageCollector()
157 {
158   return mGarbageCollector;
159 }
160
161 void DaliWrapper::CreateContext( )
162 {
163   v8::HandleScope handleScope( mIsolate );
164
165   // Create a  global JavaScript object so we can set built-in global functions, like Log.
166   v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New( mIsolate );
167
168   // Add global objects ( functions/ values ) e.g. log function and V8_VERSION
169   global->Set( v8::String::NewFromUtf8( mIsolate,  "log"),        v8::FunctionTemplate::New( mIsolate, V8Utils::Log) );
170   global->Set( v8::String::NewFromUtf8( mIsolate,  "logError"),   v8::FunctionTemplate::New( mIsolate, V8Utils::LogError) );
171   global->Set( v8::String::NewFromUtf8( mIsolate,  "require"),    v8::FunctionTemplate::New( mIsolate, DaliWrapper::Require));
172   global->Set( v8::String::NewFromUtf8( mIsolate,  "V8_VERSION") ,v8::String::NewFromUtf8( mIsolate, v8::V8::GetVersion() ));
173
174    // add the dali object to it, assume it won't be garbage collected until global is deleted
175   global->Set(v8::String::NewFromUtf8( mIsolate, DALI_API_NAME) ,  NewDaliObjectTemplate( mIsolate ));
176
177
178   // create a new context.
179   // Isolate = isolated copy of the V8 including a heap manager, a garbage collector
180   // Only 1 thread can access a single Isolate at a given time. However, multiple Isolates can be run in parallel.
181   // Context = multiple contexts can exist in a given Isolate, and share data between contexts
182   v8::Handle<v8::Context> context  = v8::Context::New( mIsolate, NULL, global);
183
184   mGlobalObjectTemplate.Reset( mIsolate,  global);
185
186   mContext.Reset( mIsolate, context);
187 }
188
189 void DaliWrapper::Initialize()
190 {
191   if( !mIsolate )
192   {
193     v8::V8::InitializeICU();
194
195     v8::V8::Initialize();
196
197     // default isolate removed from V8 version 3.27.1 and beyond.
198     mIsolate = v8::Isolate::New();
199     mIsolate->Enter();
200
201     v8::V8::SetFatalErrorHandler( FatalErrorCallback );
202
203   }
204   // if context is null, create it and add dali object to the global object.
205   if( mContext.IsEmpty())
206   {
207      v8::HandleScope handleScope( mIsolate );
208      CreateContext();
209      v8::Local<v8::Context> context = v8::Local<v8::Context>::New(mIsolate, mContext);
210
211      context->Enter();
212
213      // Add the dali global object. Used for creating objects, and accessing constant values
214      // e.g. var x =  new dali.ImageActor(), or var col = dali.COLOR_RED;
215
216      v8::Local<v8::Object> daliObject = v8::Local<v8::Object>::Cast( context->Global()->Get( v8::String::NewFromUtf8( mIsolate, DALI_API_NAME)));
217
218      v8::Local<v8::Object> stageObject = StageWrapper::WrapStage( mIsolate, Stage::GetCurrent() );
219      daliObject->Set( v8::String::NewFromUtf8( mIsolate, "stage") , stageObject );
220
221      // keyboard focus manager is a singleton
222      v8::Local<v8::Object> keyboardObject = KeyboardFocusManagerWrapper::WrapKeyboardFocusManager( mIsolate,Toolkit::KeyboardFocusManager::Get() );
223      daliObject->Set( v8::String::NewFromUtf8( mIsolate, "keyboardFocusManager") , keyboardObject );
224
225      ConstantsWrapper::AddDaliConstants( mIsolate, daliObject);
226
227   }
228   DALI_LOG_INFO( gLogExecuteFilter, Debug::Verbose, "V8 Library %s loaded \n", v8::V8::GetVersion() );
229 }
230
231 v8::Handle<v8::ObjectTemplate> DaliWrapper::NewDaliObjectTemplate( v8::Isolate* isolate )
232 {
233   v8::EscapableHandleScope handleScope( isolate );
234
235   // create the template
236   v8::Local< v8::ObjectTemplate > objTemplate = v8::ObjectTemplate::New( isolate );
237
238   // Add some value properties ( a property can be a primitive value, an object or a function).
239   objTemplate->Set( v8::String::NewFromUtf8( isolate, "BUILD"),
240                     v8::String::NewFromUtf8( isolate, "Dali binary built on:" __DATE__ ", at " __TIME__));
241
242
243   // add the data data directory,
244   objTemplate->Set( v8::String::NewFromUtf8( isolate, "DALI_DATA_DIRECTORY"),
245                       v8::String::NewFromUtf8( isolate, DALI_DATA_READ_ONLY_DIR));
246
247   // add our constructor functions
248   ObjectTemplateHelper::InstallFunctions( isolate,
249                                           objTemplate,
250                                           ConstructorFunctionTable,
251                                           PropertyFunctionTableCount,
252                                           ObjectTemplateHelper::CONSTRUCTOR_FUNCTIONS);
253
254   return handleScope.Escape( objTemplate );
255 }
256
257 void DaliWrapper::Require(const v8::FunctionCallbackInfo< v8::Value >& args)
258 {
259   DaliWrapper& wrapper( DaliWrapper::Get() );
260   wrapper.mModuleLoader.Require( args, wrapper.mGlobalObjectTemplate );
261 }
262
263
264
265
266 } // namespace V8Plugin
267
268 } // namespace Dali