object.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219
  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.argument = 0;
  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.argument = 0;
  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. return method != nullptr;
  567. }
  568. Variant Object::getvar(const Variant &p_key, bool *r_valid) const {
  569. if (r_valid) {
  570. *r_valid = false;
  571. }
  572. if (p_key.get_type() == Variant::STRING_NAME || p_key.get_type() == Variant::STRING) {
  573. return get(p_key, r_valid);
  574. }
  575. return Variant();
  576. }
  577. void Object::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) {
  578. if (r_valid) {
  579. *r_valid = false;
  580. }
  581. if (p_key.get_type() == Variant::STRING_NAME || p_key.get_type() == Variant::STRING) {
  582. return set(p_key, p_value, r_valid);
  583. }
  584. }
  585. Variant Object::callv(const StringName &p_method, const Array &p_args) {
  586. const Variant **argptrs = nullptr;
  587. if (p_args.size() > 0) {
  588. argptrs = (const Variant **)alloca(sizeof(Variant *) * p_args.size());
  589. for (int i = 0; i < p_args.size(); i++) {
  590. argptrs[i] = &p_args[i];
  591. }
  592. }
  593. Callable::CallError ce;
  594. Variant ret = callp(p_method, argptrs, p_args.size(), ce);
  595. if (ce.error != Callable::CallError::CALL_OK) {
  596. ERR_FAIL_V_MSG(Variant(), "Error calling method from 'callv': " + Variant::get_call_error_text(this, p_method, argptrs, p_args.size(), ce) + ".");
  597. }
  598. return ret;
  599. }
  600. Variant Object::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  601. r_error.error = Callable::CallError::CALL_OK;
  602. if (p_method == CoreStringNames::get_singleton()->_free) {
  603. //free must be here, before anything, always ready
  604. #ifdef DEBUG_ENABLED
  605. if (p_argcount != 0) {
  606. r_error.argument = 0;
  607. r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
  608. return Variant();
  609. }
  610. if (Object::cast_to<RefCounted>(this)) {
  611. r_error.argument = 0;
  612. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  613. ERR_FAIL_V_MSG(Variant(), "Can't 'free' a reference.");
  614. }
  615. if (_lock_index.get() > 1) {
  616. r_error.argument = 0;
  617. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  618. ERR_FAIL_V_MSG(Variant(), "Object is locked and can't be freed.");
  619. }
  620. #endif
  621. //must be here, must be before everything,
  622. memdelete(this);
  623. r_error.error = Callable::CallError::CALL_OK;
  624. return Variant();
  625. }
  626. Variant ret;
  627. OBJ_DEBUG_LOCK
  628. if (script_instance) {
  629. ret = script_instance->callp(p_method, p_args, p_argcount, r_error);
  630. //force jumptable
  631. switch (r_error.error) {
  632. case Callable::CallError::CALL_OK:
  633. return ret;
  634. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  635. break;
  636. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  637. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  638. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  639. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  640. return ret;
  641. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
  642. }
  643. }
  644. }
  645. //extension does not need this, because all methods are registered in MethodBind
  646. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  647. if (method) {
  648. ret = method->call(this, p_args, p_argcount, r_error);
  649. } else {
  650. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  651. }
  652. return ret;
  653. }
  654. Variant Object::call_const(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  655. r_error.error = Callable::CallError::CALL_OK;
  656. if (p_method == CoreStringNames::get_singleton()->_free) {
  657. // Free is not const, so fail.
  658. r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
  659. return Variant();
  660. }
  661. Variant ret;
  662. OBJ_DEBUG_LOCK
  663. if (script_instance) {
  664. ret = script_instance->call_const(p_method, p_args, p_argcount, r_error);
  665. //force jumptable
  666. switch (r_error.error) {
  667. case Callable::CallError::CALL_OK:
  668. return ret;
  669. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  670. break;
  671. case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
  672. break;
  673. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  674. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  675. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  676. return ret;
  677. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
  678. }
  679. }
  680. }
  681. //extension does not need this, because all methods are registered in MethodBind
  682. MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
  683. if (method) {
  684. if (!method->is_const()) {
  685. r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
  686. return ret;
  687. }
  688. ret = method->call(this, p_args, p_argcount, r_error);
  689. } else {
  690. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  691. }
  692. return ret;
  693. }
  694. void Object::notification(int p_notification, bool p_reversed) {
  695. if (p_reversed) {
  696. if (script_instance) {
  697. script_instance->notification(p_notification, p_reversed);
  698. }
  699. } else {
  700. _notificationv(p_notification, p_reversed);
  701. }
  702. if (_extension) {
  703. if (_extension->notification2) {
  704. _extension->notification2(_extension_instance, p_notification, static_cast<GDExtensionBool>(p_reversed));
  705. #ifndef DISABLE_DEPRECATED
  706. } else if (_extension->notification) {
  707. _extension->notification(_extension_instance, p_notification);
  708. #endif // DISABLE_DEPRECATED
  709. }
  710. }
  711. if (p_reversed) {
  712. _notificationv(p_notification, p_reversed);
  713. } else {
  714. if (script_instance) {
  715. script_instance->notification(p_notification, p_reversed);
  716. }
  717. }
  718. }
  719. String Object::to_string() {
  720. if (script_instance) {
  721. bool valid;
  722. String ret = script_instance->to_string(&valid);
  723. if (valid) {
  724. return ret;
  725. }
  726. }
  727. if (_extension && _extension->to_string) {
  728. String ret;
  729. GDExtensionBool is_valid;
  730. _extension->to_string(_extension_instance, &is_valid, &ret);
  731. return ret;
  732. }
  733. return "<" + get_class() + "#" + itos(get_instance_id()) + ">";
  734. }
  735. void Object::set_script_and_instance(const Variant &p_script, ScriptInstance *p_instance) {
  736. //this function is not meant to be used in any of these ways
  737. ERR_FAIL_COND(p_script.is_null());
  738. ERR_FAIL_NULL(p_instance);
  739. ERR_FAIL_COND(script_instance != nullptr || !script.is_null());
  740. script = p_script;
  741. script_instance = p_instance;
  742. }
  743. void Object::set_script(const Variant &p_script) {
  744. if (script == p_script) {
  745. return;
  746. }
  747. Ref<Script> s = p_script;
  748. if (!p_script.is_null()) {
  749. ERR_FAIL_COND_MSG(s.is_null(), "Cannot set object script. Parameter should be null or a reference to a valid script.");
  750. ERR_FAIL_COND_MSG(s->is_abstract(), vformat("Cannot set object script. Script '%s' should not be abstract.", s->get_path()));
  751. }
  752. script = p_script;
  753. if (script_instance) {
  754. memdelete(script_instance);
  755. script_instance = nullptr;
  756. }
  757. if (!s.is_null()) {
  758. if (s->can_instantiate()) {
  759. OBJ_DEBUG_LOCK
  760. script_instance = s->instance_create(this);
  761. } else if (Engine::get_singleton()->is_editor_hint()) {
  762. OBJ_DEBUG_LOCK
  763. script_instance = s->placeholder_instance_create(this);
  764. }
  765. }
  766. notify_property_list_changed(); //scripts may add variables, so refresh is desired
  767. emit_signal(CoreStringNames::get_singleton()->script_changed);
  768. }
  769. void Object::set_script_instance(ScriptInstance *p_instance) {
  770. if (script_instance == p_instance) {
  771. return;
  772. }
  773. if (script_instance) {
  774. memdelete(script_instance);
  775. }
  776. script_instance = p_instance;
  777. if (p_instance) {
  778. script = p_instance->get_script();
  779. } else {
  780. script = Variant();
  781. }
  782. }
  783. Variant Object::get_script() const {
  784. return script;
  785. }
  786. bool Object::has_meta(const StringName &p_name) const {
  787. return metadata.has(p_name);
  788. }
  789. void Object::set_meta(const StringName &p_name, const Variant &p_value) {
  790. if (p_value.get_type() == Variant::NIL) {
  791. if (metadata.has(p_name)) {
  792. metadata.erase(p_name);
  793. const String &sname = p_name;
  794. metadata_properties.erase("metadata/" + sname);
  795. if (!sname.begins_with("_")) {
  796. // Metadata starting with _ don't show up in the inspector, so no need to update.
  797. notify_property_list_changed();
  798. }
  799. }
  800. return;
  801. }
  802. HashMap<StringName, Variant>::Iterator E = metadata.find(p_name);
  803. if (E) {
  804. E->value = p_value;
  805. } else {
  806. ERR_FAIL_COND_MSG(!p_name.operator String().is_valid_identifier(), "Invalid metadata identifier: '" + p_name + "'.");
  807. Variant *V = &metadata.insert(p_name, p_value)->value;
  808. const String &sname = p_name;
  809. metadata_properties["metadata/" + sname] = V;
  810. if (!sname.begins_with("_")) {
  811. notify_property_list_changed();
  812. }
  813. }
  814. }
  815. Variant Object::get_meta(const StringName &p_name, const Variant &p_default) const {
  816. if (!metadata.has(p_name)) {
  817. if (p_default != Variant()) {
  818. return p_default;
  819. } else {
  820. ERR_FAIL_V_MSG(Variant(), "The object does not have any 'meta' values with the key '" + p_name + "'.");
  821. }
  822. }
  823. return metadata[p_name];
  824. }
  825. void Object::remove_meta(const StringName &p_name) {
  826. set_meta(p_name, Variant());
  827. }
  828. TypedArray<Dictionary> Object::_get_property_list_bind() const {
  829. List<PropertyInfo> lpi;
  830. get_property_list(&lpi);
  831. return convert_property_list(&lpi);
  832. }
  833. TypedArray<Dictionary> Object::_get_method_list_bind() const {
  834. List<MethodInfo> ml;
  835. get_method_list(&ml);
  836. TypedArray<Dictionary> ret;
  837. for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) {
  838. Dictionary d = E->get();
  839. //va.push_back(d);
  840. ret.push_back(d);
  841. }
  842. return ret;
  843. }
  844. TypedArray<StringName> Object::_get_meta_list_bind() const {
  845. TypedArray<StringName> _metaret;
  846. for (const KeyValue<StringName, Variant> &K : metadata) {
  847. _metaret.push_back(K.key);
  848. }
  849. return _metaret;
  850. }
  851. void Object::get_meta_list(List<StringName> *p_list) const {
  852. for (const KeyValue<StringName, Variant> &K : metadata) {
  853. p_list->push_back(K.key);
  854. }
  855. }
  856. void Object::add_user_signal(const MethodInfo &p_signal) {
  857. ERR_FAIL_COND_MSG(p_signal.name.is_empty(), "Signal name cannot be empty.");
  858. 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() + "'.");
  859. ERR_FAIL_COND_MSG(signal_map.has(p_signal.name), "Trying to add already existing signal '" + p_signal.name + "'.");
  860. SignalData s;
  861. s.user = p_signal;
  862. signal_map[p_signal.name] = s;
  863. }
  864. bool Object::_has_user_signal(const StringName &p_name) const {
  865. if (!signal_map.has(p_name)) {
  866. return false;
  867. }
  868. return signal_map[p_name].user.name.length() > 0;
  869. }
  870. struct _ObjectSignalDisconnectData {
  871. StringName signal;
  872. Callable callable;
  873. };
  874. Error Object::_emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  875. r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
  876. ERR_FAIL_COND_V(p_argcount < 1, Error::ERR_INVALID_PARAMETER);
  877. if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) {
  878. r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
  879. r_error.argument = 0;
  880. r_error.expected = Variant::STRING_NAME;
  881. ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING, Error::ERR_INVALID_PARAMETER);
  882. }
  883. r_error.error = Callable::CallError::CALL_OK;
  884. StringName signal = *p_args[0];
  885. const Variant **args = nullptr;
  886. int argc = p_argcount - 1;
  887. if (argc) {
  888. args = &p_args[1];
  889. }
  890. return emit_signalp(signal, args, argc);
  891. }
  892. Error Object::emit_signalp(const StringName &p_name, const Variant **p_args, int p_argcount) {
  893. if (_block_signals) {
  894. return ERR_CANT_ACQUIRE_RESOURCE; //no emit, signals blocked
  895. }
  896. SignalData *s = signal_map.getptr(p_name);
  897. if (!s) {
  898. #ifdef DEBUG_ENABLED
  899. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name);
  900. //check in script
  901. 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 + "\".");
  902. #endif
  903. //not connected? just return
  904. return ERR_UNAVAILABLE;
  905. }
  906. // If this is a ref-counted object, prevent it from being destroyed during signal emission,
  907. // which is needed in certain edge cases; e.g., https://github.com/godotengine/godot/issues/73889.
  908. Ref<RefCounted> rc = Ref<RefCounted>(Object::cast_to<RefCounted>(this));
  909. List<_ObjectSignalDisconnectData> disconnect_data;
  910. // Ensure that disconnecting the signal or even deleting the object
  911. // will not affect the signal calling.
  912. LocalVector<Connection> slot_conns;
  913. slot_conns.resize(s->slot_map.size());
  914. {
  915. uint32_t idx = 0;
  916. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  917. slot_conns[idx++] = slot_kv.value.conn;
  918. }
  919. DEV_ASSERT(idx == s->slot_map.size());
  920. }
  921. OBJ_DEBUG_LOCK
  922. Error err = OK;
  923. for (const Connection &c : slot_conns) {
  924. Object *target = c.callable.get_object();
  925. if (!target) {
  926. // Target might have been deleted during signal callback, this is expected and OK.
  927. continue;
  928. }
  929. const Variant **args = p_args;
  930. int argc = p_argcount;
  931. if (c.flags & CONNECT_DEFERRED) {
  932. MessageQueue::get_singleton()->push_callablep(c.callable, args, argc, true);
  933. } else {
  934. Callable::CallError ce;
  935. _emitting = true;
  936. Variant ret;
  937. c.callable.callp(args, argc, ret, ce);
  938. _emitting = false;
  939. if (ce.error != Callable::CallError::CALL_OK) {
  940. #ifdef DEBUG_ENABLED
  941. if (c.flags & CONNECT_PERSIST && Engine::get_singleton()->is_editor_hint() && (script.is_null() || !Ref<Script>(script)->is_tool())) {
  942. continue;
  943. }
  944. #endif
  945. if (ce.error == Callable::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists(target->get_class_name())) {
  946. //most likely object is not initialized yet, do not throw error.
  947. } else {
  948. ERR_PRINT("Error calling from signal '" + String(p_name) + "' to callable: " + Variant::get_callable_error_text(c.callable, args, argc, ce) + ".");
  949. err = ERR_METHOD_NOT_FOUND;
  950. }
  951. }
  952. }
  953. bool disconnect = c.flags & CONNECT_ONE_SHOT;
  954. #ifdef TOOLS_ENABLED
  955. if (disconnect && (c.flags & CONNECT_PERSIST) && Engine::get_singleton()->is_editor_hint()) {
  956. //this signal was connected from the editor, and is being edited. just don't disconnect for now
  957. disconnect = false;
  958. }
  959. #endif
  960. if (disconnect) {
  961. _ObjectSignalDisconnectData dd;
  962. dd.signal = p_name;
  963. dd.callable = c.callable;
  964. disconnect_data.push_back(dd);
  965. }
  966. }
  967. while (!disconnect_data.is_empty()) {
  968. const _ObjectSignalDisconnectData &dd = disconnect_data.front()->get();
  969. _disconnect(dd.signal, dd.callable);
  970. disconnect_data.pop_front();
  971. }
  972. return err;
  973. }
  974. void Object::_add_user_signal(const String &p_name, const Array &p_args) {
  975. // this version of add_user_signal is meant to be used from scripts or external apis
  976. // without access to ADD_SIGNAL in bind_methods
  977. // added events are per instance, as opposed to the other ones, which are global
  978. MethodInfo mi;
  979. mi.name = p_name;
  980. for (int i = 0; i < p_args.size(); i++) {
  981. Dictionary d = p_args[i];
  982. PropertyInfo param;
  983. if (d.has("name")) {
  984. param.name = d["name"];
  985. }
  986. if (d.has("type")) {
  987. param.type = (Variant::Type)(int)d["type"];
  988. }
  989. mi.arguments.push_back(param);
  990. }
  991. add_user_signal(mi);
  992. }
  993. TypedArray<Dictionary> Object::_get_signal_list() const {
  994. List<MethodInfo> signal_list;
  995. get_signal_list(&signal_list);
  996. TypedArray<Dictionary> ret;
  997. for (const MethodInfo &E : signal_list) {
  998. ret.push_back(Dictionary(E));
  999. }
  1000. return ret;
  1001. }
  1002. TypedArray<Dictionary> Object::_get_signal_connection_list(const StringName &p_signal) const {
  1003. List<Connection> conns;
  1004. get_all_signal_connections(&conns);
  1005. TypedArray<Dictionary> ret;
  1006. for (const Connection &c : conns) {
  1007. if (c.signal.get_name() == p_signal) {
  1008. ret.push_back(c);
  1009. }
  1010. }
  1011. return ret;
  1012. }
  1013. TypedArray<Dictionary> Object::_get_incoming_connections() const {
  1014. TypedArray<Dictionary> ret;
  1015. int connections_amount = connections.size();
  1016. for (int idx_conn = 0; idx_conn < connections_amount; idx_conn++) {
  1017. ret.push_back(connections[idx_conn]);
  1018. }
  1019. return ret;
  1020. }
  1021. bool Object::has_signal(const StringName &p_name) const {
  1022. if (!script.is_null()) {
  1023. Ref<Script> scr = script;
  1024. if (scr.is_valid() && scr->has_script_signal(p_name)) {
  1025. return true;
  1026. }
  1027. }
  1028. if (ClassDB::has_signal(get_class_name(), p_name)) {
  1029. return true;
  1030. }
  1031. if (_has_user_signal(p_name)) {
  1032. return true;
  1033. }
  1034. return false;
  1035. }
  1036. void Object::get_signal_list(List<MethodInfo> *p_signals) const {
  1037. if (!script.is_null()) {
  1038. Ref<Script> scr = script;
  1039. if (scr.is_valid()) {
  1040. scr->get_script_signal_list(p_signals);
  1041. }
  1042. }
  1043. ClassDB::get_signal_list(get_class_name(), p_signals);
  1044. //find maybe usersignals?
  1045. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1046. if (!E.value.user.name.is_empty()) {
  1047. //user signal
  1048. p_signals->push_back(E.value.user);
  1049. }
  1050. }
  1051. }
  1052. void Object::get_all_signal_connections(List<Connection> *p_connections) const {
  1053. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1054. const SignalData *s = &E.value;
  1055. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1056. p_connections->push_back(slot_kv.value.conn);
  1057. }
  1058. }
  1059. }
  1060. void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const {
  1061. const SignalData *s = signal_map.getptr(p_signal);
  1062. if (!s) {
  1063. return; //nothing
  1064. }
  1065. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1066. p_connections->push_back(slot_kv.value.conn);
  1067. }
  1068. }
  1069. int Object::get_persistent_signal_connection_count() const {
  1070. int count = 0;
  1071. for (const KeyValue<StringName, SignalData> &E : signal_map) {
  1072. const SignalData *s = &E.value;
  1073. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1074. if (slot_kv.value.conn.flags & CONNECT_PERSIST) {
  1075. count += 1;
  1076. }
  1077. }
  1078. }
  1079. return count;
  1080. }
  1081. void Object::get_signals_connected_to_this(List<Connection> *p_connections) const {
  1082. for (const Connection &E : connections) {
  1083. p_connections->push_back(E);
  1084. }
  1085. }
  1086. Error Object::connect(const StringName &p_signal, const Callable &p_callable, uint32_t p_flags) {
  1087. ERR_FAIL_COND_V_MSG(p_callable.is_null(), ERR_INVALID_PARAMETER, "Cannot connect to '" + p_signal + "': the provided callable is null.");
  1088. Object *target_object = p_callable.get_object();
  1089. ERR_FAIL_NULL_V_MSG(target_object, ERR_INVALID_PARAMETER, "Cannot connect to '" + p_signal + "' to callable '" + p_callable + "': the callable object is null.");
  1090. SignalData *s = signal_map.getptr(p_signal);
  1091. if (!s) {
  1092. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1093. //check in script
  1094. if (!signal_is_valid && !script.is_null()) {
  1095. if (Ref<Script>(script)->has_script_signal(p_signal)) {
  1096. signal_is_valid = true;
  1097. }
  1098. #ifdef TOOLS_ENABLED
  1099. else {
  1100. //allow connecting signals anyway if script is invalid, see issue #17070
  1101. if (!Ref<Script>(script)->is_valid()) {
  1102. signal_is_valid = true;
  1103. }
  1104. }
  1105. #endif
  1106. }
  1107. 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 + "'.");
  1108. signal_map[p_signal] = SignalData();
  1109. s = &signal_map[p_signal];
  1110. }
  1111. Callable target = p_callable;
  1112. //compare with the base callable, so binds can be ignored
  1113. if (s->slot_map.has(*target.get_base_comparator())) {
  1114. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1115. s->slot_map[*target.get_base_comparator()].reference_count++;
  1116. return OK;
  1117. } else {
  1118. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Signal '" + p_signal + "' is already connected to given callable '" + p_callable + "' in that object.");
  1119. }
  1120. }
  1121. SignalData::Slot slot;
  1122. Connection conn;
  1123. conn.callable = target;
  1124. conn.signal = ::Signal(this, p_signal);
  1125. conn.flags = p_flags;
  1126. slot.conn = conn;
  1127. slot.cE = target_object->connections.push_back(conn);
  1128. if (p_flags & CONNECT_REFERENCE_COUNTED) {
  1129. slot.reference_count = 1;
  1130. }
  1131. //use callable version as key, so binds can be ignored
  1132. s->slot_map[*target.get_base_comparator()] = slot;
  1133. return OK;
  1134. }
  1135. bool Object::is_connected(const StringName &p_signal, const Callable &p_callable) const {
  1136. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, "Cannot determine if connected to '" + p_signal + "': the provided callable is null.");
  1137. const SignalData *s = signal_map.getptr(p_signal);
  1138. if (!s) {
  1139. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
  1140. if (signal_is_valid) {
  1141. return false;
  1142. }
  1143. if (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal)) {
  1144. return false;
  1145. }
  1146. ERR_FAIL_V_MSG(false, "Nonexistent signal: " + p_signal + ".");
  1147. }
  1148. Callable target = p_callable;
  1149. return s->slot_map.has(*target.get_base_comparator());
  1150. }
  1151. void Object::disconnect(const StringName &p_signal, const Callable &p_callable) {
  1152. _disconnect(p_signal, p_callable);
  1153. }
  1154. bool Object::_disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force) {
  1155. ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, "Cannot disconnect from '" + p_signal + "': the provided callable is null.");
  1156. Object *target_object = p_callable.get_object();
  1157. ERR_FAIL_NULL_V_MSG(target_object, false, "Cannot disconnect '" + p_signal + "' from callable '" + p_callable + "': the callable object is null.");
  1158. SignalData *s = signal_map.getptr(p_signal);
  1159. if (!s) {
  1160. bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal) ||
  1161. (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal));
  1162. ERR_FAIL_COND_V_MSG(signal_is_valid, false, "Attempt to disconnect a nonexistent connection from '" + to_string() + "'. Signal: '" + p_signal + "', callable: '" + p_callable + "'.");
  1163. }
  1164. ERR_FAIL_NULL_V_MSG(s, false, vformat("Disconnecting nonexistent signal '%s' in %s.", p_signal, to_string()));
  1165. 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 + "'.");
  1166. SignalData::Slot *slot = &s->slot_map[*p_callable.get_base_comparator()];
  1167. if (!p_force) {
  1168. slot->reference_count--; // by default is zero, if it was not referenced it will go below it
  1169. if (slot->reference_count > 0) {
  1170. return false;
  1171. }
  1172. }
  1173. target_object->connections.erase(slot->cE);
  1174. s->slot_map.erase(*p_callable.get_base_comparator());
  1175. if (s->slot_map.is_empty() && ClassDB::has_signal(get_class_name(), p_signal)) {
  1176. //not user signal, delete
  1177. signal_map.erase(p_signal);
  1178. }
  1179. return true;
  1180. }
  1181. void Object::_set_bind(const StringName &p_set, const Variant &p_value) {
  1182. set(p_set, p_value);
  1183. }
  1184. Variant Object::_get_bind(const StringName &p_name) const {
  1185. return get(p_name);
  1186. }
  1187. void Object::_set_indexed_bind(const NodePath &p_name, const Variant &p_value) {
  1188. set_indexed(p_name.get_as_property_path().get_subnames(), p_value);
  1189. }
  1190. Variant Object::_get_indexed_bind(const NodePath &p_name) const {
  1191. return get_indexed(p_name.get_as_property_path().get_subnames());
  1192. }
  1193. void Object::initialize_class() {
  1194. static bool initialized = false;
  1195. if (initialized) {
  1196. return;
  1197. }
  1198. ClassDB::_add_class<Object>();
  1199. _bind_methods();
  1200. initialized = true;
  1201. }
  1202. String Object::tr(const StringName &p_message, const StringName &p_context) const {
  1203. if (!_can_translate || !TranslationServer::get_singleton()) {
  1204. return p_message;
  1205. }
  1206. if (Engine::get_singleton()->is_editor_hint()) {
  1207. return TranslationServer::get_singleton()->tool_translate(p_message, p_context);
  1208. } else {
  1209. return TranslationServer::get_singleton()->translate(p_message, p_context);
  1210. }
  1211. }
  1212. String Object::tr_n(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  1213. if (!_can_translate || !TranslationServer::get_singleton()) {
  1214. // Return message based on English plural rule if translation is not possible.
  1215. if (p_n == 1) {
  1216. return p_message;
  1217. }
  1218. return p_message_plural;
  1219. }
  1220. if (Engine::get_singleton()->is_editor_hint()) {
  1221. return TranslationServer::get_singleton()->tool_translate_plural(p_message, p_message_plural, p_n, p_context);
  1222. } else {
  1223. return TranslationServer::get_singleton()->translate_plural(p_message, p_message_plural, p_n, p_context);
  1224. }
  1225. }
  1226. void Object::_clear_internal_resource_paths(const Variant &p_var) {
  1227. switch (p_var.get_type()) {
  1228. case Variant::OBJECT: {
  1229. Ref<Resource> r = p_var;
  1230. if (!r.is_valid()) {
  1231. return;
  1232. }
  1233. if (!r->is_built_in()) {
  1234. return; //not an internal resource
  1235. }
  1236. Object *object = p_var;
  1237. if (!object) {
  1238. return;
  1239. }
  1240. r->set_path("");
  1241. r->clear_internal_resource_paths();
  1242. } break;
  1243. case Variant::ARRAY: {
  1244. Array a = p_var;
  1245. for (int i = 0; i < a.size(); i++) {
  1246. _clear_internal_resource_paths(a[i]);
  1247. }
  1248. } break;
  1249. case Variant::DICTIONARY: {
  1250. Dictionary d = p_var;
  1251. List<Variant> keys;
  1252. d.get_key_list(&keys);
  1253. for (const Variant &E : keys) {
  1254. _clear_internal_resource_paths(E);
  1255. _clear_internal_resource_paths(d[E]);
  1256. }
  1257. } break;
  1258. default: {
  1259. }
  1260. }
  1261. }
  1262. #ifdef TOOLS_ENABLED
  1263. void Object::editor_set_section_unfold(const String &p_section, bool p_unfolded) {
  1264. set_edited(true);
  1265. if (p_unfolded) {
  1266. editor_section_folding.insert(p_section);
  1267. } else {
  1268. editor_section_folding.erase(p_section);
  1269. }
  1270. }
  1271. bool Object::editor_is_section_unfolded(const String &p_section) {
  1272. return editor_section_folding.has(p_section);
  1273. }
  1274. #endif
  1275. void Object::clear_internal_resource_paths() {
  1276. List<PropertyInfo> pinfo;
  1277. get_property_list(&pinfo);
  1278. for (const PropertyInfo &E : pinfo) {
  1279. _clear_internal_resource_paths(get(E.name));
  1280. }
  1281. }
  1282. void Object::notify_property_list_changed() {
  1283. emit_signal(CoreStringNames::get_singleton()->property_list_changed);
  1284. }
  1285. void Object::_bind_methods() {
  1286. ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class);
  1287. ClassDB::bind_method(D_METHOD("is_class", "class"), &Object::is_class);
  1288. ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind);
  1289. ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind);
  1290. ClassDB::bind_method(D_METHOD("set_indexed", "property_path", "value"), &Object::_set_indexed_bind);
  1291. ClassDB::bind_method(D_METHOD("get_indexed", "property_path"), &Object::_get_indexed_bind);
  1292. ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind);
  1293. ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind);
  1294. ClassDB::bind_method(D_METHOD("property_can_revert", "property"), &Object::property_can_revert);
  1295. ClassDB::bind_method(D_METHOD("property_get_revert", "property"), &Object::property_get_revert);
  1296. ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false));
  1297. ClassDB::bind_method(D_METHOD("to_string"), &Object::to_string);
  1298. ClassDB::bind_method(D_METHOD("get_instance_id"), &Object::get_instance_id);
  1299. ClassDB::bind_method(D_METHOD("set_script", "script"), &Object::set_script);
  1300. ClassDB::bind_method(D_METHOD("get_script"), &Object::get_script);
  1301. ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta);
  1302. ClassDB::bind_method(D_METHOD("remove_meta", "name"), &Object::remove_meta);
  1303. ClassDB::bind_method(D_METHOD("get_meta", "name", "default"), &Object::get_meta, DEFVAL(Variant()));
  1304. ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta);
  1305. ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind);
  1306. ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array()));
  1307. ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal);
  1308. {
  1309. MethodInfo mi;
  1310. mi.name = "emit_signal";
  1311. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "signal"));
  1312. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi, varray(), false);
  1313. }
  1314. {
  1315. MethodInfo mi;
  1316. mi.name = "call";
  1317. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1318. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call", &Object::_call_bind, mi);
  1319. }
  1320. {
  1321. MethodInfo mi;
  1322. mi.name = "call_deferred";
  1323. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1324. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi, varray(), false);
  1325. }
  1326. ClassDB::bind_method(D_METHOD("set_deferred", "property", "value"), &Object::set_deferred);
  1327. ClassDB::bind_method(D_METHOD("callv", "method", "arg_array"), &Object::callv);
  1328. ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method);
  1329. ClassDB::bind_method(D_METHOD("has_signal", "signal"), &Object::has_signal);
  1330. ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list);
  1331. ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list);
  1332. ClassDB::bind_method(D_METHOD("get_incoming_connections"), &Object::_get_incoming_connections);
  1333. ClassDB::bind_method(D_METHOD("connect", "signal", "callable", "flags"), &Object::connect, DEFVAL(0));
  1334. ClassDB::bind_method(D_METHOD("disconnect", "signal", "callable"), &Object::disconnect);
  1335. ClassDB::bind_method(D_METHOD("is_connected", "signal", "callable"), &Object::is_connected);
  1336. ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals);
  1337. ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals);
  1338. ClassDB::bind_method(D_METHOD("notify_property_list_changed"), &Object::notify_property_list_changed);
  1339. ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation);
  1340. ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages);
  1341. ClassDB::bind_method(D_METHOD("tr", "message", "context"), &Object::tr, DEFVAL(""));
  1342. ClassDB::bind_method(D_METHOD("tr_n", "message", "plural_message", "n", "context"), &Object::tr_n, DEFVAL(""));
  1343. ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion);
  1344. ClassDB::bind_method(D_METHOD("cancel_free"), &Object::cancel_free);
  1345. ClassDB::add_virtual_method("Object", MethodInfo("free"), false);
  1346. ADD_SIGNAL(MethodInfo("script_changed"));
  1347. ADD_SIGNAL(MethodInfo("property_list_changed"));
  1348. #define BIND_OBJ_CORE_METHOD(m_method) \
  1349. ::ClassDB::add_virtual_method(get_class_static(), m_method, true, Vector<String>(), true);
  1350. MethodInfo notification_mi("_notification", PropertyInfo(Variant::INT, "what"));
  1351. notification_mi.arguments_metadata.push_back(GodotTypeInfo::Metadata::METADATA_INT_IS_INT32);
  1352. BIND_OBJ_CORE_METHOD(notification_mi);
  1353. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_set", PropertyInfo(Variant::STRING_NAME, "property"), PropertyInfo(Variant::NIL, "value")));
  1354. #ifdef TOOLS_ENABLED
  1355. MethodInfo miget("_get", PropertyInfo(Variant::STRING_NAME, "property"));
  1356. miget.return_val.name = "Variant";
  1357. miget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1358. BIND_OBJ_CORE_METHOD(miget);
  1359. MethodInfo plget("_get_property_list");
  1360. plget.return_val.type = Variant::ARRAY;
  1361. plget.return_val.hint = PROPERTY_HINT_ARRAY_TYPE;
  1362. plget.return_val.hint_string = "Dictionary";
  1363. BIND_OBJ_CORE_METHOD(plget);
  1364. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::NIL, "_validate_property", PropertyInfo(Variant::DICTIONARY, "property")));
  1365. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_property_can_revert", PropertyInfo(Variant::STRING_NAME, "property")));
  1366. MethodInfo mipgr("_property_get_revert", PropertyInfo(Variant::STRING_NAME, "property"));
  1367. mipgr.return_val.name = "Variant";
  1368. mipgr.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  1369. BIND_OBJ_CORE_METHOD(mipgr);
  1370. #endif
  1371. BIND_OBJ_CORE_METHOD(MethodInfo("_init"));
  1372. BIND_OBJ_CORE_METHOD(MethodInfo(Variant::STRING, "_to_string"));
  1373. BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE);
  1374. BIND_CONSTANT(NOTIFICATION_PREDELETE);
  1375. BIND_ENUM_CONSTANT(CONNECT_DEFERRED);
  1376. BIND_ENUM_CONSTANT(CONNECT_PERSIST);
  1377. BIND_ENUM_CONSTANT(CONNECT_ONE_SHOT);
  1378. BIND_ENUM_CONSTANT(CONNECT_REFERENCE_COUNTED);
  1379. }
  1380. void Object::set_deferred(const StringName &p_property, const Variant &p_value) {
  1381. MessageQueue::get_singleton()->push_set(this, p_property, p_value);
  1382. }
  1383. void Object::set_block_signals(bool p_block) {
  1384. _block_signals = p_block;
  1385. }
  1386. bool Object::is_blocking_signals() const {
  1387. return _block_signals;
  1388. }
  1389. Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const {
  1390. bool valid;
  1391. Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid);
  1392. if (valid) {
  1393. if (r_valid) {
  1394. *r_valid = true;
  1395. }
  1396. return t;
  1397. }
  1398. if (get_script_instance()) {
  1399. return get_script_instance()->get_property_type(p_property, r_valid);
  1400. }
  1401. if (r_valid) {
  1402. *r_valid = false;
  1403. }
  1404. return Variant::NIL;
  1405. }
  1406. Variant::Type Object::get_static_property_type_indexed(const Vector<StringName> &p_path, bool *r_valid) const {
  1407. if (p_path.size() == 0) {
  1408. if (r_valid) {
  1409. *r_valid = false;
  1410. }
  1411. return Variant::NIL;
  1412. }
  1413. bool valid = false;
  1414. Variant::Type t = get_static_property_type(p_path[0], &valid);
  1415. if (!valid) {
  1416. if (r_valid) {
  1417. *r_valid = false;
  1418. }
  1419. return Variant::NIL;
  1420. }
  1421. Callable::CallError ce;
  1422. Variant check;
  1423. Variant::construct(t, check, nullptr, 0, ce);
  1424. for (int i = 1; i < p_path.size(); i++) {
  1425. if (check.get_type() == Variant::OBJECT || check.get_type() == Variant::DICTIONARY || check.get_type() == Variant::ARRAY) {
  1426. // We cannot be sure about the type of properties this type can have
  1427. if (r_valid) {
  1428. *r_valid = false;
  1429. }
  1430. return Variant::NIL;
  1431. }
  1432. check = check.get_named(p_path[i], valid);
  1433. if (!valid) {
  1434. if (r_valid) {
  1435. *r_valid = false;
  1436. }
  1437. return Variant::NIL;
  1438. }
  1439. }
  1440. if (r_valid) {
  1441. *r_valid = true;
  1442. }
  1443. return check.get_type();
  1444. }
  1445. bool Object::is_queued_for_deletion() const {
  1446. return _is_queued_for_deletion;
  1447. }
  1448. #ifdef TOOLS_ENABLED
  1449. void Object::set_edited(bool p_edited) {
  1450. _edited = p_edited;
  1451. _edited_version++;
  1452. }
  1453. bool Object::is_edited() const {
  1454. return _edited;
  1455. }
  1456. uint32_t Object::get_edited_version() const {
  1457. return _edited_version;
  1458. }
  1459. #endif
  1460. StringName Object::get_class_name_for_extension(const GDExtension *p_library) const {
  1461. // Only return the class name per the extension if it matches the given p_library.
  1462. if (_extension && _extension->library == p_library) {
  1463. return _extension->class_name;
  1464. }
  1465. // Extensions only have wrapper classes for classes exposed in ClassDB.
  1466. const StringName *class_name = _get_class_namev();
  1467. if (ClassDB::is_class_exposed(*class_name)) {
  1468. return *class_name;
  1469. }
  1470. // Find the nearest parent class that's exposed.
  1471. StringName parent_class = ClassDB::get_parent_class(*class_name);
  1472. while (parent_class != StringName()) {
  1473. if (ClassDB::is_class_exposed(parent_class)) {
  1474. return parent_class;
  1475. }
  1476. parent_class = ClassDB::get_parent_class(parent_class);
  1477. }
  1478. return SNAME("Object");
  1479. }
  1480. void Object::set_instance_binding(void *p_token, void *p_binding, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  1481. // This is only meant to be used on creation by the binder, but we also
  1482. // need to account for reloading (where the 'binding' will be cleared).
  1483. ERR_FAIL_COND(_instance_bindings != nullptr && _instance_bindings[0].binding != nullptr);
  1484. if (_instance_bindings == nullptr) {
  1485. _instance_bindings = (InstanceBinding *)memalloc(sizeof(InstanceBinding));
  1486. _instance_binding_count = 1;
  1487. }
  1488. _instance_bindings[0].binding = p_binding;
  1489. _instance_bindings[0].free_callback = p_callbacks->free_callback;
  1490. _instance_bindings[0].reference_callback = p_callbacks->reference_callback;
  1491. _instance_bindings[0].token = p_token;
  1492. }
  1493. void *Object::get_instance_binding(void *p_token, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  1494. void *binding = nullptr;
  1495. _instance_binding_mutex.lock();
  1496. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1497. if (_instance_bindings[i].token == p_token) {
  1498. binding = _instance_bindings[i].binding;
  1499. break;
  1500. }
  1501. }
  1502. if (unlikely(!binding && p_callbacks)) {
  1503. uint32_t current_size = next_power_of_2(_instance_binding_count);
  1504. uint32_t new_size = next_power_of_2(_instance_binding_count + 1);
  1505. if (current_size == 0 || new_size > current_size) {
  1506. _instance_bindings = (InstanceBinding *)memrealloc(_instance_bindings, new_size * sizeof(InstanceBinding));
  1507. }
  1508. _instance_bindings[_instance_binding_count].free_callback = p_callbacks->free_callback;
  1509. _instance_bindings[_instance_binding_count].reference_callback = p_callbacks->reference_callback;
  1510. _instance_bindings[_instance_binding_count].token = p_token;
  1511. binding = p_callbacks->create_callback(p_token, this);
  1512. _instance_bindings[_instance_binding_count].binding = binding;
  1513. #ifdef TOOLS_ENABLED
  1514. if (!_extension && Engine::get_singleton()->is_extension_reloading_enabled()) {
  1515. GDExtensionManager::get_singleton()->track_instance_binding(p_token, this);
  1516. }
  1517. #endif
  1518. _instance_binding_count++;
  1519. }
  1520. _instance_binding_mutex.unlock();
  1521. return binding;
  1522. }
  1523. bool Object::has_instance_binding(void *p_token) {
  1524. bool found = false;
  1525. _instance_binding_mutex.lock();
  1526. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1527. if (_instance_bindings[i].token == p_token) {
  1528. found = true;
  1529. break;
  1530. }
  1531. }
  1532. _instance_binding_mutex.unlock();
  1533. return found;
  1534. }
  1535. #ifdef TOOLS_ENABLED
  1536. void Object::free_instance_binding(void *p_token) {
  1537. bool found = false;
  1538. _instance_binding_mutex.lock();
  1539. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1540. if (!found && _instance_bindings[i].token == p_token) {
  1541. if (_instance_bindings[i].free_callback) {
  1542. _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
  1543. }
  1544. found = true;
  1545. }
  1546. if (found) {
  1547. if (i + 1 < _instance_binding_count) {
  1548. _instance_bindings[i] = _instance_bindings[i + 1];
  1549. } else {
  1550. _instance_bindings[i] = { nullptr };
  1551. }
  1552. }
  1553. }
  1554. if (found) {
  1555. _instance_binding_count--;
  1556. }
  1557. _instance_binding_mutex.unlock();
  1558. }
  1559. void Object::clear_internal_extension() {
  1560. ERR_FAIL_NULL(_extension);
  1561. // Free the instance inside the GDExtension.
  1562. if (_extension->free_instance) {
  1563. _extension->free_instance(_extension->class_userdata, _extension_instance);
  1564. }
  1565. _extension = nullptr;
  1566. _extension_instance = nullptr;
  1567. // Clear the instance bindings.
  1568. _instance_binding_mutex.lock();
  1569. if (_instance_bindings[0].free_callback) {
  1570. _instance_bindings[0].free_callback(_instance_bindings[0].token, this, _instance_bindings[0].binding);
  1571. }
  1572. _instance_bindings[0].binding = nullptr;
  1573. _instance_bindings[0].token = nullptr;
  1574. _instance_bindings[0].free_callback = nullptr;
  1575. _instance_bindings[0].reference_callback = nullptr;
  1576. _instance_binding_mutex.unlock();
  1577. // Clear the virtual methods.
  1578. while (virtual_method_list) {
  1579. (*virtual_method_list->method) = nullptr;
  1580. (*virtual_method_list->initialized) = false;
  1581. virtual_method_list = virtual_method_list->next;
  1582. }
  1583. }
  1584. void Object::reset_internal_extension(ObjectGDExtension *p_extension) {
  1585. ERR_FAIL_COND(_extension != nullptr);
  1586. if (p_extension) {
  1587. _extension_instance = p_extension->recreate_instance ? p_extension->recreate_instance(p_extension->class_userdata, (GDExtensionObjectPtr)this) : nullptr;
  1588. ERR_FAIL_NULL_MSG(_extension_instance, "Unable to recreate GDExtension instance - does this extension support hot reloading?");
  1589. _extension = p_extension;
  1590. }
  1591. }
  1592. #endif
  1593. void Object::_construct_object(bool p_reference) {
  1594. type_is_reference = p_reference;
  1595. _instance_id = ObjectDB::add_instance(this);
  1596. #ifdef DEBUG_ENABLED
  1597. _lock_index.init(1);
  1598. #endif
  1599. }
  1600. Object::Object(bool p_reference) {
  1601. _construct_object(p_reference);
  1602. }
  1603. Object::Object() {
  1604. _construct_object(false);
  1605. }
  1606. void Object::detach_from_objectdb() {
  1607. if (_instance_id != ObjectID()) {
  1608. ObjectDB::remove_instance(this);
  1609. _instance_id = ObjectID();
  1610. }
  1611. }
  1612. Object::~Object() {
  1613. if (script_instance) {
  1614. memdelete(script_instance);
  1615. }
  1616. script_instance = nullptr;
  1617. if (_extension) {
  1618. #ifdef TOOLS_ENABLED
  1619. if (_extension->untrack_instance) {
  1620. _extension->untrack_instance(_extension->tracking_userdata, this);
  1621. }
  1622. #endif
  1623. if (_extension->free_instance) {
  1624. _extension->free_instance(_extension->class_userdata, _extension_instance);
  1625. }
  1626. _extension = nullptr;
  1627. _extension_instance = nullptr;
  1628. }
  1629. #ifdef TOOLS_ENABLED
  1630. else if (_instance_bindings != nullptr && Engine::get_singleton()->is_extension_reloading_enabled()) {
  1631. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1632. GDExtensionManager::get_singleton()->untrack_instance_binding(_instance_bindings[i].token, this);
  1633. }
  1634. }
  1635. #endif
  1636. if (_emitting) {
  1637. //@todo this may need to actually reach the debugger prioritarily somehow because it may crash before
  1638. 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.");
  1639. }
  1640. // Drop all connections to the signals of this object.
  1641. while (signal_map.size()) {
  1642. // Avoid regular iteration so erasing is safe.
  1643. KeyValue<StringName, SignalData> &E = *signal_map.begin();
  1644. SignalData *s = &E.value;
  1645. for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
  1646. Object *target = slot_kv.value.conn.callable.get_object();
  1647. if (likely(target)) {
  1648. target->connections.erase(slot_kv.value.cE);
  1649. }
  1650. }
  1651. signal_map.erase(E.key);
  1652. }
  1653. // Disconnect signals that connect to this object.
  1654. while (connections.size()) {
  1655. Connection c = connections.front()->get();
  1656. bool disconnected = c.signal.get_object()->_disconnect(c.signal.get_name(), c.callable, true);
  1657. if (unlikely(!disconnected)) {
  1658. // If the disconnect has failed, abandon the connection to avoid getting trapped in an infinite loop here.
  1659. connections.pop_front();
  1660. }
  1661. }
  1662. if (_instance_id != ObjectID()) {
  1663. ObjectDB::remove_instance(this);
  1664. _instance_id = ObjectID();
  1665. }
  1666. _predelete_ok = 2;
  1667. if (_instance_bindings != nullptr) {
  1668. for (uint32_t i = 0; i < _instance_binding_count; i++) {
  1669. if (_instance_bindings[i].free_callback) {
  1670. _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
  1671. }
  1672. }
  1673. memfree(_instance_bindings);
  1674. }
  1675. }
  1676. bool predelete_handler(Object *p_object) {
  1677. return p_object->_predelete();
  1678. }
  1679. void postinitialize_handler(Object *p_object) {
  1680. p_object->_postinitialize();
  1681. }
  1682. void ObjectDB::debug_objects(DebugFunc p_func) {
  1683. spin_lock.lock();
  1684. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  1685. if (object_slots[i].validator) {
  1686. p_func(object_slots[i].object);
  1687. count--;
  1688. }
  1689. }
  1690. spin_lock.unlock();
  1691. }
  1692. void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  1693. if (p_idx == 0) {
  1694. if (p_function == "connect" || p_function == "is_connected" || p_function == "disconnect" || p_function == "emit_signal" || p_function == "has_signal") {
  1695. List<MethodInfo> signals;
  1696. get_signal_list(&signals);
  1697. for (const MethodInfo &E : signals) {
  1698. r_options->push_back(E.name.quote());
  1699. }
  1700. } else if (p_function == "call" || p_function == "call_deferred" || p_function == "callv" || p_function == "has_method") {
  1701. List<MethodInfo> methods;
  1702. get_method_list(&methods);
  1703. for (const MethodInfo &E : methods) {
  1704. if (E.name.begins_with("_") && !(E.flags & METHOD_FLAG_VIRTUAL)) {
  1705. continue;
  1706. }
  1707. r_options->push_back(E.name.quote());
  1708. }
  1709. } else if (p_function == "set" || p_function == "set_deferred" || p_function == "get") {
  1710. List<PropertyInfo> properties;
  1711. get_property_list(&properties);
  1712. for (const PropertyInfo &E : properties) {
  1713. if (E.usage & PROPERTY_USAGE_DEFAULT && !(E.usage & PROPERTY_USAGE_INTERNAL)) {
  1714. r_options->push_back(E.name.quote());
  1715. }
  1716. }
  1717. } else if (p_function == "set_meta" || p_function == "get_meta" || p_function == "has_meta" || p_function == "remove_meta") {
  1718. for (const KeyValue<StringName, Variant> &K : metadata) {
  1719. r_options->push_back(String(K.key).quote());
  1720. }
  1721. }
  1722. } else if (p_idx == 2) {
  1723. if (p_function == "connect") {
  1724. // Ideally, the constants should be inferred by the parameter.
  1725. // But a parameter's PropertyInfo does not store the enum they come from, so this will do for now.
  1726. List<StringName> constants;
  1727. ClassDB::get_enum_constants("Object", "ConnectFlags", &constants);
  1728. for (const StringName &E : constants) {
  1729. r_options->push_back(String(E));
  1730. }
  1731. }
  1732. }
  1733. }
  1734. SpinLock ObjectDB::spin_lock;
  1735. uint32_t ObjectDB::slot_count = 0;
  1736. uint32_t ObjectDB::slot_max = 0;
  1737. ObjectDB::ObjectSlot *ObjectDB::object_slots = nullptr;
  1738. uint64_t ObjectDB::validator_counter = 0;
  1739. int ObjectDB::get_object_count() {
  1740. return slot_count;
  1741. }
  1742. ObjectID ObjectDB::add_instance(Object *p_object) {
  1743. spin_lock.lock();
  1744. if (unlikely(slot_count == slot_max)) {
  1745. CRASH_COND(slot_count == (1 << OBJECTDB_SLOT_MAX_COUNT_BITS));
  1746. uint32_t new_slot_max = slot_max > 0 ? slot_max * 2 : 1;
  1747. object_slots = (ObjectSlot *)memrealloc(object_slots, sizeof(ObjectSlot) * new_slot_max);
  1748. for (uint32_t i = slot_max; i < new_slot_max; i++) {
  1749. object_slots[i].object = nullptr;
  1750. object_slots[i].is_ref_counted = false;
  1751. object_slots[i].next_free = i;
  1752. object_slots[i].validator = 0;
  1753. }
  1754. slot_max = new_slot_max;
  1755. }
  1756. uint32_t slot = object_slots[slot_count].next_free;
  1757. if (object_slots[slot].object != nullptr) {
  1758. spin_lock.unlock();
  1759. ERR_FAIL_COND_V(object_slots[slot].object != nullptr, ObjectID());
  1760. }
  1761. object_slots[slot].object = p_object;
  1762. object_slots[slot].is_ref_counted = p_object->is_ref_counted();
  1763. validator_counter = (validator_counter + 1) & OBJECTDB_VALIDATOR_MASK;
  1764. if (unlikely(validator_counter == 0)) {
  1765. validator_counter = 1;
  1766. }
  1767. object_slots[slot].validator = validator_counter;
  1768. uint64_t id = validator_counter;
  1769. id <<= OBJECTDB_SLOT_MAX_COUNT_BITS;
  1770. id |= uint64_t(slot);
  1771. if (p_object->is_ref_counted()) {
  1772. id |= OBJECTDB_REFERENCE_BIT;
  1773. }
  1774. slot_count++;
  1775. spin_lock.unlock();
  1776. return ObjectID(id);
  1777. }
  1778. void ObjectDB::remove_instance(Object *p_object) {
  1779. uint64_t t = p_object->get_instance_id();
  1780. uint32_t slot = t & OBJECTDB_SLOT_MAX_COUNT_MASK; //slot is always valid on valid object
  1781. spin_lock.lock();
  1782. #ifdef DEBUG_ENABLED
  1783. if (object_slots[slot].object != p_object) {
  1784. spin_lock.unlock();
  1785. ERR_FAIL_COND(object_slots[slot].object != p_object);
  1786. }
  1787. {
  1788. uint64_t validator = (t >> OBJECTDB_SLOT_MAX_COUNT_BITS) & OBJECTDB_VALIDATOR_MASK;
  1789. if (object_slots[slot].validator != validator) {
  1790. spin_lock.unlock();
  1791. ERR_FAIL_COND(object_slots[slot].validator != validator);
  1792. }
  1793. }
  1794. #endif
  1795. //decrease slot count
  1796. slot_count--;
  1797. //set the free slot properly
  1798. object_slots[slot_count].next_free = slot;
  1799. //invalidate, so checks against it fail
  1800. object_slots[slot].validator = 0;
  1801. object_slots[slot].is_ref_counted = false;
  1802. object_slots[slot].object = nullptr;
  1803. spin_lock.unlock();
  1804. }
  1805. void ObjectDB::setup() {
  1806. //nothing to do now
  1807. }
  1808. void ObjectDB::cleanup() {
  1809. if (slot_count > 0) {
  1810. spin_lock.lock();
  1811. WARN_PRINT("ObjectDB instances leaked at exit (run with --verbose for details).");
  1812. if (OS::get_singleton()->is_stdout_verbose()) {
  1813. // Ensure calling the native classes because if a leaked instance has a script
  1814. // that overrides any of those methods, it'd not be OK to call them at this point,
  1815. // now the scripting languages have already been terminated.
  1816. MethodBind *node_get_name = ClassDB::get_method("Node", "get_name");
  1817. MethodBind *resource_get_path = ClassDB::get_method("Resource", "get_path");
  1818. Callable::CallError call_error;
  1819. for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
  1820. if (object_slots[i].validator) {
  1821. Object *obj = object_slots[i].object;
  1822. String extra_info;
  1823. if (obj->is_class("Node")) {
  1824. extra_info = " - Node name: " + String(node_get_name->call(obj, nullptr, 0, call_error));
  1825. }
  1826. if (obj->is_class("Resource")) {
  1827. extra_info = " - Resource path: " + String(resource_get_path->call(obj, nullptr, 0, call_error));
  1828. }
  1829. 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);
  1830. print_line("Leaked instance: " + String(obj->get_class()) + ":" + itos(id) + extra_info);
  1831. count--;
  1832. }
  1833. }
  1834. 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()`).");
  1835. }
  1836. spin_lock.unlock();
  1837. }
  1838. if (object_slots) {
  1839. memfree(object_slots);
  1840. }
  1841. }