object.cpp 61 KB

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