Flexbox UI control implementation
[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 ModuleLoader::~ModuleLoader()
35 {
36   VectorBase::SizeType count =  mModules.Count();
37   for( VectorBase::SizeType  i = 0; i < count ; ++i)
38   {
39     Module* module = mModules[i];
40     delete module;
41   }
42   mModules.Clear();
43 }
44
45 bool ModuleLoader::CompileAndRun(v8::Isolate* isolate,
46     const std::string& sourceCode,
47     const std::string& sourceFileName )
48 {
49
50   v8::HandleScope handleScope( isolate );
51   v8::TryCatch tryCatch;
52
53   // convert from string to v8 string
54   v8::Local<v8::String> source = v8::String::NewFromUtf8( isolate, sourceCode.c_str());
55   v8::Local<v8::String> file = v8::String::NewFromUtf8( isolate, sourceFileName.c_str());
56   v8::ScriptOrigin origin(file);
57
58   // Compile the script
59   v8::Local<v8::Script> script = v8::Script::Compile( source, &origin);
60
61   // See if an exception has been thrown
62   if( tryCatch.HasCaught() || script.IsEmpty() )
63   {
64     // Print errors that happened during compilation.
65     V8Utils::ReportException( isolate, &tryCatch );
66     return false;
67   }
68
69   // Run the script
70   v8::Local<v8::Value> result = script->Run();
71
72   // in V8 test code ( they check for an exception and empty return object )
73   if( tryCatch.HasCaught() || result.IsEmpty() )
74   {
75     // Print errors that happened during execution.
76     V8Utils::ReportException( isolate, &tryCatch);
77     return false;
78   }
79
80   return true;
81 }
82
83 bool ModuleLoader::ExecuteScript( v8::Isolate* isolate,
84                                   const std::string& sourceCode,
85                                   const std::string& sourceFileName )
86 {
87   StoreScriptInfo(  sourceFileName );
88
89   return CompileAndRun(isolate, sourceCode, sourceFileName );
90 }
91
92 bool ModuleLoader::ExecuteScriptFromFile( v8::Isolate* isolate,
93                                           const std::string& fileName  )
94 {
95   std::string contents;
96
97   V8Utils::GetFileContents( fileName, contents );
98
99   if( contents.empty() )
100   {
101     return false;
102   }
103
104   return ExecuteScript( isolate, contents, fileName );
105 }
106
107 /**
108  * ### var module = require("moduleName");
109  *
110  *
111  * There is no standard for modules or the 'require' keyword in JavaScript.<br />
112  * However CommonJS have this: http://wiki.commonjs.org/wiki/Modules/1.1.1  ( used by Node.js).
113  * <br /> <br />
114  *
115  * The concept behind 'require' keyword is simple, it allows you to include another
116  * JavaScript file, which exports an API / function / constructor / singleton.
117  *
118  *
119  *     // example_module.js
120  *     exports.hello = function() { return "hello world" }
121  *
122  * <br />
123  *
124  *     // main.js
125  *     var example = require( "example_module.js");
126  *
127  *     log( example.hello() );
128  *
129  *
130
131  * ### Module writers guide:
132  *
133  *
134  * #### Exporting as a namespace
135  *
136  * Example of using a namespace to export functions / objects.
137  *
138  *     // filesystem-helper.js
139  *     exports.version = "FileSystem helper 1.0";
140  *     exports.open = function() { }
141  *     exports.close = function() { }
142  *     exports.read = function() { }
143  *     exports.write = function() { ... }
144  *     exports.fileSize = function() {...}
145  *
146  * <br />
147  *
148  *     // main.js
149  *     var fs = require( "filesystem-helper.js");
150  *
151  *     log( fs.version );
152  *
153  *     var file = fs.open("myfile.txt");
154  *     var data = fs.read( file );
155  *
156  *
157  *
158  * #### Exporting as a function
159  *
160  * In this example we are using module.exports directly to change it
161  * from an object literal with name-value pairs (exports object) to a function.
162  *
163  *     // my_first_module.js
164  *     module.exports = function() {  log("helloWorld"); }
165  *
166  * <br />
167  *
168  *     // main.js
169  *     var func = require("my_first_module.js");
170  *     func();      // prints out hello-world
171  *
172  *
173  * #### Exporting as a constructor
174  *
175  *
176  *     // ImageView.js
177  *     function ImageView( position, orientation, image, name )
178  *     {
179  *         this = new dali.Control("ImageView");
180  *         this.image = image;
181  *         this.position = position;
182  *         this.orientation = orientation;
183  *         this.name = name;
184  *     }
185  *     module.exports = ImageView;
186  *
187  * <br />
188  *
189  *     // main.js
190  *
191  *     var ImageView = require(" ImageView.js");
192  *
193  *     var imageView = new ImageView( 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::Isolate* isolate = args.GetIsolate();
317   v8::HandleScope handleScope( isolate );
318
319   bool found( false );
320   std::string fileName = V8Utils::GetStringParameter( PARAMETER_0, found, isolate , args );
321   if( !found )
322   {
323     DALI_SCRIPT_EXCEPTION( isolate, "require missing module name");
324     return;
325   }
326
327   // strip off any path / .js
328   std::string moduleName;
329   V8Utils::GetModuleName( fileName, moduleName );
330
331   // see if the module already exists
332   const Module* existingModule = FindModule( moduleName );
333   if( existingModule )
334   {
335     // printf(" using existing module %s \n",moduleName.c_str() );
336     args.GetReturnValue().Set( existingModule->mExportsObject );
337     return;
338   }
339
340   std::string path = mCurrentScriptPath;  // path of top level script being executed
341   std::string contents;
342   V8Utils::GetFileContents(path + fileName, contents);
343
344   // wrap the module in a function to protect global namespace.
345   // the create function itself is global so we make it unique for each module
346   // For reference nodeJs does this as an anonymous function, but we're calling it from native side
347   // so need to pass parameters  / get a name for it.
348   std::string functionName ="__createModule" +  moduleName;
349   std::string source = "function " + functionName + "( exports, module, __filename, __directory)  { ";
350   source+= contents;
351   source+=" \n };";  // close the function
352
353   CompileAndRun( isolate, source, fileName );
354
355   // We need to create module object, so that the module can read / write properties to it
356
357   v8::Local<v8::Object> moduleObject = v8::Object::New( isolate );
358   v8::Local<v8::Object> exportsObject = v8::Object::New( isolate );
359   moduleObject->Set( v8::String::NewFromUtf8( isolate, "exports"),  exportsObject );
360   moduleObject->Set( v8::String::NewFromUtf8( isolate, "id"), v8::String::NewFromUtf8( isolate ,moduleName.c_str() ) );
361
362   // store the module exports object now, this is to allow for circular dependencies.
363   // If this-module requires another module, which then requires this module ( creating a circle), it will be given an export object
364   // which contains everything exported so far.
365   Module* module = StoreModule( path, fileName, moduleName, isolate, exportsObject );
366
367   v8::Local<v8::Context> currentContext =  isolate->GetCurrentContext();
368
369   // get the CreateModule function
370   v8::Local<v8::Function> createModule = v8::Local<v8::Function>::Cast(currentContext->Global()->Get(v8::String::NewFromUtf8( isolate, functionName.c_str() )));
371
372   // add the arguments
373   std::vector< v8::Local<v8::Value> > arguments;
374   arguments.push_back( exportsObject );
375   arguments.push_back( moduleObject );
376   arguments.push_back( v8::String::NewFromUtf8( isolate, fileName.c_str() ));
377   arguments.push_back( v8::String::NewFromUtf8( isolate, path.c_str() ));
378
379
380   // call the CreateModule function
381   createModule->Call( createModule, arguments.size(), &arguments[0]); //[0]
382
383   // get the module.export object, the module writer may have re-assinged module.exports, so the exports object
384   // no longer references it.
385   v8::Local<v8::Value> moduleExportsValue = moduleObject->Get( v8::String::NewFromUtf8( isolate, "exports"));
386   v8::Local<v8::Object>  moduleExports = moduleExportsValue->ToObject();
387
388   // Re-store the export ( possible nothing happens, because exports hasn't been re-assigned).
389   module->mExportsObject.Reset( isolate, moduleExports);
390
391   args.GetReturnValue().Set( moduleExports );
392
393 }
394
395 void ModuleLoader::StorePreBuiltModule( v8::Isolate* isolate, v8::Local<v8::Object>& exportObject, const std::string& name )
396 {
397   StoreModule( "", name, name, isolate, exportObject );
398 }
399
400 void ModuleLoader::StoreScriptInfo( const std::string& sourceFileName )
401 {
402   V8Utils::GetFileDirectory( sourceFileName, mCurrentScriptPath);
403 }
404
405 Module* ModuleLoader::StoreModule( const std::string& path,
406                                 const std::string& fileName,
407                                 const std::string& moduleName,
408
409                                 v8::Isolate* isolate,
410                                 v8::Local<v8::Object>& moduleExportsObject )
411 {
412   Module* module = new Module( path, fileName, moduleName, isolate, moduleExportsObject );
413   mModules.PushBack( module );
414   return module;
415
416 }
417
418 const Module* ModuleLoader::FindModule( const std::string& moduleName )
419 {
420   VectorBase::SizeType count =  mModules.Count();
421   for( VectorBase::SizeType  i = 0; i < count ; ++i)
422   {
423     const Module* module = mModules[i];
424     if (module->mModuleName == moduleName )
425     {
426       return module;
427     }
428   }
429   return NULL;
430 }
431
432
433 } // V8Plugin
434
435 } // Dali