object.cpp 68 KB

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