JSComponentFile.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  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. #include <Atomic/Core/Context.h>
  23. #include <Atomic/IO/Deserializer.h>
  24. #include <Atomic/IO/Log.h>
  25. #include <Atomic/Core/Profiler.h>
  26. #include <Atomic/Resource/ResourceCache.h>
  27. #include <Atomic/IO/Serializer.h>
  28. #include "JSComponentFile.h"
  29. #include "JSComponent.h"
  30. #include "JSVM.h"
  31. namespace Atomic
  32. {
  33. JSComponentFile::JSComponentFile(Context* context) :
  34. Resource(context),
  35. scriptClass_(false)
  36. {
  37. }
  38. JSComponentFile::~JSComponentFile()
  39. {
  40. }
  41. void JSComponentFile::RegisterObject(Context* context)
  42. {
  43. context->RegisterFactory<JSComponentFile>();
  44. }
  45. void JSComponentFile::GetDefaultFieldValue(const String& name, Variant& v)
  46. {
  47. v = Variant::EMPTY;
  48. VariantMap::ConstIterator itr = defaultFieldValues_.Find(name);
  49. if (itr == defaultFieldValues_.End())
  50. {
  51. HashMap<String, VariantType>::ConstIterator citr = fields_.Find(name);
  52. if (citr == fields_.End())
  53. return;
  54. switch (citr->second_)
  55. {
  56. case VAR_BOOL:
  57. v = false;
  58. break;
  59. case VAR_STRING:
  60. v = "";
  61. break;
  62. case VAR_FLOAT:
  63. v = 0.0f;
  64. break;
  65. case VAR_VECTOR3:
  66. v = Vector3::ZERO;
  67. break;
  68. default:
  69. break;
  70. }
  71. return;
  72. }
  73. v = itr->second_;
  74. }
  75. bool JSComponentFile::PushModule()
  76. {
  77. if (context_->GetEditorContext())
  78. return false;
  79. JSVM* vm = JSVM::GetJSVM(NULL);
  80. duk_context* ctx = vm->GetJSContext();
  81. const String& path = GetName();
  82. String pathName, fileName, ext;
  83. SplitPath(path, pathName, fileName, ext);
  84. if (path.Contains('/') || path.Contains('\\'))
  85. pathName += "/" + fileName;
  86. else
  87. pathName = fileName;
  88. duk_get_global_string(ctx, "require");
  89. duk_push_string(ctx, pathName.CString());
  90. if (duk_pcall(ctx, 1) != 0)
  91. {
  92. vm->SendJSErrorEvent();
  93. return false;
  94. }
  95. return true;
  96. }
  97. JSComponent* JSComponentFile::CreateJSComponent()
  98. {
  99. JSComponent* component = NULL;
  100. if (!scriptClass_)
  101. {
  102. component = new JSComponent(context_);
  103. }
  104. else
  105. {
  106. JSVM* vm = JSVM::GetJSVM(NULL);
  107. duk_context* ctx = vm->GetJSContext();
  108. PushModule();
  109. duk_new(ctx, 0);
  110. if (duk_is_object(ctx, -1))
  111. {
  112. component = js_to_class_instance<JSComponent>(ctx, -1, 0);
  113. component->scriptClassInstance_ = true;
  114. // store reference below so pop doesn't gc the component
  115. component->UpdateReferences();
  116. }
  117. duk_pop(ctx);
  118. }
  119. if (!component)
  120. {
  121. LOGERRORF("Failed to create script class from component file %s", GetName().CString());
  122. component = new JSComponent(context_);
  123. }
  124. component->SetComponentFile(this);
  125. return component;
  126. }
  127. bool JSComponentFile::InitModule()
  128. {
  129. if (context_->GetEditorContext())
  130. return true;
  131. JSVM* vm = JSVM::GetJSVM(NULL);
  132. duk_context* ctx = vm->GetJSContext();
  133. duk_idx_t top = duk_get_top(ctx);
  134. if (!PushModule())
  135. return false;
  136. if (!duk_is_function(ctx, -1))
  137. {
  138. LOGERRORF("Component file does not export a function: %s", GetName().CString());
  139. duk_set_top(ctx, top);
  140. return false;
  141. }
  142. // detect a script class vs a simple "flat" javascript component
  143. // this means that if a script component class defines a constructor,
  144. // it must take 0 arguments (which makes sense as when it is new'd from
  145. // serialization, etc there will be no args to pass it
  146. if (duk_get_length(ctx, -1) == 0)
  147. {
  148. scriptClass_ = true;
  149. }
  150. duk_set_top(ctx, top);
  151. return true;
  152. }
  153. bool JSComponentFile::BeginLoad(Deserializer& source)
  154. {
  155. if (!InitModule())
  156. return false;
  157. // TODO: move the inspector field parsing to the JavascriptImporter
  158. // which will work with obfusication, minimization, or bytecode dumps
  159. unsigned dataSize = source.GetSize();
  160. if (!dataSize && !source.GetName().Empty())
  161. {
  162. LOGERROR("Zero sized component file in " + source.GetName());
  163. return false;
  164. }
  165. SharedArrayPtr<char> buffer(new char[dataSize + 1]);
  166. if (source.Read(buffer.Get(), dataSize) != dataSize)
  167. return false;
  168. buffer[dataSize] = '\0';
  169. String text = buffer.Get();
  170. text.Replace("\r", "");
  171. Vector<String> lines = text.Split('\n');
  172. String eval;
  173. bool valid = false;
  174. int leftBracketCount = 0;
  175. int rightBracketCount = 0;
  176. for (unsigned i = 0; i < lines.Size(); i++)
  177. {
  178. String line = lines[i];
  179. bool added = false;
  180. if (!eval.Length())
  181. {
  182. line = line.Trimmed();
  183. if (line.StartsWith("inspectorFields"))
  184. {
  185. added = true;
  186. eval = line + "\n";
  187. }
  188. else if (line.StartsWith("this.inspectorFields"))
  189. {
  190. added = true;
  191. eval = line.Substring(5) + "\n";
  192. }
  193. else if (line.StartsWith("var inspectorFields"))
  194. {
  195. added = true;
  196. eval = line.Substring(4) + "\n";
  197. }
  198. }
  199. else
  200. {
  201. added = true;
  202. eval += line + "\n";
  203. }
  204. if (added) {
  205. for (unsigned j = 0; j < line.Length(); j++)
  206. {
  207. if (line.At(j) == '{')
  208. leftBracketCount++;
  209. else if (line.At(j) == '}')
  210. rightBracketCount++;
  211. }
  212. }
  213. if (eval.Length() && leftBracketCount && leftBracketCount == rightBracketCount)
  214. {
  215. valid = true;
  216. break;
  217. }
  218. }
  219. if (valid)
  220. {
  221. JSVM* vm = JSVM::GetJSVM(NULL);
  222. if (!vm)
  223. return true;
  224. duk_context* ctx = vm->GetJSContext();
  225. int top = duk_get_top(ctx);
  226. duk_push_string(ctx, eval.CString());
  227. duk_push_string(ctx, "eval");
  228. if (duk_pcompile(ctx, DUK_COMPILE_EVAL) != 0)
  229. {
  230. // couldn't eval the inspector fields
  231. duk_set_top(ctx, top);
  232. return true;
  233. }
  234. else if (duk_is_function(ctx, -1) && duk_pcall(ctx, 0) == DUK_EXEC_SUCCESS)
  235. {
  236. if (duk_is_object(ctx, -1))
  237. {
  238. duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY);
  239. while (duk_next(ctx, -1, 1)) {
  240. String name = duk_get_string(ctx, -2);
  241. VariantType variantType = VAR_NONE;
  242. Variant defaultValue;
  243. if (duk_is_string(ctx, -1))
  244. {
  245. variantType = VAR_STRING;
  246. defaultValue = duk_to_string(ctx, -1);
  247. }
  248. else if (duk_is_number(ctx, -1))
  249. {
  250. variantType = VAR_FLOAT;
  251. defaultValue = (float) duk_to_number(ctx, -1);
  252. }
  253. else if (duk_is_array(ctx, -1))
  254. {
  255. int length = duk_get_length(ctx, -1);
  256. if (length > 0)
  257. {
  258. duk_get_prop_index(ctx, -1, 0);
  259. // resource ref detection
  260. if (duk_is_string(ctx, -1))
  261. {
  262. const char* classname = duk_to_string(ctx, -1);
  263. duk_pop(ctx);
  264. const char* name = NULL;
  265. if (length > 1)
  266. {
  267. duk_get_prop_index(ctx, -1, 1);
  268. name = duk_require_string(ctx, -1);
  269. duk_pop(ctx);
  270. }
  271. ResourceRef resourceRef(classname);
  272. if (name)
  273. resourceRef.name_ = name;
  274. variantType = VAR_RESOURCEREF;
  275. defaultValue = resourceRef;
  276. }
  277. else
  278. {
  279. variantType = (VariantType) ((int)duk_require_number(ctx, -1));
  280. duk_pop(ctx);
  281. // detect int enum
  282. if (length > 1 && (variantType == VAR_INT || variantType == VAR_FLOAT
  283. || variantType == VAR_DOUBLE))
  284. {
  285. duk_get_prop_index(ctx, -1, 1);
  286. if (duk_is_number(ctx, -1))
  287. {
  288. js_to_variant(ctx, -1, defaultValue);
  289. }
  290. else if (duk_is_object(ctx, -1))
  291. {
  292. duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY);
  293. while (duk_next(ctx, -1, 1)) {
  294. Variant enumValue = (float) duk_to_number(ctx, -2);
  295. String enumName = duk_get_string(ctx, -1);
  296. enums_[name].Push(EnumInfo(enumName, enumValue));
  297. duk_pop_2(ctx); // pop key value
  298. }
  299. duk_pop(ctx); // pop enum object
  300. }
  301. duk_pop(ctx);
  302. if (length > 2)
  303. {
  304. duk_get_prop_index(ctx, -1, 2);
  305. // default value
  306. js_to_variant(ctx, -1, defaultValue);
  307. duk_pop(ctx);
  308. }
  309. }
  310. else if (length > 1)
  311. {
  312. duk_get_prop_index(ctx, -1, 1);
  313. // default value
  314. js_to_variant(ctx, -1, defaultValue);
  315. duk_pop(ctx);
  316. }
  317. }
  318. }
  319. }
  320. else if (duk_is_boolean(ctx, -1))
  321. {
  322. variantType = VAR_BOOL;
  323. defaultValue = duk_to_boolean(ctx, -1) ? true : false;
  324. }
  325. if (defaultValue.GetType() != VAR_NONE)
  326. {
  327. defaultFieldValues_[name] = defaultValue;
  328. }
  329. if (variantType != VAR_NONE)
  330. fields_[name] = variantType;
  331. duk_pop_2(ctx); // pop key value
  332. }
  333. duk_pop(ctx); // pop enum object
  334. }
  335. }
  336. duk_set_top(ctx, top);
  337. }
  338. SetMemoryUse(0);
  339. return true;
  340. }
  341. bool JSComponentFile::Save(Serializer& dest) const
  342. {
  343. return true;
  344. }
  345. }