Merge remote-tracking branch 'origin/tizen' into new_text
[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-attributes-wrapper.h>
28 #include <image/image-wrapper.h>
29 #include <text/font-wrapper.h>
30 #include <animation/path-wrapper.h>
31 #include <animation/animation-wrapper.h>
32 #include <events/pan-gesture-detector-wrapper.h>
33 #include <shader-effects/shader-effect-wrapper.h>
34 #include <shared/object-template-helper.h>
35 #include <constants/constants-wrapper.h>
36 #include <toolkit/builder/builder-wrapper.h>
37 #include <toolkit/focus-manager/keyboard-focus-manager-wrapper.h>
38
39
40 namespace Dali
41 {
42
43 namespace V8Plugin
44 {
45
46 namespace
47 {
48 /**
49  * This string defines how the global DALi object/namespace is used from JavaScript
50  * E.g. new dali.Image or dali.stage.add( )
51  */
52 const char* const DALI_API_NAME = "dali";
53
54 /**
55  * lookup table for setting up function calls for creating Dali objects
56  * e.g.  new dali.TextActor()
57  */
58 const ApiFunction ConstructorFunctionTable[]=
59 {
60     { "Rotation",           PropertyValueWrapper::NewRotation},
61     { "Matrix",             PropertyValueWrapper::NewMatrix},
62     { "Font",               FontWrapper::NewFont },
63     { "Path",               PathWrapper::NewPath },
64     { "Actor",              ActorWrapper::NewActor },
65     { "TextActor",          ActorWrapper::NewActor },
66     { "ImageActor",         ActorWrapper::NewActor },
67     { "MeshActor",          ActorWrapper::NewActor },
68     { "CameraActor",        ActorWrapper::NewActor },
69     { "Layer",              ActorWrapper::NewActor },
70     { "TextView",           ActorWrapper::NewActor },
71     { "ResourceImage",      ImageWrapper::NewImage },
72     { "BufferImage",        ImageWrapper::NewImage },
73     { "NinePatchImage",     ImageWrapper::NewImage },
74     { "FrameBufferImage",   ImageWrapper::NewImage },
75     { "ImageAttributes",    ImageAttributesWrapper::NewImageAttributes },
76     { "Animation",          AnimationWrapper::NewAnimation},
77     { "ShaderEffect",       ShaderEffectWrapper::NewShaderEffect},
78     { "Builder",            BuilderWrapper::NewBuilder},
79     { "PanGestureDetector", PanGestureDetectorWrapper::NewPanGestureDetector},
80
81 };
82
83 const unsigned int PropertyFunctionTableCount = sizeof(ConstructorFunctionTable)/sizeof(ConstructorFunctionTable[0]);
84
85 void FatalErrorCallback(const char* location, const char* message)
86 {
87   DALI_LOG_ERROR("%s, %s \n",location,message);
88   DALI_ASSERT_ALWAYS( 0 && "V8 fatal error");
89 }
90
91 #if defined(DEBUG_ENABLED)
92 // default to verbose logging
93 Integration::Log::Filter* gLogExecuteFilter( Integration::Log::Filter::New(Debug::Verbose, false, "EXECUTE_JAVASCRIPT") );
94 #endif
95 } // un-named name space
96
97
98
99 bool DaliWrapper::mInstanceCreated = false;
100 DaliWrapper* DaliWrapper::mWrapper = NULL;
101
102 DaliWrapper::DaliWrapper()
103 :mIsolate( NULL )
104 {
105 }
106
107 DaliWrapper::~DaliWrapper()
108 {
109   mInstanceCreated = false;
110 }
111
112 DaliWrapper& DaliWrapper::Get()
113 {
114   if(!mInstanceCreated)
115   {
116     mWrapper = new DaliWrapper();
117     mInstanceCreated = true;
118
119     if(mWrapper)
120     {
121       mWrapper->Initialize();
122     }
123   }
124
125   return *mWrapper;
126 }
127
128 void DaliWrapper::SetFlagsFromString(const std::string &flags)
129 {
130   v8::V8::SetFlagsFromString(flags.c_str(), flags.size());
131 }
132
133 void DaliWrapper::Shutdown()
134 {
135   DALI_LOG_WARNING("Destroying V8 DALi context\n");
136
137   if( !mContext.IsEmpty())
138   {
139     v8::HandleScope handleScope( mIsolate );
140     v8::Local<v8::Context> context = v8::Local<v8::Context>::New(mIsolate, mContext);
141     context->Exit();   // exit the context
142     mContext.Reset();  // destroys the context
143   }
144 }
145
146 void DaliWrapper::ExecuteBuffer(const std::string &sourceCode, const std::string &sourceFileName)
147 {
148   mModuleLoader.ExecuteScript( mIsolate,  sourceCode, sourceFileName );
149 }
150
151 void DaliWrapper::ExecuteFile( const std::string& sourceFileName )
152 {
153   DALI_LOG_INFO( gLogExecuteFilter, Debug::Verbose, "Executing source file %s \n",sourceFileName.c_str() );
154
155   mModuleLoader.ExecuteScriptFromFile( mIsolate,  sourceFileName );
156 }
157
158 GarbageCollectorInterface& DaliWrapper::GetDaliGarbageCollector()
159 {
160   return mGarbageCollector;
161 }
162
163 void DaliWrapper::CreateContext( )
164 {
165   v8::HandleScope handleScope( mIsolate );
166
167   // Create a  global JavaScript object so we can set built-in global functions, like Log.
168   v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New( mIsolate );
169
170   // Add global objects ( functions/ values ) e.g. log function and V8_VERSION
171   global->Set( v8::String::NewFromUtf8( mIsolate,  "log"),        v8::FunctionTemplate::New( mIsolate, V8Utils::Log) );
172   global->Set( v8::String::NewFromUtf8( mIsolate,  "logError"),   v8::FunctionTemplate::New( mIsolate, V8Utils::LogError) );
173   global->Set( v8::String::NewFromUtf8( mIsolate,  "require"),    v8::FunctionTemplate::New( mIsolate, DaliWrapper::Require));
174   global->Set( v8::String::NewFromUtf8( mIsolate,  "V8_VERSION") ,v8::String::NewFromUtf8( mIsolate, v8::V8::GetVersion() ));
175
176    // add the dali object to it, assume it won't be garbage collected until global is deleted
177   global->Set(v8::String::NewFromUtf8( mIsolate, DALI_API_NAME) ,  NewDaliObjectTemplate( mIsolate ));
178
179
180   // create a new context.
181   // Isolate = isolated copy of the V8 including a heap manager, a garbage collector
182   // Only 1 thread can access a single Isolate at a given time. However, multiple Isolates can be run in parallel.
183   // Context = multiple contexts can exist in a given Isolate, and share data between contexts
184   v8::Handle<v8::Context> context  = v8::Context::New( mIsolate, NULL, global);
185
186   mGlobalObjectTemplate.Reset( mIsolate,  global); 
187
188   mContext.Reset( mIsolate, context);
189 }
190
191 void DaliWrapper::Initialize()
192 {
193   if( !mIsolate )
194   {
195     v8::V8::Initialize();
196     v8::V8::InitializeICU();
197     v8::V8::SetFatalErrorHandler( FatalErrorCallback );
198     mIsolate = v8::Isolate::GetCurrent();
199   }
200   // if context is null, create it and add dali object to the global object.
201   if( mContext.IsEmpty())
202   {
203      v8::HandleScope handleScope( mIsolate );
204      CreateContext();
205      v8::Local<v8::Context> context = v8::Local<v8::Context>::New(mIsolate, mContext);
206
207      context->Enter();
208
209      // Add the dali global object. Used for creating objects, and accessing constant values
210      // e.g. var x =  new dali.ImageActor(), or var col = dali.COLOR_RED;
211
212      v8::Local<v8::Object> daliObject = v8::Local<v8::Object>::Cast( context->Global()->Get( v8::String::NewFromUtf8( mIsolate, DALI_API_NAME)));
213
214      v8::Local<v8::Object> stageObject = StageWrapper::WrapStage( mIsolate, Stage::GetCurrent() );
215      daliObject->Set( v8::String::NewFromUtf8( mIsolate, "stage") , stageObject );
216
217      // fontObject provides static font functionality like GetFontList...
218      v8::Local<v8::Object> fontObject = FontWrapper::GetStaticFontObject( mIsolate );
219      daliObject->Set( v8::String::NewFromUtf8( mIsolate, "font") , fontObject );
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