object.cpp 65 KB

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