object.cpp 65 KB

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