pluginscript_script.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /*************************************************************************/
  2. /* pluginscript_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. // Godot imports
  31. #include "core/os/file_access.h"
  32. // PluginScript imports
  33. #include "pluginscript_instance.h"
  34. #include "pluginscript_script.h"
  35. #include <stdint.h>
  36. #ifdef DEBUG_ENABLED
  37. #define __ASSERT_SCRIPT_REASON "Cannot retrieve PluginScript class for this script, is your code correct?"
  38. #define ASSERT_SCRIPT_VALID() \
  39. { \
  40. ERR_FAIL_COND_MSG(!can_instance(), __ASSERT_SCRIPT_REASON); \
  41. }
  42. #define ASSERT_SCRIPT_VALID_V(ret) \
  43. { \
  44. ERR_FAIL_COND_V_MSG(!can_instance(), ret, __ASSERT_SCRIPT_REASON); \
  45. }
  46. #else
  47. #define ASSERT_SCRIPT_VALID()
  48. #define ASSERT_SCRIPT_VALID_V(ret)
  49. #endif
  50. void PluginScript::_bind_methods() {
  51. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &PluginScript::_new, MethodInfo("new"));
  52. }
  53. PluginScriptInstance *PluginScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, Callable::CallError &r_error) {
  54. r_error.error = Callable::CallError::CALL_OK;
  55. // Create instance
  56. PluginScriptInstance *instance = memnew(PluginScriptInstance());
  57. if (instance->init(this, p_owner)) {
  58. _language->lock();
  59. _instances.insert(instance->get_owner());
  60. _language->unlock();
  61. } else {
  62. r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  63. memdelete(instance);
  64. ERR_FAIL_V(NULL);
  65. }
  66. // Construct
  67. // TODO: Support arguments in the constructor?
  68. // There is currently no way to get the constructor function name of the script.
  69. // instance->call("__init__", p_args, p_argcount, r_error);
  70. if (p_argcount > 0) {
  71. WARN_PRINT("PluginScript doesn't support arguments in the constructor");
  72. }
  73. return instance;
  74. }
  75. Variant PluginScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  76. r_error.error = Callable::CallError::CALL_OK;
  77. if (!_valid) {
  78. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  79. return Variant();
  80. }
  81. REF ref;
  82. Object *owner = NULL;
  83. if (get_instance_base_type() == "") {
  84. owner = memnew(Reference);
  85. } else {
  86. owner = ClassDB::instance(get_instance_base_type());
  87. }
  88. if (!owner) {
  89. r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  90. return Variant();
  91. }
  92. Reference *r = Object::cast_to<Reference>(owner);
  93. if (r) {
  94. ref = REF(r);
  95. }
  96. PluginScriptInstance *instance = _create_instance(p_args, p_argcount, owner, r_error);
  97. if (!instance) {
  98. if (ref.is_null()) {
  99. memdelete(owner); //no owner, sorry
  100. }
  101. return Variant();
  102. }
  103. if (ref.is_valid()) {
  104. return ref;
  105. } else {
  106. return owner;
  107. }
  108. }
  109. #ifdef TOOLS_ENABLED
  110. void PluginScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  111. placeholders.erase(p_placeholder);
  112. }
  113. #endif
  114. bool PluginScript::can_instance() const {
  115. bool can = _valid || (!_tool && !ScriptServer::is_scripting_enabled());
  116. return can;
  117. }
  118. Ref<Script> PluginScript::get_base_script() const {
  119. if (_ref_base_parent.is_valid()) {
  120. return Ref<PluginScript>(_ref_base_parent);
  121. } else {
  122. return Ref<Script>();
  123. }
  124. }
  125. StringName PluginScript::get_instance_base_type() const {
  126. if (_native_parent)
  127. return _native_parent;
  128. if (_ref_base_parent.is_valid())
  129. return _ref_base_parent->get_instance_base_type();
  130. return StringName();
  131. }
  132. void PluginScript::update_exports() {
  133. #ifdef TOOLS_ENABLED
  134. ASSERT_SCRIPT_VALID();
  135. if (placeholders.size()) {
  136. //update placeholders if any
  137. Map<StringName, Variant> propdefvalues;
  138. List<PropertyInfo> propinfos;
  139. get_script_property_list(&propinfos);
  140. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  141. E->get()->update(propinfos, _properties_default_values);
  142. }
  143. }
  144. #endif
  145. }
  146. // TODO: rename p_this "p_owner" ?
  147. ScriptInstance *PluginScript::instance_create(Object *p_this) {
  148. ASSERT_SCRIPT_VALID_V(NULL);
  149. // TODO check script validity ?
  150. if (!_tool && !ScriptServer::is_scripting_enabled()) {
  151. #ifdef TOOLS_ENABLED
  152. // Instance a fake script for editing the values
  153. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(get_language(), Ref<Script>(this), p_this));
  154. placeholders.insert(si);
  155. update_exports();
  156. return si;
  157. #else
  158. return NULL;
  159. #endif
  160. }
  161. StringName base_type = get_instance_base_type();
  162. if (base_type) {
  163. if (!ClassDB::is_parent_class(p_this->get_class_name(), base_type)) {
  164. String msg = "Script inherits from native type '" + String(base_type) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'";
  165. // TODO: implement PluginscriptLanguage::debug_break_parse
  166. // if (EngineDebugger::is_active()) {
  167. // _language->debug_break_parse(get_path(), 0, msg);
  168. // }
  169. ERR_FAIL_V_MSG(NULL, msg);
  170. }
  171. }
  172. Callable::CallError unchecked_error;
  173. return _create_instance(NULL, 0, p_this, unchecked_error);
  174. }
  175. bool PluginScript::instance_has(const Object *p_this) const {
  176. _language->lock();
  177. bool hasit = _instances.has((Object *)p_this);
  178. _language->unlock();
  179. return hasit;
  180. }
  181. bool PluginScript::has_source_code() const {
  182. bool has = _source != "";
  183. return has;
  184. }
  185. String PluginScript::get_source_code() const {
  186. return _source;
  187. }
  188. void PluginScript::set_source_code(const String &p_code) {
  189. if (_source == p_code)
  190. return;
  191. _source = p_code;
  192. }
  193. Error PluginScript::reload(bool p_keep_state) {
  194. ERR_FAIL_COND_V(!_language, ERR_UNCONFIGURED);
  195. _language->lock();
  196. ERR_FAIL_COND_V(!p_keep_state && _instances.size(), ERR_ALREADY_IN_USE);
  197. _language->unlock();
  198. _valid = false;
  199. String basedir = _path;
  200. if (basedir == "")
  201. basedir = get_path();
  202. if (basedir != "")
  203. basedir = basedir.get_base_dir();
  204. if (_data) {
  205. _desc->finish(_data);
  206. }
  207. Error err;
  208. godot_pluginscript_script_manifest manifest = _desc->init(
  209. _language->_data,
  210. (godot_string *)&_path,
  211. (godot_string *)&_source,
  212. (godot_error *)&err);
  213. // Manifest's attributes must be explicitly freed
  214. #define FREE_SCRIPT_MANIFEST(manifest) \
  215. { \
  216. godot_string_name_destroy(&manifest.name); \
  217. godot_string_name_destroy(&manifest.base); \
  218. godot_dictionary_destroy(&manifest.member_lines); \
  219. godot_array_destroy(&manifest.methods); \
  220. godot_array_destroy(&manifest.signals); \
  221. godot_array_destroy(&manifest.properties); \
  222. }
  223. if (err) {
  224. FREE_SCRIPT_MANIFEST(manifest);
  225. // TODO: GDscript uses `ScriptDebugger` here to jump into the parsing error
  226. return err;
  227. }
  228. // Script's parent is passed as base_name which can make reference to a
  229. // ClassDB name (i.e. `Node2D`) or a resource path (i.e. `res://foo/bar.gd`)
  230. StringName *base_name = (StringName *)&manifest.base;
  231. if (*base_name) {
  232. if (ClassDB::class_exists(*base_name)) {
  233. _native_parent = *base_name;
  234. } else {
  235. Ref<Script> res = ResourceLoader::load(*base_name);
  236. if (res.is_valid()) {
  237. _ref_base_parent = res;
  238. } else {
  239. String name = *(StringName *)&manifest.name;
  240. FREE_SCRIPT_MANIFEST(manifest);
  241. ERR_FAIL_V_MSG(ERR_PARSE_ERROR, _path + ": Script '" + name + "' has an invalid parent '" + *base_name + "'.");
  242. }
  243. }
  244. }
  245. _valid = true;
  246. // Use the manifest to configure this script object
  247. _data = manifest.data;
  248. _name = *(StringName *)&manifest.name;
  249. _tool = manifest.is_tool;
  250. Dictionary *members = (Dictionary *)&manifest.member_lines;
  251. for (const Variant *key = members->next(); key != NULL; key = members->next(key)) {
  252. _member_lines[*key] = (*members)[*key];
  253. }
  254. Array *methods = (Array *)&manifest.methods;
  255. _rpc_methods.clear();
  256. _rpc_variables.clear();
  257. if (_ref_base_parent.is_valid()) {
  258. _rpc_methods = _ref_base_parent->get_rpc_methods();
  259. _rpc_variables = _ref_base_parent->get_rset_properties();
  260. }
  261. for (int i = 0; i < methods->size(); ++i) {
  262. Dictionary v = (*methods)[i];
  263. MethodInfo mi = MethodInfo::from_dict(v);
  264. _methods_info[mi.name] = mi;
  265. // rpc_mode is passed as an optional field and is not part of MethodInfo
  266. Variant var = v["rpc_mode"];
  267. if (var != Variant()) {
  268. ScriptNetData nd;
  269. nd.name = mi.name;
  270. nd.mode = MultiplayerAPI::RPCMode(int(var));
  271. if (_rpc_methods.find(nd) == -1) {
  272. _rpc_methods.push_back(nd);
  273. }
  274. }
  275. }
  276. // Sort so we are 100% that they are always the same.
  277. _rpc_methods.sort_custom<SortNetData>();
  278. Array *signals = (Array *)&manifest.signals;
  279. for (int i = 0; i < signals->size(); ++i) {
  280. Variant v = (*signals)[i];
  281. MethodInfo mi = MethodInfo::from_dict(v);
  282. _signals_info[mi.name] = mi;
  283. }
  284. Array *properties = (Array *)&manifest.properties;
  285. for (int i = 0; i < properties->size(); ++i) {
  286. Dictionary v = (*properties)[i];
  287. PropertyInfo pi = PropertyInfo::from_dict(v);
  288. _properties_info[pi.name] = pi;
  289. _properties_default_values[pi.name] = v["default_value"];
  290. // rset_mode is passed as an optional field and is not part of PropertyInfo
  291. Variant var = v["rset_mode"];
  292. if (var != Variant()) {
  293. ScriptNetData nd;
  294. nd.name = pi.name;
  295. nd.mode = MultiplayerAPI::RPCMode(int(var));
  296. if (_rpc_variables.find(nd) == -1) {
  297. _rpc_variables.push_back(nd);
  298. }
  299. }
  300. }
  301. // Sort so we are 100% that they are always the same.
  302. _rpc_variables.sort_custom<SortNetData>();
  303. #ifdef TOOLS_ENABLED
  304. /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
  305. _update_placeholder(E->get());
  306. }*/
  307. #endif
  308. FREE_SCRIPT_MANIFEST(manifest);
  309. return OK;
  310. #undef FREE_SCRIPT_MANIFEST
  311. }
  312. void PluginScript::get_script_method_list(List<MethodInfo> *r_methods) const {
  313. ASSERT_SCRIPT_VALID();
  314. for (Map<StringName, MethodInfo>::Element *e = _methods_info.front(); e != NULL; e = e->next()) {
  315. r_methods->push_back(e->get());
  316. }
  317. }
  318. void PluginScript::get_script_property_list(List<PropertyInfo> *r_properties) const {
  319. ASSERT_SCRIPT_VALID();
  320. for (Map<StringName, PropertyInfo>::Element *e = _properties_info.front(); e != NULL; e = e->next()) {
  321. r_properties->push_back(e->get());
  322. }
  323. }
  324. bool PluginScript::has_method(const StringName &p_method) const {
  325. ASSERT_SCRIPT_VALID_V(false);
  326. return _methods_info.has(p_method);
  327. }
  328. MethodInfo PluginScript::get_method_info(const StringName &p_method) const {
  329. ASSERT_SCRIPT_VALID_V(MethodInfo());
  330. const Map<StringName, MethodInfo>::Element *e = _methods_info.find(p_method);
  331. if (e != NULL) {
  332. return e->get();
  333. } else {
  334. return MethodInfo();
  335. }
  336. }
  337. bool PluginScript::has_property(const StringName &p_method) const {
  338. ASSERT_SCRIPT_VALID_V(false);
  339. return _properties_info.has(p_method);
  340. }
  341. PropertyInfo PluginScript::get_property_info(const StringName &p_property) const {
  342. ASSERT_SCRIPT_VALID_V(PropertyInfo());
  343. const Map<StringName, PropertyInfo>::Element *e = _properties_info.find(p_property);
  344. if (e != NULL) {
  345. return e->get();
  346. } else {
  347. return PropertyInfo();
  348. }
  349. }
  350. bool PluginScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  351. ASSERT_SCRIPT_VALID_V(false);
  352. #ifdef TOOLS_ENABLED
  353. const Map<StringName, Variant>::Element *e = _properties_default_values.find(p_property);
  354. if (e != NULL) {
  355. r_value = e->get();
  356. return true;
  357. } else {
  358. return false;
  359. }
  360. #endif
  361. return false;
  362. }
  363. ScriptLanguage *PluginScript::get_language() const {
  364. return _language;
  365. }
  366. Error PluginScript::load_source_code(const String &p_path) {
  367. Vector<uint8_t> sourcef;
  368. Error err;
  369. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  370. ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + p_path + "'.");
  371. int len = f->get_len();
  372. sourcef.resize(len + 1);
  373. uint8_t *w = sourcef.ptrw();
  374. int r = f->get_buffer(w, len);
  375. f->close();
  376. memdelete(f);
  377. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  378. w[len] = 0;
  379. String s;
  380. if (s.parse_utf8((const char *)w)) {
  381. ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.");
  382. }
  383. _source = s;
  384. #ifdef TOOLS_ENABLED
  385. // source_changed_cache=true;
  386. #endif
  387. _path = p_path;
  388. return OK;
  389. }
  390. bool PluginScript::has_script_signal(const StringName &p_signal) const {
  391. ASSERT_SCRIPT_VALID_V(false);
  392. return _signals_info.has(p_signal);
  393. }
  394. void PluginScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  395. ASSERT_SCRIPT_VALID();
  396. for (Map<StringName, MethodInfo>::Element *e = _signals_info.front(); e != NULL; e = e->next()) {
  397. r_signals->push_back(e->get());
  398. }
  399. }
  400. int PluginScript::get_member_line(const StringName &p_member) const {
  401. #ifdef TOOLS_ENABLED
  402. if (_member_lines.has(p_member))
  403. return _member_lines[p_member];
  404. else
  405. #endif
  406. return -1;
  407. }
  408. Vector<ScriptNetData> PluginScript::get_rpc_methods() const {
  409. return _rpc_methods;
  410. }
  411. uint16_t PluginScript::get_rpc_method_id(const StringName &p_method) const {
  412. ASSERT_SCRIPT_VALID_V(UINT16_MAX);
  413. for (int i = 0; i < _rpc_methods.size(); i++) {
  414. if (_rpc_methods[i].name == p_method) {
  415. return i;
  416. }
  417. }
  418. return UINT16_MAX;
  419. }
  420. StringName PluginScript::get_rpc_method(const uint16_t p_rpc_method_id) const {
  421. ASSERT_SCRIPT_VALID_V(StringName());
  422. if (p_rpc_method_id >= _rpc_methods.size())
  423. return StringName();
  424. return _rpc_methods[p_rpc_method_id].name;
  425. }
  426. MultiplayerAPI::RPCMode PluginScript::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const {
  427. ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED);
  428. if (p_rpc_method_id >= _rpc_methods.size())
  429. return MultiplayerAPI::RPC_MODE_DISABLED;
  430. return _rpc_methods[p_rpc_method_id].mode;
  431. }
  432. MultiplayerAPI::RPCMode PluginScript::get_rpc_mode(const StringName &p_method) const {
  433. ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED);
  434. return get_rpc_mode_by_id(get_rpc_method_id(p_method));
  435. }
  436. Vector<ScriptNetData> PluginScript::get_rset_properties() const {
  437. return _rpc_variables;
  438. }
  439. uint16_t PluginScript::get_rset_property_id(const StringName &p_property) const {
  440. ASSERT_SCRIPT_VALID_V(UINT16_MAX);
  441. for (int i = 0; i < _rpc_variables.size(); i++) {
  442. if (_rpc_variables[i].name == p_property) {
  443. return i;
  444. }
  445. }
  446. return UINT16_MAX;
  447. }
  448. StringName PluginScript::get_rset_property(const uint16_t p_rset_property_id) const {
  449. ASSERT_SCRIPT_VALID_V(StringName());
  450. if (p_rset_property_id >= _rpc_variables.size())
  451. return StringName();
  452. return _rpc_variables[p_rset_property_id].name;
  453. }
  454. MultiplayerAPI::RPCMode PluginScript::get_rset_mode_by_id(const uint16_t p_rset_property_id) const {
  455. ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED);
  456. if (p_rset_property_id >= _rpc_variables.size())
  457. return MultiplayerAPI::RPC_MODE_DISABLED;
  458. return _rpc_variables[p_rset_property_id].mode;
  459. }
  460. MultiplayerAPI::RPCMode PluginScript::get_rset_mode(const StringName &p_variable) const {
  461. ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED);
  462. return get_rset_mode_by_id(get_rset_property_id(p_variable));
  463. }
  464. PluginScript::PluginScript() :
  465. _data(NULL),
  466. _desc(NULL),
  467. _language(NULL),
  468. _tool(false),
  469. _valid(false),
  470. _script_list(this) {
  471. }
  472. void PluginScript::init(PluginScriptLanguage *language) {
  473. _desc = &language->_desc.script_desc;
  474. _language = language;
  475. #ifdef DEBUG_ENABLED
  476. _language->lock();
  477. _language->_script_list.add(&_script_list);
  478. _language->unlock();
  479. #endif
  480. }
  481. PluginScript::~PluginScript() {
  482. if (_desc && _data) {
  483. _desc->finish(_data);
  484. }
  485. #ifdef DEBUG_ENABLED
  486. if (_language) {
  487. _language->lock();
  488. _language->_script_list.remove(&_script_list);
  489. _language->unlock();
  490. }
  491. #endif
  492. }