object.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084
  1. /**************************************************************************/
  2. /* object.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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. #include "object.h"
  31. #include "core/core_string_names.h"
  32. #include "core/io/resource.h"
  33. #include "core/object/class_db.h"
  34. #include "core/object/message_queue.h"
  35. #include "core/object/script_language.h"
  36. #include "core/os/os.h"
  37. #include "core/string/print_string.h"
  38. #include "core/string/translation.h"
  39. #include "core/templates/local_vector.h"
  40. #include "core/variant/typed_array.h"
  41. #ifdef DEBUG_ENABLED
  42. struct _ObjectDebugLock {
  43. Object *obj;
  44. _ObjectDebugLock(Object *p_obj) {
  45. obj = p_obj;
  46. obj->_lock_index.ref();
  47. }
  48. ~_ObjectDebugLock() {
  49. obj->_lock_index.unref();
  50. }
  51. };
  52. #define OBJ_DEBUG_LOCK _ObjectDebugLock _debug_lock(this);
  53. #else
  54. #define OBJ_DEBUG_LOCK
  55. #endif
  56. PropertyInfo::operator Dictionary() const {
  57. Dictionary d;
  58. d["name"] = name;
  59. d["class_name"] = class_name;
  60. d["type"] = type;
  61. d["hint"] = hint;
  62. d["hint_string"] = hint_string;
  63. d["usage"] = usage;
  64. return d;
  65. }
  66. PropertyInfo PropertyInfo::from_dict(const Dictionary &p_dict) {
  67. PropertyInfo pi;
  68. if (p_dict.has("type")) {
  69. pi.type = Variant::Type(int(p_dict["type"]));
  70. }
  71. if (p_dict.has("name")) {
  72. pi.name = p_dict["name"];
  73. }
  74. if (p_dict.has("class_name")) {
  75. pi.class_name = p_dict["class_name"];
  76. }
  77. if (p_dict.has("hint")) {
  78. pi.hint = PropertyHint(int(p_dict["hint"]));
  79. }
  80. if (p_dict.has("hint_string")) {
  81. pi.hint_string = p_dict["hint_string"];
  82. }
  83. if (p_dict.has("usage")) {
  84. pi.usage = p_dict["usage"];
  85. }
  86. return pi;
  87. }
  88. TypedArray<Dictionary> convert_property_list(const List<PropertyInfo> *p_list) {
  89. TypedArray<Dictionary> va;
  90. for (const List<PropertyInfo>::Element *E = p_list->front(); E; E = E->next()) {
  91. va.push_back(Dictionary(E->get()));
  92. }
  93. return va;
  94. }
  95. MethodInfo::operator Dictionary() const {
  96. Dictionary d;
  97. d["name"] = name;
  98. d["args"] = convert_property_list(&arguments);
  99. Array da;
  100. for (int i = 0; i < default_arguments.size(); i++) {
  101. da.push_back(default_arguments[i]);
  102. }
  103. d["default_args"] = da;
  104. d["flags"] = flags;
  105. d["id"] = id;
  106. Dictionary r = return_val;
  107. d["return"] = r;
  108. return d;
  109. }
  110. MethodInfo MethodInfo::from_dict(const Dictionary &p_dict) {
  111. MethodInfo mi;
  112. if (p_dict.has("name")) {
  113. mi.name = p_dict["name"];
  114. }
  115. Array args;
  116. if (p_dict.has("args")) {
  117. args = p_dict["args"];
  118. }
  119. for (int i = 0; i < args.size(); i++) {
  120. Dictionary d = args[i];
  121. mi.arguments.push_back(PropertyInfo::from_dict(d));
  122. }
  123. Array defargs;
  124. if (p_dict.has("default_args")) {
  125. defargs = p_dict["default_args"];
  126. }
  127. for (int i = 0; i < defargs.size(); i++) {
  128. mi.default_arguments.push_back(defargs[i]);
  129. }
  130. if (p_dict.has("return")) {
  131. mi.return_val = PropertyInfo::from_dict(p_dict["return"]);
  132. }
  133. if (p_dict.has("flags")) {
  134. mi.flags = p_dict["flags"];
  135. }
  136. return mi;
  137. }
  138. Object::Connection::operator Variant() const {
  139. Dictionary d;
  140. d["signal"] = signal;
  141. d["callable"] = callable;
  142. d["flags"] = flags;
  143. return d;
  144. }
  145. bool Object::Connection::operator<(const Connection &p_conn) const {
  146. if (signal == p_conn.signal) {
  147. return callable < p_conn.callable;
  148. } else {
  149. return signal < p_conn.signal;
  150. }
  151. }
  152. Object::Connection::Connection(const Variant &p_variant) {
  153. Dictionary d = p_variant;
  154. if (d.has("signal")) {
  155. signal = d["signal"];
  156. }
  157. if (d.has("callable")) {
  158. callable = d["callable"];
  159. }
  160. if (d.has("flags")) {
  161. flags = d["flags"];
  162. }
  163. }
  164. bool Object::_predelete() {
  165. _predelete_ok = 1;
  166. notification(NOTIFICATION_PREDELETE, true);
  167. if (_predelete_ok) {
  168. _class_name_ptr = nullptr; // Must restore, so constructors/destructors have proper class name access at each stage.
  169. }
  170. return _predelete_ok;
  171. }
  172. void Object::cancel_free() {
  173. _predelete_ok = false;
  174. }
  175. void Object::_postinitialize() {
  176. _class_name_ptr = _get_class_namev(); // Set the direct pointer, which is much faster to obtain, but can only happen after postinitialize.
  177. _initialize_classv();
  178. _class_name_ptr = nullptr; // May have been called from a constructor.
  179. notification(NOTIFICATION_POSTINITIALIZE);
  180. }
  181. void Object::get_valid_parents_static(List<String> *p_parents) {
  182. }
  183. void Object::_get_valid_parents_static(List<String> *p_parents) {
  184. }
  185. void Object::set(const StringName &p_name, const Variant &p_value, bool *r_valid) {
  186. #ifdef TOOLS_ENABLED
  187. _edited = true;
  188. #endif
  189. if (script_instance) {
  190. if (script_instance->set(p_name, p_value)) {
  191. if (r_valid) {
  192. *r_valid = true;
  193. }
  194. return;
  195. }
  196. }
  197. if (_extension && _extension->set) {
  198. // C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
  199. #if defined(__GNUC__) && !defined(__clang__)
  200. #pragma GCC diagnostic push
  201. #pragma GCC diagnostic ignored "-Wignored-qualifiers"
  202. #endif
  203. if (_extension->set(_extension_instance, (const GDExtensionStringNamePtr)&p_name, (const GDExtensionVariantPtr)&p_value)) {
  204. if (r_valid) {
  205. *r_valid = true;
  206. }
  207. return;
  208. }
  209. #if defined(__GNUC__) && !defined(__clang__)
  210. #pragma GCC diagnostic pop
  211. #endif
  212. }
  213. // Try built-in setter.
  214. {
  215. if (ClassDB::set_property(this, p_name, p_value, r_valid)) {
  216. return;
  217. }
  218. }
  219. if (p_name == CoreStringNames::get_singleton()->_script) {
  220. set_script(p_value);
  221. if (r_valid) {
  222. *r_valid = true;
  223. }
  224. return;
  225. } else {
  226. Variant **V = metadata_properties.getptr(p_name);
  227. if (V) {
  228. **V = p_value;
  229. if (r_valid) {
  230. *r_valid = true;
  231. }
  232. return;
  233. } else if (p_name.operator String().begins_with("metadata/")) {
  234. // Must exist, otherwise duplicate() will not work.
  235. set_meta(p_name.operator String().replace_first("metadata/", ""), p_value);
  236. if (r_valid) {
  237. *r_valid = true;
  238. }
  239. return;
  240. }
  241. }
  242. #ifdef TOOLS_ENABLED
  243. if (script_instance) {
  244. bool valid;
  245. script_instance->property_set_fallback(p_name, p_value, &valid);
  246. if (valid) {
  247. if (r_valid) {
  248. *r_valid = true;
  249. }
  250. return;
  251. }
  252. }
  253. #endif
  254. // Something inside the object... :|
  255. bool success = _setv(p_name, p_value);
  256. if (success) {
  257. if (r_valid) {
  258. *r_valid = true;
  259. }
  260. return;
  261. }
  262. if (r_valid) {
  263. *r_valid = false;
  264. }
  265. }
  266. Variant Object::get(const StringName &p_name, bool *r_valid) const {
  267. Variant ret;
  268. if (script_instance) {
  269. if (script_instance->get(p_name, ret)) {
  270. if (r_valid) {
  271. *r_valid = true;
  272. }
  273. return ret;
  274. }
  275. }
  276. if (_extension && _extension->get) {
  277. // C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
  278. #if defined(__GNUC__) && !defined(__clang__)
  279. #pragma GCC diagnostic push
  280. #pragma GCC diagnostic ignored "-Wignored-qualifiers"
  281. #endif
  282. if (_extension->get(_extension_instance, (const GDExtensionStringNamePtr)&p_name, (GDExtensionVariantPtr)&ret)) {
  283. if (r_valid) {
  284. *r_valid = true;
  285. }
  286. return ret;
  287. }
  288. #if defined(__GNUC__) && !defined(__clang__)
  289. #pragma GCC diagnostic pop
  290. #endif
  291. }
  292. // Try built-in getter.
  293. {
  294. if (ClassDB::get_property(const_cast<Object *>(this), p_name, ret)) {
  295. if (r_valid) {
  296. *r_valid = true;
  297. }
  298. return ret;
  299. }
  300. }
  301. if (p_name == CoreStringNames::get_singleton()->_script) {
  302. ret = get_script();
  303. if (r_valid) {
  304. *r_valid = true;
  305. }
  306. return ret;
  307. }
  308. const Variant *const *V = metadata_properties.getptr(p_name);
  309. if (V) {
  310. ret = **V;
  311. if (r_valid) {
  312. *r_valid = true;
  313. }
  314. return ret;
  315. } else {
  316. #ifdef TOOLS_ENABLED
  317. if (script_instance) {
  318. bool valid;
  319. ret = script_instance->property_get_fallback(p_name, &valid);
  320. if (valid) {
  321. if (r_valid) {
  322. *r_valid = true;
  323. }
  324. return ret;
  325. }
  326. }
  327. #endif
  328. // Something inside the object... :|
  329. bool success = _getv(p_name, ret);
  330. if (success) {
  331. if (r_valid) {
  332. *r_valid = true;
  333. }
  334. return ret;
  335. }
  336. if (r_valid) {
  337. *r_valid = false;
  338. }
  339. return Variant();
  340. }
  341. }
  342. void Object::set_indexed(const Vector<StringName> &p_names, const Variant &p_value, bool *r_valid) {
  343. if (p_names.is_empty()) {
  344. if (r_valid) {
  345. *r_valid = false;
  346. }
  347. return;
  348. }
  349. if (p_names.size() == 1) {
  350. set(p_names[0], p_value, r_valid);
  351. return;
  352. }
  353. bool valid = false;
  354. if (!r_valid) {
  355. r_valid = &valid;
  356. }
  357. List<Variant> value_stack;
  358. value_stack.push_back(get(p_names[0], r_valid));
  359. if (!*r_valid) {
  360. value_stack.clear();
  361. return;
  362. }
  363. for (int i = 1; i < p_names.size() - 1; i++) {
  364. value_stack.push_back(value_stack.back()->get().get_named(p_names[i], valid));
  365. if (r_valid) {
  366. *r_valid = valid;
  367. }
  368. if (!valid) {
  369. value_stack.clear();
  370. return;
  371. }
  372. }
  373. value_stack.push_back(p_value); // p_names[p_names.size() - 1]
  374. for (int i = p_names.size() - 1; i > 0; i--) {
  375. value_stack.back()->prev()->get().set_named(p_names[i], value_stack.back()->get(), valid);
  376. value_stack.pop_back();
  377. if (r_valid) {
  378. *r_valid = valid;
  379. }
  380. if (!valid) {
  381. value_stack.clear();
  382. return;
  383. }
  384. }
  385. set(p_names[0], value_stack.back()->get(), r_valid);
  386. value_stack.pop_back();
  387. ERR_FAIL_COND(!value_stack.is_empty());
  388. }
  389. Variant Object::get_indexed(const Vector<StringName> &p_names, bool *r_valid) const {
  390. if (p_names.is_empty()) {
  391. if (r_valid) {
  392. *r_valid = false;
  393. }
  394. return Variant();
  395. }
  396. bool valid = false;
  397. Variant current_value = get(p_names[0], &valid);
  398. for (int i = 1; i < p_names.size(); i++) {
  399. current_value = current_value.get_named(p_names[i], valid);
  400. if (!valid) {
  401. break;
  402. }
  403. }
  404. if (r_valid) {
  405. *r_valid = valid;
  406. }
  407. return current_value;
  408. }
  409. void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) const {
  410. if (script_instance && p_reversed) {
  411. script_instance->get_property_list(p_list);
  412. }
  413. if (_extension) {
  414. const ObjectGDExtension *current_extension = _extension;
  415. while (current_extension) {
  416. p_list->push_back(PropertyInfo(Variant::NIL, current_extension->class_name, PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY));
  417. ClassDB::get_property_list(current_extension->class_name, p_list, true, this);
  418. if (current_extension->get_property_list) {
  419. uint32_t pcount;
  420. const GDExtensionPropertyInfo *pinfo = current_extension->get_property_list(_extension_instance, &pcount);
  421. for (uint32_t i = 0; i < pcount; i++) {
  422. p_list->push_back(PropertyInfo(pinfo[i]));
  423. }
  424. if (current_extension->free_property_list) {
  425. current_extension->free_property_list(_extension_instance, pinfo);
  426. }
  427. }
  428. current_extension = current_extension->parent;
  429. }
  430. }
  431. _get_property_listv(p_list, p_reversed);
  432. if (!is_class("Script")) { // can still be set, but this is for user-friendliness
  433. p_list->push_back(PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NEVER_DUPLICATE));
  434. }
  435. if (script_instance && !p_reversed) {
  436. script_instance->get_property_list(p_list);
  437. }
  438. for (const KeyValue<StringName, Variant> &K : metadata) {
  439. PropertyInfo pi = PropertyInfo(K.value.get_type(), "metadata/" + K.key.operator String());
  440. if (K.value.get_type() == Variant::OBJECT) {
  441. pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
  442. pi.hint_string = "Resource";
  443. }
  444. p_list->push_back(pi);
  445. }
  446. }
  447. void Object::validate_property(PropertyInfo &p_property) const {
  448. _validate_propertyv(p_property);
  449. }
  450. bool Object::property_can_revert(const StringName &p_name) const {
  451. if (script_instance) {
  452. if (script_instance->property_can_revert(p_name)) {
  453. return true;
  454. }
  455. }
  456. // C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
  457. #if defined(__GNUC__) && !defined(__clang__)
  458. #pragma GCC diagnostic push
  459. #pragma GCC diagnostic ignored "-Wignored-qualifiers"
  460. #endif
  461. if (_extension && _extension->property_can_revert) {
  462. if (_extension->property_can_revert(_extension_instance, (const GDExtensionStringNamePtr)&p_name)) {
  463. return true;
  464. }
  465. }
  466. #if defined(__GNUC__) && !defined(__clang__)
  467. #pragma GCC diagnostic pop
  468. #endif
  469. return _property_can_revertv(p_name);
  470. }
  471. Variant Object::property_get_revert(const StringName &p_name) const {
  472. Variant ret;
  473. if (script_instance) {
  474. if (script_instance->property_get_revert(p_name, ret)) {
  475. return ret;
  476. }
  477. }
  478. // C style pointer casts should never trigger a compiler warning because the risk is assumed by the user, so GCC should keep quiet about it.
  479. #if defined(__GNUC__) && !defined(__clang__)
  480. #pragma GCC diagnostic push
  481. #pragma GCC diagnostic ignored "-Wignored-qualifiers"
  482. #endif
  483. if (_extension && _extension->property_get_revert) {
  484. if (_extension->property_get_revert(_extension_instance, (const GDExtensionStringNamePtr)&p_name, (GDExtensionVariantPtr)&ret)) {
  485. return ret;
  486. }
  487. }
  488. #if defined(__GNUC__) && !defined(__clang__)
  489. #pragma GCC diagnostic pop
  490. #endif
  491. if (_property_get_revertv(p_name, ret)) {
  492. return ret;
  493. }
  494. return Variant();
  495. }
  496. void Object::get_method_list(List<MethodInfo> *p_list) const {
  497. ClassDB::get_method_list(get_class_name(), p_list);
  498. if (script_instance) {
  499. script_instance->get_method_list(p_list);
  500. }
  501. }
  502. Variant Object::_call_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  503. if (p_argcount < 1) {
  504. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  505. r_error.argument = 0;
  506. return Variant();
  507. }
  508. if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) {
  509. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  510. r_error.argument = 0;
  511. r_error.expected = Variant::STRING_NAME;
  512. return Variant();
  513. }
  514. StringName method = *p_args[0];
  515. return callp(method, &p_args[1], p_argcount - 1, r_error);
  516. }
  517. Variant Object::_call_deferred_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  518. if (p_argcount < 1) {
  519. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  520. r_error.argument = 0;
  521. return Variant();
  522. }
  523. if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) {
  524. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  525. r_error.argument = 0;
  526. r_error.expected = Variant::STRING_NAME;
  527. return Variant();
  528. }
  529. r_error.error = Callable::CallError::CALL_OK;
  530. StringName method = *p_args[0];
  531. MessageQueue::get_singleton()->push_callp(get_instance_id(), method, &p_args[1], p_argcount - 1, true);
  532. return Variant();
  533. }
  534. bool Object::has_method(const StringName &p_method) const {
  535. if (p_method == CoreStringNames::get_singleton()->_free) {
  536. return true;
  537. }
  538. if (script_instance && script_instance->has_method(p_method)) {
  539. return true;
  540. }
  541. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  542. return method != nullptr;
  543. }
  544. Variant Object::getvar(const Variant &p_key, bool *r_valid) const {
  545. if (r_valid) {
  546. *r_valid = false;
  547. }
  548. if (p_key.get_type() == Variant::STRING_NAME || p_key.get_type() == Variant::STRING) {
  549. return get(p_key, r_valid);
  550. }
  551. return Variant();
  552. }
  553. void Object::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) {
  554. if (r_valid) {
  555. *r_valid = false;
  556. }
  557. if (p_key.get_type() == Variant::STRING_NAME || p_key.get_type() == Variant::STRING) {
  558. return set(p_key, p_value, r_valid);
  559. }
  560. }
  561. Variant Object::callv(const StringName &p_method, const Array &p_args) {
  562. const Variant **argptrs = nullptr;
  563. if (p_args.size() > 0) {
  564. argptrs = (const Variant **)alloca(sizeof(Variant *) * p_args.size());
  565. for (int i = 0; i < p_args.size(); i++) {
  566. argptrs[i] = &p_args[i];
  567. }
  568. }
  569. Callable::CallError ce;
  570. Variant ret = callp(p_method, argptrs, p_args.size(), ce);
  571. if (ce.error != Callable::CallError::CALL_OK) {
  572. ERR_FAIL_V_MSG(Variant(), "Error calling method from 'callv': " + Variant::get_call_error_text(this, p_method, argptrs, p_args.size(), ce) + ".");
  573. }
  574. return ret;
  575. }
  576. Variant Object::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  577. r_error.error = Callable::CallError::CALL_OK;
  578. if (p_method == CoreStringNames::get_singleton()->_free) {
  579. //free must be here, before anything, always ready
  580. #ifdef DEBUG_ENABLED
  581. if (p_argcount != 0) {
  582. r_error.argument = 0;
  583. r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
  584. return Variant();
  585. }
  586. if (Object::cast_to<RefCounted>(this)) {
  587. r_error.argument = 0;
  588. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  589. ERR_FAIL_V_MSG(Variant(), "Can't 'free' a reference.");
  590. }
  591. if (_lock_index.get() > 1) {
  592. r_error.argument = 0;
  593. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  594. ERR_FAIL_V_MSG(Variant(), "Object is locked and can't be freed.");
  595. }
  596. #endif
  597. //must be here, must be before everything,
  598. memdelete(this);
  599. r_error.error = Callable::CallError::CALL_OK;
  600. return Variant();
  601. }
  602. Variant ret;
  603. OBJ_DEBUG_LOCK
  604. if (script_instance) {
  605. ret = script_instance->callp(p_method, p_args, p_argcount, r_error);
  606. //force jumptable
  607. switch (r_error.error) {
  608. case Callable::CallError::CALL_OK:
  609. return ret;
  610. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  611. break;
  612. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  613. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  614. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  615. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  616. return ret;
  617. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
  618. }
  619. }
  620. }
  621. //extension does not need this, because all methods are registered in MethodBind
  622. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  623. if (method) {
  624. ret = method->call(this, p_args, p_argcount, r_error);
  625. } else {
  626. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  627. }
  628. return ret;
  629. }
  630. Variant Object::call_const(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  631. r_error.error = Callable::CallError::CALL_OK;
  632. if (p_method == CoreStringNames::get_singleton()->_free) {
  633. // Free is not const, so fail.
  634. r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
  635. return Variant();
  636. }
  637. Variant ret;
  638. OBJ_DEBUG_LOCK
  639. if (script_instance) {
  640. ret = script_instance->call_const(p_method, p_args, p_argcount, r_error);
  641. //force jumptable
  642. switch (r_error.error) {
  643. case Callable::CallError::CALL_OK:
  644. return ret;
  645. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  646. break;
  647. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  648. break;
  649. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  650. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  651. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  652. return ret;
  653. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
  654. }
  655. }
  656. }
  657. //extension does not need this, because all methods are registered in MethodBind
  658. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  659. if (method) {
  660. if (!method->is_const()) {
  661. r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
  662. return ret;
  663. }
  664. ret = method->call(this, p_args, p_argcount, r_error);
  665. } else {
  666. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  667. }
  668. return ret;
  669. }
  670. void Object::notification(int p_notification, bool p_reversed) {
  671. _notificationv(p_notification, p_reversed);
  672. if (script_instance) {
  673. script_instance->notification(p_notification);
  674. }
  675. if (_extension && _extension->notification) {
  676. _extension->notification(_extension_instance, p_notification);
  677. }
  678. }
  679. String Object::to_string() {
  680. if (script_instance) {
  681. bool valid;
  682. String ret = script_instance->to_string(&valid);
  683. if (valid) {
  684. return ret;
  685. }
  686. }
  687. if (_extension && _extension->to_string) {
  688. String ret;
  689. GDExtensionBool is_valid;
  690. _extension->to_string(_extension_instance, &is_valid, &ret);
  691. return ret;
  692. }
  693. return "<" + get_class() + "#" + itos(get_instance_id()) + ">";
  694. }
  695. void Object::set_script_and_instance(const Variant &p_script, ScriptInstance *p_instance) {
  696. //this function is not meant to be used in any of these ways
  697. ERR_FAIL_COND(p_script.is_null());
  698. ERR_FAIL_COND(!p_instance);
  699. ERR_FAIL_COND(script_instance != nullptr || !script.is_null());
  700. script = p_script;
  701. script_instance = p_instance;
  702. }
  703. void Object::set_script(const Variant &p_script) {
  704. if (script == p_script) {
  705. return;
  706. }
  707. Ref<Script> s = p_script;
  708. ERR_FAIL_COND_MSG(s.is_null() && !p_script.is_null(), "Invalid parameter, it should be a reference to a valid script (or null).");
  709. script = p_script;
  710. if (script_instance) {
  711. memdelete(script_instance);
  712. script_instance = nullptr;
  713. }
  714. if (!s.is_null()) {
  715. if (s->can_instantiate()) {
  716. OBJ_DEBUG_LOCK
  717. script_instance = s->instance_create(this);
  718. } else if (Engine::get_singleton()->is_editor_hint()) {
  719. OBJ_DEBUG_LOCK
  720. script_instance = s->placeholder_instance_create(this);
  721. }
  722. }
  723. notify_property_list_changed(); //scripts may add variables, so refresh is desired
  724. emit_signal(CoreStringNames::get_singleton()->script_changed);
  725. }
  726. void Object::set_script_instance(ScriptInstance *p_instance) {
  727. if (script_instance == p_instance) {
  728. return;
  729. }
  730. if (script_instance) {
  731. memdelete(script_instance);
  732. }
  733. script_instance = p_instance;
  734. if (p_instance) {
  735. script = p_instance->get_script();
  736. } else {
  737. script = Variant();
  738. }
  739. }
  740. Variant Object::get_script() const {
  741. return script;
  742. }
  743. bool Object::has_meta(const StringName &p_name) const {
  744. return metadata.has(p_name);
  745. }
  746. void Object::set_meta(const StringName &p_name, const Variant &p_value) {
  747. if (p_value.get_type() == Variant::NIL) {
  748. if (metadata.has(p_name)) {
  749. metadata.erase(p_name);
  750. const String &sname = p_name;
  751. metadata_properties.erase("metadata/" + sname);
  752. if (!sname.begins_with("_")) {
  753. // Metadata starting with _ don't show up in the inspector, so no need to update.
  754. notify_property_list_changed();
  755. }
  756. }
  757. return;
  758. }
  759. HashMap<StringName, Variant>::Iterator E = metadata.find(p_name);
  760. if (E) {
  761. E->value = p_value;
  762. } else {
  763. ERR_FAIL_COND_MSG(!p_name.operator String().is_valid_identifier(), "Invalid metadata identifier: '" + p_name + "'.");
  764. Variant *V = &metadata.insert(p_name, p_value)->value;
  765. const String &sname = p_name;
  766. metadata_properties["metadata/" + sname] = V;
  767. if (!sname.begins_with("_")) {
  768. notify_property_list_changed();
  769. }
  770. }
  771. }
  772. Variant Object::get_meta(const StringName &p_name, const Variant &p_default) const {
  773. if (!metadata.has(p_name)) {
  774. if (p_default != Variant()) {
  775. return p_default;
  776. } else {
  777. ERR_FAIL_V_MSG(Variant(), "The object does not have any 'meta' values with the key '" + p_name + "'.");
  778. }
  779. }
  780. return metadata[p_name];
  781. }
  782. void Object::remove_meta(const StringName &p_name) {
  783. set_meta(p_name, Variant());
  784. }
  785. TypedArray<Dictionary> Object::_get_property_list_bind() const {
  786. List<PropertyInfo> lpi;
  787. get_property_list(&lpi);
  788. return convert_property_list(&lpi);
  789. }
  790. TypedArray<Dictionary> Object::_get_method_list_bind() const {
  791. List<MethodInfo> ml;
  792. get_method_list(&ml);
  793. TypedArray<Dictionary> ret;
  794. for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) {
  795. Dictionary d = E->get();
  796. //va.push_back(d);
  797. ret.push_back(d);
  798. }
  799. return ret;
  800. }
  801. TypedArray<StringName> Object::_get_meta_list_bind() const {
  802. TypedArray<StringName> _metaret;
  803. for (const KeyValue<StringName, Variant> &K : metadata) {
  804. _metaret.push_back(K.key);
  805. }
  806. return _metaret;
  807. }
  808. void Object::get_meta_list(List<StringName> *p_list) const {
  809. for (const KeyValue<StringName, Variant> &K : metadata) {
  810. p_list->push_back(K.key);
  811. }
  812. }
  813. void Object::add_user_signal(const MethodInfo &p_signal) {
  814. ERR_FAIL_COND_MSG(p_signal.name.is_empty(), "Signal name cannot be empty.");
  815. ERR_FAIL_COND_MSG(ClassDB::has_signal(get_class_name(), p_signal.name), "User signal's name conflicts with a built-in signal of '" + get_class_name() + "'.");
  816. ERR_FAIL_COND_MSG(signal_map.has(p_signal.name), "Trying to add already existing signal '" + p_signal.name + "'.");
  817. SignalData s;
  818. s.user = p_signal;
  819. signal_map[p_signal.name] = s;
  820. }
  821. bool Object::_has_user_signal(const StringName &p_name) const {
  822. if (!signal_map.has(p_name)) {
  823. return false;
  824. }
  825. return signal_map[p_name].user.name.length() > 0;
  826. }
  827. struct _ObjectSignalDisconnectData {
  828. StringName signal;
  829. Callable callable;
  830. };
  831. Error Object::_emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  832. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  833. ERR_FAIL_COND_V(p_argcount < 1, Error::ERR_INVALID_PARAMETER);
  834. if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) {
  835. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  836. r_error.argument = 0;
  837. r_error.expected = Variant::STRING_NAME;
  838. ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING, Error::ERR_INVALID_PARAMETER);
  839. }
  840. r_error.error = Callable::CallError::CALL_OK;
  841. StringName signal = *p_args[0];
  842. const Variant **args = nullptr;
  843. int argc = p_argcount - 1;
  844. if (argc) {
  845. args = &p_args[1];
  846. }
  847. return emit_signalp(signal, args, argc);
  848. }
  849. Error Object::emit_signalp(const StringName &p_name, const Variant **p_args, int p_argcount) {
  850. if (_block_signals) {
  851. return ERR_CANT_ACQUIRE_RESOURCE; //no emit, signals blocked
  852. }
  853. SignalData *s = signal_map.getptr(p_name);
  854. if (!s) {
  855. #ifdef DEBUG_ENABLED
  856. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name);
  857. //check in script
  858. ERR_FAIL_COND_V_MSG(!signal_is_valid && !script.is_null() && !Ref<Script>(script)->has_script_signal(p_name), ERR_UNAVAILABLE, "Can't emit non-existing signal " + String("\"") + p_name + "\".");
  859. #endif
  860. //not connected? just return
  861. return ERR_UNAVAILABLE;
  862. }
  863. // If this is a ref-counted object, prevent it from being destroyed during signal emission,
  864. // which is needed in certain edge cases; e.g., https://github.com/godotengine/godot/issues/73889.
  865. Ref<RefCounted> rc = Ref<RefCounted>(Object::cast_to<RefCounted>(this));
  866. List<_ObjectSignalDisconnectData> disconnect_data;
  867. // Ensure that disconnecting the signal or even deleting the object
  868. // will not affect the signal calling.
  869. LocalVector<Connection> slot_conns;
  870. slot_conns.resize(s->slot_map.size());
  871. {
  872. uint32_t idx = 0;
  873. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  874. slot_conns[idx++] = slot_kv.value.conn;
  875. }
  876. DEV_ASSERT(idx == s->slot_map.size());
  877. }
  878. OBJ_DEBUG_LOCK
  879. Error err = OK;
  880. for (const Connection &c : slot_conns) {
  881. Object *target = c.callable.get_object();
  882. if (!target) {
  883. // Target might have been deleted during signal callback, this is expected and OK.
  884. continue;
  885. }
  886. const Variant **args = p_args;
  887. int argc = p_argcount;
  888. if (c.flags & CONNECT_DEFERRED) {
  889. MessageQueue::get_singleton()->push_callablep(c.callable, args, argc, true);
  890. } else {
  891. Callable::CallError ce;
  892. _emitting = true;
  893. Variant ret;
  894. c.callable.callp(args, argc, ret, ce);
  895. _emitting = false;
  896. if (ce.error != Callable::CallError::CALL_OK) {
  897. #ifdef DEBUG_ENABLED
  898. if (c.flags & CONNECT_PERSIST && Engine::get_singleton()->is_editor_hint() && (script.is_null() || !Ref<Script>(script)->is_tool())) {
  899. continue;
  900. }
  901. #endif
  902. if (ce.error == Callable::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists(target->get_class_name())) {
  903. //most likely object is not initialized yet, do not throw error.
  904. } else {
  905. ERR_PRINT("Error calling from signal '" + String(p_name) + "' to callable: " + Variant::get_callable_error_text(c.callable, args, argc, ce) + ".");
  906. err = ERR_METHOD_NOT_FOUND;
  907. }
  908. }
  909. }
  910. bool disconnect = c.flags & CONNECT_ONE_SHOT;
  911. #ifdef TOOLS_ENABLED
  912. if (disconnect && (c.flags & CONNECT_PERSIST) && Engine::get_singleton()->is_editor_hint()) {
  913. //this signal was connected from the editor, and is being edited. just don't disconnect for now
  914. disconnect = false;
  915. }
  916. #endif
  917. if (disconnect) {
  918. _ObjectSignalDisconnectData dd;
  919. dd.signal = p_name;
  920. dd.callable = c.callable;
  921. disconnect_data.push_back(dd);
  922. }
  923. }
  924. while (!disconnect_data.is_empty()) {
  925. const _ObjectSignalDisconnectData &dd = disconnect_data.front()->get();
  926. _disconnect(dd.signal, dd.callable);
  927. disconnect_data.pop_front();
  928. }
  929. return err;
  930. }
  931. void Object::_add_user_signal(const String &p_name, const Array &p_args) {
  932. // this version of add_user_signal is meant to be used from scripts or external apis
  933. // without access to ADD_SIGNAL in bind_methods
  934. // added events are per instance, as opposed to the other ones, which are global
  935. MethodInfo mi;
  936. mi.name = p_name;
  937. for (int i = 0; i < p_args.size(); i++) {
  938. Dictionary d = p_args[i];
  939. PropertyInfo param;
  940. if (d.has("name")) {
  941. param.name = d["name"];
  942. }
  943. if (d.has("type")) {
  944. param.type = (Variant::Type)(int)d["type"];
  945. }
  946. mi.arguments.push_back(param);
  947. }
  948. add_user_signal(mi);
  949. }
  950. TypedArray<Dictionary> Object::_get_signal_list() const {
  951. List<MethodInfo> signal_list;
  952. get_signal_list(&signal_list);
  953. TypedArray<Dictionary> ret;
  954. for (const MethodInfo &E : signal_list) {
  955. ret.push_back(Dictionary(E));
  956. }
  957. return ret;
  958. }
  959. TypedArray<Dictionary> Object::_get_signal_connection_list(const StringName &p_signal) const {
  960. List<Connection> conns;
  961. get_all_signal_connections(&conns);
  962. TypedArray<Dictionary> ret;
  963. for (const Connection &c : conns) {
  964. if (c.signal.get_name() == p_signal) {
  965. ret.push_back(c);
  966. }
  967. }
  968. return ret;
  969. }
  970. TypedArray<Dictionary> Object::_get_incoming_connections() const {
  971. TypedArray<Dictionary> ret;
  972. int connections_amount = connections.size();
  973. for (int idx_conn = 0; idx_conn < connections_amount; idx_conn++) {
  974. ret.push_back(connections[idx_conn]);
  975. }
  976. return ret;
  977. }
  978. bool Object::has_signal(const StringName &p_name) const {
  979. if (!script.is_null()) {
  980. Ref<Script> scr = script;
  981. if (scr.is_valid() && scr->has_script_signal(p_name)) {
  982. return true;
  983. }
  984. }
  985. if (ClassDB::has_signal(get_class_name(), p_name)) {
  986. return true;
  987. }
  988. if (_has_user_signal(p_name)) {
  989. return true;
  990. }
  991. return false;
  992. }
  993. void Object::get_signal_list(List<MethodInfo> *p_signals) const {
  994. if (!script.is_null()) {
  995. Ref<Script> scr = script;
  996. if (scr.is_valid()) {
  997. scr->get_script_signal_list(p_signals);
  998. }
  999. }
  1000. ClassDB::get_signal_list(get_class_name(), p_signals);
  1001. //find maybe usersignals?
  1002. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1003. if (!E.value.user.name.is_empty()) {
  1004. //user signal
  1005. p_signals->push_back(E.value.user);
  1006. }
  1007. }
  1008. }
  1009. void Object::get_all_signal_connections(List<Connection> *p_connections) const {
  1010. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1011. const SignalData *s = &E.value;
  1012. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1013. p_connections->push_back(slot_kv.value.conn);
  1014. }
  1015. }
  1016. }
  1017. void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const {
  1018. const SignalData *s = signal_map.getptr(p_signal);
  1019. if (!s) {
  1020. return; //nothing
  1021. }
  1022. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1023. p_connections->push_back(slot_kv.value.conn);
  1024. }
  1025. }
  1026. int Object::get_persistent_signal_connection_count() const {
  1027. int count = 0;
  1028. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1029. const SignalData *s = &E.value;
  1030. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1031. if (slot_kv.value.conn.flags & CONNECT_PERSIST) {
  1032. count += 1;
  1033. }
  1034. }
  1035. }
  1036. return count;
  1037. }
  1038. void Object::get_signals_connected_to_this(List<Connection> *p_connections) const {
  1039. for (const Connection &E : connections) {
  1040. p_connections->push_back(E);
  1041. }
  1042. }
  1043. Error Object::connect(const StringName &p_signal, const Callable &p_callable, uint32_t p_flags) {
  1044. ERR_FAIL_COND_V_MSG(p_callable.is_null(), ERR_INVALID_PARAMETER, "Cannot connect to '" + p_signal + "': the provided callable is null.");
  1045. Object *target_object = p_callable.get_object();
  1046. ERR_FAIL_COND_V_MSG(!target_object, ERR_INVALID_PARAMETER, "Cannot connect to '" + p_signal + "' to callable '" + p_callable + "': the callable object is null.");
  1047. SignalData *s = signal_map.getptr(p_signal);
  1048. if (!s) {
  1049. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1050. //check in script
  1051. if (!signal_is_valid && !script.is_null()) {
  1052. if (Ref<Script>(script)->has_script_signal(p_signal)) {
  1053. signal_is_valid = true;
  1054. }
  1055. #ifdef TOOLS_ENABLED
  1056. else {
  1057. //allow connecting signals anyway if script is invalid, see issue #17070
  1058. if (!Ref<Script>(script)->is_valid()) {
  1059. signal_is_valid = true;
  1060. }
  1061. }
  1062. #endif
  1063. }
  1064. ERR_FAIL_COND_V_MSG(!signal_is_valid, ERR_INVALID_PARAMETER, "In Object of type '" + String(get_class()) + "': Attempt to connect nonexistent signal '" + p_signal + "' to callable '" + p_callable + "'.");
  1065. signal_map[p_signal] = SignalData();
  1066. s = &signal_map[p_signal];
  1067. }
  1068. Callable target = p_callable;
  1069. //compare with the base callable, so binds can be ignored
  1070. if (s->slot_map.has(*target.get_base_comparator())) {
  1071. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1072. s->slot_map[*target.get_base_comparator()].reference_count++;
  1073. return OK;
  1074. } else {
  1075. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Signal '" + p_signal + "' is already connected to given callable '" + p_callable + "' in that object.");
  1076. }
  1077. }
  1078. SignalData::Slot slot;
  1079. Connection conn;
  1080. conn.callable = target;
  1081. conn.signal = ::Signal(this, p_signal);
  1082. conn.flags = p_flags;
  1083. slot.conn = conn;
  1084. slot.cE = target_object->connections.push_back(conn);
  1085. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1086. slot.reference_count = 1;
  1087. }
  1088. //use callable version as key, so binds can be ignored
  1089. s->slot_map[*target.get_base_comparator()] = slot;
  1090. return OK;
  1091. }
  1092. bool Object::is_connected(const StringName &p_signal, const Callable &p_callable) const {
  1093. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, "Cannot determine if connected to '" + p_signal + "': the provided callable is null.");
  1094. const SignalData *s = signal_map.getptr(p_signal);
  1095. if (!s) {
  1096. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1097. if (signal_is_valid) {
  1098. return false;
  1099. }
  1100. if (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal)) {
  1101. return false;
  1102. }
  1103. ERR_FAIL_V_MSG(false, "Nonexistent signal: " + p_signal + ".");
  1104. }
  1105. Callable target = p_callable;
  1106. return s->slot_map.has(*target.get_base_comparator());
  1107. }
  1108. void Object::disconnect(const StringName &p_signal, const Callable &p_callable) {
  1109. _disconnect(p_signal, p_callable);
  1110. }
  1111. bool Object::_disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force) {
  1112. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, "Cannot disconnect from '" + p_signal + "': the provided callable is null.");
  1113. Object *target_object = p_callable.get_object();
  1114. ERR_FAIL_COND_V_MSG(!target_object, false, "Cannot disconnect '" + p_signal + "' from callable '" + p_callable + "': the callable object is null.");
  1115. SignalData *s = signal_map.getptr(p_signal);
  1116. if (!s) {
  1117. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal) ||
  1118. (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal));
  1119. ERR_FAIL_COND_V_MSG(signal_is_valid, false, "Attempt to disconnect a nonexistent connection from '" + to_string() + "'. Signal: '" + p_signal + "', callable: '" + p_callable + "'.");
  1120. }
  1121. ERR_FAIL_COND_V_MSG(!s, false, vformat("Disconnecting nonexistent signal '%s' in %s.", p_signal, to_string()));
  1122. ERR_FAIL_COND_V_MSG(!s->slot_map.has(*p_callable.get_base_comparator()), false, "Attempt to disconnect a nonexistent connection from '" + to_string() + "'. Signal: '" + p_signal + "', callable: '" + p_callable + "'.");
  1123. SignalData::Slot *slot = &s->slot_map[*p_callable.get_base_comparator()];
  1124. if (!p_force) {
  1125. slot->reference_count--; // by default is zero, if it was not referenced it will go below it
  1126. if (slot->reference_count > 0) {
  1127. return false;
  1128. }
  1129. }
  1130. target_object->connections.erase(slot->cE);
  1131. s->slot_map.erase(*p_callable.get_base_comparator());
  1132. if (s->slot_map.is_empty() && ClassDB::has_signal(get_class_name(), p_signal)) {
  1133. //not user signal, delete
  1134. signal_map.erase(p_signal);
  1135. }
  1136. return true;
  1137. }
  1138. void Object::_set_bind(const StringName &p_set, const Variant &p_value) {
  1139. set(p_set, p_value);
  1140. }
  1141. Variant Object::_get_bind(const StringName &p_name) const {
  1142. return get(p_name);
  1143. }
  1144. void Object::_set_indexed_bind(const NodePath &p_name, const Variant &p_value) {
  1145. set_indexed(p_name.get_as_property_path().get_subnames(), p_value);
  1146. }
  1147. Variant Object::_get_indexed_bind(const NodePath &p_name) const {
  1148. return get_indexed(p_name.get_as_property_path().get_subnames());
  1149. }
  1150. void Object::initialize_class() {
  1151. static bool initialized = false;
  1152. if (initialized) {
  1153. return;
  1154. }
  1155. ClassDB::_add_class<Object>();
  1156. _bind_methods();
  1157. initialized = true;
  1158. }
  1159. String Object::tr(const StringName &p_message, const StringName &p_context) const {
  1160. if (!_can_translate || !TranslationServer::get_singleton()) {
  1161. return p_message;
  1162. }
  1163. if (Engine::get_singleton()->is_editor_hint()) {
  1164. return TranslationServer::get_singleton()->tool_translate(p_message, p_context);
  1165. } else {
  1166. return TranslationServer::get_singleton()->translate(p_message, p_context);
  1167. }
  1168. }
  1169. String Object::tr_n(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  1170. if (!_can_translate || !TranslationServer::get_singleton()) {
  1171. // Return message based on English plural rule if translation is not possible.
  1172. if (p_n == 1) {
  1173. return p_message;
  1174. }
  1175. return p_message_plural;
  1176. }
  1177. if (Engine::get_singleton()->is_editor_hint()) {
  1178. return TranslationServer::get_singleton()->tool_translate_plural(p_message, p_message_plural, p_n, p_context);
  1179. } else {
  1180. return TranslationServer::get_singleton()->translate_plural(p_message, p_message_plural, p_n, p_context);
  1181. }
  1182. }
  1183. void Object::_clear_internal_resource_paths(const Variant &p_var) {
  1184. switch (p_var.get_type()) {
  1185. case Variant::OBJECT: {
  1186. Ref<Resource> r = p_var;
  1187. if (!r.is_valid()) {
  1188. return;
  1189. }
  1190. if (!r->is_built_in()) {
  1191. return; //not an internal resource
  1192. }
  1193. Object *object = p_var;
  1194. if (!object) {
  1195. return;
  1196. }
  1197. r->set_path("");
  1198. r->clear_internal_resource_paths();
  1199. } break;
  1200. case Variant::ARRAY: {
  1201. Array a = p_var;
  1202. for (int i = 0; i < a.size(); i++) {
  1203. _clear_internal_resource_paths(a[i]);
  1204. }
  1205. } break;
  1206. case Variant::DICTIONARY: {
  1207. Dictionary d = p_var;
  1208. List<Variant> keys;
  1209. d.get_key_list(&keys);
  1210. for (const Variant &E : keys) {
  1211. _clear_internal_resource_paths(E);
  1212. _clear_internal_resource_paths(d[E]);
  1213. }
  1214. } break;
  1215. default: {
  1216. }
  1217. }
  1218. }
  1219. #ifdef TOOLS_ENABLED
  1220. void Object::editor_set_section_unfold(const String &p_section, bool p_unfolded) {
  1221. set_edited(true);
  1222. if (p_unfolded) {
  1223. editor_section_folding.insert(p_section);
  1224. } else {
  1225. editor_section_folding.erase(p_section);
  1226. }
  1227. }
  1228. bool Object::editor_is_section_unfolded(const String &p_section) {
  1229. return editor_section_folding.has(p_section);
  1230. }
  1231. #endif
  1232. void Object::clear_internal_resource_paths() {
  1233. List<PropertyInfo> pinfo;
  1234. get_property_list(&pinfo);
  1235. for (const PropertyInfo &E : pinfo) {
  1236. _clear_internal_resource_paths(get(E.name));
  1237. }
  1238. }
  1239. void Object::notify_property_list_changed() {
  1240. emit_signal(CoreStringNames::get_singleton()->property_list_changed);
  1241. }
  1242. void Object::_bind_methods() {
  1243. ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class);
  1244. ClassDB::bind_method(D_METHOD("is_class", "class"), &Object::is_class);
  1245. ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind);
  1246. ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind);
  1247. ClassDB::bind_method(D_METHOD("set_indexed", "property_path", "value"), &Object::_set_indexed_bind);
  1248. ClassDB::bind_method(D_METHOD("get_indexed", "property_path"), &Object::_get_indexed_bind);
  1249. ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind);
  1250. ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind);
  1251. ClassDB::bind_method(D_METHOD("property_can_revert", "property"), &Object::property_can_revert);
  1252. ClassDB::bind_method(D_METHOD("property_get_revert", "property"), &Object::property_get_revert);
  1253. ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false));
  1254. ClassDB::bind_method(D_METHOD("to_string"), &Object::to_string);
  1255. ClassDB::bind_method(D_METHOD("get_instance_id"), &Object::get_instance_id);
  1256. ClassDB::bind_method(D_METHOD("set_script", "script"), &Object::set_script);
  1257. ClassDB::bind_method(D_METHOD("get_script"), &Object::get_script);
  1258. ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta);
  1259. ClassDB::bind_method(D_METHOD("remove_meta", "name"), &Object::remove_meta);
  1260. ClassDB::bind_method(D_METHOD("get_meta", "name", "default"), &Object::get_meta, DEFVAL(Variant()));
  1261. ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta);
  1262. ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind);
  1263. ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array()));
  1264. ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal);
  1265. {
  1266. MethodInfo mi;
  1267. mi.name = "emit_signal";
  1268. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "signal"));
  1269. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi, varray(), false);
  1270. }
  1271. {
  1272. MethodInfo mi;
  1273. mi.name = "call";
  1274. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1275. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call", &Object::_call_bind, mi);
  1276. }
  1277. {
  1278. MethodInfo mi;
  1279. mi.name = "call_deferred";
  1280. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1281. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi, varray(), false);
  1282. }
  1283. ClassDB::bind_method(D_METHOD("set_deferred", "property", "value"), &Object::set_deferred);
  1284. ClassDB::bind_method(D_METHOD("callv", "method", "arg_array"), &Object::callv);
  1285. ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method);
  1286. ClassDB::bind_method(D_METHOD("has_signal", "signal"), &Object::has_signal);
  1287. ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list);
  1288. ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list);
  1289. ClassDB::bind_method(D_METHOD("get_incoming_connections"), &Object::_get_incoming_connections);
  1290. ClassDB::bind_method(D_METHOD("connect", "signal", "callable", "flags"), &Object::connect, DEFVAL(0));
  1291. ClassDB::bind_method(D_METHOD("disconnect", "signal", "callable"), &Object::disconnect);
  1292. ClassDB::bind_method(D_METHOD("is_connected", "signal", "callable"), &Object::is_connected);
  1293. ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals);
  1294. ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals);
  1295. ClassDB::bind_method(D_METHOD("notify_property_list_changed"), &Object::notify_property_list_changed);
  1296. ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation);
  1297. ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages);
  1298. ClassDB::bind_method(D_METHOD("tr", "message", "context"), &Object::tr, DEFVAL(""));
  1299. ClassDB::bind_method(D_METHOD("tr_n", "message", "plural_message", "n", "context"), &Object::tr_n, DEFVAL(""));
  1300. ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion);
  1301. ClassDB::bind_method(D_METHOD("cancel_free"), &Object::cancel_free);
  1302. ClassDB::add_virtual_method("Object", MethodInfo("free"), false);
  1303. ADD_SIGNAL(MethodInfo("script_changed"));
  1304. ADD_SIGNAL(MethodInfo("property_list_changed"));
  1305. #define BIND_OBJ_CORE_METHOD(m_method) \
  1306. ::ClassDB::add_virtual_method(get_class_static(), m_method, true, Vector<String>(), true);
  1307. MethodInfo notification_mi("_notification", PropertyInfo(Variant::INT, "what"));
  1308. notification_mi.arguments_metadata.push_back(GodotTypeInfo::Metadata::METADATA_INT_IS_INT32);
  1309. BIND_OBJ_CORE_METHOD(notification_mi);
  1310. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_set", PropertyInfo(Variant::STRING_NAME, "property"), PropertyInfo(Variant::NIL, "value")));
  1311. #ifdef TOOLS_ENABLED
  1312. MethodInfo miget("_get", PropertyInfo(Variant::STRING_NAME, "property"));
  1313. miget.return_val.name = "Variant";
  1314. miget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1315. BIND_OBJ_CORE_METHOD(miget);
  1316. MethodInfo plget("_get_property_list");
  1317. plget.return_val.type = Variant::ARRAY;
  1318. plget.return_val.hint = PROPERTY_HINT_ARRAY_TYPE;
  1319. plget.return_val.hint_string = "Dictionary";
  1320. BIND_OBJ_CORE_METHOD(plget);
  1321. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_property_can_revert", PropertyInfo(Variant::STRING_NAME, "property")));
  1322. MethodInfo mipgr("_property_get_revert", PropertyInfo(Variant::STRING_NAME, "property"));
  1323. mipgr.return_val.name = "Variant";
  1324. mipgr.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1325. BIND_OBJ_CORE_METHOD(mipgr);
  1326. #endif
  1327. BIND_OBJ_CORE_METHOD(MethodInfo("_init"));
  1328. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::STRING, "_to_string"));
  1329. BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE);
  1330. BIND_CONSTANT(NOTIFICATION_PREDELETE);
  1331. BIND_ENUM_CONSTANT(CONNECT_DEFERRED);
  1332. BIND_ENUM_CONSTANT(CONNECT_PERSIST);
  1333. BIND_ENUM_CONSTANT(CONNECT_ONE_SHOT);
  1334. BIND_ENUM_CONSTANT(CONNECT_REFERENCE_COUNTED);
  1335. }
  1336. void Object::set_deferred(const StringName &p_property, const Variant &p_value) {
  1337. MessageQueue::get_singleton()->push_set(this, p_property, p_value);
  1338. }
  1339. void Object::set_block_signals(bool p_block) {
  1340. _block_signals = p_block;
  1341. }
  1342. bool Object::is_blocking_signals() const {
  1343. return _block_signals;
  1344. }
  1345. Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const {
  1346. bool valid;
  1347. Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid);
  1348. if (valid) {
  1349. if (r_valid) {
  1350. *r_valid = true;
  1351. }
  1352. return t;
  1353. }
  1354. if (get_script_instance()) {
  1355. return get_script_instance()->get_property_type(p_property, r_valid);
  1356. }
  1357. if (r_valid) {
  1358. *r_valid = false;
  1359. }
  1360. return Variant::NIL;
  1361. }
  1362. Variant::Type Object::get_static_property_type_indexed(const Vector<StringName> &p_path, bool *r_valid) const {
  1363. if (p_path.size() == 0) {
  1364. if (r_valid) {
  1365. *r_valid = false;
  1366. }
  1367. return Variant::NIL;
  1368. }
  1369. bool valid = false;
  1370. Variant::Type t = get_static_property_type(p_path[0], &valid);
  1371. if (!valid) {
  1372. if (r_valid) {
  1373. *r_valid = false;
  1374. }
  1375. return Variant::NIL;
  1376. }
  1377. Callable::CallError ce;
  1378. Variant check;
  1379. Variant::construct(t, check, nullptr, 0, ce);
  1380. for (int i = 1; i < p_path.size(); i++) {
  1381. if (check.get_type() == Variant::OBJECT || check.get_type() == Variant::DICTIONARY || check.get_type() == Variant::ARRAY) {
  1382. // We cannot be sure about the type of properties this type can have
  1383. if (r_valid) {
  1384. *r_valid = false;
  1385. }
  1386. return Variant::NIL;
  1387. }
  1388. check = check.get_named(p_path[i], valid);
  1389. if (!valid) {
  1390. if (r_valid) {
  1391. *r_valid = false;
  1392. }
  1393. return Variant::NIL;
  1394. }
  1395. }
  1396. if (r_valid) {
  1397. *r_valid = true;
  1398. }
  1399. return check.get_type();
  1400. }
  1401. bool Object::is_queued_for_deletion() const {
  1402. return _is_queued_for_deletion;
  1403. }
  1404. #ifdef TOOLS_ENABLED
  1405. void Object::set_edited(bool p_edited) {
  1406. _edited = p_edited;
  1407. _edited_version++;
  1408. }
  1409. bool Object::is_edited() const {
  1410. return _edited;
  1411. }
  1412. uint32_t Object::get_edited_version() const {
  1413. return _edited_version;
  1414. }
  1415. #endif
  1416. StringName Object::get_class_name_for_extension(const GDExtension *p_library) const {
  1417. // Only return the class name per the extension if it matches the given p_library.
  1418. if (_extension && _extension->library == p_library) {
  1419. return _extension->class_name;
  1420. }
  1421. // Extensions only have wrapper classes for classes exposed in ClassDB.
  1422. const StringName *class_name = _get_class_namev();
  1423. if (ClassDB::is_class_exposed(*class_name)) {
  1424. return *class_name;
  1425. }
  1426. // Find the nearest parent class that's exposed.
  1427. StringName parent_class = ClassDB::get_parent_class(*class_name);
  1428. while (parent_class != StringName()) {
  1429. if (ClassDB::is_class_exposed(parent_class)) {
  1430. return parent_class;
  1431. }
  1432. parent_class = ClassDB::get_parent_class(parent_class);
  1433. }
  1434. return SNAME("Object");
  1435. }
  1436. void Object::set_instance_binding(void *p_token, void *p_binding, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  1437. // This is only meant to be used on creation by the binder.
  1438. ERR_FAIL_COND(_instance_bindings != nullptr);
  1439. _instance_bindings = (InstanceBinding *)memalloc(sizeof(InstanceBinding));
  1440. _instance_bindings[0].binding = p_binding;
  1441. _instance_bindings[0].free_callback = p_callbacks->free_callback;
  1442. _instance_bindings[0].reference_callback = p_callbacks->reference_callback;
  1443. _instance_bindings[0].token = p_token;
  1444. _instance_binding_count = 1;
  1445. }
  1446. void *Object::get_instance_binding(void *p_token, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  1447. void *binding = nullptr;
  1448. _instance_binding_mutex.lock();
  1449. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1450. if (_instance_bindings[i].token == p_token) {
  1451. binding = _instance_bindings[i].binding;
  1452. break;
  1453. }
  1454. }
  1455. if (unlikely(!binding && p_callbacks)) {
  1456. uint32_t current_size = next_power_of_2(_instance_binding_count);
  1457. uint32_t new_size = next_power_of_2(_instance_binding_count + 1);
  1458. if (current_size == 0 || new_size > current_size) {
  1459. _instance_bindings = (InstanceBinding *)memrealloc(_instance_bindings, new_size * sizeof(InstanceBinding));
  1460. }
  1461. _instance_bindings[_instance_binding_count].free_callback = p_callbacks->free_callback;
  1462. _instance_bindings[_instance_binding_count].reference_callback = p_callbacks->reference_callback;
  1463. _instance_bindings[_instance_binding_count].token = p_token;
  1464. binding = p_callbacks->create_callback(p_token, this);
  1465. _instance_bindings[_instance_binding_count].binding = binding;
  1466. _instance_binding_count++;
  1467. }
  1468. _instance_binding_mutex.unlock();
  1469. return binding;
  1470. }
  1471. bool Object::has_instance_binding(void *p_token) {
  1472. bool found = false;
  1473. _instance_binding_mutex.lock();
  1474. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1475. if (_instance_bindings[i].token == p_token) {
  1476. found = true;
  1477. break;
  1478. }
  1479. }
  1480. _instance_binding_mutex.unlock();
  1481. return found;
  1482. }
  1483. void Object::_construct_object(bool p_reference) {
  1484. type_is_reference = p_reference;
  1485. _instance_id = ObjectDB::add_instance(this);
  1486. #ifdef DEBUG_ENABLED
  1487. _lock_index.init(1);
  1488. #endif
  1489. }
  1490. Object::Object(bool p_reference) {
  1491. _construct_object(p_reference);
  1492. }
  1493. Object::Object() {
  1494. _construct_object(false);
  1495. }
  1496. void Object::detach_from_objectdb() {
  1497. if (_instance_id != ObjectID()) {
  1498. ObjectDB::remove_instance(this);
  1499. _instance_id = ObjectID();
  1500. }
  1501. }
  1502. Object::~Object() {
  1503. if (script_instance) {
  1504. memdelete(script_instance);
  1505. }
  1506. script_instance = nullptr;
  1507. if (_extension && _extension->free_instance) {
  1508. _extension->free_instance(_extension->class_userdata, _extension_instance);
  1509. _extension = nullptr;
  1510. _extension_instance = nullptr;
  1511. }
  1512. if (_emitting) {
  1513. //@todo this may need to actually reach the debugger prioritarily somehow because it may crash before
  1514. ERR_PRINT("Object " + to_string() + " was freed or unreferenced while a signal is being emitted from it. Try connecting to the signal using 'CONNECT_DEFERRED' flag, or use queue_free() to free the object (if this object is a Node) to avoid this error and potential crashes.");
  1515. }
  1516. // Drop all connections to the signals of this object.
  1517. while (signal_map.size()) {
  1518. // Avoid regular iteration so erasing is safe.
  1519. KeyValue<StringName, SignalData> &E = *signal_map.begin();
  1520. SignalData *s = &E.value;
  1521. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1522. Object *target = slot_kv.value.conn.callable.get_object();
  1523. if (likely(target)) {
  1524. target->connections.erase(slot_kv.value.cE);
  1525. }
  1526. }
  1527. signal_map.erase(E.key);
  1528. }
  1529. // Disconnect signals that connect to this object.
  1530. while (connections.size()) {
  1531. Connection c = connections.front()->get();
  1532. bool disconnected = c.signal.get_object()->_disconnect(c.signal.get_name(), c.callable, true);
  1533. if (unlikely(!disconnected)) {
  1534. // If the disconnect has failed, abandon the connection to avoid getting trapped in an infinite loop here.
  1535. connections.pop_front();
  1536. }
  1537. }
  1538. if (_instance_id != ObjectID()) {
  1539. ObjectDB::remove_instance(this);
  1540. _instance_id = ObjectID();
  1541. }
  1542. _predelete_ok = 2;
  1543. if (_instance_bindings != nullptr) {
  1544. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1545. if (_instance_bindings[i].free_callback) {
  1546. _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
  1547. }
  1548. }
  1549. memfree(_instance_bindings);
  1550. }
  1551. }
  1552. bool predelete_handler(Object *p_object) {
  1553. return p_object->_predelete();
  1554. }
  1555. void postinitialize_handler(Object *p_object) {
  1556. p_object->_postinitialize();
  1557. }
  1558. void ObjectDB::debug_objects(DebugFunc p_func) {
  1559. spin_lock.lock();
  1560. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  1561. if (object_slots[i].validator) {
  1562. p_func(object_slots[i].object);
  1563. count--;
  1564. }
  1565. }
  1566. spin_lock.unlock();
  1567. }
  1568. void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  1569. if (p_idx == 0) {
  1570. if (p_function == "connect" || p_function == "is_connected" || p_function == "disconnect" || p_function == "emit_signal" || p_function == "has_signal") {
  1571. List<MethodInfo> signals;
  1572. get_signal_list(&signals);
  1573. for (const MethodInfo &E : signals) {
  1574. r_options->push_back(E.name.quote());
  1575. }
  1576. } else if (p_function == "call" || p_function == "call_deferred" || p_function == "callv" || p_function == "has_method") {
  1577. List<MethodInfo> methods;
  1578. get_method_list(&methods);
  1579. for (const MethodInfo &E : methods) {
  1580. if (E.name.begins_with("_") && !(E.flags & METHOD_FLAG_VIRTUAL)) {
  1581. continue;
  1582. }
  1583. r_options->push_back(E.name.quote());
  1584. }
  1585. } else if (p_function == "set" || p_function == "set_deferred" || p_function == "get") {
  1586. List<PropertyInfo> properties;
  1587. get_property_list(&properties);
  1588. for (const PropertyInfo &E : properties) {
  1589. if (E.usage & PROPERTY_USAGE_DEFAULT && !(E.usage & PROPERTY_USAGE_INTERNAL)) {
  1590. r_options->push_back(E.name.quote());
  1591. }
  1592. }
  1593. } else if (p_function == "set_meta" || p_function == "get_meta" || p_function == "has_meta" || p_function == "remove_meta") {
  1594. for (const KeyValue<StringName, Variant> &K : metadata) {
  1595. r_options->push_back(String(K.key).quote());
  1596. }
  1597. }
  1598. } else if (p_idx == 2) {
  1599. if (p_function == "connect") {
  1600. // Ideally, the constants should be inferred by the parameter.
  1601. // But a parameter's PropertyInfo does not store the enum they come from, so this will do for now.
  1602. List<StringName> constants;
  1603. ClassDB::get_enum_constants("Object", "ConnectFlags", &constants);
  1604. for (const StringName &E : constants) {
  1605. r_options->push_back(String(E));
  1606. }
  1607. }
  1608. }
  1609. }
  1610. SpinLock ObjectDB::spin_lock;
  1611. uint32_t ObjectDB::slot_count = 0;
  1612. uint32_t ObjectDB::slot_max = 0;
  1613. ObjectDB::ObjectSlot *ObjectDB::object_slots = nullptr;
  1614. uint64_t ObjectDB::validator_counter = 0;
  1615. int ObjectDB::get_object_count() {
  1616. return slot_count;
  1617. }
  1618. ObjectID ObjectDB::add_instance(Object *p_object) {
  1619. spin_lock.lock();
  1620. if (unlikely(slot_count == slot_max)) {
  1621. CRASH_COND(slot_count == (1 << OBJECTDB_SLOT_MAX_COUNT_BITS));
  1622. uint32_t new_slot_max = slot_max > 0 ? slot_max * 2 : 1;
  1623. object_slots = (ObjectSlot *)memrealloc(object_slots, sizeof(ObjectSlot) * new_slot_max);
  1624. for (uint32_t i = slot_max; i < new_slot_max; i++) {
  1625. object_slots[i].object = nullptr;
  1626. object_slots[i].is_ref_counted = false;
  1627. object_slots[i].next_free = i;
  1628. object_slots[i].validator = 0;
  1629. }
  1630. slot_max = new_slot_max;
  1631. }
  1632. uint32_t slot = object_slots[slot_count].next_free;
  1633. if (object_slots[slot].object != nullptr) {
  1634. spin_lock.unlock();
  1635. ERR_FAIL_COND_V(object_slots[slot].object != nullptr, ObjectID());
  1636. }
  1637. object_slots[slot].object = p_object;
  1638. object_slots[slot].is_ref_counted = p_object->is_ref_counted();
  1639. validator_counter = (validator_counter + 1) & OBJECTDB_VALIDATOR_MASK;
  1640. if (unlikely(validator_counter == 0)) {
  1641. validator_counter = 1;
  1642. }
  1643. object_slots[slot].validator = validator_counter;
  1644. uint64_t id = validator_counter;
  1645. id <<= OBJECTDB_SLOT_MAX_COUNT_BITS;
  1646. id |= uint64_t(slot);
  1647. if (p_object->is_ref_counted()) {
  1648. id |= OBJECTDB_REFERENCE_BIT;
  1649. }
  1650. slot_count++;
  1651. spin_lock.unlock();
  1652. return ObjectID(id);
  1653. }
  1654. void ObjectDB::remove_instance(Object *p_object) {
  1655. uint64_t t = p_object->get_instance_id();
  1656. uint32_t slot = t & OBJECTDB_SLOT_MAX_COUNT_MASK; //slot is always valid on valid object
  1657. spin_lock.lock();
  1658. #ifdef DEBUG_ENABLED
  1659. if (object_slots[slot].object != p_object) {
  1660. spin_lock.unlock();
  1661. ERR_FAIL_COND(object_slots[slot].object != p_object);
  1662. }
  1663. {
  1664. uint64_t validator = (t >> OBJECTDB_SLOT_MAX_COUNT_BITS) & OBJECTDB_VALIDATOR_MASK;
  1665. if (object_slots[slot].validator != validator) {
  1666. spin_lock.unlock();
  1667. ERR_FAIL_COND(object_slots[slot].validator != validator);
  1668. }
  1669. }
  1670. #endif
  1671. //decrease slot count
  1672. slot_count--;
  1673. //set the free slot properly
  1674. object_slots[slot_count].next_free = slot;
  1675. //invalidate, so checks against it fail
  1676. object_slots[slot].validator = 0;
  1677. object_slots[slot].is_ref_counted = false;
  1678. object_slots[slot].object = nullptr;
  1679. spin_lock.unlock();
  1680. }
  1681. void ObjectDB::setup() {
  1682. //nothing to do now
  1683. }
  1684. void ObjectDB::cleanup() {
  1685. if (slot_count > 0) {
  1686. spin_lock.lock();
  1687. WARN_PRINT("ObjectDB instances leaked at exit (run with --verbose for details).");
  1688. if (OS::get_singleton()->is_stdout_verbose()) {
  1689. // Ensure calling the native classes because if a leaked instance has a script
  1690. // that overrides any of those methods, it'd not be OK to call them at this point,
  1691. // now the scripting languages have already been terminated.
  1692. MethodBind *node_get_name = ClassDB::get_method("Node", "get_name");
  1693. MethodBind *resource_get_path = ClassDB::get_method("Resource", "get_path");
  1694. Callable::CallError call_error;
  1695. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  1696. if (object_slots[i].validator) {
  1697. Object *obj = object_slots[i].object;
  1698. String extra_info;
  1699. if (obj->is_class("Node")) {
  1700. extra_info = " - Node name: " + String(node_get_name->call(obj, nullptr, 0, call_error));
  1701. }
  1702. if (obj->is_class("Resource")) {
  1703. extra_info = " - Resource path: " + String(resource_get_path->call(obj, nullptr, 0, call_error));
  1704. }
  1705. uint64_t id = uint64_t(i) | (uint64_t(object_slots[i].validator) << OBJECTDB_VALIDATOR_BITS) | (object_slots[i].is_ref_counted ? OBJECTDB_REFERENCE_BIT : 0);
  1706. print_line("Leaked instance: " + String(obj->get_class()) + ":" + itos(id) + extra_info);
  1707. count--;
  1708. }
  1709. }
  1710. print_line("Hint: Leaked instances typically happen when nodes are removed from the scene tree (with `remove_child()`) but not freed (with `free()` or `queue_free()`).");
  1711. }
  1712. spin_lock.unlock();
  1713. }
  1714. if (object_slots) {
  1715. memfree(object_slots);
  1716. }
  1717. }