object.cpp 64 KB

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