object.cpp 68 KB

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