tizen 2.4 release
[framework/web/wrt-plugins-common.git] / src / xwalk-module / object_tools_module.cpp
1 // Copyright 2015 Samsung Electronics Co, Ltd. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <dlog.h>
6 #include "object_tools_module.h"
7 #include "js_utils.h"
8 #include "JSLifeManager.h"
9 #include "xwalk_module_system.h"
10
11 extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx);
12
13
14 namespace wrt {
15
16 namespace {
17
18 JSObjectRef CreateObjectFunctions(JSContextRef context) {
19   const char *code =
20     "(function(object) {"
21     "  var newobject = Object.create(object);"
22     "  Object.getOwnPropertyNames(object).forEach(function(name) {"
23     "    if (object[name] instanceof Function) {"
24     "      newobject[name] = object[name];"
25     "    }"
26     "  });"
27     "  newobject['origin_prototype'] = {};"
28     "  Object.getOwnPropertyNames(object.prototype).forEach(function(name) {"
29     "    if (object.prototype[name] instanceof Function) {"
30     "      newobject['origin_prototype'][name] = object.prototype[name];"
31     "    }"
32     "  });"
33     "  return function() {"
34     "    return newobject;"
35     "  };"
36     "}(Object));";
37
38   std::string exception;
39   JSValueRef ret_value = JsUtils::RunString(context, code, &exception);
40   JSObjectRef ret_object = JSValueToObject(context, ret_value, NULL);
41   if (!JSValueIsObject(context, ret_value) || !JSObjectIsFunction(context, ret_object)) {
42     LOGE("Couldn't get CreateObjectFunctions : %s", exception.c_str());
43     return NULL;
44   }
45   return ret_object;
46 }
47
48 }  //  namespace
49
50
51 ObjectToolsModule::ObjectToolsModule(JSContextRef context) {
52   js_context_ = context;
53   object_function_ = CreateObjectFunctions(js_context_);
54   JSValueSafeProtect(js_context_, object_function_);
55 }
56
57 ObjectToolsModule::~ObjectToolsModule() {
58   JSValueSafeUnprotect(js_context_, object_function_);
59   js_context_ = NULL;
60 }
61
62
63 JSObjectRef ObjectToolsModule::NewInstance(JSContextRef context) {
64   JSObjectRef func = object_function_;
65   JSValueRef except_value = NULL;
66   JSValueRef ret_value = JSObjectCallAsFunction(context, func, NULL, 0, NULL, &except_value);
67   if (except_value != NULL) {
68     std::string error = JsUtils::ExceptionToString(context, except_value);
69     LOGE("Error NewInstance : %s", error.c_str());
70   }
71   JSObjectRef objecttools = JSValueToObject(context, ret_value, NULL);
72   return objecttools;
73 }
74
75
76 }  // namespace wrt
77