object.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  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. current_extension = current_extension->parent;
  419. }
  420. }
  421. if (_extension && _extension->get_property_list) {
  422. uint32_t pcount;
  423. const GDExtensionPropertyInfo *pinfo = _extension->get_property_list(_extension_instance, &pcount);
  424. for (uint32_t i = 0; i < pcount; i++) {
  425. p_list->push_back(PropertyInfo(pinfo[i]));
  426. }
  427. if (_extension->free_property_list) {
  428. _extension->free_property_list(_extension_instance, pinfo);
  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. if (script_instance) {
  708. memdelete(script_instance);
  709. script_instance = nullptr;
  710. }
  711. script = p_script;
  712. Ref<Script> s = script;
  713. if (!s.is_null()) {
  714. if (s->can_instantiate()) {
  715. OBJ_DEBUG_LOCK
  716. script_instance = s->instance_create(this);
  717. } else if (Engine::get_singleton()->is_editor_hint()) {
  718. OBJ_DEBUG_LOCK
  719. script_instance = s->placeholder_instance_create(this);
  720. }
  721. }
  722. notify_property_list_changed(); //scripts may add variables, so refresh is desired
  723. emit_signal(CoreStringNames::get_singleton()->script_changed);
  724. }
  725. void Object::set_script_instance(ScriptInstance *p_instance) {
  726. if (script_instance == p_instance) {
  727. return;
  728. }
  729. if (script_instance) {
  730. memdelete(script_instance);
  731. }
  732. script_instance = p_instance;
  733. if (p_instance) {
  734. script = p_instance->get_script();
  735. } else {
  736. script = Variant();
  737. }
  738. }
  739. Variant Object::get_script() const {
  740. return script;
  741. }
  742. bool Object::has_meta(const StringName &p_name) const {
  743. return metadata.has(p_name);
  744. }
  745. void Object::set_meta(const StringName &p_name, const Variant &p_value) {
  746. if (p_value.get_type() == Variant::NIL) {
  747. if (metadata.has(p_name)) {
  748. metadata.erase(p_name);
  749. const String &sname = p_name;
  750. metadata_properties.erase("metadata/" + sname);
  751. if (!sname.begins_with("_")) {
  752. // Metadata starting with _ don't show up in the inspector, so no need to update.
  753. notify_property_list_changed();
  754. }
  755. }
  756. return;
  757. }
  758. HashMap<StringName, Variant>::Iterator E = metadata.find(p_name);
  759. if (E) {
  760. E->value = p_value;
  761. } else {
  762. ERR_FAIL_COND(!p_name.operator String().is_valid_identifier());
  763. Variant *V = &metadata.insert(p_name, p_value)->value;
  764. const String &sname = p_name;
  765. metadata_properties["metadata/" + sname] = V;
  766. if (!sname.begins_with("_")) {
  767. notify_property_list_changed();
  768. }
  769. }
  770. }
  771. Variant Object::get_meta(const StringName &p_name, const Variant &p_default) const {
  772. if (!metadata.has(p_name)) {
  773. if (p_default != Variant()) {
  774. return p_default;
  775. } else {
  776. ERR_FAIL_V_MSG(Variant(), "The object does not have any 'meta' values with the key '" + p_name + "'.");
  777. }
  778. }
  779. return metadata[p_name];
  780. }
  781. void Object::remove_meta(const StringName &p_name) {
  782. set_meta(p_name, Variant());
  783. }
  784. TypedArray<Dictionary> Object::_get_property_list_bind() const {
  785. List<PropertyInfo> lpi;
  786. get_property_list(&lpi);
  787. return convert_property_list(&lpi);
  788. }
  789. TypedArray<Dictionary> Object::_get_method_list_bind() const {
  790. List<MethodInfo> ml;
  791. get_method_list(&ml);
  792. TypedArray<Dictionary> ret;
  793. for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) {
  794. Dictionary d = E->get();
  795. //va.push_back(d);
  796. ret.push_back(d);
  797. }
  798. return ret;
  799. }
  800. TypedArray<StringName> Object::_get_meta_list_bind() const {
  801. TypedArray<StringName> _metaret;
  802. for (const KeyValue<StringName, Variant> &K : metadata) {
  803. _metaret.push_back(K.key);
  804. }
  805. return _metaret;
  806. }
  807. void Object::get_meta_list(List<StringName> *p_list) const {
  808. for (const KeyValue<StringName, Variant> &K : metadata) {
  809. p_list->push_back(K.key);
  810. }
  811. }
  812. void Object::add_user_signal(const MethodInfo &p_signal) {
  813. ERR_FAIL_COND_MSG(p_signal.name.is_empty(), "Signal name cannot be empty.");
  814. 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() + "'.");
  815. ERR_FAIL_COND_MSG(signal_map.has(p_signal.name), "Trying to add already existing signal '" + p_signal.name + "'.");
  816. SignalData s;
  817. s.user = p_signal;
  818. signal_map[p_signal.name] = s;
  819. }
  820. bool Object::_has_user_signal(const StringName &p_name) const {
  821. if (!signal_map.has(p_name)) {
  822. return false;
  823. }
  824. return signal_map[p_name].user.name.length() > 0;
  825. }
  826. struct _ObjectSignalDisconnectData {
  827. StringName signal;
  828. Callable callable;
  829. };
  830. Error Object::_emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  831. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  832. ERR_FAIL_COND_V(p_argcount < 1, Error::ERR_INVALID_PARAMETER);
  833. if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) {
  834. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  835. r_error.argument = 0;
  836. r_error.expected = Variant::STRING_NAME;
  837. ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING, Error::ERR_INVALID_PARAMETER);
  838. }
  839. r_error.error = Callable::CallError::CALL_OK;
  840. StringName signal = *p_args[0];
  841. const Variant **args = nullptr;
  842. int argc = p_argcount - 1;
  843. if (argc) {
  844. args = &p_args[1];
  845. }
  846. return emit_signalp(signal, args, argc);
  847. }
  848. Error Object::emit_signalp(const StringName &p_name, const Variant **p_args, int p_argcount) {
  849. if (_block_signals) {
  850. return ERR_CANT_ACQUIRE_RESOURCE; //no emit, signals blocked
  851. }
  852. SignalData *s = signal_map.getptr(p_name);
  853. if (!s) {
  854. #ifdef DEBUG_ENABLED
  855. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name);
  856. //check in script
  857. 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 + "\".");
  858. #endif
  859. //not connected? just return
  860. return ERR_UNAVAILABLE;
  861. }
  862. // If this is a ref-counted object, prevent it from being destroyed during signal emission,
  863. // which is needed in certain edge cases; e.g., https://github.com/godotengine/godot/issues/73889.
  864. Ref<RefCounted> rc = Ref<RefCounted>(Object::cast_to<RefCounted>(this));
  865. List<_ObjectSignalDisconnectData> disconnect_data;
  866. // Ensure that disconnecting the signal or even deleting the object
  867. // will not affect the signal calling.
  868. LocalVector<Connection> slot_conns;
  869. slot_conns.resize(s->slot_map.size());
  870. {
  871. uint32_t idx = 0;
  872. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  873. slot_conns[idx++] = slot_kv.value.conn;
  874. }
  875. DEV_ASSERT(idx == s->slot_map.size());
  876. }
  877. OBJ_DEBUG_LOCK
  878. Error err = OK;
  879. for (const Connection &c : slot_conns) {
  880. Object *target = c.callable.get_object();
  881. if (!target) {
  882. // Target might have been deleted during signal callback, this is expected and OK.
  883. continue;
  884. }
  885. const Variant **args = p_args;
  886. int argc = p_argcount;
  887. if (c.flags & CONNECT_DEFERRED) {
  888. MessageQueue::get_singleton()->push_callablep(c.callable, args, argc, true);
  889. } else {
  890. Callable::CallError ce;
  891. _emitting = true;
  892. Variant ret;
  893. c.callable.callp(args, argc, ret, ce);
  894. _emitting = false;
  895. if (ce.error != Callable::CallError::CALL_OK) {
  896. #ifdef DEBUG_ENABLED
  897. if (c.flags & CONNECT_PERSIST && Engine::get_singleton()->is_editor_hint() && (script.is_null() || !Ref<Script>(script)->is_tool())) {
  898. continue;
  899. }
  900. #endif
  901. if (ce.error == Callable::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists(target->get_class_name())) {
  902. //most likely object is not initialized yet, do not throw error.
  903. } else {
  904. ERR_PRINT("Error calling from signal '" + String(p_name) + "' to callable: " + Variant::get_callable_error_text(c.callable, args, argc, ce) + ".");
  905. err = ERR_METHOD_NOT_FOUND;
  906. }
  907. }
  908. }
  909. bool disconnect = c.flags & CONNECT_ONE_SHOT;
  910. #ifdef TOOLS_ENABLED
  911. if (disconnect && (c.flags & CONNECT_PERSIST) && Engine::get_singleton()->is_editor_hint()) {
  912. //this signal was connected from the editor, and is being edited. just don't disconnect for now
  913. disconnect = false;
  914. }
  915. #endif
  916. if (disconnect) {
  917. _ObjectSignalDisconnectData dd;
  918. dd.signal = p_name;
  919. dd.callable = c.callable;
  920. disconnect_data.push_back(dd);
  921. }
  922. }
  923. while (!disconnect_data.is_empty()) {
  924. const _ObjectSignalDisconnectData &dd = disconnect_data.front()->get();
  925. _disconnect(dd.signal, dd.callable);
  926. disconnect_data.pop_front();
  927. }
  928. return err;
  929. }
  930. void Object::_add_user_signal(const String &p_name, const Array &p_args) {
  931. // this version of add_user_signal is meant to be used from scripts or external apis
  932. // without access to ADD_SIGNAL in bind_methods
  933. // added events are per instance, as opposed to the other ones, which are global
  934. MethodInfo mi;
  935. mi.name = p_name;
  936. for (int i = 0; i < p_args.size(); i++) {
  937. Dictionary d = p_args[i];
  938. PropertyInfo param;
  939. if (d.has("name")) {
  940. param.name = d["name"];
  941. }
  942. if (d.has("type")) {
  943. param.type = (Variant::Type)(int)d["type"];
  944. }
  945. mi.arguments.push_back(param);
  946. }
  947. add_user_signal(mi);
  948. }
  949. TypedArray<Dictionary> Object::_get_signal_list() const {
  950. List<MethodInfo> signal_list;
  951. get_signal_list(&signal_list);
  952. TypedArray<Dictionary> ret;
  953. for (const MethodInfo &E : signal_list) {
  954. ret.push_back(Dictionary(E));
  955. }
  956. return ret;
  957. }
  958. TypedArray<Dictionary> Object::_get_signal_connection_list(const StringName &p_signal) const {
  959. List<Connection> conns;
  960. get_all_signal_connections(&conns);
  961. TypedArray<Dictionary> ret;
  962. for (const Connection &c : conns) {
  963. if (c.signal.get_name() == p_signal) {
  964. ret.push_back(c);
  965. }
  966. }
  967. return ret;
  968. }
  969. TypedArray<Dictionary> Object::_get_incoming_connections() const {
  970. TypedArray<Dictionary> ret;
  971. int connections_amount = connections.size();
  972. for (int idx_conn = 0; idx_conn < connections_amount; idx_conn++) {
  973. ret.push_back(connections[idx_conn]);
  974. }
  975. return ret;
  976. }
  977. bool Object::has_signal(const StringName &p_name) const {
  978. if (!script.is_null()) {
  979. Ref<Script> scr = script;
  980. if (scr.is_valid() && scr->has_script_signal(p_name)) {
  981. return true;
  982. }
  983. }
  984. if (ClassDB::has_signal(get_class_name(), p_name)) {
  985. return true;
  986. }
  987. if (_has_user_signal(p_name)) {
  988. return true;
  989. }
  990. return false;
  991. }
  992. void Object::get_signal_list(List<MethodInfo> *p_signals) const {
  993. if (!script.is_null()) {
  994. Ref<Script> scr = script;
  995. if (scr.is_valid()) {
  996. scr->get_script_signal_list(p_signals);
  997. }
  998. }
  999. ClassDB::get_signal_list(get_class_name(), p_signals);
  1000. //find maybe usersignals?
  1001. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1002. if (!E.value.user.name.is_empty()) {
  1003. //user signal
  1004. p_signals->push_back(E.value.user);
  1005. }
  1006. }
  1007. }
  1008. void Object::get_all_signal_connections(List<Connection> *p_connections) const {
  1009. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1010. const SignalData *s = &E.value;
  1011. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1012. p_connections->push_back(slot_kv.value.conn);
  1013. }
  1014. }
  1015. }
  1016. void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const {
  1017. const SignalData *s = signal_map.getptr(p_signal);
  1018. if (!s) {
  1019. return; //nothing
  1020. }
  1021. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1022. p_connections->push_back(slot_kv.value.conn);
  1023. }
  1024. }
  1025. int Object::get_persistent_signal_connection_count() const {
  1026. int count = 0;
  1027. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1028. const SignalData *s = &E.value;
  1029. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1030. if (slot_kv.value.conn.flags & CONNECT_PERSIST) {
  1031. count += 1;
  1032. }
  1033. }
  1034. }
  1035. return count;
  1036. }
  1037. void Object::get_signals_connected_to_this(List<Connection> *p_connections) const {
  1038. for (const Connection &E : connections) {
  1039. p_connections->push_back(E);
  1040. }
  1041. }
  1042. Error Object::connect(const StringName &p_signal, const Callable &p_callable, uint32_t p_flags) {
  1043. ERR_FAIL_COND_V_MSG(p_callable.is_null(), ERR_INVALID_PARAMETER, "Cannot connect to '" + p_signal + "': the provided callable is null.");
  1044. Object *target_object = p_callable.get_object();
  1045. ERR_FAIL_COND_V_MSG(!target_object, ERR_INVALID_PARAMETER, "Cannot connect to '" + p_signal + "' to callable '" + p_callable + "': the callable object is null.");
  1046. SignalData *s = signal_map.getptr(p_signal);
  1047. if (!s) {
  1048. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1049. //check in script
  1050. if (!signal_is_valid && !script.is_null()) {
  1051. if (Ref<Script>(script)->has_script_signal(p_signal)) {
  1052. signal_is_valid = true;
  1053. }
  1054. #ifdef TOOLS_ENABLED
  1055. else {
  1056. //allow connecting signals anyway if script is invalid, see issue #17070
  1057. if (!Ref<Script>(script)->is_valid()) {
  1058. signal_is_valid = true;
  1059. }
  1060. }
  1061. #endif
  1062. }
  1063. 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 + "'.");
  1064. signal_map[p_signal] = SignalData();
  1065. s = &signal_map[p_signal];
  1066. }
  1067. Callable target = p_callable;
  1068. //compare with the base callable, so binds can be ignored
  1069. if (s->slot_map.has(*target.get_base_comparator())) {
  1070. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1071. s->slot_map[*target.get_base_comparator()].reference_count++;
  1072. return OK;
  1073. } else {
  1074. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Signal '" + p_signal + "' is already connected to given callable '" + p_callable + "' in that object.");
  1075. }
  1076. }
  1077. SignalData::Slot slot;
  1078. Connection conn;
  1079. conn.callable = target;
  1080. conn.signal = ::Signal(this, p_signal);
  1081. conn.flags = p_flags;
  1082. slot.conn = conn;
  1083. slot.cE = target_object->connections.push_back(conn);
  1084. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1085. slot.reference_count = 1;
  1086. }
  1087. //use callable version as key, so binds can be ignored
  1088. s->slot_map[*target.get_base_comparator()] = slot;
  1089. return OK;
  1090. }
  1091. bool Object::is_connected(const StringName &p_signal, const Callable &p_callable) const {
  1092. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, "Cannot determine if connected to '" + p_signal + "': the provided callable is null.");
  1093. const SignalData *s = signal_map.getptr(p_signal);
  1094. if (!s) {
  1095. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1096. if (signal_is_valid) {
  1097. return false;
  1098. }
  1099. if (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal)) {
  1100. return false;
  1101. }
  1102. ERR_FAIL_V_MSG(false, "Nonexistent signal: " + p_signal + ".");
  1103. }
  1104. Callable target = p_callable;
  1105. return s->slot_map.has(*target.get_base_comparator());
  1106. }
  1107. void Object::disconnect(const StringName &p_signal, const Callable &p_callable) {
  1108. _disconnect(p_signal, p_callable);
  1109. }
  1110. bool Object::_disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force) {
  1111. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, "Cannot disconnect from '" + p_signal + "': the provided callable is null.");
  1112. Object *target_object = p_callable.get_object();
  1113. ERR_FAIL_COND_V_MSG(!target_object, false, "Cannot disconnect '" + p_signal + "' from callable '" + p_callable + "': the callable object is null.");
  1114. SignalData *s = signal_map.getptr(p_signal);
  1115. if (!s) {
  1116. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal) ||
  1117. (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal));
  1118. ERR_FAIL_COND_V_MSG(signal_is_valid, false, "Attempt to disconnect a nonexistent connection from '" + to_string() + "'. Signal: '" + p_signal + "', callable: '" + p_callable + "'.");
  1119. }
  1120. ERR_FAIL_COND_V_MSG(!s, false, vformat("Disconnecting nonexistent signal '%s' in %s.", p_signal, to_string()));
  1121. ERR_FAIL_COND_V_MSG(!s->slot_map.has(*p_callable.get_base_comparator()), false, "Disconnecting nonexistent signal '" + p_signal + "', callable: " + p_callable + ".");
  1122. SignalData::Slot *slot = &s->slot_map[*p_callable.get_base_comparator()];
  1123. if (!p_force) {
  1124. slot->reference_count--; // by default is zero, if it was not referenced it will go below it
  1125. if (slot->reference_count > 0) {
  1126. return false;
  1127. }
  1128. }
  1129. target_object->connections.erase(slot->cE);
  1130. s->slot_map.erase(*p_callable.get_base_comparator());
  1131. if (s->slot_map.is_empty() && ClassDB::has_signal(get_class_name(), p_signal)) {
  1132. //not user signal, delete
  1133. signal_map.erase(p_signal);
  1134. }
  1135. return true;
  1136. }
  1137. void Object::_set_bind(const StringName &p_set, const Variant &p_value) {
  1138. set(p_set, p_value);
  1139. }
  1140. Variant Object::_get_bind(const StringName &p_name) const {
  1141. return get(p_name);
  1142. }
  1143. void Object::_set_indexed_bind(const NodePath &p_name, const Variant &p_value) {
  1144. set_indexed(p_name.get_as_property_path().get_subnames(), p_value);
  1145. }
  1146. Variant Object::_get_indexed_bind(const NodePath &p_name) const {
  1147. return get_indexed(p_name.get_as_property_path().get_subnames());
  1148. }
  1149. void Object::initialize_class() {
  1150. static bool initialized = false;
  1151. if (initialized) {
  1152. return;
  1153. }
  1154. ClassDB::_add_class<Object>();
  1155. _bind_methods();
  1156. initialized = true;
  1157. }
  1158. String Object::tr(const StringName &p_message, const StringName &p_context) const {
  1159. if (!_can_translate || !TranslationServer::get_singleton()) {
  1160. return p_message;
  1161. }
  1162. if (Engine::get_singleton()->is_editor_hint()) {
  1163. return TranslationServer::get_singleton()->tool_translate(p_message, p_context);
  1164. } else {
  1165. return TranslationServer::get_singleton()->translate(p_message, p_context);
  1166. }
  1167. }
  1168. String Object::tr_n(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  1169. if (!_can_translate || !TranslationServer::get_singleton()) {
  1170. // Return message based on English plural rule if translation is not possible.
  1171. if (p_n == 1) {
  1172. return p_message;
  1173. }
  1174. return p_message_plural;
  1175. }
  1176. if (Engine::get_singleton()->is_editor_hint()) {
  1177. return TranslationServer::get_singleton()->tool_translate_plural(p_message, p_message_plural, p_n, p_context);
  1178. } else {
  1179. return TranslationServer::get_singleton()->translate_plural(p_message, p_message_plural, p_n, p_context);
  1180. }
  1181. }
  1182. void Object::_clear_internal_resource_paths(const Variant &p_var) {
  1183. switch (p_var.get_type()) {
  1184. case Variant::OBJECT: {
  1185. Ref<Resource> r = p_var;
  1186. if (!r.is_valid()) {
  1187. return;
  1188. }
  1189. if (!r->is_built_in()) {
  1190. return; //not an internal resource
  1191. }
  1192. Object *object = p_var;
  1193. if (!object) {
  1194. return;
  1195. }
  1196. r->set_path("");
  1197. r->clear_internal_resource_paths();
  1198. } break;
  1199. case Variant::ARRAY: {
  1200. Array a = p_var;
  1201. for (int i = 0; i < a.size(); i++) {
  1202. _clear_internal_resource_paths(a[i]);
  1203. }
  1204. } break;
  1205. case Variant::DICTIONARY: {
  1206. Dictionary d = p_var;
  1207. List<Variant> keys;
  1208. d.get_key_list(&keys);
  1209. for (const Variant &E : keys) {
  1210. _clear_internal_resource_paths(E);
  1211. _clear_internal_resource_paths(d[E]);
  1212. }
  1213. } break;
  1214. default: {
  1215. }
  1216. }
  1217. }
  1218. #ifdef TOOLS_ENABLED
  1219. void Object::editor_set_section_unfold(const String &p_section, bool p_unfolded) {
  1220. set_edited(true);
  1221. if (p_unfolded) {
  1222. editor_section_folding.insert(p_section);
  1223. } else {
  1224. editor_section_folding.erase(p_section);
  1225. }
  1226. }
  1227. bool Object::editor_is_section_unfolded(const String &p_section) {
  1228. return editor_section_folding.has(p_section);
  1229. }
  1230. #endif
  1231. void Object::clear_internal_resource_paths() {
  1232. List<PropertyInfo> pinfo;
  1233. get_property_list(&pinfo);
  1234. for (const PropertyInfo &E : pinfo) {
  1235. _clear_internal_resource_paths(get(E.name));
  1236. }
  1237. }
  1238. void Object::notify_property_list_changed() {
  1239. emit_signal(CoreStringNames::get_singleton()->property_list_changed);
  1240. }
  1241. void Object::_bind_methods() {
  1242. ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class);
  1243. ClassDB::bind_method(D_METHOD("is_class", "class"), &Object::is_class);
  1244. ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind);
  1245. ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind);
  1246. ClassDB::bind_method(D_METHOD("set_indexed", "property_path", "value"), &Object::_set_indexed_bind);
  1247. ClassDB::bind_method(D_METHOD("get_indexed", "property_path"), &Object::_get_indexed_bind);
  1248. ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind);
  1249. ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind);
  1250. ClassDB::bind_method(D_METHOD("property_can_revert", "property"), &Object::property_can_revert);
  1251. ClassDB::bind_method(D_METHOD("property_get_revert", "property"), &Object::property_get_revert);
  1252. ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false));
  1253. ClassDB::bind_method(D_METHOD("to_string"), &Object::to_string);
  1254. ClassDB::bind_method(D_METHOD("get_instance_id"), &Object::get_instance_id);
  1255. ClassDB::bind_method(D_METHOD("set_script", "script"), &Object::set_script);
  1256. ClassDB::bind_method(D_METHOD("get_script"), &Object::get_script);
  1257. ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta);
  1258. ClassDB::bind_method(D_METHOD("remove_meta", "name"), &Object::remove_meta);
  1259. ClassDB::bind_method(D_METHOD("get_meta", "name", "default"), &Object::get_meta, DEFVAL(Variant()));
  1260. ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta);
  1261. ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind);
  1262. ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array()));
  1263. ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal);
  1264. {
  1265. MethodInfo mi;
  1266. mi.name = "emit_signal";
  1267. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "signal"));
  1268. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi, varray(), false);
  1269. }
  1270. {
  1271. MethodInfo mi;
  1272. mi.name = "call";
  1273. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1274. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call", &Object::_call_bind, mi);
  1275. }
  1276. {
  1277. MethodInfo mi;
  1278. mi.name = "call_deferred";
  1279. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1280. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi, varray(), false);
  1281. }
  1282. ClassDB::bind_method(D_METHOD("set_deferred", "property", "value"), &Object::set_deferred);
  1283. ClassDB::bind_method(D_METHOD("callv", "method", "arg_array"), &Object::callv);
  1284. ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method);
  1285. ClassDB::bind_method(D_METHOD("has_signal", "signal"), &Object::has_signal);
  1286. ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list);
  1287. ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list);
  1288. ClassDB::bind_method(D_METHOD("get_incoming_connections"), &Object::_get_incoming_connections);
  1289. ClassDB::bind_method(D_METHOD("connect", "signal", "callable", "flags"), &Object::connect, DEFVAL(0));
  1290. ClassDB::bind_method(D_METHOD("disconnect", "signal", "callable"), &Object::disconnect);
  1291. ClassDB::bind_method(D_METHOD("is_connected", "signal", "callable"), &Object::is_connected);
  1292. ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals);
  1293. ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals);
  1294. ClassDB::bind_method(D_METHOD("notify_property_list_changed"), &Object::notify_property_list_changed);
  1295. ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation);
  1296. ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages);
  1297. ClassDB::bind_method(D_METHOD("tr", "message", "context"), &Object::tr, DEFVAL(""));
  1298. ClassDB::bind_method(D_METHOD("tr_n", "message", "plural_message", "n", "context"), &Object::tr_n, DEFVAL(""));
  1299. ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion);
  1300. ClassDB::bind_method(D_METHOD("cancel_free"), &Object::cancel_free);
  1301. ClassDB::add_virtual_method("Object", MethodInfo("free"), false);
  1302. ADD_SIGNAL(MethodInfo("script_changed"));
  1303. ADD_SIGNAL(MethodInfo("property_list_changed"));
  1304. #define BIND_OBJ_CORE_METHOD(m_method) \
  1305. ::ClassDB::add_virtual_method(get_class_static(), m_method, true, Vector<String>(), true);
  1306. MethodInfo notification_mi("_notification", PropertyInfo(Variant::INT, "what"));
  1307. notification_mi.arguments_metadata.push_back(GodotTypeInfo::Metadata::METADATA_INT_IS_INT32);
  1308. BIND_OBJ_CORE_METHOD(notification_mi);
  1309. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_set", PropertyInfo(Variant::STRING_NAME, "property"), PropertyInfo(Variant::NIL, "value")));
  1310. #ifdef TOOLS_ENABLED
  1311. MethodInfo miget("_get", PropertyInfo(Variant::STRING_NAME, "property"));
  1312. miget.return_val.name = "Variant";
  1313. miget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1314. BIND_OBJ_CORE_METHOD(miget);
  1315. MethodInfo plget("_get_property_list");
  1316. plget.return_val.type = Variant::ARRAY;
  1317. plget.return_val.hint = PROPERTY_HINT_ARRAY_TYPE;
  1318. plget.return_val.hint_string = "Dictionary";
  1319. BIND_OBJ_CORE_METHOD(plget);
  1320. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_property_can_revert", PropertyInfo(Variant::STRING_NAME, "property")));
  1321. MethodInfo mipgr("_property_get_revert", PropertyInfo(Variant::STRING_NAME, "property"));
  1322. mipgr.return_val.name = "Variant";
  1323. mipgr.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1324. BIND_OBJ_CORE_METHOD(mipgr);
  1325. #endif
  1326. BIND_OBJ_CORE_METHOD(MethodInfo("_init"));
  1327. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::STRING, "_to_string"));
  1328. BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE);
  1329. BIND_CONSTANT(NOTIFICATION_PREDELETE);
  1330. BIND_ENUM_CONSTANT(CONNECT_DEFERRED);
  1331. BIND_ENUM_CONSTANT(CONNECT_PERSIST);
  1332. BIND_ENUM_CONSTANT(CONNECT_ONE_SHOT);
  1333. BIND_ENUM_CONSTANT(CONNECT_REFERENCE_COUNTED);
  1334. }
  1335. void Object::set_deferred(const StringName &p_property, const Variant &p_value) {
  1336. MessageQueue::get_singleton()->push_set(this, p_property, p_value);
  1337. }
  1338. void Object::set_block_signals(bool p_block) {
  1339. _block_signals = p_block;
  1340. }
  1341. bool Object::is_blocking_signals() const {
  1342. return _block_signals;
  1343. }
  1344. Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const {
  1345. bool valid;
  1346. Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid);
  1347. if (valid) {
  1348. if (r_valid) {
  1349. *r_valid = true;
  1350. }
  1351. return t;
  1352. }
  1353. if (get_script_instance()) {
  1354. return get_script_instance()->get_property_type(p_property, r_valid);
  1355. }
  1356. if (r_valid) {
  1357. *r_valid = false;
  1358. }
  1359. return Variant::NIL;
  1360. }
  1361. Variant::Type Object::get_static_property_type_indexed(const Vector<StringName> &p_path, bool *r_valid) const {
  1362. if (p_path.size() == 0) {
  1363. if (r_valid) {
  1364. *r_valid = false;
  1365. }
  1366. return Variant::NIL;
  1367. }
  1368. bool valid = false;
  1369. Variant::Type t = get_static_property_type(p_path[0], &valid);
  1370. if (!valid) {
  1371. if (r_valid) {
  1372. *r_valid = false;
  1373. }
  1374. return Variant::NIL;
  1375. }
  1376. Callable::CallError ce;
  1377. Variant check;
  1378. Variant::construct(t, check, nullptr, 0, ce);
  1379. for (int i = 1; i < p_path.size(); i++) {
  1380. if (check.get_type() == Variant::OBJECT || check.get_type() == Variant::DICTIONARY || check.get_type() == Variant::ARRAY) {
  1381. // We cannot be sure about the type of properties this type can have
  1382. if (r_valid) {
  1383. *r_valid = false;
  1384. }
  1385. return Variant::NIL;
  1386. }
  1387. check = check.get_named(p_path[i], valid);
  1388. if (!valid) {
  1389. if (r_valid) {
  1390. *r_valid = false;
  1391. }
  1392. return Variant::NIL;
  1393. }
  1394. }
  1395. if (r_valid) {
  1396. *r_valid = true;
  1397. }
  1398. return check.get_type();
  1399. }
  1400. bool Object::is_queued_for_deletion() const {
  1401. return _is_queued_for_deletion;
  1402. }
  1403. #ifdef TOOLS_ENABLED
  1404. void Object::set_edited(bool p_edited) {
  1405. _edited = p_edited;
  1406. _edited_version++;
  1407. }
  1408. bool Object::is_edited() const {
  1409. return _edited;
  1410. }
  1411. uint32_t Object::get_edited_version() const {
  1412. return _edited_version;
  1413. }
  1414. #endif
  1415. void Object::set_instance_binding(void *p_token, void *p_binding, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  1416. // This is only meant to be used on creation by the binder.
  1417. ERR_FAIL_COND(_instance_bindings != nullptr);
  1418. _instance_bindings = (InstanceBinding *)memalloc(sizeof(InstanceBinding));
  1419. _instance_bindings[0].binding = p_binding;
  1420. _instance_bindings[0].free_callback = p_callbacks->free_callback;
  1421. _instance_bindings[0].reference_callback = p_callbacks->reference_callback;
  1422. _instance_bindings[0].token = p_token;
  1423. _instance_binding_count = 1;
  1424. }
  1425. void *Object::get_instance_binding(void *p_token, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  1426. void *binding = nullptr;
  1427. _instance_binding_mutex.lock();
  1428. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1429. if (_instance_bindings[i].token == p_token) {
  1430. binding = _instance_bindings[i].binding;
  1431. break;
  1432. }
  1433. }
  1434. if (unlikely(!binding && p_callbacks)) {
  1435. uint32_t current_size = next_power_of_2(_instance_binding_count);
  1436. uint32_t new_size = next_power_of_2(_instance_binding_count + 1);
  1437. if (current_size == 0 || new_size > current_size) {
  1438. _instance_bindings = (InstanceBinding *)memrealloc(_instance_bindings, new_size * sizeof(InstanceBinding));
  1439. }
  1440. _instance_bindings[_instance_binding_count].free_callback = p_callbacks->free_callback;
  1441. _instance_bindings[_instance_binding_count].reference_callback = p_callbacks->reference_callback;
  1442. _instance_bindings[_instance_binding_count].token = p_token;
  1443. binding = p_callbacks->create_callback(p_token, this);
  1444. _instance_bindings[_instance_binding_count].binding = binding;
  1445. _instance_binding_count++;
  1446. }
  1447. _instance_binding_mutex.unlock();
  1448. return binding;
  1449. }
  1450. bool Object::has_instance_binding(void *p_token) {
  1451. bool found = false;
  1452. _instance_binding_mutex.lock();
  1453. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1454. if (_instance_bindings[i].token == p_token) {
  1455. found = true;
  1456. break;
  1457. }
  1458. }
  1459. _instance_binding_mutex.unlock();
  1460. return found;
  1461. }
  1462. void Object::_construct_object(bool p_reference) {
  1463. type_is_reference = p_reference;
  1464. _instance_id = ObjectDB::add_instance(this);
  1465. #ifdef DEBUG_ENABLED
  1466. _lock_index.init(1);
  1467. #endif
  1468. }
  1469. Object::Object(bool p_reference) {
  1470. _construct_object(p_reference);
  1471. }
  1472. Object::Object() {
  1473. _construct_object(false);
  1474. }
  1475. void Object::detach_from_objectdb() {
  1476. if (_instance_id != ObjectID()) {
  1477. ObjectDB::remove_instance(this);
  1478. _instance_id = ObjectID();
  1479. }
  1480. }
  1481. Object::~Object() {
  1482. if (script_instance) {
  1483. memdelete(script_instance);
  1484. }
  1485. script_instance = nullptr;
  1486. if (_extension && _extension->free_instance) {
  1487. _extension->free_instance(_extension->class_userdata, _extension_instance);
  1488. _extension = nullptr;
  1489. _extension_instance = nullptr;
  1490. }
  1491. if (_emitting) {
  1492. //@todo this may need to actually reach the debugger prioritarily somehow because it may crash before
  1493. 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.");
  1494. }
  1495. // Drop all connections to the signals of this object.
  1496. while (signal_map.size()) {
  1497. // Avoid regular iteration so erasing is safe.
  1498. KeyValue<StringName, SignalData> &E = *signal_map.begin();
  1499. SignalData *s = &E.value;
  1500. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1501. Object *target = slot_kv.value.conn.callable.get_object();
  1502. if (likely(target)) {
  1503. target->connections.erase(slot_kv.value.cE);
  1504. }
  1505. }
  1506. signal_map.erase(E.key);
  1507. }
  1508. // Disconnect signals that connect to this object.
  1509. while (connections.size()) {
  1510. Connection c = connections.front()->get();
  1511. bool disconnected = c.signal.get_object()->_disconnect(c.signal.get_name(), c.callable, true);
  1512. if (unlikely(!disconnected)) {
  1513. // If the disconnect has failed, abandon the connection to avoid getting trapped in an infinite loop here.
  1514. connections.pop_front();
  1515. }
  1516. }
  1517. if (_instance_id != ObjectID()) {
  1518. ObjectDB::remove_instance(this);
  1519. _instance_id = ObjectID();
  1520. }
  1521. _predelete_ok = 2;
  1522. if (_instance_bindings != nullptr) {
  1523. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1524. if (_instance_bindings[i].free_callback) {
  1525. _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
  1526. }
  1527. }
  1528. memfree(_instance_bindings);
  1529. }
  1530. }
  1531. bool predelete_handler(Object *p_object) {
  1532. return p_object->_predelete();
  1533. }
  1534. void postinitialize_handler(Object *p_object) {
  1535. p_object->_postinitialize();
  1536. }
  1537. void ObjectDB::debug_objects(DebugFunc p_func) {
  1538. spin_lock.lock();
  1539. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  1540. if (object_slots[i].validator) {
  1541. p_func(object_slots[i].object);
  1542. count--;
  1543. }
  1544. }
  1545. spin_lock.unlock();
  1546. }
  1547. void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  1548. if (p_idx == 0) {
  1549. if (p_function == "connect" || p_function == "is_connected" || p_function == "disconnect" || p_function == "emit_signal" || p_function == "has_signal") {
  1550. List<MethodInfo> signals;
  1551. get_signal_list(&signals);
  1552. for (const MethodInfo &E : signals) {
  1553. r_options->push_back(E.name.quote());
  1554. }
  1555. } else if (p_function == "call" || p_function == "call_deferred" || p_function == "callv" || p_function == "has_method") {
  1556. List<MethodInfo> methods;
  1557. get_method_list(&methods);
  1558. for (const MethodInfo &E : methods) {
  1559. if (E.name.begins_with("_") && !(E.flags & METHOD_FLAG_VIRTUAL)) {
  1560. continue;
  1561. }
  1562. r_options->push_back(E.name.quote());
  1563. }
  1564. } else if (p_function == "set" || p_function == "set_deferred" || p_function == "get") {
  1565. List<PropertyInfo> properties;
  1566. get_property_list(&properties);
  1567. for (const PropertyInfo &E : properties) {
  1568. if (E.usage & PROPERTY_USAGE_DEFAULT && !(E.usage & PROPERTY_USAGE_INTERNAL)) {
  1569. r_options->push_back(E.name.quote());
  1570. }
  1571. }
  1572. } else if (p_function == "set_meta" || p_function == "get_meta" || p_function == "has_meta" || p_function == "remove_meta") {
  1573. for (const KeyValue<StringName, Variant> &K : metadata) {
  1574. r_options->push_back(String(K.key).quote());
  1575. }
  1576. }
  1577. } else if (p_idx == 2) {
  1578. if (p_function == "connect") {
  1579. // Ideally, the constants should be inferred by the parameter.
  1580. // But a parameter's PropertyInfo does not store the enum they come from, so this will do for now.
  1581. List<StringName> constants;
  1582. ClassDB::get_enum_constants("Object", "ConnectFlags", &constants);
  1583. for (const StringName &E : constants) {
  1584. r_options->push_back(String(E));
  1585. }
  1586. }
  1587. }
  1588. }
  1589. SpinLock ObjectDB::spin_lock;
  1590. uint32_t ObjectDB::slot_count = 0;
  1591. uint32_t ObjectDB::slot_max = 0;
  1592. ObjectDB::ObjectSlot *ObjectDB::object_slots = nullptr;
  1593. uint64_t ObjectDB::validator_counter = 0;
  1594. int ObjectDB::get_object_count() {
  1595. return slot_count;
  1596. }
  1597. ObjectID ObjectDB::add_instance(Object *p_object) {
  1598. spin_lock.lock();
  1599. if (unlikely(slot_count == slot_max)) {
  1600. CRASH_COND(slot_count == (1 << OBJECTDB_SLOT_MAX_COUNT_BITS));
  1601. uint32_t new_slot_max = slot_max > 0 ? slot_max * 2 : 1;
  1602. object_slots = (ObjectSlot *)memrealloc(object_slots, sizeof(ObjectSlot) * new_slot_max);
  1603. for (uint32_t i = slot_max; i < new_slot_max; i++) {
  1604. object_slots[i].object = nullptr;
  1605. object_slots[i].is_ref_counted = false;
  1606. object_slots[i].next_free = i;
  1607. object_slots[i].validator = 0;
  1608. }
  1609. slot_max = new_slot_max;
  1610. }
  1611. uint32_t slot = object_slots[slot_count].next_free;
  1612. if (object_slots[slot].object != nullptr) {
  1613. spin_lock.unlock();
  1614. ERR_FAIL_COND_V(object_slots[slot].object != nullptr, ObjectID());
  1615. }
  1616. object_slots[slot].object = p_object;
  1617. object_slots[slot].is_ref_counted = p_object->is_ref_counted();
  1618. validator_counter = (validator_counter + 1) & OBJECTDB_VALIDATOR_MASK;
  1619. if (unlikely(validator_counter == 0)) {
  1620. validator_counter = 1;
  1621. }
  1622. object_slots[slot].validator = validator_counter;
  1623. uint64_t id = validator_counter;
  1624. id <<= OBJECTDB_SLOT_MAX_COUNT_BITS;
  1625. id |= uint64_t(slot);
  1626. if (p_object->is_ref_counted()) {
  1627. id |= OBJECTDB_REFERENCE_BIT;
  1628. }
  1629. slot_count++;
  1630. spin_lock.unlock();
  1631. return ObjectID(id);
  1632. }
  1633. void ObjectDB::remove_instance(Object *p_object) {
  1634. uint64_t t = p_object->get_instance_id();
  1635. uint32_t slot = t & OBJECTDB_SLOT_MAX_COUNT_MASK; //slot is always valid on valid object
  1636. spin_lock.lock();
  1637. #ifdef DEBUG_ENABLED
  1638. if (object_slots[slot].object != p_object) {
  1639. spin_lock.unlock();
  1640. ERR_FAIL_COND(object_slots[slot].object != p_object);
  1641. }
  1642. {
  1643. uint64_t validator = (t >> OBJECTDB_SLOT_MAX_COUNT_BITS) & OBJECTDB_VALIDATOR_MASK;
  1644. if (object_slots[slot].validator != validator) {
  1645. spin_lock.unlock();
  1646. ERR_FAIL_COND(object_slots[slot].validator != validator);
  1647. }
  1648. }
  1649. #endif
  1650. //decrease slot count
  1651. slot_count--;
  1652. //set the free slot properly
  1653. object_slots[slot_count].next_free = slot;
  1654. //invalidate, so checks against it fail
  1655. object_slots[slot].validator = 0;
  1656. object_slots[slot].is_ref_counted = false;
  1657. object_slots[slot].object = nullptr;
  1658. spin_lock.unlock();
  1659. }
  1660. void ObjectDB::setup() {
  1661. //nothing to do now
  1662. }
  1663. void ObjectDB::cleanup() {
  1664. if (slot_count > 0) {
  1665. spin_lock.lock();
  1666. WARN_PRINT("ObjectDB instances leaked at exit (run with --verbose for details).");
  1667. if (OS::get_singleton()->is_stdout_verbose()) {
  1668. // Ensure calling the native classes because if a leaked instance has a script
  1669. // that overrides any of those methods, it'd not be OK to call them at this point,
  1670. // now the scripting languages have already been terminated.
  1671. MethodBind *node_get_name = ClassDB::get_method("Node", "get_name");
  1672. MethodBind *resource_get_path = ClassDB::get_method("Resource", "get_path");
  1673. Callable::CallError call_error;
  1674. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  1675. if (object_slots[i].validator) {
  1676. Object *obj = object_slots[i].object;
  1677. String extra_info;
  1678. if (obj->is_class("Node")) {
  1679. extra_info = " - Node name: " + String(node_get_name->call(obj, nullptr, 0, call_error));
  1680. }
  1681. if (obj->is_class("Resource")) {
  1682. extra_info = " - Resource path: " + String(resource_get_path->call(obj, nullptr, 0, call_error));
  1683. }
  1684. 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);
  1685. print_line("Leaked instance: " + String(obj->get_class()) + ":" + itos(id) + extra_info);
  1686. count--;
  1687. }
  1688. }
  1689. 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()`).");
  1690. }
  1691. spin_lock.unlock();
  1692. }
  1693. if (object_slots) {
  1694. memfree(object_slots);
  1695. }
  1696. }