JSVM.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 mapPath = fileName;
  189. if (!mapPath.EndsWith(".js.map"))
  190. mapPath += ".js.map";
  191. if (mapPath.EndsWith(".js")) {
  192. return realLineNumber;
  193. }
  194. ResourceCache* cache = GetSubsystem<ResourceCache>();
  195. String path;
  196. const Vector<String>& searchPaths = GetModuleSearchPaths();
  197. for (unsigned i = 0; i < searchPaths.Size(); i++)
  198. {
  199. String checkPath = searchPaths[i] + mapPath;
  200. if (cache->Exists(checkPath))
  201. {
  202. path = checkPath;
  203. break;
  204. }
  205. }
  206. if (!path.Length())
  207. return realLineNumber;
  208. SharedPtr<File> mapFile(GetSubsystem<ResourceCache>()->GetFile(path));
  209. //if there's no source map file, maybe you use a pure js, so give an error, or maybe forgot to generate source-maps :(
  210. if (mapFile.Null())
  211. {
  212. return realLineNumber;
  213. }
  214. String map;
  215. mapFile->ReadText(map);
  216. int top = duk_get_top(ctx_);
  217. duk_get_global_string(ctx_, "require");
  218. duk_push_string(ctx_, "AtomicEditor/EditorScripts/Lib/jsutils");
  219. if (duk_pcall(ctx_, 1))
  220. {
  221. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  222. duk_set_top(ctx_, top);
  223. return false;
  224. }
  225. duk_get_prop_string(ctx_, -1, "getRealLineNumber");
  226. duk_push_string(ctx_, map.CString());
  227. duk_push_int(ctx_, lineNumber);
  228. bool ok = true;
  229. if (duk_pcall(ctx_, 2))
  230. {
  231. ok = false;
  232. printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
  233. }
  234. else
  235. {
  236. realLineNumber = duk_to_int(ctx_, -1);
  237. }
  238. duk_set_top(ctx_, top);
  239. return realLineNumber;
  240. }
  241. bool JSVM::ExecuteScript(const String& scriptPath)
  242. {
  243. String path = scriptPath;
  244. if (!path.StartsWith("Scripts/"))
  245. path = "Scripts/" + path;
  246. if (!path.EndsWith(".js"))
  247. path += ".js";
  248. SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));
  249. if (file.Null())
  250. {
  251. return false;
  252. }
  253. String source;
  254. file->ReadText(source);
  255. source.Append('\n');
  256. duk_push_string(ctx_, file->GetFullPath().CString());
  257. if (duk_eval_raw(ctx_, source.CString(), 0,
  258. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  259. {
  260. if (duk_is_object(ctx_, -1))
  261. SendJSErrorEvent(path);
  262. duk_pop(ctx_);
  263. return false;
  264. }
  265. duk_pop(ctx_);
  266. return true;
  267. }
  268. bool JSVM::ExecuteFile(File *file)
  269. {
  270. if (!file)
  271. return false;
  272. String source;
  273. file->ReadText(source);
  274. source.Append('\n');
  275. duk_push_string(ctx_, file->GetFullPath().CString());
  276. if (duk_eval_raw(ctx_, source.CString(), 0,
  277. DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
  278. {
  279. SendJSErrorEvent(file->GetFullPath());
  280. duk_pop(ctx_);
  281. return false;
  282. }
  283. duk_pop(ctx_);
  284. return true;
  285. }
  286. void JSVM::GC()
  287. {
  288. // run twice to ensure finalizers are run
  289. duk_gc(ctx_, 0);
  290. duk_gc(ctx_, 0);
  291. }
  292. bool JSVM::ExecuteMain()
  293. {
  294. if (!GetSubsystem<ResourceCache>()->Exists("Scripts/main.js"))
  295. return true;
  296. duk_get_global_string(ctx_, "require");
  297. duk_push_string(ctx_, "Scripts/main");
  298. if (duk_pcall(ctx_, 1) != 0)
  299. {
  300. SendJSErrorEvent();
  301. return false;
  302. }
  303. if (duk_is_object(ctx_, -1))
  304. {
  305. duk_get_prop_string(ctx_, -1, "update");
  306. if (duk_is_function(ctx_, -1))
  307. {
  308. // store function for main loop
  309. duk_put_global_string(ctx_, "__js_atomic_main_update");
  310. }
  311. else
  312. {
  313. duk_pop(ctx_);
  314. }
  315. }
  316. // pop main module
  317. duk_pop(ctx_);
  318. return true;
  319. }
  320. }