JSVM.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  2. // Please see LICENSE.md in repository root for license information
  3. // https://github.com/AtomicGameEngine/AtomicGameEngine
  4. #include <Duktape/duktape.h>
  5. #include <Atomic/Core/Profiler.h>
  6. #include <Atomic/Core/CoreEvents.h>
  7. #include <Atomic/IO/File.h>
  8. #include <Atomic/IO/Log.h>
  9. #include <Atomic/IO/FileSystem.h>
  10. #include <Atomic/IO/PackageFile.h>
  11. #include <Atomic/Resource/ResourceCache.h>
  12. #include "JSRequire.h"
  13. #include "JSPlugin.h"
  14. #include "JSEvents.h"
  15. #include "JSVM.h"
  16. #include "JSAtomic.h"
  17. #include "JSUI.h"
  18. #include "JSMetrics.h"
  19. #include "JSEventHelper.h"
  20. namespace Atomic
  21. {
  22. JSVM* JSVM::instance_ = NULL;
  23. JSVM::JSVM(Context* context) :
  24. Object(context),
  25. ctx_(0),
  26. gcTime_(0.0f)
  27. {
  28. assert(!instance_);
  29. instance_ = this;
  30. metrics_ = new JSMetrics(context, this);
  31. context_->RegisterSubsystem(new JSEventDispatcher(context_));
  32. context_->SetGlobalEventListener(context_->GetSubsystem<JSEventDispatcher>());
  33. }
  34. JSVM::~JSVM()
  35. {
  36. context_->SetGlobalEventListener(0);
  37. context_->RemoveSubsystem(JSEventDispatcher::GetTypeStatic());
  38. duk_destroy_heap(ctx_);
  39. instance_ = NULL;
  40. }
  41. void JSVM::InitJSContext()
  42. {
  43. ctx_ = duk_create_heap_default();
  44. jsapi_init_atomic(this);
  45. // register whether we are in the editor
  46. duk_get_global_string(ctx_, "Atomic");
  47. duk_push_boolean(ctx_, context_->GetEditorContext() ? 1 : 0);
  48. duk_put_prop_string(ctx_, -2, "editor");
  49. duk_pop(ctx_);
  50. duk_push_global_stash(ctx_);
  51. duk_push_object(ctx_);
  52. duk_put_prop_index(ctx_, -2, JS_GLOBALSTASH_INDEX_COMPONENTS);
  53. duk_pop(ctx_);
  54. js_init_require(this);
  55. js_init_jsplugin(this);
  56. ui_ = new JSUI(context_);
  57. // handle this elsewhere?
  58. SubscribeToEvents();
  59. }
  60. void JSVM::SubscribeToEvents()
  61. {
  62. SubscribeToEvent(E_UPDATE, HANDLER(JSVM, HandleUpdate));
  63. }
  64. void JSVM::HandleUpdate(StringHash eventType, VariantMap& eventData)
  65. {
  66. PROFILE(JSVM_HandleUpdate);
  67. using namespace Update;
  68. // Take the frame time step, which is stored as a float
  69. float timeStep = eventData[P_TIMESTEP].GetFloat();
  70. gcTime_ += timeStep;
  71. if (gcTime_ > 5.0f)
  72. {
  73. PROFILE(JSVM_GC);
  74. // run twice to call finalizers
  75. // see duktape docs
  76. // also ensure #define DUK_OPT_NO_VOLUNTARY_GC
  77. // is enabled in duktape.h
  78. duk_gc(ctx_, 0);
  79. duk_gc(ctx_, 0);
  80. gcTime_ = 0;
  81. }
  82. duk_get_global_string(ctx_, "__js_atomic_main_update");
  83. if (duk_is_function(ctx_, -1))
  84. {
  85. duk_push_number(ctx_, timeStep);
  86. duk_pcall(ctx_, 1);
  87. duk_pop(ctx_);
  88. }
  89. else
  90. {
  91. duk_pop(ctx_);
  92. }
  93. }
  94. bool JSVM::ExecuteFunction(const String& functionName)
  95. {
  96. duk_get_global_string(ctx_, functionName.CString());
  97. if (duk_is_function(ctx_, -1))
  98. {
  99. bool ok = true;
  100. if (duk_pcall(ctx_, 0) != 0)
  101. {
  102. ok = false;
  103. if (duk_is_object(ctx_, -1))
  104. {
  105. SendJSErrorEvent();
  106. }
  107. else
  108. {
  109. assert(0);
  110. }
  111. }
  112. duk_pop(ctx_);
  113. return ok;
  114. }
  115. else
  116. {
  117. duk_pop(ctx_);
  118. }
  119. return false;
  120. }
  121. void JSVM::SendJSErrorEvent(const String& filename)
  122. {
  123. duk_context* ctx = GetJSContext();
  124. using namespace JSError;
  125. VariantMap eventData;
  126. if (duk_is_string(ctx, -1))
  127. {
  128. eventData[P_ERRORNAME] = "(Unknown Error Name)";
  129. eventData[P_ERRORFILENAME] = "(Unknown Filename)";
  130. eventData[P_ERRORLINENUMBER] = -1;
  131. eventData[P_ERRORMESSAGE] = duk_to_string(ctx, -1);
  132. eventData[P_ERRORSTACK] = "";
  133. SendEvent(E_JSERROR, eventData);
  134. return;
  135. }
  136. assert(duk_is_object(ctx, -1));
  137. duk_get_prop_string(ctx, -1, "fileName");
  138. if (duk_is_string(ctx, -1))
  139. {
  140. eventData[P_ERRORFILENAME] = duk_to_string(ctx, -1);
  141. }
  142. else
  143. {
  144. eventData[P_ERRORFILENAME] = filename;
  145. }
  146. // Component script are wrapped within a closure, the line number
  147. // needs to be offset by this header
  148. duk_get_prop_string(ctx, -2, "lineNumber");
  149. int lineNumber = (int) (duk_to_number(ctx, -1));
  150. eventData[P_ERRORLINENUMBER] = lineNumber;
  151. duk_get_prop_string(ctx, -3, "name");
  152. String name = duk_to_string(ctx, -1);
  153. eventData[P_ERRORNAME] = name;
  154. duk_get_prop_string(ctx, -4, "message");
  155. String message = duk_to_string(ctx, -1);
  156. eventData[P_ERRORMESSAGE] = message;
  157. // we're not getting good file/line from duktape on parser errors
  158. if (name == "SyntaxError")
  159. {
  160. lineNumber = -1;
  161. // parse line if we have it
  162. if (message.Contains("(line "))
  163. {
  164. if (!filename.Length())
  165. eventData[P_ERRORFILENAME] = lastModuleSearchFilename_;
  166. unsigned pos = message.Find("(line ");
  167. const char* parse = message.CString() + pos + 6;
  168. String number;
  169. while (*parse >= '0' && *parse<='9')
  170. {
  171. number += *parse;
  172. parse++;
  173. }
  174. lineNumber = ToInt(number);
  175. }
  176. eventData[P_ERRORLINENUMBER] = lineNumber;
  177. }
  178. duk_get_prop_string(ctx, -5, "stack");
  179. String stack = duk_to_string(ctx, -1);
  180. eventData[P_ERRORSTACK] = stack;
  181. duk_pop_n(ctx, 5);
  182. LOGERRORF("JSErrorEvent: %s : Line %i\n Name: %s\n Message: %s\n Stack:%s",
  183. filename.CString(), lineNumber, name.CString(), message.CString(), stack.CString());
  184. SendEvent(E_JSERROR, eventData);
  185. }
  186. int JSVM::GetRealLineNumber(const String& fileName, const int lineNumber) {
  187. int realLineNumber = lineNumber;
  188. String path = fileName;
  189. if (!path.EndsWith(".js.map"))
  190. path += ".js.map";
  191. if (path.EndsWith(".js")) {
  192. return realLineNumber;
  193. }
  194. SharedPtr<File> mapFile(GetSubsystem<ResourceCache>()->GetFile(path));
  195. //if there's no source map file, maybe you use a pure js, so give an error, or maybe forgot to generate source-maps :(
  196. if (mapFile.Null())
  197. {
  198. return realLineNumber;
  199. }
  200. String map;
  201. mapFile->ReadText(map);
  202. int top = duk_get_top(ctx_);
  203. duk_get_global_string(ctx_, "require");
  204. duk_push_string(ctx_, "AtomicEditor/Script/jsutils");
  205. if (duk_pcall(ctx_, 1))
  206. {
  207. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  208. duk_set_top(ctx_, top);
  209. return false;
  210. }
  211. duk_get_prop_string(ctx_, -1, "getRealLineNumber");
  212. duk_push_string(ctx_, map.CString());
  213. duk_push_int(ctx_, lineNumber);
  214. bool ok = true;
  215. if (duk_pcall(ctx_, 2))
  216. {
  217. ok = false;
  218. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  219. }
  220. else
  221. {
  222. realLineNumber = duk_to_int(ctx_, -1);
  223. }
  224. duk_set_top(ctx_, top);
  225. return realLineNumber;
  226. }
  227. bool JSVM::ExecuteScript(const String& scriptPath)
  228. {
  229. String path = scriptPath;
  230. if (!path.StartsWith("Scripts/"))
  231. path = "Scripts/" + path;
  232. if (!path.EndsWith(".js"))
  233. path += ".js";
  234. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  235. if (file.Null())
  236. {
  237. return false;
  238. }
  239. String source;
  240. file->ReadText(source);
  241. source.Append('\n');
  242. duk_push_string(ctx_, file->GetFullPath().CString());
  243. if (duk_eval_raw(ctx_, source.CString(), 0,
  244. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  245. {
  246. if (duk_is_object(ctx_, -1))
  247. SendJSErrorEvent(path);
  248. duk_pop(ctx_);
  249. return false;
  250. }
  251. duk_pop(ctx_);
  252. return true;
  253. }
  254. bool JSVM::ExecuteFile(File *file)
  255. {
  256. if (!file)
  257. return false;
  258. String source;
  259. file->ReadText(source);
  260. source.Append('\n');
  261. duk_push_string(ctx_, file->GetFullPath().CString());
  262. if (duk_eval_raw(ctx_, source.CString(), 0,
  263. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  264. {
  265. SendJSErrorEvent(file->GetFullPath());
  266. duk_pop(ctx_);
  267. return false;
  268. }
  269. duk_pop(ctx_);
  270. return true;
  271. }
  272. void JSVM::GC()
  273. {
  274. // run twice to ensure finalizers are run
  275. duk_gc(ctx_, 0);
  276. duk_gc(ctx_, 0);
  277. }
  278. bool JSVM::ExecuteMain()
  279. {
  280. if (!GetSubsystem<ResourceCache>()->Exists("Scripts/main.js"))
  281. return true;
  282. duk_get_global_string(ctx_, "require");
  283. duk_push_string(ctx_, "Scripts/main");
  284. if (duk_pcall(ctx_, 1) != 0)
  285. {
  286. SendJSErrorEvent();
  287. return false;
  288. }
  289. if (duk_is_object(ctx_, -1))
  290. {
  291. duk_get_prop_string(ctx_, -1, "update");
  292. if (duk_is_function(ctx_, -1))
  293. {
  294. // store function for main loop
  295. duk_put_global_string(ctx_, "__js_atomic_main_update");
  296. }
  297. else
  298. {
  299. duk_pop(ctx_);
  300. }
  301. }
  302. // pop main module
  303. duk_pop(ctx_);
  304. return true;
  305. }
  306. }