JSVM.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include <Atomic/Core/Context.h>
  24. #include <Atomic/Core/Object.h>
  25. #include <Atomic/Container/List.h>
  26. #include <Atomic/IO/Log.h>
  27. #include <Atomic/IO/FileSystem.h>
  28. #include "JSAPI.h"
  29. #include "JSEvents.h"
  30. //#define JSVM_DEBUG
  31. namespace Atomic
  32. {
  33. class JSFile;
  34. class JSUI;
  35. class JSMetrics;
  36. class JSVM;
  37. /// Registration signature for JSVM package registration
  38. typedef void(*JSVMPackageRegistrationFunction)(JSVM* vm);
  39. /// Registration signature for JSVM package registration with settings
  40. typedef void(*JSVMPackageRegistrationSettingsFunction)(JSVM* vm, const VariantMap& setting);
  41. class ATOMIC_API JSVM : public Object
  42. {
  43. friend class JSMetrics;
  44. OBJECT(JSVM)
  45. public:
  46. /// Construct.
  47. JSVM(Context* context);
  48. /// Destruct.
  49. virtual ~JSVM();
  50. void InitJSContext();
  51. /// Package registration
  52. static void RegisterPackage(JSVMPackageRegistrationFunction regFunction);
  53. static void RegisterPackage(JSVMPackageRegistrationSettingsFunction regFunction, const VariantMap& settings);
  54. /// Initialize registered packages
  55. void InitializePackages();
  56. bool ExecuteFile(File* file);
  57. // Resources/Scripts/*.js
  58. bool ExecuteScript(const String& scriptPath);
  59. // Resources/Script/main.js
  60. bool ExecuteMain();
  61. bool ExecuteFunction(const String& functionName);
  62. inline static JSVM* GetJSVM(duk_context* context)
  63. {
  64. return instance_;
  65. }
  66. inline duk_context* GetJSContext() { return ctx_; }
  67. void GC();
  68. JSMetrics* GetMetrics() { return metrics_; }
  69. void DumpJavascriptObjects() {}
  70. #ifdef JSVM_DEBUG
  71. inline void ValidateJSHeapPtr(void* heapptr)
  72. {
  73. assert(removedHeapPtr_.Find(heapptr) == removedHeapPtr_.End());
  74. assert(heapToObject_.Find(heapptr) != heapToObject_.End());
  75. }
  76. #endif
  77. inline void AddObject(void* heapptr, RefCounted* object)
  78. {
  79. assert(!object->JSGetHeapPtr());
  80. object->JSSetHeapPtr(heapptr);
  81. #ifdef JSVM_DEBUG
  82. assert(heapToObject_.Find(heapptr) == heapToObject_.End());
  83. #endif
  84. heapToObject_[heapptr] = object;
  85. #ifdef JSVM_DEBUG
  86. HashMap<void*, void*>::Iterator itr = removedHeapPtr_.Find(heapptr);
  87. if (itr != removedHeapPtr_.End())
  88. removedHeapPtr_.Erase(itr);
  89. #endif
  90. if (object->IsObject())
  91. {
  92. objectAddedData_[ObjectAdded::P_OBJECT] = object;
  93. SendEvent(E_JSOBJECTADDED, objectAddedData_);
  94. }
  95. }
  96. inline void RemoveObject(RefCounted* object)
  97. {
  98. if (object->IsObject())
  99. {
  100. objectRemovedData_[ObjectRemoved::P_OBJECT] = object;
  101. SendEvent(E_JSOBJECTREMOVED, objectRemovedData_);
  102. }
  103. void* heapptr = object->JSGetHeapPtr();
  104. assert(heapptr);
  105. object->JSSetHeapPtr(NULL);
  106. HashMap<void*, RefCounted*>::Iterator hitr = heapToObject_.Find(heapptr);
  107. assert(hitr != heapToObject_.End());
  108. heapToObject_.Erase(hitr);
  109. #ifdef JSVM_DEBUG
  110. assert(removedHeapPtr_.Find(heapptr) == removedHeapPtr_.End());
  111. removedHeapPtr_[heapptr] = heapptr;
  112. #endif
  113. }
  114. inline RefCounted* GetObjectPtr(void* heapptr, bool allowNull = false)
  115. {
  116. #ifdef JSVM_DEBUG
  117. assert(!removedHeapPtr_.Contains(heapptr));
  118. #endif
  119. if (allowNull && !heapToObject_.Contains(heapptr))
  120. {
  121. return NULL;
  122. }
  123. assert(heapToObject_.Contains(heapptr));
  124. #ifdef JSVM_DEBUG
  125. RefCounted* ref = heapToObject_[heapptr];
  126. assert(ref->JSGetHeapPtr() == heapptr);
  127. #endif
  128. return heapToObject_[heapptr];
  129. }
  130. void SetModuleSearchPaths(const String& searchPath)
  131. {
  132. moduleSearchPath_ = searchPath.Split(';');
  133. for (unsigned i = 0; i < moduleSearchPath_.Size(); i++)
  134. {
  135. moduleSearchPath_[i] = AddTrailingSlash(moduleSearchPath_[i]);
  136. }
  137. }
  138. const Vector<String>& GetModuleSearchPaths()
  139. {
  140. return moduleSearchPath_;
  141. }
  142. void SetLastModuleSearchFile(const String& fileName) { lastModuleSearchFilename_ = fileName; }
  143. const String& GetLastModuleSearchFile() { return lastModuleSearchFilename_; }
  144. const String& GetErrorString() { return errorString_; }
  145. void SendJSErrorEvent(const String& filename = String::EMPTY);
  146. int GetRealLineNumber(const String& fileName, const int lineNumber);
  147. private:
  148. struct JSAPIPackageRegistration
  149. {
  150. JSAPIPackageRegistration()
  151. {
  152. registrationFunction = 0;
  153. registrationSettingsFunction = 0;
  154. }
  155. JSAPIPackageRegistration(JSVMPackageRegistrationFunction regFunction)
  156. {
  157. registrationFunction = regFunction;
  158. registrationSettingsFunction = 0;
  159. }
  160. JSAPIPackageRegistration(JSVMPackageRegistrationSettingsFunction regFunction, const VariantMap& regSettings)
  161. {
  162. registrationFunction = 0;
  163. registrationSettingsFunction = regFunction;
  164. settings = regSettings;
  165. }
  166. JSVMPackageRegistrationFunction registrationFunction;
  167. JSVMPackageRegistrationSettingsFunction registrationSettingsFunction;
  168. VariantMap settings;
  169. };
  170. void SubscribeToEvents();
  171. void HandleUpdate(StringHash eventType, VariantMap& eventData);
  172. duk_context* ctx_;
  173. HashMap<void*, RefCounted*> heapToObject_;
  174. #ifdef JSVM_DEBUG
  175. // Debugging
  176. HashMap<void*, void*> removedHeapPtr_;
  177. #endif
  178. float gcTime_;
  179. Vector<String> moduleSearchPath_;
  180. String lastModuleSearchFilename_;
  181. String errorString_;
  182. SharedPtr<JSUI> ui_;
  183. VariantMap objectAddedData_;
  184. VariantMap objectRemovedData_;
  185. SharedPtr<JSMetrics> metrics_;
  186. static Vector<JSAPIPackageRegistration*> packageRegistrations_;
  187. static JSVM* instance_;
  188. };
  189. template<typename T>
  190. T* js_to_class_instance(duk_context* ctx, int index, unsigned classID)
  191. {
  192. if (!duk_is_object(ctx, index))
  193. return NULL;
  194. return (T*) JSVM::GetJSVM(ctx)->GetObjectPtr(duk_get_heapptr(ctx, index));
  195. }
  196. // pushes null if instance is null
  197. // pushes from object store if already wrapped
  198. // pushes a new'd instance with wrapped native
  199. // must be an Object (so downcast works)
  200. inline bool js_push_class_object_instance(duk_context* ctx, const RefCounted *instance, const char* classname = "")
  201. {
  202. if (!instance)
  203. {
  204. duk_push_null(ctx);
  205. return true;
  206. }
  207. int top = duk_get_top(ctx);
  208. if (instance->JSGetHeapPtr())
  209. {
  210. duk_push_heapptr(ctx, instance->JSGetHeapPtr());
  211. assert(duk_is_object(ctx, -1));
  212. return true;
  213. }
  214. duk_push_heap_stash(ctx);
  215. duk_push_pointer(ctx, (void*) instance->GetClassID());
  216. duk_get_prop(ctx, -2);
  217. // if not an object, this instance isn't not a scriptable class
  218. // reset top and return false
  219. if (!duk_is_object(ctx, -1))
  220. {
  221. if (instance->IsObject())
  222. {
  223. LOGERRORF("Unable to push class object instance due to missing ClassID: %s", ((Object*)instance)->GetTypeName().CString());
  224. }
  225. else
  226. {
  227. LOGERROR("Unable to push RefCounted instance due to missing ClassID");
  228. }
  229. duk_set_top(ctx, top);
  230. return false;
  231. }
  232. duk_get_prop_index(ctx, -1, 0);
  233. const char* package = duk_require_string(ctx, -1);
  234. duk_get_prop_index(ctx, -2, 1);
  235. const char* jclassname = duk_require_string(ctx, -1);
  236. duk_set_top(ctx, top);
  237. duk_get_global_string(ctx, package);
  238. duk_get_prop_string(ctx, -1, jclassname);
  239. assert(duk_is_function(ctx, -1));
  240. duk_push_pointer(ctx, (void*) instance);
  241. duk_new(ctx, 1);
  242. duk_remove(ctx, -2); // remove Atomic object
  243. assert(duk_is_object(ctx, -1));
  244. assert ((top + 1) == duk_get_top(ctx));
  245. return true;
  246. }
  247. }