Merge branch 'devel/master' into devel/new_mesh
[platform/core/uifw/dali-toolkit.git] / plugins / dali-script-v8 / src / module-loader / module-loader.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 "module-loader.h"
20
21 // INTERNAL INCLUDES
22 #include <v8-utils.h>
23
24 namespace Dali
25 {
26
27 namespace V8Plugin
28 {
29
30 ModuleLoader::ModuleLoader()
31 {
32
33 }
34
35 ModuleLoader::~ModuleLoader()
36 {
37   VectorBase::SizeType count =  mModules.Count();
38   for( VectorBase::SizeType  i = 0; i < count ; ++i)
39   {
40     Module* module = mModules[i];
41     delete module;
42   }
43   mModules.Clear();
44 }
45
46 bool ModuleLoader::CompileAndRun(v8::Isolate* isolate,
47     const std::string& sourceCode,
48     const std::string& sourceFileName )
49 {
50
51   v8::HandleScope handleScope( isolate );
52   v8::TryCatch tryCatch;
53
54   // convert from string to v8 string
55   v8::Local<v8::String> source = v8::String::NewFromUtf8( isolate, sourceCode.c_str());
56   v8::Local<v8::String> file = v8::String::NewFromUtf8( isolate, sourceFileName.c_str());
57   v8::ScriptOrigin origin(file);
58
59   // Compile the script
60   v8::Local<v8::Script> script = v8::Script::Compile( source, &origin);
61
62   // See if an exception has been thrown
63   if( tryCatch.HasCaught() || script.IsEmpty() )
64   {
65     // Print errors that happened during compilation.
66     V8Utils::ReportException( isolate, &tryCatch );
67     return false;
68   }
69
70   // Run the script
71   v8::Local<v8::Value> result = script->Run();
72
73   // in V8 test code ( they check for an exception and empty return object )
74   if( tryCatch.HasCaught() || result.IsEmpty() )
75   {
76     // Print errors that happened during execution.
77     V8Utils::ReportException( isolate, &tryCatch);
78     return false;
79   }
80
81   return true;
82 }
83
84 bool ModuleLoader::ExecuteScript( v8::Isolate* isolate,
85                                   const std::string& sourceCode,
86                                   const std::string& sourceFileName )
87 {
88   StoreScriptInfo(  sourceFileName );
89
90   return CompileAndRun(isolate, sourceCode, sourceFileName );
91 }
92
93 bool ModuleLoader::ExecuteScriptFromFile( v8::Isolate* isolate,
94                                           const std::string& fileName  )
95 {
96   std::string contents;
97
98   V8Utils::GetFileContents( fileName, contents );
99
100   if( contents.empty() )
101   {
102     return false;
103   }
104
105   return ExecuteScript( isolate, contents, fileName );
106 }
107
108 /**
109  * ### var module = require("module-name");
110  *
111  *
112  * There is no standard for modules or the 'require' keyword in JavaScript.<br />
113  * However CommonJS have this: http://wiki.commonjs.org/wiki/Modules/1.1.1  ( used by Node.js).
114  * <br /> <br />
115  *
116  * The concept behind 'require' keyword is simple, it allows you to include another
117  * JavaScript file, which exports an API / function / constructor / singleton.
118  *
119  *
120  *     // example_module.js
121  *     exports.hello = function() { return "hello world" }
122  *
123  * <br />
124  *
125  *     // main.js
126  *     var example = require( "example_module.js");
127  *
128  *     log( example.hello() );
129  *
130  *
131
132  * ### Module writers guide:
133  *
134  *
135  * #### Exporting as a namespace
136  *
137  * Example of using a namespace to export functions / objects.
138  *
139  *     // filesystem-helper.js
140  *     exports.version = "FileSystem helper 1.0";
141  *     exports.open = function() { }
142  *     exports.close = function() { }
143  *     exports.read = function() { }
144  *     exports.write = function() { ... }
145  *     exports.fileSize = function() {...}
146  *
147  * <br />
148  *
149  *     // main.js
150  *     var fs = require( "filesystem-helper.js");
151  *
152  *     log( fs.version );
153  *
154  *     var file = fs.open("myfile.txt");
155  *     var data = fs.read( file );
156  *
157  *
158  *
159  * #### Exporting as a function
160  *
161  * In this example we are using module.exports directly to change it
162  * from an object literal with name-value pairs (exports object) to a function.
163  *
164  *     // my_first_module.js
165  *     module.exports = function() {  log("hello-world"); }
166  *
167  * <br />
168  *
169  *     // main.js
170  *     var func = require("my_first_module.js");
171  *     func();      // prints out hello-world
172  *
173  *
174  * #### Exporting as a constructor
175  *
176  *
177  *     // ImageActor.js
178  *     function ImageActor( position, orientation, image, name )
179  *     {
180  *         this = new dali.ImageActor( image );
181  *         this.position = position;
182  *         this.orientation = orientation;
183  *         this.name = name;
184  *     }
185  *     module.exports = ImageActor;
186  *
187  * <br />
188  *
189  *     // main.js
190  *
191  *     var ImageActor = require(" ImageActor.js");
192  *
193  *     var imageActor = new ImageActor( position, orientation, image, "my first image actor");
194  *
195  * #### Exporting as a singleton
196  *
197  * By exporting a singleton you have an object which has shared state between
198  * any modules using it.
199  *
200  * example:
201  *
202  *     // image-database.js
203  *
204  *     function ImageDatabase( )
205  *     {
206  *       this.addImage  = function() {  ... };
207  *       this.removeImage = function() { ... };
208  *       this.getImage = function()  { ...};
209  *       this.getImageCount = function() { ... };
210  *     }
211  *
212  *     module.exports = new ImageDatabase();
213  *
214  *
215  * <br />
216  *
217  *     // main.js
218  *
219  *     var database = require('image-database.js');
220  *
221  *     database.addImage( myImage );
222  *
223  * <br />
224  *
225  *     // another-module.js
226  *     var database = require('image-database.js');
227  *
228  *     // gets the same database object as main.js
229  *
230  *
231  * The first call to require('image-database.js') will create the image database.
232  * Further calls, will return the same instance, because require caches module.exports.
233  * Otherwise it would have to recompile and run the module every time require is called.
234  *
235  * ## Notes
236  *
237  * #### Automatic wrapping of a module by DALi:
238  *
239  * The module is automatically wrapped in a function by DALi before being executed ( similar technique to Node.js). </br>
240  * This is to prevent any functions / variables declared by the module entering the global namespace. </br>
241  * Currently the module will have access to all DALi global functions, like log, require and the DALi API ( actors / stage etc).</br>
242  *
243  *
244  *     // Parameters passed to the internally generated function
245  *     // module = reference to current module
246  *     // module.exports = defines what the module exports
247  *     // exports = reference to module.exports
248  *     // __filename = module filename
249  *     // __dirname = module directory
250  *
251  *     function createModuleXYZ( exports ( === module.exports), module, __filename, __dirname )
252  *     {
253  *       //
254  *       // Module code automatically inserted here.
255  *       //
256  *       log(" my first module ");
257  *       var version = "1.3";      // this won't pollute global namespace
258  *       exports.version = version;
259  *       exports.logActorPosition = function( actorName )
260  *       {
261  *         var actor = dali.stage.getRootLayer().findChildByName(actorName );
262  *         log( actor.x + "," + actor.y + "," + actor.z );
263  *        }
264  *       //
265  *       // End module code
266  *       //
267  *
268  *       return module.exports;
269  *     }
270
271  *
272  * Initially module.exports is an object literal with name-value pairs ( exports object).
273  * However it can be re-assigned to a constructor / function / singleton object as shown
274  * in the examples above.
275  *
276  *
277  *  ### Circular dependencies:
278  *
279  *  DALi JS supports circular dependencies as required by the CommonJS specification.
280  *
281  *  #### a.js
282  *
283  *
284  *     export.version = "1.3"
285  *     export.loaded = false;
286  *     var bModule = require('b.js')
287  *     export.loaded = true;
288  *
289  *  #### b.js
290  *
291  *     var aModule = require('a.js')
292  *     log( "aModule version = " + aModule.version + ", aModule loaded = " + aModule.loaded );
293  *
294  *     //prints  aModule = 1.3, aModule loaded = false
295  *
296  *  #### main.js
297  *
298  *      var aModule = require("a.js");
299  *
300  *
301  *  When b.js requires a.js, it is given everything that is exported from a.js, up to the point
302  *  b.js is required by a.js.
303  *
304  * ### 'require' background
305  *
306  * There is alternative to module spec in CommonJS called RequireJs ( http://requirejs.org/docs/node.html) <br />
307  * DALi JS tries to follows the CommonJS  specification (used by Node.js) as it
308  * is supposed to be better suited to server side development. <br /><br />
309  *
310  * @method require
311  * @for ModuleLoader
312  *
313  */
314 void ModuleLoader::Require(const v8::FunctionCallbackInfo< v8::Value >& args,
315
316                            v8::Persistent<v8::ObjectTemplate>& globalObjectTemplate )
317 {
318   v8::Isolate* isolate = args.GetIsolate();
319   v8::HandleScope handleScope( isolate );
320
321   bool found( false );
322   std::string fileName = V8Utils::GetStringParameter( PARAMETER_0, found, isolate , args );
323   if( !found )
324   {
325     DALI_SCRIPT_EXCEPTION( isolate, "require missing module name");
326     return;
327   }
328
329   // strip off any path / .js
330   std::string moduleName;
331   V8Utils::GetModuleName( fileName, moduleName );
332
333   // see if the module already exists
334   const Module* existingModule = FindModule( moduleName );
335   if( existingModule )
336   {
337     // printf(" using existing module %s \n",moduleName.c_str() );
338     args.GetReturnValue().Set( existingModule->mExportsObject );
339     return;
340   }
341
342   std::string path = mCurrentScriptPath;  // path of top level script being executed
343   std::string contents;
344   V8Utils::GetFileContents(path + fileName, contents);
345
346   // wrap the module in a function to protect global namespace.
347   // the create function itself is global so we make it unique for each module
348   // For reference nodeJs does this as an anonymous function, but we're calling it from native side
349   // so need to pass parameters  / get a name for it.
350   std::string functionName ="__createModule" +  moduleName;
351   std::string source = "function " + functionName + "( exports, module, __filename, __directory)  { ";
352   source+= contents;
353   source+=" \n };";  // close the function
354
355   CompileAndRun( isolate, source, fileName );
356
357   // We need to create module object, so that the module can read / write properties to it
358
359   v8::Local<v8::Object> moduleObject = v8::Object::New( isolate );
360   v8::Local<v8::Object> exportsObject = v8::Object::New( isolate );
361   moduleObject->Set( v8::String::NewFromUtf8( isolate, "exports"),  exportsObject );
362   moduleObject->Set( v8::String::NewFromUtf8( isolate, "id"), v8::String::NewFromUtf8( isolate ,moduleName.c_str() ) );
363
364   // store the module exports object now, this is to allow for circular dependencies.
365   // If this-module requires another module, which then requires this module ( creating a circle), it will be given an export object
366   // which contains everything exported so far.
367   Module* module = StoreModule( path, fileName, moduleName, isolate, exportsObject );
368
369   v8::Local<v8::Context> currentContext =  isolate->GetCurrentContext();
370
371   // get the CreateModule function
372   v8::Local<v8::Function> createModule = v8::Local<v8::Function>::Cast(currentContext->Global()->Get(v8::String::NewFromUtf8( isolate, functionName.c_str() )));
373
374   // add the arguments
375   std::vector< v8::Local<v8::Value> > arguments;
376   arguments.push_back( exportsObject );
377   arguments.push_back( moduleObject );
378   arguments.push_back( v8::String::NewFromUtf8( isolate, fileName.c_str() ));
379   arguments.push_back( v8::String::NewFromUtf8( isolate, path.c_str() ));
380
381
382   // call the CreateModule function
383   createModule->Call( createModule, arguments.size(), &arguments[0]); //[0]
384
385   // get the module.export object, the module writer may have re-assinged module.exports, so the exports object
386   // no longer references it.
387   v8::Local<v8::Value> moduleExportsValue = moduleObject->Get( v8::String::NewFromUtf8( isolate, "exports"));
388   v8::Local<v8::Object>  moduleExports = moduleExportsValue->ToObject();
389
390   // Re-store the export ( possible nothing happens, because exports hasn't been re-assigned).
391   module->mExportsObject.Reset( isolate, moduleExports);
392
393   args.GetReturnValue().Set( moduleExports );
394
395 }
396 void ModuleLoader::StoreScriptInfo( const std::string& sourceFileName )
397 {
398   V8Utils::GetFileDirectory( sourceFileName, mCurrentScriptPath);
399 }
400
401 Module* ModuleLoader::StoreModule( const std::string& path,
402                                 const std::string& fileName,
403                                 const std::string& moduleName,
404
405                                 v8::Isolate* isolate,
406                                 v8::Local<v8::Object>& moduleExportsObject )
407 {
408   Module* module = new Module( path, fileName, moduleName, isolate, moduleExportsObject );
409   mModules.PushBack( module );
410   return module;
411
412 }
413
414 const Module* ModuleLoader::FindModule( const std::string& moduleName )
415 {
416   VectorBase::SizeType count =  mModules.Count();
417   for( VectorBase::SizeType  i = 0; i < count ; ++i)
418   {
419     const Module* module = mModules[i];
420     if (module->mModuleName == moduleName )
421     {
422       return module;
423     }
424   }
425   return NULL;
426 }
427
428
429 } // V8Plugin
430
431 } // Dali