object.cpp 67 KB

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