object.cpp 68 KB

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