object.cpp 64 KB

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