object.cpp 66 KB

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