csharp_script.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870
  1. /**************************************************************************/
  2. /* csharp_script.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 "csharp_script.h"
  31. #include <stdint.h>
  32. #include "core/config/project_settings.h"
  33. #include "core/debugger/engine_debugger.h"
  34. #include "core/debugger/script_debugger.h"
  35. #include "core/io/file_access.h"
  36. #include "core/os/mutex.h"
  37. #include "core/os/os.h"
  38. #include "core/os/thread.h"
  39. #ifdef TOOLS_ENABLED
  40. #include "core/os/keyboard.h"
  41. #include "editor/editor_file_system.h"
  42. #include "editor/editor_internal_calls.h"
  43. #include "editor/editor_node.h"
  44. #include "editor/editor_settings.h"
  45. #include "editor/inspector_dock.h"
  46. #include "editor/node_dock.h"
  47. #include "editor/script_templates/templates.gen.h"
  48. #endif
  49. #ifdef DEBUG_METHODS_ENABLED
  50. #include "class_db_api_json.h"
  51. #endif
  52. #include "godotsharp_dirs.h"
  53. #include "managed_callable.h"
  54. #include "mono_gd/gd_mono_cache.h"
  55. #include "servers/text_server.h"
  56. #include "signal_awaiter_utils.h"
  57. #include "utils/macros.h"
  58. #include "utils/naming_utils.h"
  59. #include "utils/string_utils.h"
  60. #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var)
  61. #ifdef TOOLS_ENABLED
  62. static bool _create_project_solution_if_needed() {
  63. CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == nullptr);
  64. return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolutionIfNeeded");
  65. }
  66. #endif
  67. CSharpLanguage *CSharpLanguage::singleton = nullptr;
  68. GDExtensionInstanceBindingCallbacks CSharpLanguage::_instance_binding_callbacks = {
  69. &_instance_binding_create_callback,
  70. &_instance_binding_free_callback,
  71. &_instance_binding_reference_callback
  72. };
  73. String CSharpLanguage::get_name() const {
  74. return "C#";
  75. }
  76. String CSharpLanguage::get_type() const {
  77. return "CSharpScript";
  78. }
  79. String CSharpLanguage::get_extension() const {
  80. return "cs";
  81. }
  82. void CSharpLanguage::init() {
  83. #ifdef TOOLS_ENABLED
  84. if (OS::get_singleton()->get_cmdline_args().find("--generate-mono-glue")) {
  85. print_verbose(".NET: Skipping runtime initialization because glue generation is enabled.");
  86. return;
  87. }
  88. #endif
  89. #ifdef DEBUG_METHODS_ENABLED
  90. if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
  91. class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
  92. #ifdef TOOLS_ENABLED
  93. class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
  94. #endif
  95. }
  96. #endif
  97. GLOBAL_DEF("dotnet/project/assembly_name", "");
  98. #ifdef TOOLS_ENABLED
  99. GLOBAL_DEF("dotnet/project/solution_directory", "");
  100. #endif
  101. gdmono = memnew(GDMono);
  102. gdmono->initialize();
  103. #ifdef TOOLS_ENABLED
  104. if (gdmono->is_runtime_initialized()) {
  105. gdmono->initialize_load_assemblies();
  106. }
  107. EditorNode::add_init_callback(&_editor_init_callback);
  108. #endif
  109. }
  110. void CSharpLanguage::finish() {
  111. finalize();
  112. }
  113. void CSharpLanguage::finalize() {
  114. if (finalized) {
  115. return;
  116. }
  117. finalizing = true;
  118. // Make sure all script binding gchandles are released before finalizing GDMono
  119. for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  120. CSharpScriptBinding &script_binding = E.value;
  121. if (!script_binding.gchandle.is_released()) {
  122. script_binding.gchandle.release();
  123. script_binding.inited = false;
  124. }
  125. }
  126. if (gdmono) {
  127. memdelete(gdmono);
  128. gdmono = nullptr;
  129. }
  130. // Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
  131. script_bindings.clear();
  132. #ifdef DEBUG_ENABLED
  133. for (const KeyValue<ObjectID, int> &E : unsafe_object_references) {
  134. const ObjectID &id = E.key;
  135. Object *obj = ObjectDB::get_instance(id);
  136. if (obj) {
  137. ERR_PRINT("Leaked unsafe reference to object: " + obj->to_string());
  138. } else {
  139. ERR_PRINT("Leaked unsafe reference to deleted object: " + itos(id));
  140. }
  141. }
  142. #endif
  143. memdelete(managed_callable_middleman);
  144. finalizing = false;
  145. finalized = true;
  146. }
  147. void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
  148. static const char *_reserved_words[] = {
  149. // Reserved keywords
  150. "abstract",
  151. "as",
  152. "base",
  153. "bool",
  154. "break",
  155. "byte",
  156. "case",
  157. "catch",
  158. "char",
  159. "checked",
  160. "class",
  161. "const",
  162. "continue",
  163. "decimal",
  164. "default",
  165. "delegate",
  166. "do",
  167. "double",
  168. "else",
  169. "enum",
  170. "event",
  171. "explicit",
  172. "extern",
  173. "false",
  174. "finally",
  175. "fixed",
  176. "float",
  177. "for",
  178. "foreach",
  179. "goto",
  180. "if",
  181. "implicit",
  182. "in",
  183. "int",
  184. "interface",
  185. "internal",
  186. "is",
  187. "lock",
  188. "long",
  189. "namespace",
  190. "new",
  191. "null",
  192. "object",
  193. "operator",
  194. "out",
  195. "override",
  196. "params",
  197. "private",
  198. "protected",
  199. "public",
  200. "readonly",
  201. "ref",
  202. "return",
  203. "sbyte",
  204. "sealed",
  205. "short",
  206. "sizeof",
  207. "stackalloc",
  208. "static",
  209. "string",
  210. "struct",
  211. "switch",
  212. "this",
  213. "throw",
  214. "true",
  215. "try",
  216. "typeof",
  217. "uint",
  218. "ulong",
  219. "unchecked",
  220. "unsafe",
  221. "ushort",
  222. "using",
  223. "virtual",
  224. "void",
  225. "volatile",
  226. "while",
  227. // Contextual keywords. Not reserved words, but I guess we should include
  228. // them because this seems to be used only for syntax highlighting.
  229. "add",
  230. "alias",
  231. "ascending",
  232. "async",
  233. "await",
  234. "by",
  235. "descending",
  236. "dynamic",
  237. "equals",
  238. "from",
  239. "get",
  240. "global",
  241. "group",
  242. "into",
  243. "join",
  244. "let",
  245. "nameof",
  246. "on",
  247. "orderby",
  248. "partial",
  249. "remove",
  250. "select",
  251. "set",
  252. "value",
  253. "var",
  254. "when",
  255. "where",
  256. "yield",
  257. nullptr
  258. };
  259. const char **w = _reserved_words;
  260. while (*w) {
  261. p_words->push_back(*w);
  262. w++;
  263. }
  264. }
  265. bool CSharpLanguage::is_control_flow_keyword(String p_keyword) const {
  266. return p_keyword == "break" ||
  267. p_keyword == "case" ||
  268. p_keyword == "catch" ||
  269. p_keyword == "continue" ||
  270. p_keyword == "default" ||
  271. p_keyword == "do" ||
  272. p_keyword == "else" ||
  273. p_keyword == "finally" ||
  274. p_keyword == "for" ||
  275. p_keyword == "foreach" ||
  276. p_keyword == "goto" ||
  277. p_keyword == "if" ||
  278. p_keyword == "return" ||
  279. p_keyword == "switch" ||
  280. p_keyword == "throw" ||
  281. p_keyword == "try" ||
  282. p_keyword == "while";
  283. }
  284. void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  285. p_delimiters->push_back("//"); // single-line comment
  286. p_delimiters->push_back("/* */"); // delimited comment
  287. }
  288. void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  289. p_delimiters->push_back("' '"); // character literal
  290. p_delimiters->push_back("\" \""); // regular string literal
  291. p_delimiters->push_back("@\" \""); // verbatim string literal
  292. // Generic string highlighting suffices as a workaround for now.
  293. }
  294. static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
  295. String base_class = pascal_to_pascal_case(p_base_class_name);
  296. if (p_class_name == base_class) {
  297. base_class = "Godot." + base_class;
  298. }
  299. return base_class;
  300. }
  301. bool CSharpLanguage::is_using_templates() {
  302. return true;
  303. }
  304. Ref<Script> CSharpLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const {
  305. Ref<CSharpScript> scr;
  306. scr.instantiate();
  307. String class_name_no_spaces = p_class_name.replace(" ", "_");
  308. String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
  309. String processed_template = p_template;
  310. processed_template = processed_template.replace("_BINDINGS_NAMESPACE_", BINDINGS_NAMESPACE)
  311. .replace("_BASE_", base_class_name)
  312. .replace("_CLASS_", class_name_no_spaces)
  313. .replace("_TS_", _get_indentation());
  314. scr->set_source_code(processed_template);
  315. return scr;
  316. }
  317. Vector<ScriptLanguage::ScriptTemplate> CSharpLanguage::get_built_in_templates(StringName p_object) {
  318. Vector<ScriptLanguage::ScriptTemplate> templates;
  319. #ifdef TOOLS_ENABLED
  320. for (int i = 0; i < TEMPLATES_ARRAY_SIZE; i++) {
  321. if (TEMPLATES[i].inherit == p_object) {
  322. templates.append(TEMPLATES[i]);
  323. }
  324. }
  325. #endif
  326. return templates;
  327. }
  328. String CSharpLanguage::validate_path(const String &p_path) const {
  329. String class_name = p_path.get_file().get_basename();
  330. List<String> keywords;
  331. get_reserved_words(&keywords);
  332. if (keywords.find(class_name)) {
  333. return RTR("Class name can't be a reserved keyword");
  334. }
  335. if (!TS->is_valid_identifier(class_name)) {
  336. return RTR("Class name must be a valid identifier");
  337. }
  338. return "";
  339. }
  340. Script *CSharpLanguage::create_script() const {
  341. return memnew(CSharpScript);
  342. }
  343. bool CSharpLanguage::has_named_classes() const {
  344. return false;
  345. }
  346. bool CSharpLanguage::supports_builtin_mode() const {
  347. return false;
  348. }
  349. #ifdef TOOLS_ENABLED
  350. struct VariantCsName {
  351. Variant::Type variant_type;
  352. const String cs_type;
  353. };
  354. static String variant_type_to_managed_name(const String &p_var_type_name) {
  355. if (p_var_type_name.is_empty()) {
  356. return "Variant";
  357. }
  358. if (ClassDB::class_exists(p_var_type_name)) {
  359. return pascal_to_pascal_case(p_var_type_name);
  360. }
  361. if (p_var_type_name == Variant::get_type_name(Variant::OBJECT)) {
  362. return "GodotObject";
  363. }
  364. if (p_var_type_name == Variant::get_type_name(Variant::INT)) {
  365. return "long";
  366. }
  367. if (p_var_type_name == Variant::get_type_name(Variant::FLOAT)) {
  368. return "double";
  369. }
  370. if (p_var_type_name == Variant::get_type_name(Variant::STRING)) {
  371. return "string"; // I prefer this one >:[
  372. }
  373. if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY)) {
  374. return "Collections.Dictionary";
  375. }
  376. if (p_var_type_name == Variant::get_type_name(Variant::ARRAY)) {
  377. return "Collections.Array";
  378. }
  379. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_BYTE_ARRAY)) {
  380. return "byte[]";
  381. }
  382. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT32_ARRAY)) {
  383. return "int[]";
  384. }
  385. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT64_ARRAY)) {
  386. return "long[]";
  387. }
  388. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT32_ARRAY)) {
  389. return "float[]";
  390. }
  391. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT64_ARRAY)) {
  392. return "double[]";
  393. }
  394. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_STRING_ARRAY)) {
  395. return "string[]";
  396. }
  397. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR2_ARRAY)) {
  398. return "Vector2[]";
  399. }
  400. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR3_ARRAY)) {
  401. return "Vector3[]";
  402. }
  403. if (p_var_type_name == Variant::get_type_name(Variant::PACKED_COLOR_ARRAY)) {
  404. return "Color[]";
  405. }
  406. if (p_var_type_name == Variant::get_type_name(Variant::SIGNAL)) {
  407. return "Signal";
  408. }
  409. const VariantCsName var_types[] = {
  410. { Variant::BOOL, "bool" },
  411. { Variant::INT, "long" },
  412. { Variant::VECTOR2, "Vector2" },
  413. { Variant::VECTOR2I, "Vector2I" },
  414. { Variant::RECT2, "Rect2" },
  415. { Variant::RECT2I, "Rect2I" },
  416. { Variant::VECTOR3, "Vector3" },
  417. { Variant::VECTOR3I, "Vector3I" },
  418. { Variant::TRANSFORM2D, "Transform2D" },
  419. { Variant::VECTOR4, "Vector4" },
  420. { Variant::VECTOR4I, "Vector4I" },
  421. { Variant::PLANE, "Plane" },
  422. { Variant::QUATERNION, "Quaternion" },
  423. { Variant::AABB, "Aabb" },
  424. { Variant::BASIS, "Basis" },
  425. { Variant::TRANSFORM3D, "Transform3D" },
  426. { Variant::PROJECTION, "Projection" },
  427. { Variant::COLOR, "Color" },
  428. { Variant::STRING_NAME, "StringName" },
  429. { Variant::NODE_PATH, "NodePath" },
  430. { Variant::RID, "Rid" },
  431. { Variant::CALLABLE, "Callable" },
  432. };
  433. for (unsigned int i = 0; i < sizeof(var_types) / sizeof(VariantCsName); i++) {
  434. if (p_var_type_name == Variant::get_type_name(var_types[i].variant_type)) {
  435. return var_types[i].cs_type;
  436. }
  437. }
  438. return "Variant";
  439. }
  440. String CSharpLanguage::make_function(const String &, const String &p_name, const PackedStringArray &p_args) const {
  441. // FIXME
  442. // - Due to Godot's API limitation this just appends the function to the end of the file
  443. // - Use fully qualified name if there is ambiguity
  444. String s = "private void " + p_name + "(";
  445. for (int i = 0; i < p_args.size(); i++) {
  446. const String &arg = p_args[i];
  447. if (i > 0) {
  448. s += ", ";
  449. }
  450. s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
  451. }
  452. s += ")\n{\n // Replace with function body.\n}\n";
  453. return s;
  454. }
  455. #else
  456. String CSharpLanguage::make_function(const String &, const String &, const PackedStringArray &) const {
  457. return String();
  458. }
  459. #endif
  460. String CSharpLanguage::_get_indentation() const {
  461. #ifdef TOOLS_ENABLED
  462. if (Engine::get_singleton()->is_editor_hint()) {
  463. bool use_space_indentation = EDITOR_GET("text_editor/behavior/indent/type");
  464. if (use_space_indentation) {
  465. int indent_size = EDITOR_GET("text_editor/behavior/indent/size");
  466. return String(" ").repeat(indent_size);
  467. }
  468. }
  469. #endif
  470. return "\t";
  471. }
  472. bool CSharpLanguage::handles_global_class_type(const String &p_type) const {
  473. return p_type == get_type();
  474. }
  475. String CSharpLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const {
  476. Ref<CSharpScript> scr = ResourceLoader::load(p_path, get_type());
  477. if (!scr.is_valid() || !scr->valid || !scr->global_class) {
  478. // Invalid script or the script is not a global class.
  479. return String();
  480. }
  481. String name = scr->class_name;
  482. if (unlikely(name.is_empty())) {
  483. return String();
  484. }
  485. if (r_icon_path) {
  486. if (scr->icon_path.is_empty() || scr->icon_path.is_absolute_path()) {
  487. *r_icon_path = scr->icon_path.simplify_path();
  488. } else if (scr->icon_path.is_relative_path()) {
  489. *r_icon_path = p_path.get_base_dir().path_join(scr->icon_path).simplify_path();
  490. }
  491. }
  492. if (r_base_type) {
  493. bool found_global_base_script = false;
  494. const CSharpScript *top = scr->base_script.ptr();
  495. while (top != nullptr) {
  496. if (top->global_class) {
  497. *r_base_type = top->class_name;
  498. found_global_base_script = true;
  499. break;
  500. }
  501. top = top->base_script.ptr();
  502. }
  503. if (!found_global_base_script) {
  504. *r_base_type = scr->get_instance_base_type();
  505. }
  506. }
  507. return name;
  508. }
  509. String CSharpLanguage::debug_get_error() const {
  510. return _debug_error;
  511. }
  512. int CSharpLanguage::debug_get_stack_level_count() const {
  513. if (_debug_parse_err_line >= 0) {
  514. return 1;
  515. }
  516. // TODO: StackTrace
  517. return 1;
  518. }
  519. int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
  520. if (_debug_parse_err_line >= 0) {
  521. return _debug_parse_err_line;
  522. }
  523. // TODO: StackTrace
  524. return 1;
  525. }
  526. String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
  527. if (_debug_parse_err_line >= 0) {
  528. return String();
  529. }
  530. // TODO: StackTrace
  531. return String();
  532. }
  533. String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
  534. if (_debug_parse_err_line >= 0) {
  535. return _debug_parse_err_file;
  536. }
  537. // TODO: StackTrace
  538. return String();
  539. }
  540. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  541. #ifdef DEBUG_ENABLED
  542. // Printing an error here will result in endless recursion, so we must be careful
  543. static thread_local bool _recursion_flag_ = false;
  544. if (_recursion_flag_) {
  545. return Vector<StackInfo>();
  546. }
  547. _recursion_flag_ = true;
  548. SCOPE_EXIT {
  549. _recursion_flag_ = false;
  550. };
  551. if (!gdmono || !gdmono->is_runtime_initialized()) {
  552. return Vector<StackInfo>();
  553. }
  554. Vector<StackInfo> si;
  555. if (GDMonoCache::godot_api_cache_updated) {
  556. GDMonoCache::managed_callbacks.DebuggingUtils_GetCurrentStackInfo(&si);
  557. }
  558. return si;
  559. #else
  560. return Vector<StackInfo>();
  561. #endif
  562. }
  563. void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
  564. #ifdef DEBUG_ENABLED
  565. MutexLock lock(unsafe_object_references_lock);
  566. ObjectID id = p_obj->get_instance_id();
  567. unsafe_object_references[id]++;
  568. #endif
  569. }
  570. void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
  571. #ifdef DEBUG_ENABLED
  572. MutexLock lock(unsafe_object_references_lock);
  573. ObjectID id = p_obj->get_instance_id();
  574. HashMap<ObjectID, int>::Iterator elem = unsafe_object_references.find(id);
  575. ERR_FAIL_NULL(elem);
  576. if (--elem->value == 0) {
  577. unsafe_object_references.remove(elem);
  578. }
  579. #endif
  580. }
  581. void CSharpLanguage::frame() {
  582. if (gdmono && gdmono->is_runtime_initialized() && GDMonoCache::godot_api_cache_updated) {
  583. GDMonoCache::managed_callbacks.ScriptManagerBridge_FrameCallback();
  584. }
  585. }
  586. struct CSharpScriptDepSort {
  587. // Must support sorting so inheritance works properly (parent must be reloaded first)
  588. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  589. if (A == B) {
  590. // Shouldn't happen but just in case...
  591. return false;
  592. }
  593. const Script *I = B->get_base_script().ptr();
  594. while (I) {
  595. if (I == A.ptr()) {
  596. // A is a base of B
  597. return true;
  598. }
  599. I = I->get_base_script().ptr();
  600. }
  601. // A isn't a base of B
  602. return false;
  603. }
  604. };
  605. void CSharpLanguage::reload_all_scripts() {
  606. #ifdef GD_MONO_HOT_RELOAD
  607. if (is_assembly_reloading_needed()) {
  608. reload_assemblies(false);
  609. }
  610. #endif
  611. }
  612. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  613. (void)p_script; // UNUSED
  614. CRASH_COND(!Engine::get_singleton()->is_editor_hint());
  615. #ifdef TOOLS_ENABLED
  616. get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
  617. #endif
  618. #ifdef GD_MONO_HOT_RELOAD
  619. if (is_assembly_reloading_needed()) {
  620. reload_assemblies(p_soft_reload);
  621. }
  622. #endif
  623. }
  624. #ifdef GD_MONO_HOT_RELOAD
  625. bool CSharpLanguage::is_assembly_reloading_needed() {
  626. ERR_FAIL_NULL_V(gdmono, false);
  627. if (!gdmono->is_runtime_initialized()) {
  628. return false;
  629. }
  630. String assembly_path = gdmono->get_project_assembly_path();
  631. if (!assembly_path.is_empty()) {
  632. if (!FileAccess::exists(assembly_path)) {
  633. return false; // No assembly to load
  634. }
  635. if (FileAccess::get_modified_time(assembly_path) <= gdmono->get_project_assembly_modified_time()) {
  636. return false; // Already up to date
  637. }
  638. } else {
  639. String assembly_name = GLOBAL_GET("dotnet/project/assembly_name");
  640. if (assembly_name.is_empty()) {
  641. assembly_name = ProjectSettings::get_singleton()->get_safe_project_name();
  642. }
  643. assembly_path = GodotSharpDirs::get_res_temp_assemblies_dir()
  644. .path_join(assembly_name + ".dll");
  645. assembly_path = ProjectSettings::get_singleton()->globalize_path(assembly_path);
  646. if (!FileAccess::exists(assembly_path)) {
  647. return false; // No assembly to load
  648. }
  649. }
  650. return true;
  651. }
  652. void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
  653. ERR_FAIL_NULL(gdmono);
  654. if (!gdmono->is_runtime_initialized()) {
  655. return;
  656. }
  657. if (!Engine::get_singleton()->is_editor_hint()) {
  658. // We disable collectible assemblies in the game player, because the limitations cause
  659. // issues with mocking libraries. As such, we can only reload assemblies in the editor.
  660. return;
  661. }
  662. // TODO:
  663. // Currently, this reloads all scripts, including those whose class is not part of the
  664. // assembly load context being unloaded. As such, we unnecessarily reload GodotTools.
  665. print_verbose(".NET: Reloading assemblies...");
  666. // There is no soft reloading with Mono. It's always hard reloading.
  667. List<Ref<CSharpScript>> scripts;
  668. {
  669. MutexLock lock(script_instances_mutex);
  670. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  671. // Cast to CSharpScript to avoid being erased by accident
  672. scripts.push_back(Ref<CSharpScript>(elem->self()));
  673. }
  674. }
  675. scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
  676. // Serialize managed callables
  677. {
  678. MutexLock lock(ManagedCallable::instances_mutex);
  679. for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
  680. ManagedCallable *managed_callable = elem->self();
  681. ERR_CONTINUE(managed_callable->delegate_handle.value == nullptr);
  682. Array serialized_data;
  683. bool success = GDMonoCache::managed_callbacks.DelegateUtils_TrySerializeDelegateWithGCHandle(
  684. managed_callable->delegate_handle, &serialized_data);
  685. if (success) {
  686. ManagedCallable::instances_pending_reload.insert(managed_callable, serialized_data);
  687. } else if (OS::get_singleton()->is_stdout_verbose()) {
  688. OS::get_singleton()->print("Failed to serialize delegate\n");
  689. }
  690. }
  691. }
  692. List<Ref<CSharpScript>> to_reload;
  693. // We need to keep reference instances alive during reloading
  694. List<Ref<RefCounted>> rc_instances;
  695. for (const KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) {
  696. const CSharpScriptBinding &script_binding = E.value;
  697. RefCounted *rc = Object::cast_to<RefCounted>(script_binding.owner);
  698. if (rc) {
  699. rc_instances.push_back(Ref<RefCounted>(rc));
  700. }
  701. }
  702. // As scripts are going to be reloaded, must proceed without locking here
  703. for (Ref<CSharpScript> &scr : scripts) {
  704. // If someone removes a script from a node, deletes the script, builds, adds a script to the
  705. // same node, then builds again, the script might have no path and also no script_class. In
  706. // that case, we can't (and don't need to) reload it.
  707. if (scr->get_path().is_empty() && !scr->valid) {
  708. continue;
  709. }
  710. to_reload.push_back(scr);
  711. // Script::instances are deleted during managed object disposal, which happens on domain finalize.
  712. // Only placeholders are kept. Therefore we need to keep a copy before that happens.
  713. for (Object *obj : scr->instances) {
  714. scr->pending_reload_instances.insert(obj->get_instance_id());
  715. // Since this script instance wasn't a placeholder, add it to the list of placeholders
  716. // that will have to be eventually replaced with a script instance in case it turns into one.
  717. // This list is not cleared after the reload and the collected instances only leave
  718. // the list if the script is instantiated or if it was a tool script but becomes a
  719. // non-tool script in a rebuild.
  720. scr->pending_replace_placeholders.insert(obj->get_instance_id());
  721. RefCounted *rc = Object::cast_to<RefCounted>(obj);
  722. if (rc) {
  723. rc_instances.push_back(Ref<RefCounted>(rc));
  724. }
  725. }
  726. #ifdef TOOLS_ENABLED
  727. for (PlaceHolderScriptInstance *instance : scr->placeholders) {
  728. Object *obj = instance->get_owner();
  729. scr->pending_reload_instances.insert(obj->get_instance_id());
  730. RefCounted *rc = Object::cast_to<RefCounted>(obj);
  731. if (rc) {
  732. rc_instances.push_back(Ref<RefCounted>(rc));
  733. }
  734. }
  735. #endif
  736. // Save state and remove script from instances
  737. RBMap<ObjectID, CSharpScript::StateBackup> &owners_map = scr->pending_reload_state;
  738. for (Object *obj : scr->instances) {
  739. ERR_CONTINUE(!obj->get_script_instance());
  740. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  741. // Call OnBeforeSerialize and save instance info
  742. CSharpScript::StateBackup state;
  743. Dictionary properties;
  744. GDMonoCache::managed_callbacks.CSharpInstanceBridge_SerializeState(
  745. csi->get_gchandle_intptr(), &properties, &state.event_signals);
  746. for (const Variant *s = properties.next(nullptr); s != nullptr; s = properties.next(s)) {
  747. StringName name = *s;
  748. Variant value = properties[*s];
  749. state.properties.push_back(Pair<StringName, Variant>(name, value));
  750. }
  751. owners_map[obj->get_instance_id()] = state;
  752. }
  753. }
  754. // After the state of all instances is saved, clear scripts and script instances
  755. for (Ref<CSharpScript> &scr : scripts) {
  756. while (scr->instances.begin()) {
  757. Object *obj = *scr->instances.begin();
  758. obj->set_script(Ref<RefCounted>()); // Remove script and existing script instances (placeholder are not removed before domain reload)
  759. }
  760. scr->was_tool_before_reload = scr->tool;
  761. scr->_clear();
  762. }
  763. // Do domain reload
  764. if (gdmono->reload_project_assemblies() != OK) {
  765. // Failed to reload the scripts domain
  766. // Make sure to add the scripts back to their owners before returning
  767. for (Ref<CSharpScript> &scr : to_reload) {
  768. for (const KeyValue<ObjectID, CSharpScript::StateBackup> &F : scr->pending_reload_state) {
  769. Object *obj = ObjectDB::get_instance(F.key);
  770. if (!obj) {
  771. continue;
  772. }
  773. ObjectID obj_id = obj->get_instance_id();
  774. // Use a placeholder for now to avoid losing the state when saving a scene
  775. PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
  776. obj->set_script_instance(placeholder);
  777. #ifdef TOOLS_ENABLED
  778. // Even though build didn't fail, this tells the placeholder to keep properties and
  779. // it allows using property_set_fallback for restoring the state without a valid script.
  780. scr->placeholder_fallback_enabled = true;
  781. #endif
  782. // Restore Variant properties state, it will be kept by the placeholder until the next script reloading
  783. for (const Pair<StringName, Variant> &G : scr->pending_reload_state[obj_id].properties) {
  784. placeholder->property_set_fallback(G.first, G.second, nullptr);
  785. }
  786. scr->pending_reload_state.erase(obj_id);
  787. }
  788. scr->pending_reload_instances.clear();
  789. scr->pending_reload_state.clear();
  790. }
  791. return;
  792. }
  793. List<Ref<CSharpScript>> to_reload_state;
  794. for (Ref<CSharpScript> &scr : to_reload) {
  795. #ifdef TOOLS_ENABLED
  796. scr->exports_invalidated = true;
  797. #endif
  798. if (!scr->get_path().is_empty()) {
  799. scr->reload(p_soft_reload);
  800. if (!scr->valid) {
  801. scr->pending_reload_instances.clear();
  802. scr->pending_reload_state.clear();
  803. continue;
  804. }
  805. } else {
  806. bool success = GDMonoCache::managed_callbacks.ScriptManagerBridge_TryReloadRegisteredScriptWithClass(scr.ptr());
  807. if (!success) {
  808. // Couldn't reload
  809. scr->pending_reload_instances.clear();
  810. scr->pending_reload_state.clear();
  811. continue;
  812. }
  813. }
  814. StringName native_name = scr->get_instance_base_type();
  815. {
  816. for (const ObjectID &obj_id : scr->pending_reload_instances) {
  817. Object *obj = ObjectDB::get_instance(obj_id);
  818. if (!obj) {
  819. scr->pending_reload_state.erase(obj_id);
  820. continue;
  821. }
  822. if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
  823. // No longer inherits the same compatible type, can't reload
  824. scr->pending_reload_state.erase(obj_id);
  825. continue;
  826. }
  827. ScriptInstance *si = obj->get_script_instance();
  828. // Check if the script must be instantiated or kept as a placeholder
  829. // when the script may not be a tool (see #65266)
  830. bool replace_placeholder = scr->pending_replace_placeholders.has(obj->get_instance_id());
  831. if (!scr->is_tool() && scr->was_tool_before_reload) {
  832. // The script was a tool before the rebuild so the removal was intentional.
  833. replace_placeholder = false;
  834. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  835. }
  836. #ifdef TOOLS_ENABLED
  837. if (si) {
  838. // If the script instance is not null, then it must be a placeholder.
  839. // Non-placeholder script instances are removed in godot_icall_Object_Disposed.
  840. CRASH_COND(!si->is_placeholder());
  841. if (replace_placeholder || scr->is_tool() || ScriptServer::is_scripting_enabled()) {
  842. // Replace placeholder with a script instance.
  843. CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id];
  844. // Backup placeholder script instance state before replacing it with a script instance.
  845. si->get_property_state(state_backup.properties);
  846. ScriptInstance *instance = scr->instance_create(obj);
  847. if (instance) {
  848. scr->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
  849. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  850. obj->set_script_instance(instance);
  851. }
  852. }
  853. continue;
  854. }
  855. #else
  856. CRASH_COND(si != nullptr);
  857. #endif
  858. // Re-create the script instance.
  859. if (replace_placeholder || scr->is_tool() || ScriptServer::is_scripting_enabled()) {
  860. // Create script instance or replace placeholder with a script instance.
  861. ScriptInstance *instance = scr->instance_create(obj);
  862. if (instance) {
  863. scr->pending_replace_placeholders.erase(obj->get_instance_id());
  864. obj->set_script_instance(instance);
  865. continue;
  866. }
  867. }
  868. // The script instance could not be instantiated or wasn't in the list of placeholders to replace.
  869. obj->set_script(scr);
  870. #if DEBUG_ENABLED
  871. // If we reached here, the instantiated script must be a placeholder.
  872. CRASH_COND(!obj->get_script_instance()->is_placeholder());
  873. #endif
  874. }
  875. }
  876. to_reload_state.push_back(scr);
  877. }
  878. for (Ref<CSharpScript> &scr : to_reload_state) {
  879. for (const ObjectID &obj_id : scr->pending_reload_instances) {
  880. Object *obj = ObjectDB::get_instance(obj_id);
  881. if (!obj) {
  882. scr->pending_reload_state.erase(obj_id);
  883. continue;
  884. }
  885. ERR_CONTINUE(!obj->get_script_instance());
  886. CSharpScript::StateBackup &state_backup = scr->pending_reload_state[obj_id];
  887. CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
  888. if (csi) {
  889. Dictionary properties;
  890. for (const Pair<StringName, Variant> &G : state_backup.properties) {
  891. properties[G.first] = G.second;
  892. }
  893. // Restore serialized state and call OnAfterDeserialization
  894. GDMonoCache::managed_callbacks.CSharpInstanceBridge_DeserializeState(
  895. csi->get_gchandle_intptr(), &properties, &state_backup.event_signals);
  896. }
  897. }
  898. scr->pending_reload_instances.clear();
  899. scr->pending_reload_state.clear();
  900. }
  901. // Deserialize managed callables
  902. {
  903. MutexLock lock(ManagedCallable::instances_mutex);
  904. for (const KeyValue<ManagedCallable *, Array> &elem : ManagedCallable::instances_pending_reload) {
  905. ManagedCallable *managed_callable = elem.key;
  906. const Array &serialized_data = elem.value;
  907. GCHandleIntPtr delegate = { nullptr };
  908. bool success = GDMonoCache::managed_callbacks.DelegateUtils_TryDeserializeDelegateWithGCHandle(
  909. &serialized_data, &delegate);
  910. if (success) {
  911. ERR_CONTINUE(delegate.value == nullptr);
  912. managed_callable->delegate_handle = delegate;
  913. } else if (OS::get_singleton()->is_stdout_verbose()) {
  914. OS::get_singleton()->print("Failed to deserialize delegate\n");
  915. }
  916. }
  917. ManagedCallable::instances_pending_reload.clear();
  918. }
  919. #ifdef TOOLS_ENABLED
  920. // FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
  921. if (Engine::get_singleton()->is_editor_hint()) {
  922. InspectorDock::get_inspector_singleton()->update_tree();
  923. NodeDock::get_singleton()->update_lists();
  924. }
  925. #endif
  926. }
  927. #endif
  928. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  929. p_extensions->push_back("cs");
  930. }
  931. #ifdef TOOLS_ENABLED
  932. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  933. return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
  934. }
  935. bool CSharpLanguage::overrides_external_editor() {
  936. return get_godotsharp_editor()->call("OverridesExternalEditor");
  937. }
  938. #endif
  939. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  940. // Not a parser error in our case, but it's still used for other type of errors
  941. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  942. _debug_parse_err_line = p_line;
  943. _debug_parse_err_file = p_file;
  944. _debug_error = p_error;
  945. EngineDebugger::get_script_debugger()->debug(this, false, true);
  946. return true;
  947. } else {
  948. return false;
  949. }
  950. }
  951. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  952. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  953. _debug_parse_err_line = -1;
  954. _debug_parse_err_file = "";
  955. _debug_error = p_error;
  956. EngineDebugger::get_script_debugger()->debug(this, p_allow_continue);
  957. return true;
  958. } else {
  959. return false;
  960. }
  961. }
  962. void CSharpLanguage::_on_scripts_domain_about_to_unload() {
  963. #ifdef GD_MONO_HOT_RELOAD
  964. {
  965. MutexLock lock(ManagedCallable::instances_mutex);
  966. for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
  967. ManagedCallable *managed_callable = elem->self();
  968. managed_callable->release_delegate_handle();
  969. }
  970. }
  971. #endif
  972. }
  973. #ifdef TOOLS_ENABLED
  974. void CSharpLanguage::_editor_init_callback() {
  975. // Load GodotTools and initialize GodotSharpEditor
  976. int32_t interop_funcs_size = 0;
  977. const void **interop_funcs = godotsharp::get_editor_interop_funcs(interop_funcs_size);
  978. Object *editor_plugin_obj = GDMono::get_singleton()->get_plugin_callbacks().LoadToolsAssemblyCallback(
  979. GodotSharpDirs::get_data_editor_tools_dir().path_join("GodotTools.dll").utf16(),
  980. interop_funcs, interop_funcs_size);
  981. CRASH_COND(editor_plugin_obj == nullptr);
  982. EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(editor_plugin_obj);
  983. CRASH_COND(godotsharp_editor == nullptr);
  984. // Add plugin to EditorNode and enable it
  985. EditorNode::add_editor_plugin(godotsharp_editor);
  986. ED_SHORTCUT("mono/build_solution", TTR("Build Solution"), KeyModifierMask::ALT | Key::B);
  987. ED_SHORTCUT_OVERRIDE("mono/build_solution", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::B);
  988. godotsharp_editor->enable_plugin();
  989. get_singleton()->godotsharp_editor = godotsharp_editor;
  990. }
  991. #endif
  992. void CSharpLanguage::set_language_index(int p_idx) {
  993. ERR_FAIL_COND(lang_idx != -1);
  994. lang_idx = p_idx;
  995. }
  996. void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) {
  997. if (!p_gchandle.is_released()) { // Do not lock unnecessarily
  998. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  999. p_gchandle.release();
  1000. }
  1001. }
  1002. void CSharpLanguage::release_script_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, MonoGCHandleData &r_gchandle) {
  1003. if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
  1004. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  1005. if (!r_gchandle.is_released() && r_gchandle.get_intptr() == p_gchandle_to_free) {
  1006. r_gchandle.release();
  1007. }
  1008. }
  1009. }
  1010. void CSharpLanguage::release_binding_gchandle_thread_safe(GCHandleIntPtr p_gchandle_to_free, CSharpScriptBinding &r_script_binding) {
  1011. MonoGCHandleData &gchandle = r_script_binding.gchandle;
  1012. if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) { // Do not lock unnecessarily
  1013. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  1014. if (!gchandle.is_released() && gchandle.get_intptr() == p_gchandle_to_free) {
  1015. gchandle.release();
  1016. r_script_binding.inited = false; // Here too, to be thread safe
  1017. }
  1018. }
  1019. }
  1020. CSharpLanguage::CSharpLanguage() {
  1021. ERR_FAIL_COND_MSG(singleton, "C# singleton already exist.");
  1022. singleton = this;
  1023. }
  1024. CSharpLanguage::~CSharpLanguage() {
  1025. finalize();
  1026. singleton = nullptr;
  1027. }
  1028. bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
  1029. #ifdef DEBUG_ENABLED
  1030. // I don't trust you
  1031. if (p_object->get_script_instance()) {
  1032. CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  1033. CRASH_COND(csharp_instance != nullptr && !csharp_instance->is_destructing_script_instance());
  1034. }
  1035. #endif
  1036. StringName type_name = p_object->get_class_name();
  1037. // ¯\_(ツ)_/¯
  1038. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  1039. while (classinfo && !classinfo->exposed) {
  1040. classinfo = classinfo->inherits_ptr;
  1041. }
  1042. ERR_FAIL_NULL_V(classinfo, false);
  1043. type_name = classinfo->name;
  1044. bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), type_name);
  1045. ERR_FAIL_COND_V_MSG(!parent_is_object_class, false,
  1046. "Type inherits from native type '" + type_name + "', so it can't be instantiated in object of type: '" + p_object->get_class() + "'.");
  1047. #ifdef DEBUG_ENABLED
  1048. CRASH_COND(!r_script_binding.gchandle.is_released());
  1049. #endif
  1050. GCHandleIntPtr strong_gchandle =
  1051. GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectBinding(
  1052. &type_name, p_object);
  1053. ERR_FAIL_NULL_V(strong_gchandle.value, false);
  1054. r_script_binding.inited = true;
  1055. r_script_binding.type_name = type_name;
  1056. r_script_binding.gchandle = MonoGCHandleData(strong_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1057. r_script_binding.owner = p_object;
  1058. // Tie managed to unmanaged
  1059. RefCounted *rc = Object::cast_to<RefCounted>(p_object);
  1060. if (rc) {
  1061. // Unsafe refcount increment. The managed instance also counts as a reference.
  1062. // This way if the unmanaged world has no references to our owner
  1063. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1064. // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
  1065. rc->reference();
  1066. CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
  1067. }
  1068. return true;
  1069. }
  1070. RBMap<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
  1071. return script_bindings.insert(p_object, p_script_binding);
  1072. }
  1073. void *CSharpLanguage::_instance_binding_create_callback(void *, void *p_instance) {
  1074. CSharpLanguage *csharp_lang = CSharpLanguage::get_singleton();
  1075. MutexLock lock(csharp_lang->language_bind_mutex);
  1076. RBMap<Object *, CSharpScriptBinding>::Element *match = csharp_lang->script_bindings.find((Object *)p_instance);
  1077. if (match) {
  1078. return (void *)match;
  1079. }
  1080. CSharpScriptBinding script_binding;
  1081. return (void *)csharp_lang->insert_script_binding((Object *)p_instance, script_binding);
  1082. }
  1083. void CSharpLanguage::_instance_binding_free_callback(void *, void *, void *p_binding) {
  1084. CSharpLanguage *csharp_lang = CSharpLanguage::get_singleton();
  1085. if (GDMono::get_singleton() == nullptr) {
  1086. #ifdef DEBUG_ENABLED
  1087. CRASH_COND(csharp_lang && !csharp_lang->script_bindings.is_empty());
  1088. #endif
  1089. // Mono runtime finalized, all the gchandle bindings were already released
  1090. return;
  1091. }
  1092. if (csharp_lang->finalizing) {
  1093. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  1094. }
  1095. {
  1096. MutexLock lock(csharp_lang->language_bind_mutex);
  1097. RBMap<Object *, CSharpScriptBinding>::Element *data = (RBMap<Object *, CSharpScriptBinding>::Element *)p_binding;
  1098. CSharpScriptBinding &script_binding = data->value();
  1099. if (script_binding.inited) {
  1100. // Set the native instance field to IntPtr.Zero, if not yet garbage collected.
  1101. // This is done to avoid trying to dispose the native instance from Dispose(bool).
  1102. GDMonoCache::managed_callbacks.ScriptManagerBridge_SetGodotObjectPtr(
  1103. script_binding.gchandle.get_intptr(), nullptr);
  1104. script_binding.gchandle.release();
  1105. script_binding.inited = false;
  1106. }
  1107. csharp_lang->script_bindings.erase(data);
  1108. }
  1109. }
  1110. GDExtensionBool CSharpLanguage::_instance_binding_reference_callback(void *p_token, void *p_binding, GDExtensionBool p_reference) {
  1111. CRASH_COND(!p_binding);
  1112. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)p_binding)->get();
  1113. RefCounted *rc_owner = Object::cast_to<RefCounted>(script_binding.owner);
  1114. #ifdef DEBUG_ENABLED
  1115. CRASH_COND(!rc_owner);
  1116. #endif
  1117. MonoGCHandleData &gchandle = script_binding.gchandle;
  1118. int refcount = rc_owner->get_reference_count();
  1119. if (!script_binding.inited) {
  1120. return refcount == 0;
  1121. }
  1122. if (p_reference) {
  1123. // Refcount incremented
  1124. if (refcount > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1125. // The reference count was increased after the managed side was the only one referencing our owner.
  1126. // This means the owner is being referenced again by the unmanaged side,
  1127. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1128. // Release the current weak handle and replace it with a strong handle.
  1129. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1130. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1131. GCHandleIntPtr new_gchandle = { nullptr };
  1132. bool create_weak = false;
  1133. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1134. old_gchandle, &new_gchandle, create_weak);
  1135. if (!target_alive) {
  1136. return false; // Called after the managed side was collected, so nothing to do here
  1137. }
  1138. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1139. }
  1140. return false;
  1141. } else {
  1142. // Refcount decremented
  1143. if (refcount == 1 && !gchandle.is_released() && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1144. // If owner owner is no longer referenced by the unmanaged side,
  1145. // the managed instance takes responsibility of deleting the owner when GCed.
  1146. // Release the current strong handle and replace it with a weak handle.
  1147. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1148. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1149. GCHandleIntPtr new_gchandle = { nullptr };
  1150. bool create_weak = true;
  1151. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1152. old_gchandle, &new_gchandle, create_weak);
  1153. if (!target_alive) {
  1154. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1155. }
  1156. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
  1157. return false;
  1158. }
  1159. return refcount == 0;
  1160. }
  1161. }
  1162. void *CSharpLanguage::get_instance_binding(Object *p_object) {
  1163. void *binding = p_object->get_instance_binding(get_singleton(), &_instance_binding_callbacks);
  1164. // Initially this was in `_instance_binding_create_callback`. However, after the new instance
  1165. // binding re-write it was resulting in a deadlock in `_instance_binding_reference`, as
  1166. // `setup_csharp_script_binding` may call `reference()`. It was moved here outside to fix that.
  1167. if (binding) {
  1168. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)binding)->value();
  1169. if (!script_binding.inited) {
  1170. MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1171. if (!script_binding.inited) { // Another thread may have set it up
  1172. CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, p_object);
  1173. }
  1174. }
  1175. }
  1176. return binding;
  1177. }
  1178. void *CSharpLanguage::get_existing_instance_binding(Object *p_object) {
  1179. #ifdef DEBUG_ENABLED
  1180. CRASH_COND(p_object->has_instance_binding(p_object));
  1181. #endif
  1182. return p_object->get_instance_binding(get_singleton(), &_instance_binding_callbacks);
  1183. }
  1184. void CSharpLanguage::set_instance_binding(Object *p_object, void *p_binding) {
  1185. p_object->set_instance_binding(get_singleton(), p_binding, &_instance_binding_callbacks);
  1186. }
  1187. bool CSharpLanguage::has_instance_binding(Object *p_object) {
  1188. return p_object->has_instance_binding(get_singleton());
  1189. }
  1190. void CSharpLanguage::tie_native_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, const StringName *p_native_name, bool p_ref_counted) {
  1191. // This method should not fail
  1192. CRASH_COND(!p_unmanaged);
  1193. // All mono objects created from the managed world (e.g.: 'new Player()')
  1194. // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
  1195. RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
  1196. CRASH_COND(p_ref_counted != (bool)rc);
  1197. MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
  1198. p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
  1199. // If it's just a wrapper Godot class and not a custom inheriting class, then attach a
  1200. // script binding instead. One of the advantages of this is that if a script is attached
  1201. // later and it's not a C# script, then the managed object won't have to be disposed.
  1202. // Another reason for doing this is that this instance could outlive CSharpLanguage, which would
  1203. // be problematic when using a script. See: https://github.com/godotengine/godot/issues/25621
  1204. CSharpScriptBinding script_binding;
  1205. script_binding.inited = true;
  1206. script_binding.type_name = *p_native_name;
  1207. script_binding.gchandle = gchandle;
  1208. script_binding.owner = p_unmanaged;
  1209. if (p_ref_counted) {
  1210. // Unsafe refcount increment. The managed instance also counts as a reference.
  1211. // This way if the unmanaged world has no references to our owner
  1212. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1213. // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr)
  1214. // May not me referenced yet, so we must use init_ref() instead of reference()
  1215. if (rc->init_ref()) {
  1216. CSharpLanguage::get_singleton()->post_unsafe_reference(rc);
  1217. }
  1218. }
  1219. // The object was just created, no script instance binding should have been attached
  1220. CRASH_COND(CSharpLanguage::has_instance_binding(p_unmanaged));
  1221. void *data;
  1222. {
  1223. MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1224. data = (void *)CSharpLanguage::get_singleton()->insert_script_binding(p_unmanaged, script_binding);
  1225. }
  1226. // Should be thread safe because the object was just created and nothing else should be referencing it
  1227. CSharpLanguage::set_instance_binding(p_unmanaged, data);
  1228. }
  1229. void CSharpLanguage::tie_user_managed_to_unmanaged(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged, Ref<CSharpScript> *p_script, bool p_ref_counted) {
  1230. // This method should not fail
  1231. Ref<CSharpScript> script = *p_script;
  1232. // We take care of destructing this reference here, so the managed code won't need to do another P/Invoke call
  1233. p_script->~Ref();
  1234. CRASH_COND(!p_unmanaged);
  1235. // All mono objects created from the managed world (e.g.: 'new Player()')
  1236. // need to have a CSharpScript in order for their methods to be callable from the unmanaged side
  1237. RefCounted *rc = Object::cast_to<RefCounted>(p_unmanaged);
  1238. CRASH_COND(p_ref_counted != (bool)rc);
  1239. MonoGCHandleData gchandle = MonoGCHandleData(p_gchandle_intptr,
  1240. p_ref_counted ? gdmono::GCHandleType::WEAK_HANDLE : gdmono::GCHandleType::STRONG_HANDLE);
  1241. CRASH_COND(script.is_null());
  1242. CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(p_unmanaged, script.ptr(), gchandle);
  1243. p_unmanaged->set_script_and_instance(script, csharp_instance);
  1244. csharp_instance->connect_event_signals();
  1245. }
  1246. void CSharpLanguage::tie_managed_to_unmanaged_with_pre_setup(GCHandleIntPtr p_gchandle_intptr, Object *p_unmanaged) {
  1247. // This method should not fail
  1248. CRASH_COND(!p_unmanaged);
  1249. CSharpInstance *instance = CAST_CSHARP_INSTANCE(p_unmanaged->get_script_instance());
  1250. if (!instance) {
  1251. // Native bindings don't need post-setup
  1252. return;
  1253. }
  1254. CRASH_COND(!instance->gchandle.is_released());
  1255. // Tie managed to unmanaged
  1256. instance->gchandle = MonoGCHandleData(p_gchandle_intptr, gdmono::GCHandleType::STRONG_HANDLE);
  1257. if (instance->base_ref_counted) {
  1258. instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1259. }
  1260. {
  1261. MutexLock lock(CSharpLanguage::get_singleton()->get_script_instances_mutex());
  1262. // instances is a set, so it's safe to insert multiple times (e.g.: from _internal_new_managed)
  1263. instance->script->instances.insert(instance->owner);
  1264. }
  1265. instance->connect_event_signals();
  1266. }
  1267. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) {
  1268. CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script)));
  1269. RefCounted *rc = Object::cast_to<RefCounted>(p_owner);
  1270. instance->base_ref_counted = rc != nullptr;
  1271. instance->owner = p_owner;
  1272. instance->gchandle = p_gchandle;
  1273. if (instance->base_ref_counted) {
  1274. instance->_reference_owner_unsafe();
  1275. }
  1276. p_script->instances.insert(p_owner);
  1277. return instance;
  1278. }
  1279. Object *CSharpInstance::get_owner() {
  1280. return owner;
  1281. }
  1282. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  1283. ERR_FAIL_COND_V(!script.is_valid(), false);
  1284. return GDMonoCache::managed_callbacks.CSharpInstanceBridge_Set(
  1285. gchandle.get_intptr(), &p_name, &p_value);
  1286. }
  1287. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  1288. ERR_FAIL_COND_V(!script.is_valid(), false);
  1289. Variant ret_value;
  1290. bool ret = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Get(
  1291. gchandle.get_intptr(), &p_name, &ret_value);
  1292. if (ret) {
  1293. r_ret = ret_value;
  1294. return true;
  1295. }
  1296. return false;
  1297. }
  1298. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1299. List<PropertyInfo> props;
  1300. script->get_script_property_list(&props);
  1301. // Call _get_property_list
  1302. ERR_FAIL_COND(!script.is_valid());
  1303. StringName method = SNAME("_get_property_list");
  1304. Variant ret;
  1305. Callable::CallError call_error;
  1306. bool ok = GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1307. gchandle.get_intptr(), &method, nullptr, 0, &call_error, &ret);
  1308. // CALL_ERROR_INVALID_METHOD would simply mean it was not overridden
  1309. if (call_error.error != Callable::CallError::CALL_ERROR_INVALID_METHOD) {
  1310. if (call_error.error != Callable::CallError::CALL_OK) {
  1311. ERR_PRINT("Error calling '_get_property_list': " + Variant::get_call_error_text(method, nullptr, 0, call_error));
  1312. } else if (!ok) {
  1313. ERR_PRINT("Unexpected error calling '_get_property_list'");
  1314. } else {
  1315. Array array = ret;
  1316. for (int i = 0, size = array.size(); i < size; i++) {
  1317. p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
  1318. }
  1319. }
  1320. }
  1321. for (const PropertyInfo &prop : props) {
  1322. p_properties->push_back(prop);
  1323. }
  1324. }
  1325. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1326. if (script->member_info.has(p_name)) {
  1327. if (r_is_valid) {
  1328. *r_is_valid = true;
  1329. }
  1330. return script->member_info[p_name].type;
  1331. }
  1332. if (r_is_valid) {
  1333. *r_is_valid = false;
  1334. }
  1335. return Variant::NIL;
  1336. }
  1337. bool CSharpInstance::property_can_revert(const StringName &p_name) const {
  1338. ERR_FAIL_COND_V(!script.is_valid(), false);
  1339. Variant name_arg = p_name;
  1340. const Variant *args[1] = { &name_arg };
  1341. Variant ret;
  1342. Callable::CallError call_error;
  1343. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1344. gchandle.get_intptr(), &CACHED_STRING_NAME(_property_can_revert), args, 1, &call_error, &ret);
  1345. if (call_error.error != Callable::CallError::CALL_OK) {
  1346. return false;
  1347. }
  1348. return (bool)ret;
  1349. }
  1350. bool CSharpInstance::property_get_revert(const StringName &p_name, Variant &r_ret) const {
  1351. ERR_FAIL_COND_V(!script.is_valid(), false);
  1352. Variant name_arg = p_name;
  1353. const Variant *args[1] = { &name_arg };
  1354. Variant ret;
  1355. Callable::CallError call_error;
  1356. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1357. gchandle.get_intptr(), &CACHED_STRING_NAME(_property_get_revert), args, 1, &call_error, &ret);
  1358. if (call_error.error != Callable::CallError::CALL_OK) {
  1359. return false;
  1360. }
  1361. r_ret = ret;
  1362. return true;
  1363. }
  1364. void CSharpInstance::get_method_list(List<MethodInfo> *p_list) const {
  1365. if (!script->is_valid() || !script->valid) {
  1366. return;
  1367. }
  1368. const CSharpScript *top = script.ptr();
  1369. while (top != nullptr) {
  1370. for (const CSharpScript::CSharpMethodInfo &E : top->methods) {
  1371. p_list->push_back(E.method_info);
  1372. }
  1373. top = top->base_script.ptr();
  1374. }
  1375. }
  1376. bool CSharpInstance::has_method(const StringName &p_method) const {
  1377. if (!script.is_valid()) {
  1378. return false;
  1379. }
  1380. if (!GDMonoCache::godot_api_cache_updated) {
  1381. return false;
  1382. }
  1383. return GDMonoCache::managed_callbacks.CSharpInstanceBridge_HasMethodUnknownParams(
  1384. gchandle.get_intptr(), &p_method);
  1385. }
  1386. Variant CSharpInstance::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1387. ERR_FAIL_COND_V(!script.is_valid(), Variant());
  1388. Variant ret;
  1389. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1390. gchandle.get_intptr(), &p_method, p_args, p_argcount, &r_error, &ret);
  1391. return ret;
  1392. }
  1393. bool CSharpInstance::_reference_owner_unsafe() {
  1394. #ifdef DEBUG_ENABLED
  1395. CRASH_COND(!base_ref_counted);
  1396. CRASH_COND(owner == nullptr);
  1397. CRASH_COND(unsafe_referenced); // already referenced
  1398. #endif
  1399. // Unsafe refcount increment. The managed instance also counts as a reference.
  1400. // This way if the unmanaged world has no references to our owner
  1401. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1402. // See: _unreference_owner_unsafe()
  1403. // May not me referenced yet, so we must use init_ref() instead of reference()
  1404. if (static_cast<RefCounted *>(owner)->init_ref()) {
  1405. CSharpLanguage::get_singleton()->post_unsafe_reference(owner);
  1406. unsafe_referenced = true;
  1407. }
  1408. return unsafe_referenced;
  1409. }
  1410. bool CSharpInstance::_unreference_owner_unsafe() {
  1411. #ifdef DEBUG_ENABLED
  1412. CRASH_COND(!base_ref_counted);
  1413. CRASH_COND(owner == nullptr);
  1414. #endif
  1415. if (!unsafe_referenced) {
  1416. return false; // Already unreferenced
  1417. }
  1418. unsafe_referenced = false;
  1419. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1420. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1421. // See: _reference_owner_unsafe()
  1422. // Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
  1423. CSharpLanguage::get_singleton()->pre_unsafe_unreference(owner);
  1424. return static_cast<RefCounted *>(owner)->unreference();
  1425. }
  1426. bool CSharpInstance::_internal_new_managed() {
  1427. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1428. ERR_FAIL_NULL_V(owner, false);
  1429. ERR_FAIL_COND_V(script.is_null(), false);
  1430. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
  1431. script.ptr(), owner, nullptr, 0);
  1432. if (!ok) {
  1433. // Important to clear this before destroying the script instance here
  1434. script = Ref<CSharpScript>();
  1435. owner = nullptr;
  1436. return false;
  1437. }
  1438. CRASH_COND(gchandle.is_released());
  1439. return true;
  1440. }
  1441. void CSharpInstance::mono_object_disposed(GCHandleIntPtr p_gchandle_to_free) {
  1442. // Must make sure event signals are not left dangling
  1443. disconnect_event_signals();
  1444. #ifdef DEBUG_ENABLED
  1445. CRASH_COND(base_ref_counted);
  1446. CRASH_COND(gchandle.is_released());
  1447. #endif
  1448. CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
  1449. }
  1450. void CSharpInstance::mono_object_disposed_baseref(GCHandleIntPtr p_gchandle_to_free, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
  1451. #ifdef DEBUG_ENABLED
  1452. CRASH_COND(!base_ref_counted);
  1453. CRASH_COND(gchandle.is_released());
  1454. #endif
  1455. // Must make sure event signals are not left dangling
  1456. disconnect_event_signals();
  1457. r_remove_script_instance = false;
  1458. if (_unreference_owner_unsafe()) {
  1459. // Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
  1460. r_delete_owner = true;
  1461. } else {
  1462. r_delete_owner = false;
  1463. CSharpLanguage::get_singleton()->release_script_gchandle_thread_safe(p_gchandle_to_free, gchandle);
  1464. if (!p_is_finalizer) {
  1465. // If the native instance is still alive and Dispose() was called
  1466. // (instead of the finalizer), then we remove the script instance.
  1467. r_remove_script_instance = true;
  1468. // TODO: Last usage of 'is_finalizing_scripts_domain'. It should be replaced with a check to determine if the load context is being unloaded.
  1469. } else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  1470. // If the native instance is still alive and this is called from the finalizer,
  1471. // then it was referenced from another thread before the finalizer could
  1472. // unreference and delete it, so we want to keep it.
  1473. // GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
  1474. // could have already been collected. Instead we will create a new managed instance here.
  1475. if (!_internal_new_managed()) {
  1476. r_remove_script_instance = true;
  1477. }
  1478. }
  1479. }
  1480. }
  1481. void CSharpInstance::connect_event_signals() {
  1482. // The script signals list includes the signals declared in base scripts.
  1483. for (CSharpScript::EventSignalInfo &signal : script->get_script_event_signals()) {
  1484. String signal_name = signal.name;
  1485. // TODO: Use pooling for ManagedCallable instances.
  1486. EventSignalCallable *event_signal_callable = memnew(EventSignalCallable(owner, signal_name));
  1487. Callable callable(event_signal_callable);
  1488. connected_event_signals.push_back(callable);
  1489. owner->connect(signal_name, callable);
  1490. }
  1491. }
  1492. void CSharpInstance::disconnect_event_signals() {
  1493. for (const Callable &callable : connected_event_signals) {
  1494. const EventSignalCallable *event_signal_callable = static_cast<const EventSignalCallable *>(callable.get_custom());
  1495. owner->disconnect(event_signal_callable->get_signal(), callable);
  1496. }
  1497. connected_event_signals.clear();
  1498. }
  1499. void CSharpInstance::refcount_incremented() {
  1500. #ifdef DEBUG_ENABLED
  1501. CRASH_COND(!base_ref_counted);
  1502. CRASH_COND(owner == nullptr);
  1503. #endif
  1504. RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
  1505. if (rc_owner->get_reference_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1506. // The reference count was increased after the managed side was the only one referencing our owner.
  1507. // This means the owner is being referenced again by the unmanaged side,
  1508. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1509. // Release the current weak handle and replace it with a strong handle.
  1510. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1511. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1512. GCHandleIntPtr new_gchandle = { nullptr };
  1513. bool create_weak = false;
  1514. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1515. old_gchandle, &new_gchandle, create_weak);
  1516. if (!target_alive) {
  1517. return; // Called after the managed side was collected, so nothing to do here
  1518. }
  1519. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::STRONG_HANDLE);
  1520. }
  1521. }
  1522. bool CSharpInstance::refcount_decremented() {
  1523. #ifdef DEBUG_ENABLED
  1524. CRASH_COND(!base_ref_counted);
  1525. CRASH_COND(owner == nullptr);
  1526. #endif
  1527. RefCounted *rc_owner = Object::cast_to<RefCounted>(owner);
  1528. int refcount = rc_owner->get_reference_count();
  1529. if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1530. // If owner owner is no longer referenced by the unmanaged side,
  1531. // the managed instance takes responsibility of deleting the owner when GCed.
  1532. // Release the current strong handle and replace it with a weak handle.
  1533. GCHandleIntPtr old_gchandle = gchandle.get_intptr();
  1534. gchandle.handle = { nullptr }; // No longer owns the handle (released by swap function)
  1535. GCHandleIntPtr new_gchandle = { nullptr };
  1536. bool create_weak = true;
  1537. bool target_alive = GDMonoCache::managed_callbacks.ScriptManagerBridge_SwapGCHandleForType(
  1538. old_gchandle, &new_gchandle, create_weak);
  1539. if (!target_alive) {
  1540. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1541. }
  1542. gchandle = MonoGCHandleData(new_gchandle, gdmono::GCHandleType::WEAK_HANDLE);
  1543. return false;
  1544. }
  1545. ref_dying = (refcount == 0);
  1546. return ref_dying;
  1547. }
  1548. const Variant CSharpInstance::get_rpc_config() const {
  1549. return script->get_rpc_config();
  1550. }
  1551. void CSharpInstance::notification(int p_notification) {
  1552. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1553. // When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
  1554. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
  1555. // to be sent at least once, which happens right before the call to the destructor.
  1556. predelete_notified = true;
  1557. if (base_ref_counted) {
  1558. // It's not safe to proceed if the owner derives RefCounted and the refcount reached 0.
  1559. // At this point, Dispose() was already called (manually or from the finalizer) so
  1560. // that's not a problem. The refcount wouldn't have reached 0 otherwise, since the
  1561. // managed side references it and Dispose() needs to be called to release it.
  1562. // However, this means C# RefCounted scripts can't receive NOTIFICATION_PREDELETE, but
  1563. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1564. return;
  1565. }
  1566. _call_notification(p_notification);
  1567. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1568. gchandle.get_intptr(), /* okIfNull */ false);
  1569. return;
  1570. }
  1571. _call_notification(p_notification);
  1572. }
  1573. void CSharpInstance::_call_notification(int p_notification) {
  1574. Variant arg = p_notification;
  1575. const Variant *args[1] = { &arg };
  1576. StringName method_name = SNAME("_notification");
  1577. Callable::CallError call_error;
  1578. Variant ret;
  1579. GDMonoCache::managed_callbacks.CSharpInstanceBridge_Call(
  1580. gchandle.get_intptr(), &method_name, args, 1, &call_error, &ret);
  1581. }
  1582. String CSharpInstance::to_string(bool *r_valid) {
  1583. String res;
  1584. bool valid;
  1585. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallToString(
  1586. gchandle.get_intptr(), &res, &valid);
  1587. if (r_valid) {
  1588. *r_valid = valid;
  1589. }
  1590. return res;
  1591. }
  1592. Ref<Script> CSharpInstance::get_script() const {
  1593. return script;
  1594. }
  1595. ScriptLanguage *CSharpInstance::get_language() {
  1596. return CSharpLanguage::get_singleton();
  1597. }
  1598. CSharpInstance::CSharpInstance(const Ref<CSharpScript> &p_script) :
  1599. script(p_script) {
  1600. }
  1601. CSharpInstance::~CSharpInstance() {
  1602. destructing_script_instance = true;
  1603. // Must make sure event signals are not left dangling
  1604. disconnect_event_signals();
  1605. if (!gchandle.is_released()) {
  1606. if (!predelete_notified && !ref_dying) {
  1607. // This destructor is not called from the owners destructor.
  1608. // This could be being called from the owner's set_script_instance method,
  1609. // meaning this script is being replaced with another one. If this is the case,
  1610. // we must call Dispose here, because Dispose calls owner->set_script_instance(nullptr)
  1611. // and that would mess up with the new script instance if called later.
  1612. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1613. gchandle.get_intptr(), /* okIfNull */ true);
  1614. }
  1615. gchandle.release(); // Make sure the gchandle is released
  1616. }
  1617. // If not being called from the owner's destructor, and we still hold a reference to the owner
  1618. if (base_ref_counted && !ref_dying && owner && unsafe_referenced) {
  1619. // The owner's script or script instance is being replaced (or removed)
  1620. // Transfer ownership to an "instance binding"
  1621. RefCounted *rc_owner = static_cast<RefCounted *>(owner);
  1622. // We will unreference the owner before referencing it again, so we need to keep it alive
  1623. Ref<RefCounted> scope_keep_owner_alive(rc_owner);
  1624. (void)scope_keep_owner_alive;
  1625. // Unreference the owner here, before the new "instance binding" references it.
  1626. // Otherwise, the unsafe reference debug checks will incorrectly detect a bug.
  1627. bool die = _unreference_owner_unsafe();
  1628. CRASH_COND(die); // `owner_keep_alive` holds a reference, so it can't die
  1629. void *data = CSharpLanguage::get_instance_binding(owner);
  1630. CRASH_COND(data == nullptr);
  1631. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
  1632. CRASH_COND(!script_binding.inited);
  1633. #ifdef DEBUG_ENABLED
  1634. // The "instance binding" holds a reference so the refcount should be at least 2 before `scope_keep_owner_alive` goes out of scope
  1635. CRASH_COND(rc_owner->get_reference_count() <= 1);
  1636. #endif
  1637. }
  1638. if (script.is_valid() && owner) {
  1639. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  1640. #ifdef DEBUG_ENABLED
  1641. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1642. HashSet<Object *>::Iterator match = script->instances.find(owner);
  1643. CRASH_COND(!match);
  1644. script->instances.remove(match);
  1645. #else
  1646. script->instances.erase(owner);
  1647. #endif
  1648. }
  1649. }
  1650. #ifdef TOOLS_ENABLED
  1651. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1652. placeholders.erase(p_placeholder);
  1653. }
  1654. #endif
  1655. #ifdef TOOLS_ENABLED
  1656. void CSharpScript::_update_exports_values(HashMap<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1657. for (const KeyValue<StringName, Variant> &E : exported_members_defval_cache) {
  1658. values[E.key] = E.value;
  1659. }
  1660. for (const PropertyInfo &prop_info : exported_members_cache) {
  1661. propnames.push_back(prop_info);
  1662. }
  1663. if (base_script.is_valid()) {
  1664. base_script->_update_exports_values(values, propnames);
  1665. }
  1666. }
  1667. #endif
  1668. void GD_CLR_STDCALL CSharpScript::_add_property_info_list_callback(CSharpScript *p_script, const String *p_current_class_name, void *p_props, int32_t p_count) {
  1669. GDMonoCache::godotsharp_property_info *props = (GDMonoCache::godotsharp_property_info *)p_props;
  1670. #ifdef TOOLS_ENABLED
  1671. p_script->exported_members_cache.push_back(PropertyInfo(
  1672. Variant::NIL, *p_current_class_name, PROPERTY_HINT_NONE,
  1673. p_script->get_path(), PROPERTY_USAGE_CATEGORY));
  1674. #endif
  1675. for (int i = 0; i < p_count; i++) {
  1676. const GDMonoCache::godotsharp_property_info &prop = props[i];
  1677. StringName name = *reinterpret_cast<const StringName *>(&prop.name);
  1678. String hint_string = *reinterpret_cast<const String *>(&prop.hint_string);
  1679. PropertyInfo pinfo(prop.type, name, prop.hint, hint_string, prop.usage);
  1680. p_script->member_info[name] = pinfo;
  1681. if (prop.exported) {
  1682. #ifdef TOOLS_ENABLED
  1683. p_script->exported_members_cache.push_back(pinfo);
  1684. #endif
  1685. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  1686. p_script->exported_members_names.insert(name);
  1687. #endif
  1688. }
  1689. }
  1690. }
  1691. #ifdef TOOLS_ENABLED
  1692. void GD_CLR_STDCALL CSharpScript::_add_property_default_values_callback(CSharpScript *p_script, void *p_def_vals, int32_t p_count) {
  1693. GDMonoCache::godotsharp_property_def_val_pair *def_vals = (GDMonoCache::godotsharp_property_def_val_pair *)p_def_vals;
  1694. for (int i = 0; i < p_count; i++) {
  1695. const GDMonoCache::godotsharp_property_def_val_pair &def_val_pair = def_vals[i];
  1696. StringName name = *reinterpret_cast<const StringName *>(&def_val_pair.name);
  1697. Variant value = *reinterpret_cast<const Variant *>(&def_val_pair.value);
  1698. p_script->exported_members_defval_cache[name] = value;
  1699. }
  1700. }
  1701. #endif
  1702. bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_update) {
  1703. #ifdef TOOLS_ENABLED
  1704. bool is_editor = Engine::get_singleton()->is_editor_hint();
  1705. if (is_editor) {
  1706. placeholder_fallback_enabled = true; // until proven otherwise
  1707. }
  1708. #endif
  1709. if (!valid) {
  1710. return false;
  1711. }
  1712. bool changed = false;
  1713. #ifdef TOOLS_ENABLED
  1714. if (exports_invalidated)
  1715. #endif
  1716. {
  1717. #ifdef TOOLS_ENABLED
  1718. exports_invalidated = false;
  1719. #endif
  1720. changed = true;
  1721. member_info.clear();
  1722. #ifdef TOOLS_ENABLED
  1723. exported_members_cache.clear();
  1724. exported_members_defval_cache.clear();
  1725. #endif
  1726. if (GDMonoCache::godot_api_cache_updated) {
  1727. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyInfoList(this, &_add_property_info_list_callback);
  1728. #ifdef TOOLS_ENABLED
  1729. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyDefaultValues(this, &_add_property_default_values_callback);
  1730. #endif
  1731. }
  1732. }
  1733. #ifdef TOOLS_ENABLED
  1734. if (is_editor) {
  1735. placeholder_fallback_enabled = false;
  1736. if ((changed || p_instance_to_update) && placeholders.size()) {
  1737. // Update placeholders if any
  1738. HashMap<StringName, Variant> values;
  1739. List<PropertyInfo> propnames;
  1740. _update_exports_values(values, propnames);
  1741. if (changed) {
  1742. for (PlaceHolderScriptInstance *instance : placeholders) {
  1743. instance->update(propnames, values);
  1744. }
  1745. } else {
  1746. p_instance_to_update->update(propnames, values);
  1747. }
  1748. }
  1749. }
  1750. #endif
  1751. return changed;
  1752. }
  1753. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1754. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1755. r_ret = get_source_code();
  1756. return true;
  1757. }
  1758. return false;
  1759. }
  1760. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1761. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1762. set_source_code(p_value);
  1763. reload();
  1764. return true;
  1765. }
  1766. return false;
  1767. }
  1768. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1769. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
  1770. }
  1771. void CSharpScript::_bind_methods() {
  1772. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
  1773. }
  1774. void CSharpScript::reload_registered_script(Ref<CSharpScript> p_script) {
  1775. // IMPORTANT:
  1776. // This method must be called only after the CSharpScript and its associated type
  1777. // have been added to the script bridge map in the ScriptManagerBridge C# class.
  1778. // Other than that, it's the same as `CSharpScript::reload`.
  1779. // This method should not fail, only assertions allowed.
  1780. // Unlike `reload`, we print an error rather than silently returning,
  1781. // as we can assert this won't be called a second time until invalidated.
  1782. ERR_FAIL_COND(!p_script->reload_invalidated);
  1783. p_script->valid = true;
  1784. p_script->reload_invalidated = false;
  1785. update_script_class_info(p_script);
  1786. p_script->_update_exports();
  1787. #if TOOLS_ENABLED
  1788. // If the EditorFileSystem singleton is available, update the file;
  1789. // otherwise, the file will be updated when the singleton becomes available.
  1790. EditorFileSystem *efs = EditorFileSystem::get_singleton();
  1791. if (efs) {
  1792. efs->update_file(p_script->get_path());
  1793. }
  1794. #endif
  1795. }
  1796. // Extract information about the script using the mono class.
  1797. void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) {
  1798. bool tool = false;
  1799. bool global_class = false;
  1800. // TODO: Use GDExtension godot_dictionary
  1801. Array methods_array;
  1802. methods_array.~Array();
  1803. Dictionary rpc_functions_dict;
  1804. rpc_functions_dict.~Dictionary();
  1805. Dictionary signals_dict;
  1806. signals_dict.~Dictionary();
  1807. String class_name;
  1808. String icon_path;
  1809. Ref<CSharpScript> base_script;
  1810. GDMonoCache::managed_callbacks.ScriptManagerBridge_UpdateScriptClassInfo(
  1811. p_script.ptr(), &class_name, &tool, &global_class, &icon_path,
  1812. &methods_array, &rpc_functions_dict, &signals_dict, &base_script);
  1813. p_script->class_name = class_name;
  1814. p_script->tool = tool;
  1815. p_script->global_class = global_class;
  1816. p_script->icon_path = icon_path;
  1817. p_script->rpc_config.clear();
  1818. p_script->rpc_config = rpc_functions_dict;
  1819. // Methods
  1820. p_script->methods.clear();
  1821. p_script->methods.resize(methods_array.size());
  1822. int push_index = 0;
  1823. for (int i = 0; i < methods_array.size(); i++) {
  1824. Dictionary method_info_dict = methods_array[i];
  1825. StringName name = method_info_dict["name"];
  1826. MethodInfo mi;
  1827. mi.name = name;
  1828. Array params = method_info_dict["params"];
  1829. for (int j = 0; j < params.size(); j++) {
  1830. Dictionary param = params[j];
  1831. Variant::Type param_type = (Variant::Type)(int)param["type"];
  1832. PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
  1833. arg_info.usage = (uint32_t)param["usage"];
  1834. mi.arguments.push_back(arg_info);
  1835. }
  1836. p_script->methods.set(push_index++, CSharpMethodInfo{ name, mi });
  1837. }
  1838. // Event signals
  1839. // Performance is not critical here as this will be replaced with source generators.
  1840. p_script->event_signals.clear();
  1841. // Sigh... can't we just have capacity?
  1842. p_script->event_signals.resize(signals_dict.size());
  1843. push_index = 0;
  1844. for (const Variant *s = signals_dict.next(nullptr); s != nullptr; s = signals_dict.next(s)) {
  1845. StringName name = *s;
  1846. MethodInfo mi;
  1847. mi.name = name;
  1848. Array params = signals_dict[*s];
  1849. for (int i = 0; i < params.size(); i++) {
  1850. Dictionary param = params[i];
  1851. Variant::Type param_type = (Variant::Type)(int)param["type"];
  1852. PropertyInfo arg_info = PropertyInfo(param_type, (String)param["name"]);
  1853. arg_info.usage = (uint32_t)param["usage"];
  1854. mi.arguments.push_back(arg_info);
  1855. }
  1856. p_script->event_signals.set(push_index++, EventSignalInfo{ name, mi });
  1857. }
  1858. p_script->base_script = base_script;
  1859. }
  1860. bool CSharpScript::can_instantiate() const {
  1861. #ifdef TOOLS_ENABLED
  1862. bool extra_cond = tool || ScriptServer::is_scripting_enabled();
  1863. #else
  1864. bool extra_cond = true;
  1865. #endif
  1866. // FIXME Need to think this through better.
  1867. // For tool scripts, this will never fire if the class is not found. That's because we
  1868. // don't know if it's a tool script if we can't find the class to access the attributes.
  1869. if (extra_cond && !valid) {
  1870. ERR_FAIL_V_MSG(false, "Cannot instance script because the associated class could not be found. Script: '" + get_path() + "'. Make sure the script exists and contains a class definition with a name that matches the filename of the script exactly (it's case-sensitive).");
  1871. }
  1872. return valid && extra_cond;
  1873. }
  1874. StringName CSharpScript::get_instance_base_type() const {
  1875. StringName native_name;
  1876. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1877. return native_name;
  1878. }
  1879. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error) {
  1880. /* STEP 1, CREATE */
  1881. Ref<RefCounted> ref;
  1882. if (p_is_ref_counted) {
  1883. // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
  1884. ref = Ref<RefCounted>(static_cast<RefCounted *>(p_owner));
  1885. }
  1886. // If the object had a script instance binding, dispose it before adding the CSharpInstance
  1887. if (CSharpLanguage::has_instance_binding(p_owner)) {
  1888. void *data = CSharpLanguage::get_existing_instance_binding(p_owner);
  1889. CRASH_COND(data == nullptr);
  1890. CSharpScriptBinding &script_binding = ((RBMap<Object *, CSharpScriptBinding>::Element *)data)->get();
  1891. if (script_binding.inited && !script_binding.gchandle.is_released()) {
  1892. GDMonoCache::managed_callbacks.CSharpInstanceBridge_CallDispose(
  1893. script_binding.gchandle.get_intptr(), /* okIfNull */ true);
  1894. script_binding.gchandle.release(); // Just in case
  1895. script_binding.inited = false;
  1896. }
  1897. }
  1898. CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(this)));
  1899. instance->base_ref_counted = p_is_ref_counted;
  1900. instance->owner = p_owner;
  1901. instance->owner->set_script_instance(instance);
  1902. /* STEP 2, INITIALIZE AND CONSTRUCT */
  1903. bool ok = GDMonoCache::managed_callbacks.ScriptManagerBridge_CreateManagedForGodotObjectScriptInstance(
  1904. this, p_owner, p_args, p_argcount);
  1905. if (!ok) {
  1906. // Important to clear this before destroying the script instance here
  1907. instance->script = Ref<CSharpScript>();
  1908. instance->owner = nullptr;
  1909. p_owner->set_script_instance(nullptr);
  1910. return nullptr;
  1911. }
  1912. CRASH_COND(instance->gchandle.is_released());
  1913. /* STEP 3, PARTY */
  1914. //@TODO make thread safe
  1915. return instance;
  1916. }
  1917. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1918. if (!valid) {
  1919. r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
  1920. return Variant();
  1921. }
  1922. r_error.error = Callable::CallError::CALL_OK;
  1923. StringName native_name;
  1924. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1925. ERR_FAIL_COND_V(native_name == StringName(), Variant());
  1926. Object *owner = ClassDB::instantiate(native_name);
  1927. Ref<RefCounted> ref;
  1928. RefCounted *r = Object::cast_to<RefCounted>(owner);
  1929. if (r) {
  1930. ref = Ref<RefCounted>(r);
  1931. }
  1932. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != nullptr, r_error);
  1933. if (!instance) {
  1934. if (ref.is_null()) {
  1935. memdelete(owner); // no owner, sorry
  1936. }
  1937. return Variant();
  1938. }
  1939. if (ref.is_valid()) {
  1940. return ref;
  1941. } else {
  1942. return owner;
  1943. }
  1944. }
  1945. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  1946. #ifdef DEBUG_ENABLED
  1947. CRASH_COND(!valid);
  1948. #endif
  1949. StringName native_name;
  1950. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetScriptNativeName(this, &native_name);
  1951. ERR_FAIL_COND_V(native_name == StringName(), nullptr);
  1952. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  1953. if (EngineDebugger::is_active()) {
  1954. CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0,
  1955. "Script inherits from native type '" + String(native_name) +
  1956. "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'");
  1957. }
  1958. ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) + "', so it can't be assigned to an object of type: '" + p_this->get_class() + "'.");
  1959. }
  1960. Callable::CallError unchecked_error;
  1961. return _create_instance(nullptr, 0, p_this, Object::cast_to<RefCounted>(p_this) != nullptr, unchecked_error);
  1962. }
  1963. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  1964. #ifdef TOOLS_ENABLED
  1965. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  1966. placeholders.insert(si);
  1967. _update_exports(si);
  1968. return si;
  1969. #else
  1970. return nullptr;
  1971. #endif
  1972. }
  1973. bool CSharpScript::instance_has(const Object *p_this) const {
  1974. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  1975. return instances.has((Object *)p_this);
  1976. }
  1977. bool CSharpScript::has_source_code() const {
  1978. return !source.is_empty();
  1979. }
  1980. String CSharpScript::get_source_code() const {
  1981. return source;
  1982. }
  1983. void CSharpScript::set_source_code(const String &p_code) {
  1984. if (source == p_code) {
  1985. return;
  1986. }
  1987. source = p_code;
  1988. #ifdef TOOLS_ENABLED
  1989. source_changed_cache = true;
  1990. #endif
  1991. }
  1992. void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
  1993. if (!valid) {
  1994. return;
  1995. }
  1996. const CSharpScript *top = this;
  1997. while (top != nullptr) {
  1998. for (const CSharpMethodInfo &E : top->methods) {
  1999. p_list->push_back(E.method_info);
  2000. }
  2001. top = top->base_script.ptr();
  2002. }
  2003. }
  2004. bool CSharpScript::has_method(const StringName &p_method) const {
  2005. if (!valid) {
  2006. return false;
  2007. }
  2008. for (const CSharpMethodInfo &E : methods) {
  2009. if (E.name == p_method) {
  2010. return true;
  2011. }
  2012. }
  2013. return false;
  2014. }
  2015. MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
  2016. if (!valid) {
  2017. return MethodInfo();
  2018. }
  2019. for (const CSharpMethodInfo &E : methods) {
  2020. if (E.name == p_method) {
  2021. return E.method_info;
  2022. }
  2023. }
  2024. return MethodInfo();
  2025. }
  2026. Error CSharpScript::reload(bool p_keep_state) {
  2027. if (!reload_invalidated) {
  2028. return OK;
  2029. }
  2030. // In the case of C#, reload doesn't really do any script reloading.
  2031. // That's done separately via domain reloading.
  2032. reload_invalidated = false;
  2033. String script_path = get_path();
  2034. valid = GDMonoCache::managed_callbacks.ScriptManagerBridge_AddScriptBridge(this, &script_path);
  2035. if (valid) {
  2036. #ifdef DEBUG_ENABLED
  2037. print_verbose("Found class for script " + get_path());
  2038. #endif
  2039. update_script_class_info(this);
  2040. _update_exports();
  2041. #if TOOLS_ENABLED
  2042. // If the EditorFileSystem singleton is available, update the file;
  2043. // otherwise, the file will be updated when the singleton becomes available.
  2044. EditorFileSystem *efs = EditorFileSystem::get_singleton();
  2045. if (efs) {
  2046. efs->update_file(script_path);
  2047. }
  2048. #endif
  2049. }
  2050. return OK;
  2051. }
  2052. ScriptLanguage *CSharpScript::get_language() const {
  2053. return CSharpLanguage::get_singleton();
  2054. }
  2055. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  2056. #ifdef TOOLS_ENABLED
  2057. HashMap<StringName, Variant>::ConstIterator E = exported_members_defval_cache.find(p_property);
  2058. if (E) {
  2059. r_value = E->value;
  2060. return true;
  2061. }
  2062. if (base_script.is_valid()) {
  2063. return base_script->get_property_default_value(p_property, r_value);
  2064. }
  2065. #endif
  2066. return false;
  2067. }
  2068. void CSharpScript::update_exports() {
  2069. #ifdef TOOLS_ENABLED
  2070. _update_exports();
  2071. #endif
  2072. }
  2073. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  2074. if (!valid) {
  2075. return false;
  2076. }
  2077. if (!GDMonoCache::godot_api_cache_updated) {
  2078. return false;
  2079. }
  2080. for (const EventSignalInfo &signal : event_signals) {
  2081. if (signal.name == p_signal) {
  2082. return true;
  2083. }
  2084. }
  2085. return false;
  2086. }
  2087. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  2088. if (!valid) {
  2089. return;
  2090. }
  2091. for (const EventSignalInfo &signal : get_script_event_signals()) {
  2092. r_signals->push_back(signal.method_info);
  2093. }
  2094. }
  2095. Vector<CSharpScript::EventSignalInfo> CSharpScript::get_script_event_signals() const {
  2096. if (!valid) {
  2097. return Vector<EventSignalInfo>();
  2098. }
  2099. return event_signals;
  2100. }
  2101. bool CSharpScript::inherits_script(const Ref<Script> &p_script) const {
  2102. Ref<CSharpScript> cs = p_script;
  2103. if (cs.is_null()) {
  2104. return false;
  2105. }
  2106. if (!valid || !cs->valid) {
  2107. return false;
  2108. }
  2109. if (!GDMonoCache::godot_api_cache_updated) {
  2110. return false;
  2111. }
  2112. return GDMonoCache::managed_callbacks.ScriptManagerBridge_ScriptIsOrInherits(this, cs.ptr());
  2113. }
  2114. Ref<Script> CSharpScript::get_base_script() const {
  2115. return base_script.is_valid() && !base_script->get_path().is_empty() ? base_script : nullptr;
  2116. }
  2117. StringName CSharpScript::get_global_name() const {
  2118. return global_class ? StringName(class_name) : StringName();
  2119. }
  2120. void CSharpScript::get_script_property_list(List<PropertyInfo> *r_list) const {
  2121. #ifdef TOOLS_ENABLED
  2122. const CSharpScript *top = this;
  2123. while (top != nullptr) {
  2124. for (const PropertyInfo &E : top->exported_members_cache) {
  2125. r_list->push_back(E);
  2126. }
  2127. top = top->base_script.ptr();
  2128. }
  2129. #else
  2130. const CSharpScript *top = this;
  2131. while (top != nullptr) {
  2132. List<PropertyInfo> props;
  2133. for (const KeyValue<StringName, PropertyInfo> &E : top->member_info) {
  2134. props.push_front(E.value);
  2135. }
  2136. for (const PropertyInfo &prop : props) {
  2137. r_list->push_back(prop);
  2138. }
  2139. top = top->base_script.ptr();
  2140. }
  2141. #endif
  2142. }
  2143. int CSharpScript::get_member_line(const StringName &p_member) const {
  2144. // TODO omnisharp
  2145. return -1;
  2146. }
  2147. const Variant CSharpScript::get_rpc_config() const {
  2148. return rpc_config;
  2149. }
  2150. Error CSharpScript::load_source_code(const String &p_path) {
  2151. Error ferr = read_all_file_utf8(p_path, source);
  2152. ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
  2153. ferr == ERR_INVALID_DATA
  2154. ? "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
  2155. " Please ensure that scripts are saved in valid UTF-8 unicode."
  2156. : "Failed to read file: '" + p_path + "'.");
  2157. #ifdef TOOLS_ENABLED
  2158. source_changed_cache = true;
  2159. #endif
  2160. return OK;
  2161. }
  2162. void CSharpScript::_clear() {
  2163. tool = false;
  2164. valid = false;
  2165. reload_invalidated = true;
  2166. }
  2167. CSharpScript::CSharpScript() {
  2168. _clear();
  2169. #ifdef DEBUG_ENABLED
  2170. {
  2171. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2172. CSharpLanguage::get_singleton()->script_list.add(&this->script_list);
  2173. }
  2174. #endif
  2175. }
  2176. CSharpScript::~CSharpScript() {
  2177. #ifdef DEBUG_ENABLED
  2178. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2179. CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
  2180. #endif
  2181. if (GDMonoCache::godot_api_cache_updated) {
  2182. GDMonoCache::managed_callbacks.ScriptManagerBridge_RemoveScriptBridge(this);
  2183. }
  2184. }
  2185. void CSharpScript::get_members(HashSet<StringName> *p_members) {
  2186. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  2187. if (p_members) {
  2188. for (const StringName &member_name : exported_members_names) {
  2189. p_members->insert(member_name);
  2190. }
  2191. }
  2192. #endif
  2193. }
  2194. /*************** RESOURCE ***************/
  2195. Ref<Resource> ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  2196. if (r_error) {
  2197. *r_error = ERR_FILE_CANT_OPEN;
  2198. }
  2199. // TODO ignore anything inside bin/ and obj/ in tools builds?
  2200. Ref<CSharpScript> scr;
  2201. if (GDMonoCache::godot_api_cache_updated) {
  2202. GDMonoCache::managed_callbacks.ScriptManagerBridge_GetOrCreateScriptBridgeForPath(&p_path, &scr);
  2203. } else {
  2204. scr = Ref<CSharpScript>(memnew(CSharpScript));
  2205. }
  2206. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  2207. Error err = scr->load_source_code(p_path);
  2208. ERR_FAIL_COND_V_MSG(err != OK, Ref<Resource>(), "Cannot load C# script file '" + p_path + "'.");
  2209. #endif
  2210. scr->set_path(p_original_path);
  2211. scr->reload();
  2212. if (r_error) {
  2213. *r_error = OK;
  2214. }
  2215. return scr;
  2216. }
  2217. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2218. p_extensions->push_back("cs");
  2219. }
  2220. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2221. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2222. }
  2223. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2224. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  2225. }
  2226. Error ResourceFormatSaverCSharpScript::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  2227. Ref<CSharpScript> sqscr = p_resource;
  2228. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2229. String source = sqscr->get_source_code();
  2230. #ifdef TOOLS_ENABLED
  2231. if (!FileAccess::exists(p_path)) {
  2232. // The file does not yet exist, let's assume the user just created this script. In such
  2233. // cases we need to check whether the solution and csproj were already created or not.
  2234. if (!_create_project_solution_if_needed()) {
  2235. ERR_PRINT("C# project could not be created; cannot add file: '" + p_path + "'.");
  2236. }
  2237. }
  2238. #endif
  2239. {
  2240. Error err;
  2241. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2242. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'.");
  2243. file->store_string(source);
  2244. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2245. return ERR_CANT_CREATE;
  2246. }
  2247. }
  2248. #ifdef TOOLS_ENABLED
  2249. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2250. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2251. }
  2252. #endif
  2253. return OK;
  2254. }
  2255. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  2256. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2257. p_extensions->push_back("cs");
  2258. }
  2259. }
  2260. bool ResourceFormatSaverCSharpScript::recognize(const Ref<Resource> &p_resource) const {
  2261. return Object::cast_to<CSharpScript>(p_resource.ptr()) != nullptr;
  2262. }
  2263. CSharpLanguage::StringNameCache::StringNameCache() {
  2264. _property_can_revert = StaticCString::create("_property_can_revert");
  2265. _property_get_revert = StaticCString::create("_property_get_revert");
  2266. _script_source = StaticCString::create("script/source");
  2267. }