csharp_script.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489
  1. /*************************************************************************/
  2. /* csharp_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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 <mono/metadata/threads.h>
  32. #include "core/io/json.h"
  33. #include "core/os/file_access.h"
  34. #include "core/os/os.h"
  35. #include "core/os/thread.h"
  36. #include "core/project_settings.h"
  37. #ifdef TOOLS_ENABLED
  38. #include "editor/bindings_generator.h"
  39. #include "editor/csharp_project.h"
  40. #include "editor/editor_node.h"
  41. #include "editor/node_dock.h"
  42. #endif
  43. #ifdef DEBUG_METHODS_ENABLED
  44. #include "class_db_api_json.h"
  45. #endif
  46. #include "editor/editor_internal_calls.h"
  47. #include "godotsharp_dirs.h"
  48. #include "mono_gd/gd_mono_cache.h"
  49. #include "mono_gd/gd_mono_class.h"
  50. #include "mono_gd/gd_mono_marshal.h"
  51. #include "mono_gd/gd_mono_utils.h"
  52. #include "signal_awaiter_utils.h"
  53. #include "utils/macros.h"
  54. #include "utils/string_utils.h"
  55. #include "utils/thread_local.h"
  56. #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var)
  57. #ifdef TOOLS_ENABLED
  58. static bool _create_project_solution_if_needed() {
  59. String sln_path = GodotSharpDirs::get_project_sln_path();
  60. String csproj_path = GodotSharpDirs::get_project_csproj_path();
  61. if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
  62. // A solution does not yet exist, create a new one
  63. CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == NULL);
  64. return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolution");
  65. }
  66. return true;
  67. }
  68. #endif
  69. CSharpLanguage *CSharpLanguage::singleton = NULL;
  70. String CSharpLanguage::get_name() const {
  71. return "C#";
  72. }
  73. String CSharpLanguage::get_type() const {
  74. return "CSharpScript";
  75. }
  76. String CSharpLanguage::get_extension() const {
  77. return "cs";
  78. }
  79. Error CSharpLanguage::execute_file(const String &p_path) {
  80. // ??
  81. return OK;
  82. }
  83. void CSharpLanguage::init() {
  84. #ifdef DEBUG_METHODS_ENABLED
  85. if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
  86. class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
  87. #ifdef TOOLS_ENABLED
  88. class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
  89. #endif
  90. }
  91. #endif
  92. gdmono = memnew(GDMono);
  93. gdmono->initialize();
  94. #if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
  95. // Generate bindings here, before loading assemblies. 'initialize_load_assemblies' aborts
  96. // the applications if the api assemblies or the main tools assembly is missing, but this
  97. // is not a problem for BindingsGenerator as it only needs the tools project editor assembly.
  98. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  99. BindingsGenerator::handle_cmdline_args(cmdline_args);
  100. #endif
  101. #ifndef MONO_GLUE_ENABLED
  102. print_line("Run this binary with '--generate-mono-glue path/to/modules/mono/glue'");
  103. #endif
  104. if (gdmono->is_runtime_initialized())
  105. gdmono->initialize_load_assemblies();
  106. #ifdef TOOLS_ENABLED
  107. EditorNode::add_init_callback(&_editor_init_callback);
  108. #endif
  109. }
  110. void CSharpLanguage::finish() {
  111. finalizing = true;
  112. // Make sure all script binding gchandles are released before finalizing GDMono
  113. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  114. CSharpScriptBinding &script_binding = E->value();
  115. if (script_binding.gchandle.is_valid()) {
  116. script_binding.gchandle->release();
  117. script_binding.inited = false;
  118. }
  119. }
  120. if (gdmono) {
  121. memdelete(gdmono);
  122. gdmono = NULL;
  123. }
  124. // Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
  125. script_bindings.clear();
  126. #ifdef DEBUG_ENABLED
  127. for (Map<ObjectID, int>::Element *E = unsafe_object_references.front(); E; E = E->next()) {
  128. const ObjectID &id = E->key();
  129. Object *obj = ObjectDB::get_instance(id);
  130. if (obj) {
  131. ERR_PRINTS("Leaked unsafe reference to object: " + obj->to_string());
  132. } else {
  133. ERR_PRINTS("Leaked unsafe reference to deleted object: " + itos(id));
  134. }
  135. }
  136. #endif
  137. finalizing = false;
  138. }
  139. void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
  140. static const char *_reserved_words[] = {
  141. // Reserved keywords
  142. "abstract",
  143. "as",
  144. "base",
  145. "bool",
  146. "break",
  147. "byte",
  148. "case",
  149. "catch",
  150. "char",
  151. "checked",
  152. "class",
  153. "const",
  154. "continue",
  155. "decimal",
  156. "default",
  157. "delegate",
  158. "do",
  159. "double",
  160. "else",
  161. "enum",
  162. "event",
  163. "explicit",
  164. "extern",
  165. "false",
  166. "finally",
  167. "fixed",
  168. "float",
  169. "for",
  170. "foreach",
  171. "goto",
  172. "if",
  173. "implicit",
  174. "in",
  175. "int",
  176. "interface",
  177. "internal",
  178. "is",
  179. "lock",
  180. "long",
  181. "namespace",
  182. "new",
  183. "null",
  184. "object",
  185. "operator",
  186. "out",
  187. "override",
  188. "params",
  189. "private",
  190. "protected",
  191. "public",
  192. "readonly",
  193. "ref",
  194. "return",
  195. "sbyte",
  196. "sealed",
  197. "short",
  198. "sizeof",
  199. "stackalloc",
  200. "static",
  201. "string",
  202. "struct",
  203. "switch",
  204. "this",
  205. "throw",
  206. "true",
  207. "try",
  208. "typeof",
  209. "uint",
  210. "ulong",
  211. "unchecked",
  212. "unsafe",
  213. "ushort",
  214. "using",
  215. "virtual",
  216. "void",
  217. "volatile",
  218. "while",
  219. // Contextual keywords. Not reserved words, but I guess we should include
  220. // them because this seems to be used only for syntax highlighting.
  221. "add",
  222. "alias",
  223. "ascending",
  224. "async",
  225. "await",
  226. "by",
  227. "descending",
  228. "dynamic",
  229. "equals",
  230. "from",
  231. "get",
  232. "global",
  233. "group",
  234. "into",
  235. "join",
  236. "let",
  237. "nameof",
  238. "on",
  239. "orderby",
  240. "partial",
  241. "remove",
  242. "select",
  243. "set",
  244. "value",
  245. "var",
  246. "when",
  247. "where",
  248. "yield",
  249. 0
  250. };
  251. const char **w = _reserved_words;
  252. while (*w) {
  253. p_words->push_back(*w);
  254. w++;
  255. }
  256. }
  257. void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  258. p_delimiters->push_back("//"); // single-line comment
  259. p_delimiters->push_back("/* */"); // delimited comment
  260. }
  261. void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  262. p_delimiters->push_back("' '"); // character literal
  263. p_delimiters->push_back("\" \""); // regular string literal
  264. // Verbatim string literals (`@" "`) don't render correctly, so don't highlight them.
  265. // Generic string highlighting suffices as a workaround for now.
  266. }
  267. static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
  268. String base_class = p_base_class_name;
  269. if (p_class_name == base_class) {
  270. base_class = "Godot." + base_class;
  271. }
  272. return base_class;
  273. }
  274. Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
  275. String script_template = "using " BINDINGS_NAMESPACE ";\n"
  276. "using System;\n"
  277. "\n"
  278. "public class %CLASS% : %BASE%\n"
  279. "{\n"
  280. " // Declare member variables here. Examples:\n"
  281. " // private int a = 2;\n"
  282. " // private string b = \"text\";\n"
  283. "\n"
  284. " // Called when the node enters the scene tree for the first time.\n"
  285. " public override void _Ready()\n"
  286. " {\n"
  287. " \n"
  288. " }\n"
  289. "\n"
  290. "// // Called every frame. 'delta' is the elapsed time since the previous frame.\n"
  291. "// public override void _Process(float delta)\n"
  292. "// {\n"
  293. "// \n"
  294. "// }\n"
  295. "}\n";
  296. // Replaces all spaces in p_class_name with underscores to prevent
  297. // invalid C# Script templates from being generated when the object name
  298. // has spaces in it.
  299. String class_name_no_spaces = p_class_name.replace(" ", "_");
  300. String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
  301. script_template = script_template.replace("%BASE%", base_class_name)
  302. .replace("%CLASS%", class_name_no_spaces);
  303. Ref<CSharpScript> script;
  304. script.instance();
  305. script->set_source_code(script_template);
  306. script->set_name(class_name_no_spaces);
  307. return script;
  308. }
  309. bool CSharpLanguage::is_using_templates() {
  310. return true;
  311. }
  312. void CSharpLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
  313. String src = p_script->get_source_code();
  314. String class_name_no_spaces = p_class_name.replace(" ", "_");
  315. String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces);
  316. src = src.replace("%BASE%", base_class_name)
  317. .replace("%CLASS%", class_name_no_spaces)
  318. .replace("%TS%", _get_indentation());
  319. p_script->set_source_code(src);
  320. }
  321. String CSharpLanguage::validate_path(const String &p_path) const {
  322. String class_name = p_path.get_file().get_basename();
  323. List<String> keywords;
  324. get_reserved_words(&keywords);
  325. if (keywords.find(class_name)) {
  326. return TTR("Class name can't be a reserved keyword");
  327. }
  328. return "";
  329. }
  330. Script *CSharpLanguage::create_script() const {
  331. return memnew(CSharpScript);
  332. }
  333. bool CSharpLanguage::has_named_classes() const {
  334. return false;
  335. }
  336. bool CSharpLanguage::supports_builtin_mode() const {
  337. return false;
  338. }
  339. #ifdef TOOLS_ENABLED
  340. static String variant_type_to_managed_name(const String &p_var_type_name) {
  341. if (p_var_type_name.empty())
  342. return "object";
  343. if (!ClassDB::class_exists(p_var_type_name)) {
  344. return p_var_type_name;
  345. }
  346. if (p_var_type_name == Variant::get_type_name(Variant::OBJECT))
  347. return "Godot.Object";
  348. if (p_var_type_name == Variant::get_type_name(Variant::REAL)) {
  349. #ifdef REAL_T_IS_DOUBLE
  350. return "double";
  351. #else
  352. return "float";
  353. #endif
  354. }
  355. if (p_var_type_name == Variant::get_type_name(Variant::STRING))
  356. return "string"; // I prefer this one >:[
  357. if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY))
  358. return "Collections.Dictionary";
  359. if (p_var_type_name == Variant::get_type_name(Variant::ARRAY))
  360. return "Collections.Array";
  361. if (p_var_type_name == Variant::get_type_name(Variant::POOL_BYTE_ARRAY))
  362. return "byte[]";
  363. if (p_var_type_name == Variant::get_type_name(Variant::POOL_INT_ARRAY))
  364. return "int[]";
  365. if (p_var_type_name == Variant::get_type_name(Variant::POOL_REAL_ARRAY)) {
  366. #ifdef REAL_T_IS_DOUBLE
  367. return "double[]";
  368. #else
  369. return "float[]";
  370. #endif
  371. }
  372. if (p_var_type_name == Variant::get_type_name(Variant::POOL_STRING_ARRAY))
  373. return "string[]";
  374. if (p_var_type_name == Variant::get_type_name(Variant::POOL_VECTOR2_ARRAY))
  375. return "Vector2[]";
  376. if (p_var_type_name == Variant::get_type_name(Variant::POOL_VECTOR3_ARRAY))
  377. return "Vector3[]";
  378. if (p_var_type_name == Variant::get_type_name(Variant::POOL_COLOR_ARRAY))
  379. return "Color[]";
  380. Variant::Type var_types[] = {
  381. Variant::BOOL,
  382. Variant::INT,
  383. Variant::VECTOR2,
  384. Variant::RECT2,
  385. Variant::VECTOR3,
  386. Variant::TRANSFORM2D,
  387. Variant::PLANE,
  388. Variant::QUAT,
  389. Variant::AABB,
  390. Variant::BASIS,
  391. Variant::TRANSFORM,
  392. Variant::COLOR,
  393. Variant::NODE_PATH,
  394. Variant::_RID
  395. };
  396. for (unsigned int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) {
  397. if (p_var_type_name == Variant::get_type_name(var_types[i]))
  398. return p_var_type_name;
  399. }
  400. return "object";
  401. }
  402. String CSharpLanguage::make_function(const String &, const String &p_name, const PoolStringArray &p_args) const {
  403. // FIXME
  404. // - Due to Godot's API limitation this just appends the function to the end of the file
  405. // - Use fully qualified name if there is ambiguity
  406. String s = "private void " + p_name + "(";
  407. for (int i = 0; i < p_args.size(); i++) {
  408. const String &arg = p_args[i];
  409. if (i > 0)
  410. s += ", ";
  411. s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
  412. }
  413. s += ")\n{\n // Replace with function body.\n}\n";
  414. return s;
  415. }
  416. #else
  417. String CSharpLanguage::make_function(const String &, const String &, const PoolStringArray &) const {
  418. return String();
  419. }
  420. #endif
  421. String CSharpLanguage::_get_indentation() const {
  422. #ifdef TOOLS_ENABLED
  423. if (Engine::get_singleton()->is_editor_hint()) {
  424. bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", 0);
  425. if (use_space_indentation) {
  426. int indent_size = EDITOR_DEF("text_editor/indent/size", 4);
  427. String space_indent = "";
  428. for (int i = 0; i < indent_size; i++) {
  429. space_indent += " ";
  430. }
  431. return space_indent;
  432. }
  433. }
  434. #endif
  435. return "\t";
  436. }
  437. String CSharpLanguage::debug_get_error() const {
  438. return _debug_error;
  439. }
  440. int CSharpLanguage::debug_get_stack_level_count() const {
  441. if (_debug_parse_err_line >= 0)
  442. return 1;
  443. // TODO: StackTrace
  444. return 1;
  445. }
  446. int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
  447. if (_debug_parse_err_line >= 0)
  448. return _debug_parse_err_line;
  449. // TODO: StackTrace
  450. return 1;
  451. }
  452. String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
  453. if (_debug_parse_err_line >= 0)
  454. return String();
  455. // TODO: StackTrace
  456. return String();
  457. }
  458. String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
  459. if (_debug_parse_err_line >= 0)
  460. return _debug_parse_err_file;
  461. // TODO: StackTrace
  462. return String();
  463. }
  464. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  465. #ifdef DEBUG_ENABLED
  466. _TLS_RECURSION_GUARD_V_(Vector<StackInfo>());
  467. GD_MONO_SCOPE_THREAD_ATTACH;
  468. if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoCache::cached_data.corlib_cache_updated)
  469. return Vector<StackInfo>();
  470. MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr());
  471. MonoBoolean need_file_info = true;
  472. void *ctor_args[1] = { &need_file_info };
  473. CACHED_METHOD(System_Diagnostics_StackTrace, ctor_bool)->invoke_raw(stack_trace, ctor_args);
  474. Vector<StackInfo> si;
  475. si = stack_trace_get_info(stack_trace);
  476. return si;
  477. #else
  478. return Vector<StackInfo>();
  479. #endif
  480. }
  481. #ifdef DEBUG_ENABLED
  482. Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObject *p_stack_trace) {
  483. _TLS_RECURSION_GUARD_V_(Vector<StackInfo>());
  484. GD_MONO_SCOPE_THREAD_ATTACH;
  485. MonoException *exc = NULL;
  486. MonoArray *frames = CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames).invoke(p_stack_trace, &exc);
  487. if (exc) {
  488. GDMonoUtils::debug_print_unhandled_exception(exc);
  489. return Vector<StackInfo>();
  490. }
  491. int frame_count = mono_array_length(frames);
  492. if (frame_count <= 0)
  493. return Vector<StackInfo>();
  494. Vector<StackInfo> si;
  495. si.resize(frame_count);
  496. for (int i = 0; i < frame_count; i++) {
  497. StackInfo &sif = si.write[i];
  498. MonoObject *frame = mono_array_get(frames, MonoObject *, i);
  499. MonoString *file_name;
  500. int file_line_num;
  501. MonoString *method_decl;
  502. CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo).invoke(frame, &file_name, &file_line_num, &method_decl, &exc);
  503. if (exc) {
  504. GDMonoUtils::debug_print_unhandled_exception(exc);
  505. return Vector<StackInfo>();
  506. }
  507. // TODO
  508. // what if the StackFrame method is null (method_decl is empty). should we skip this frame?
  509. // can reproduce with a MissingMethodException on internal calls
  510. sif.file = GDMonoMarshal::mono_string_to_godot(file_name);
  511. sif.line = file_line_num;
  512. sif.func = GDMonoMarshal::mono_string_to_godot(method_decl);
  513. }
  514. return si;
  515. }
  516. #endif
  517. void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
  518. #ifdef DEBUG_ENABLED
  519. MutexLock lock(unsafe_object_references_lock);
  520. ObjectID id = p_obj->get_instance_id();
  521. unsafe_object_references[id]++;
  522. #endif
  523. }
  524. void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
  525. #ifdef DEBUG_ENABLED
  526. MutexLock lock(unsafe_object_references_lock);
  527. ObjectID id = p_obj->get_instance_id();
  528. Map<ObjectID, int>::Element *elem = unsafe_object_references.find(id);
  529. ERR_FAIL_NULL(elem);
  530. if (--elem->value() == 0)
  531. unsafe_object_references.erase(elem);
  532. #endif
  533. }
  534. void CSharpLanguage::frame() {
  535. if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != NULL) {
  536. const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoCache::cached_data.task_scheduler_handle;
  537. if (task_scheduler_handle.is_valid()) {
  538. MonoObject *task_scheduler = task_scheduler_handle->get_target();
  539. if (task_scheduler) {
  540. MonoException *exc = NULL;
  541. CACHED_METHOD_THUNK(GodotTaskScheduler, Activate).invoke(task_scheduler, &exc);
  542. if (exc) {
  543. GDMonoUtils::debug_unhandled_exception(exc);
  544. }
  545. }
  546. }
  547. }
  548. }
  549. struct CSharpScriptDepSort {
  550. // must support sorting so inheritance works properly (parent must be reloaded first)
  551. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  552. if (A == B)
  553. return false; // shouldn't happen but..
  554. GDMonoClass *I = B->base;
  555. while (I) {
  556. if (I == A->script_class) {
  557. // A is a base of B
  558. return true;
  559. }
  560. I = I->get_parent_class();
  561. }
  562. return false; // not a base
  563. }
  564. };
  565. void CSharpLanguage::reload_all_scripts() {
  566. #ifdef GD_MONO_HOT_RELOAD
  567. if (is_assembly_reloading_needed()) {
  568. GD_MONO_SCOPE_THREAD_ATTACH;
  569. reload_assemblies(false);
  570. }
  571. #endif
  572. }
  573. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  574. (void)p_script; // UNUSED
  575. CRASH_COND(!Engine::get_singleton()->is_editor_hint());
  576. #ifdef TOOLS_ENABLED
  577. get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
  578. #endif
  579. #ifdef GD_MONO_HOT_RELOAD
  580. if (is_assembly_reloading_needed()) {
  581. GD_MONO_SCOPE_THREAD_ATTACH;
  582. reload_assemblies(p_soft_reload);
  583. }
  584. #endif
  585. }
  586. #ifdef GD_MONO_HOT_RELOAD
  587. bool CSharpLanguage::is_assembly_reloading_needed() {
  588. if (!gdmono->is_runtime_initialized())
  589. return false;
  590. GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
  591. String appname = ProjectSettings::get_singleton()->get("application/config/name");
  592. String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
  593. if (appname_safe.empty()) {
  594. appname_safe = "UnnamedProject";
  595. }
  596. appname_safe += ".dll";
  597. if (proj_assembly) {
  598. String proj_asm_path = proj_assembly->get_path();
  599. if (!FileAccess::exists(proj_asm_path)) {
  600. // Maybe it wasn't loaded from the default path, so check this as well
  601. proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe);
  602. if (!FileAccess::exists(proj_asm_path))
  603. return false; // No assembly to load
  604. }
  605. if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
  606. return false; // Already up to date
  607. } else {
  608. if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe)))
  609. return false; // No assembly to load
  610. }
  611. return true;
  612. }
  613. void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
  614. if (!gdmono->is_runtime_initialized())
  615. return;
  616. // There is no soft reloading with Mono. It's always hard reloading.
  617. List<Ref<CSharpScript> > scripts;
  618. {
  619. MutexLock lock(script_instances_mutex);
  620. for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
  621. // Cast to CSharpScript to avoid being erased by accident
  622. scripts.push_back(Ref<CSharpScript>(elem->self()));
  623. }
  624. }
  625. List<Ref<CSharpScript> > to_reload;
  626. // We need to keep reference instances alive during reloading
  627. List<Ref<Reference> > ref_instances;
  628. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  629. CSharpScriptBinding &script_binding = E->value();
  630. Reference *ref = Object::cast_to<Reference>(script_binding.owner);
  631. if (ref) {
  632. ref_instances.push_back(Ref<Reference>(ref));
  633. }
  634. }
  635. // As scripts are going to be reloaded, must proceed without locking here
  636. scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order
  637. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  638. Ref<CSharpScript> &script = E->get();
  639. to_reload.push_back(script);
  640. if (script->get_path().empty()) {
  641. script->tied_class_name_for_reload = script->script_class->get_name_for_lookup();
  642. script->tied_class_namespace_for_reload = script->script_class->get_namespace();
  643. }
  644. // Script::instances are deleted during managed object disposal, which happens on domain finalize.
  645. // Only placeholders are kept. Therefore we need to keep a copy before that happens.
  646. for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
  647. Object *obj = F->get();
  648. script->pending_reload_instances.insert(obj->get_instance_id());
  649. Reference *ref = Object::cast_to<Reference>(obj);
  650. if (ref) {
  651. ref_instances.push_back(Ref<Reference>(ref));
  652. }
  653. }
  654. #ifdef TOOLS_ENABLED
  655. for (Set<PlaceHolderScriptInstance *>::Element *F = script->placeholders.front(); F; F = F->next()) {
  656. Object *obj = F->get()->get_owner();
  657. script->pending_reload_instances.insert(obj->get_instance_id());
  658. Reference *ref = Object::cast_to<Reference>(obj);
  659. if (ref) {
  660. ref_instances.push_back(Ref<Reference>(ref));
  661. }
  662. }
  663. #endif
  664. // Save state and remove script from instances
  665. Map<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state;
  666. for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
  667. Object *obj = F->get();
  668. ERR_CONTINUE(!obj->get_script_instance());
  669. CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());
  670. // Call OnBeforeSerialize
  671. if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
  672. obj->get_script_instance()->call_multilevel(string_names.on_before_serialize);
  673. // Save instance info
  674. CSharpScript::StateBackup state;
  675. // TODO: Proper state backup (Not only variants, serialize managed state of scripts)
  676. csi->get_properties_state_for_reloading(state.properties);
  677. owners_map[obj->get_instance_id()] = state;
  678. }
  679. }
  680. // After the state of all instances is saved, clear scripts and script instances
  681. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  682. Ref<CSharpScript> &script = E->get();
  683. while (script->instances.front()) {
  684. Object *obj = script->instances.front()->get();
  685. obj->set_script(RefPtr()); // Remove script and existing script instances (placeholder are not removed before domain reload)
  686. }
  687. script->_clear();
  688. }
  689. // Do domain reload
  690. if (gdmono->reload_scripts_domain() != OK) {
  691. // Failed to reload the scripts domain
  692. // Make sure to add the scripts back to their owners before returning
  693. for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
  694. Ref<CSharpScript> scr = E->get();
  695. for (const Map<ObjectID, CSharpScript::StateBackup>::Element *F = scr->pending_reload_state.front(); F; F = F->next()) {
  696. Object *obj = ObjectDB::get_instance(F->key());
  697. if (!obj)
  698. continue;
  699. ObjectID obj_id = obj->get_instance_id();
  700. // Use a placeholder for now to avoid losing the state when saving a scene
  701. obj->set_script(scr.get_ref_ptr());
  702. PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
  703. obj->set_script_instance(placeholder);
  704. #ifdef TOOLS_ENABLED
  705. // Even though build didn't fail, this tells the placeholder to keep properties and
  706. // it allows using property_set_fallback for restoring the state without a valid script.
  707. scr->placeholder_fallback_enabled = true;
  708. #endif
  709. // Restore Variant properties state, it will be kept by the placeholder until the next script reloading
  710. for (List<Pair<StringName, Variant> >::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) {
  711. placeholder->property_set_fallback(G->get().first, G->get().second, NULL);
  712. }
  713. scr->pending_reload_state.erase(obj_id);
  714. }
  715. }
  716. return;
  717. }
  718. List<Ref<CSharpScript> > to_reload_state;
  719. for (List<Ref<CSharpScript> >::Element *E = to_reload.front(); E; E = E->next()) {
  720. Ref<CSharpScript> script = E->get();
  721. if (!script->get_path().empty()) {
  722. #ifdef TOOLS_ENABLED
  723. script->exports_invalidated = true;
  724. #endif
  725. script->signals_invalidated = true;
  726. script->reload(p_soft_reload);
  727. script->update_exports();
  728. if (!script->valid) {
  729. script->pending_reload_instances.clear();
  730. continue;
  731. }
  732. } else {
  733. const StringName &class_namespace = script->tied_class_namespace_for_reload;
  734. const StringName &class_name = script->tied_class_name_for_reload;
  735. GDMonoAssembly *project_assembly = gdmono->get_project_assembly();
  736. // Search in project and tools assemblies first as those are the most likely to have the class
  737. GDMonoClass *script_class = (project_assembly ? project_assembly->get_class(class_namespace, class_name) : NULL);
  738. #ifdef TOOLS_ENABLED
  739. if (!script_class) {
  740. GDMonoAssembly *tools_assembly = gdmono->get_tools_assembly();
  741. script_class = (tools_assembly ? tools_assembly->get_class(class_namespace, class_name) : NULL);
  742. }
  743. #endif
  744. if (!script_class) {
  745. script_class = gdmono->get_class(class_namespace, class_name);
  746. }
  747. if (!script_class) {
  748. // The class was removed, can't reload
  749. script->pending_reload_instances.clear();
  750. continue;
  751. }
  752. bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(script_class);
  753. if (!obj_type) {
  754. // The class no longer inherits Godot.Object, can't reload
  755. script->pending_reload_instances.clear();
  756. continue;
  757. }
  758. GDMonoClass *native = GDMonoUtils::get_class_native_base(script_class);
  759. CSharpScript::initialize_for_managed_type(script, script_class, native);
  760. }
  761. String native_name = NATIVE_GDMONOCLASS_NAME(script->native);
  762. {
  763. for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
  764. ObjectID obj_id = F->get();
  765. Object *obj = ObjectDB::get_instance(obj_id);
  766. if (!obj) {
  767. script->pending_reload_state.erase(obj_id);
  768. continue;
  769. }
  770. if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
  771. // No longer inherits the same compatible type, can't reload
  772. script->pending_reload_state.erase(obj_id);
  773. continue;
  774. }
  775. ScriptInstance *si = obj->get_script_instance();
  776. #ifdef TOOLS_ENABLED
  777. if (si) {
  778. // If the script instance is not null, then it must be a placeholder.
  779. // Non-placeholder script instances are removed in godot_icall_Object_Disposed.
  780. CRASH_COND(!si->is_placeholder());
  781. if (script->is_tool() || ScriptServer::is_scripting_enabled()) {
  782. // Replace placeholder with a script instance
  783. CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
  784. // Backup placeholder script instance state before replacing it with a script instance
  785. si->get_property_state(state_backup.properties);
  786. ScriptInstance *script_instance = script->instance_create(obj);
  787. if (script_instance) {
  788. script->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
  789. obj->set_script_instance(script_instance);
  790. }
  791. }
  792. continue;
  793. }
  794. #else
  795. CRASH_COND(si != NULL);
  796. #endif
  797. // Re-create script instance
  798. obj->set_script(script.get_ref_ptr()); // will create the script instance as well
  799. }
  800. }
  801. to_reload_state.push_back(script);
  802. }
  803. for (List<Ref<CSharpScript> >::Element *E = to_reload_state.front(); E; E = E->next()) {
  804. Ref<CSharpScript> script = E->get();
  805. for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
  806. ObjectID obj_id = F->get();
  807. Object *obj = ObjectDB::get_instance(obj_id);
  808. if (!obj) {
  809. script->pending_reload_state.erase(obj_id);
  810. continue;
  811. }
  812. ERR_CONTINUE(!obj->get_script_instance());
  813. // TODO: Restore serialized state
  814. CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];
  815. for (List<Pair<StringName, Variant> >::Element *G = state_backup.properties.front(); G; G = G->next()) {
  816. obj->get_script_instance()->set(G->get().first, G->get().second);
  817. }
  818. // Call OnAfterDeserialization
  819. CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());
  820. if (csi && csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
  821. obj->get_script_instance()->call_multilevel(string_names.on_after_deserialize);
  822. }
  823. script->pending_reload_instances.clear();
  824. }
  825. #ifdef TOOLS_ENABLED
  826. // FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
  827. if (Engine::get_singleton()->is_editor_hint()) {
  828. EditorNode::get_singleton()->get_inspector()->update_tree();
  829. NodeDock::singleton->update_lists();
  830. }
  831. #endif
  832. }
  833. #endif
  834. void CSharpLanguage::_load_scripts_metadata() {
  835. scripts_metadata.clear();
  836. String scripts_metadata_filename = "scripts_metadata.";
  837. #ifdef TOOLS_ENABLED
  838. scripts_metadata_filename += Engine::get_singleton()->is_editor_hint() ? "editor" : "editor_player";
  839. #else
  840. #ifdef DEBUG_ENABLED
  841. scripts_metadata_filename += "debug";
  842. #else
  843. scripts_metadata_filename += "release";
  844. #endif
  845. #endif
  846. String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file(scripts_metadata_filename);
  847. if (FileAccess::exists(scripts_metadata_path)) {
  848. String old_json;
  849. Error ferr = read_all_file_utf8(scripts_metadata_path, old_json);
  850. ERR_FAIL_COND(ferr != OK);
  851. Variant old_dict_var;
  852. String err_str;
  853. int err_line;
  854. Error json_err = JSON::parse(old_json, old_dict_var, err_str, err_line);
  855. if (json_err != OK) {
  856. ERR_PRINTS("Failed to parse metadata file: '" + err_str + "' (" + String::num_int64(err_line) + ").");
  857. return;
  858. }
  859. scripts_metadata = old_dict_var.operator Dictionary();
  860. scripts_metadata_invalidated = false;
  861. print_verbose("Successfully loaded scripts metadata");
  862. } else {
  863. if (!Engine::get_singleton()->is_editor_hint()) {
  864. ERR_PRINT("Missing scripts metadata file.");
  865. }
  866. }
  867. }
  868. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  869. p_extensions->push_back("cs");
  870. }
  871. #ifdef TOOLS_ENABLED
  872. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  873. return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
  874. }
  875. bool CSharpLanguage::overrides_external_editor() {
  876. return get_godotsharp_editor()->call("OverridesExternalEditor");
  877. }
  878. #endif
  879. void CSharpLanguage::thread_enter() {
  880. #if 0
  881. if (gdmono->is_runtime_initialized()) {
  882. GDMonoUtils::attach_current_thread();
  883. }
  884. #endif
  885. }
  886. void CSharpLanguage::thread_exit() {
  887. #if 0
  888. if (gdmono->is_runtime_initialized()) {
  889. GDMonoUtils::detach_current_thread();
  890. }
  891. #endif
  892. }
  893. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  894. // Not a parser error in our case, but it's still used for other type of errors
  895. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  896. _debug_parse_err_line = p_line;
  897. _debug_parse_err_file = p_file;
  898. _debug_error = p_error;
  899. ScriptDebugger::get_singleton()->debug(this, false, true);
  900. return true;
  901. } else {
  902. return false;
  903. }
  904. }
  905. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  906. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  907. _debug_parse_err_line = -1;
  908. _debug_parse_err_file = "";
  909. _debug_error = p_error;
  910. ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
  911. return true;
  912. } else {
  913. return false;
  914. }
  915. }
  916. void CSharpLanguage::_on_scripts_domain_unloaded() {
  917. for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
  918. CSharpScriptBinding &script_binding = E->value();
  919. script_binding.inited = false;
  920. }
  921. scripts_metadata_invalidated = true;
  922. }
  923. #ifdef TOOLS_ENABLED
  924. void CSharpLanguage::_editor_init_callback() {
  925. register_editor_internal_calls();
  926. // Initialize GodotSharpEditor
  927. GDMonoClass *editor_klass = GDMono::get_singleton()->get_tools_assembly()->get_class("GodotTools", "GodotSharpEditor");
  928. CRASH_COND(editor_klass == NULL);
  929. MonoObject *mono_object = mono_object_new(mono_domain_get(), editor_klass->get_mono_ptr());
  930. CRASH_COND(mono_object == NULL);
  931. MonoException *exc = NULL;
  932. GDMonoUtils::runtime_object_init(mono_object, editor_klass, &exc);
  933. UNHANDLED_EXCEPTION(exc);
  934. EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(GDMonoMarshal::mono_object_to_variant(mono_object));
  935. CRASH_COND(godotsharp_editor == NULL);
  936. // Enable it as a plugin
  937. EditorNode::add_editor_plugin(godotsharp_editor);
  938. godotsharp_editor->enable_plugin();
  939. get_singleton()->godotsharp_editor = godotsharp_editor;
  940. }
  941. #endif
  942. void CSharpLanguage::set_language_index(int p_idx) {
  943. ERR_FAIL_COND(lang_idx != -1);
  944. lang_idx = p_idx;
  945. }
  946. void CSharpLanguage::release_script_gchandle(Ref<MonoGCHandle> &p_gchandle) {
  947. if (!p_gchandle->is_released()) { // Do not lock unnecessarily
  948. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  949. p_gchandle->release();
  950. }
  951. }
  952. void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, Ref<MonoGCHandle> &p_gchandle) {
  953. uint32_t pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(p_expected_obj); // We might lock after this, so pin it
  954. if (!p_gchandle->is_released()) { // Do not lock unnecessarily
  955. MutexLock lock(get_singleton()->script_gchandle_release_mutex);
  956. MonoObject *target = p_gchandle->get_target();
  957. // We release the gchandle if it points to the MonoObject* we expect (otherwise it was
  958. // already released and could have been replaced) or if we can't get its target MonoObject*
  959. // (which doesn't necessarily mean it was released, and we want it released in order to
  960. // avoid locking other threads unnecessarily).
  961. if (target == p_expected_obj || target == NULL) {
  962. p_gchandle->release();
  963. }
  964. }
  965. MonoGCHandle::free_handle(pinned_gchandle);
  966. }
  967. CSharpLanguage::CSharpLanguage() {
  968. ERR_FAIL_COND_MSG(singleton, "C# singleton already exist.");
  969. singleton = this;
  970. finalizing = false;
  971. gdmono = NULL;
  972. lang_idx = -1;
  973. scripts_metadata_invalidated = true;
  974. #ifdef TOOLS_ENABLED
  975. godotsharp_editor = NULL;
  976. #endif
  977. }
  978. CSharpLanguage::~CSharpLanguage() {
  979. finish();
  980. singleton = NULL;
  981. }
  982. bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
  983. #ifdef DEBUG_ENABLED
  984. // I don't trust you
  985. if (p_object->get_script_instance()) {
  986. CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
  987. CRASH_COND(csharp_instance != NULL && !csharp_instance->is_destructing_script_instance());
  988. }
  989. #endif
  990. StringName type_name = p_object->get_class_name();
  991. // ¯\_(ツ)_/¯
  992. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  993. while (classinfo && !classinfo->exposed)
  994. classinfo = classinfo->inherits_ptr;
  995. ERR_FAIL_NULL_V(classinfo, false);
  996. type_name = classinfo->name;
  997. GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);
  998. ERR_FAIL_NULL_V(type_class, false);
  999. MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);
  1000. ERR_FAIL_NULL_V(mono_object, false);
  1001. r_script_binding.inited = true;
  1002. r_script_binding.type_name = type_name;
  1003. r_script_binding.wrapper_class = type_class; // cache
  1004. r_script_binding.gchandle = MonoGCHandle::create_strong(mono_object);
  1005. r_script_binding.owner = p_object;
  1006. // Tie managed to unmanaged
  1007. Reference *ref = Object::cast_to<Reference>(p_object);
  1008. if (ref) {
  1009. // Unsafe refcount increment. The managed instance also counts as a reference.
  1010. // This way if the unmanaged world has no references to our owner
  1011. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1012. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)
  1013. ref->reference();
  1014. CSharpLanguage::get_singleton()->post_unsafe_reference(ref);
  1015. }
  1016. return true;
  1017. }
  1018. void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
  1019. MutexLock lock(language_bind_mutex);
  1020. Map<Object *, CSharpScriptBinding>::Element *match = script_bindings.find(p_object);
  1021. if (match)
  1022. return (void *)match;
  1023. CSharpScriptBinding script_binding;
  1024. if (!setup_csharp_script_binding(script_binding, p_object))
  1025. return NULL;
  1026. return (void *)insert_script_binding(p_object, script_binding);
  1027. }
  1028. Map<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
  1029. return script_bindings.insert(p_object, p_script_binding);
  1030. }
  1031. void CSharpLanguage::free_instance_binding_data(void *p_data) {
  1032. if (GDMono::get_singleton() == NULL) {
  1033. #ifdef DEBUG_ENABLED
  1034. CRASH_COND(!script_bindings.empty());
  1035. #endif
  1036. // Mono runtime finalized, all the gchandle bindings were already released
  1037. return;
  1038. }
  1039. if (finalizing)
  1040. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  1041. GD_MONO_ASSERT_THREAD_ATTACHED;
  1042. {
  1043. MutexLock lock(language_bind_mutex);
  1044. Map<Object *, CSharpScriptBinding>::Element *data = (Map<Object *, CSharpScriptBinding>::Element *)p_data;
  1045. CSharpScriptBinding &script_binding = data->value();
  1046. if (script_binding.inited) {
  1047. // Set the native instance field to IntPtr.Zero, if not yet garbage collected.
  1048. // This is done to avoid trying to dispose the native instance from Dispose(bool).
  1049. MonoObject *mono_object = script_binding.gchandle->get_target();
  1050. if (mono_object) {
  1051. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  1052. }
  1053. }
  1054. script_bindings.erase(data);
  1055. }
  1056. }
  1057. void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
  1058. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  1059. #ifdef DEBUG_ENABLED
  1060. CRASH_COND(!ref_owner);
  1061. CRASH_COND(!p_object->has_script_instance_binding(get_language_index()));
  1062. #endif
  1063. void *data = p_object->get_script_instance_binding(get_language_index());
  1064. CRASH_COND(!data);
  1065. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1066. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  1067. if (!script_binding.inited)
  1068. return;
  1069. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1070. GD_MONO_SCOPE_THREAD_ATTACH;
  1071. // The reference count was increased after the managed side was the only one referencing our owner.
  1072. // This means the owner is being referenced again by the unmanaged side,
  1073. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1074. MonoObject *target = gchandle->get_target();
  1075. if (!target)
  1076. return; // Called after the managed side was collected, so nothing to do here
  1077. // Release the current weak handle and replace it with a strong handle.
  1078. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(target);
  1079. gchandle->release();
  1080. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  1081. }
  1082. }
  1083. bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
  1084. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  1085. #ifdef DEBUG_ENABLED
  1086. CRASH_COND(!ref_owner);
  1087. CRASH_COND(!p_object->has_script_instance_binding(get_language_index()));
  1088. #endif
  1089. void *data = p_object->get_script_instance_binding(get_language_index());
  1090. CRASH_COND(!data);
  1091. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1092. Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
  1093. int refcount = ref_owner->reference_get_count();
  1094. if (!script_binding.inited)
  1095. return refcount == 0;
  1096. if (refcount == 1 && gchandle.is_valid() && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1097. GD_MONO_SCOPE_THREAD_ATTACH;
  1098. // If owner owner is no longer referenced by the unmanaged side,
  1099. // the managed instance takes responsibility of deleting the owner when GCed.
  1100. MonoObject *target = gchandle->get_target();
  1101. if (!target)
  1102. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  1103. // Release the current strong handle and replace it with a weak handle.
  1104. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(target);
  1105. gchandle->release();
  1106. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  1107. return false;
  1108. }
  1109. return refcount == 0;
  1110. }
  1111. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle) {
  1112. CSharpInstance *instance = memnew(CSharpInstance);
  1113. Reference *ref = Object::cast_to<Reference>(p_owner);
  1114. instance->base_ref = ref != NULL;
  1115. instance->script = Ref<CSharpScript>(p_script);
  1116. instance->owner = p_owner;
  1117. instance->gchandle = p_gchandle;
  1118. if (instance->base_ref)
  1119. instance->_reference_owner_unsafe();
  1120. p_script->instances.insert(p_owner);
  1121. return instance;
  1122. }
  1123. MonoObject *CSharpInstance::get_mono_object() const {
  1124. ERR_FAIL_COND_V(gchandle.is_null(), NULL);
  1125. return gchandle->get_target();
  1126. }
  1127. Object *CSharpInstance::get_owner() {
  1128. return owner;
  1129. }
  1130. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  1131. ERR_FAIL_COND_V(!script.is_valid(), false);
  1132. GD_MONO_SCOPE_THREAD_ATTACH;
  1133. MonoObject *mono_object = get_mono_object();
  1134. ERR_FAIL_NULL_V(mono_object, false);
  1135. GDMonoClass *top = script->script_class;
  1136. while (top && top != script->native) {
  1137. GDMonoField *field = top->get_field(p_name);
  1138. if (field) {
  1139. field->set_value_from_variant(mono_object, p_value);
  1140. return true;
  1141. }
  1142. GDMonoProperty *property = top->get_property(p_name);
  1143. if (property) {
  1144. property->set_value(mono_object, GDMonoMarshal::variant_to_mono_object(p_value, property->get_type()));
  1145. return true;
  1146. }
  1147. top = top->get_parent_class();
  1148. }
  1149. // Call _set
  1150. top = script->script_class;
  1151. while (top && top != script->native) {
  1152. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);
  1153. if (method) {
  1154. Variant name = p_name;
  1155. const Variant *args[2] = { &name, &p_value };
  1156. MonoObject *ret = method->invoke(mono_object, args);
  1157. if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret))
  1158. return true;
  1159. break;
  1160. }
  1161. top = top->get_parent_class();
  1162. }
  1163. return false;
  1164. }
  1165. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  1166. ERR_FAIL_COND_V(!script.is_valid(), false);
  1167. GD_MONO_SCOPE_THREAD_ATTACH;
  1168. MonoObject *mono_object = get_mono_object();
  1169. ERR_FAIL_NULL_V(mono_object, false);
  1170. GDMonoClass *top = script->script_class;
  1171. while (top && top != script->native) {
  1172. GDMonoField *field = top->get_field(p_name);
  1173. if (field) {
  1174. MonoObject *value = field->get_value(mono_object);
  1175. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  1176. return true;
  1177. }
  1178. GDMonoProperty *property = top->get_property(p_name);
  1179. if (property) {
  1180. MonoException *exc = NULL;
  1181. MonoObject *value = property->get_value(mono_object, &exc);
  1182. if (exc) {
  1183. r_ret = Variant();
  1184. GDMonoUtils::set_pending_exception(exc);
  1185. } else {
  1186. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  1187. }
  1188. return true;
  1189. }
  1190. top = top->get_parent_class();
  1191. }
  1192. // Call _get
  1193. top = script->script_class;
  1194. while (top && top != script->native) {
  1195. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);
  1196. if (method) {
  1197. Variant name = p_name;
  1198. const Variant *args[1] = { &name };
  1199. MonoObject *ret = method->invoke(mono_object, args);
  1200. if (ret) {
  1201. r_ret = GDMonoMarshal::mono_object_to_variant(ret);
  1202. return true;
  1203. }
  1204. break;
  1205. }
  1206. top = top->get_parent_class();
  1207. }
  1208. return false;
  1209. }
  1210. void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant> > &r_state) {
  1211. List<PropertyInfo> pinfo;
  1212. get_property_list(&pinfo);
  1213. for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
  1214. Pair<StringName, Variant> state_pair;
  1215. state_pair.first = E->get().name;
  1216. ManagedType managedType;
  1217. GDMonoField *field = script->script_class->get_field(state_pair.first);
  1218. if (!field)
  1219. continue; // Properties ignored. We get the property baking fields instead.
  1220. managedType = field->get_type();
  1221. if (GDMonoMarshal::managed_to_variant_type(managedType) != Variant::NIL) { // If we can marshal it
  1222. if (get(state_pair.first, state_pair.second)) {
  1223. r_state.push_back(state_pair);
  1224. }
  1225. }
  1226. }
  1227. }
  1228. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  1229. for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
  1230. p_properties->push_back(E->value());
  1231. }
  1232. // Call _get_property_list
  1233. ERR_FAIL_COND(!script.is_valid());
  1234. GD_MONO_SCOPE_THREAD_ATTACH;
  1235. MonoObject *mono_object = get_mono_object();
  1236. ERR_FAIL_NULL(mono_object);
  1237. GDMonoClass *top = script->script_class;
  1238. while (top && top != script->native) {
  1239. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get_property_list), 0);
  1240. if (method) {
  1241. MonoObject *ret = method->invoke(mono_object);
  1242. if (ret) {
  1243. Array array = Array(GDMonoMarshal::mono_object_to_variant(ret));
  1244. for (int i = 0, size = array.size(); i < size; i++)
  1245. p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
  1246. return;
  1247. }
  1248. break;
  1249. }
  1250. top = top->get_parent_class();
  1251. }
  1252. }
  1253. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  1254. if (script->member_info.has(p_name)) {
  1255. if (r_is_valid)
  1256. *r_is_valid = true;
  1257. return script->member_info[p_name].type;
  1258. }
  1259. if (r_is_valid)
  1260. *r_is_valid = false;
  1261. return Variant::NIL;
  1262. }
  1263. bool CSharpInstance::has_method(const StringName &p_method) const {
  1264. if (!script.is_valid())
  1265. return false;
  1266. GD_MONO_SCOPE_THREAD_ATTACH;
  1267. GDMonoClass *top = script->script_class;
  1268. while (top && top != script->native) {
  1269. if (top->has_fetched_method_unknown_params(p_method)) {
  1270. return true;
  1271. }
  1272. top = top->get_parent_class();
  1273. }
  1274. return false;
  1275. }
  1276. Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1277. if (!script.is_valid())
  1278. ERR_FAIL_V(Variant());
  1279. GD_MONO_SCOPE_THREAD_ATTACH;
  1280. MonoObject *mono_object = get_mono_object();
  1281. if (!mono_object) {
  1282. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1283. ERR_FAIL_V(Variant());
  1284. }
  1285. GDMonoClass *top = script->script_class;
  1286. while (top && top != script->native) {
  1287. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1288. if (method) {
  1289. MonoObject *return_value = method->invoke(mono_object, p_args);
  1290. r_error.error = Variant::CallError::CALL_OK;
  1291. if (return_value) {
  1292. return GDMonoMarshal::mono_object_to_variant(return_value);
  1293. } else {
  1294. return Variant();
  1295. }
  1296. }
  1297. top = top->get_parent_class();
  1298. }
  1299. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1300. return Variant();
  1301. }
  1302. void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1303. GD_MONO_SCOPE_THREAD_ATTACH;
  1304. if (script.is_valid()) {
  1305. MonoObject *mono_object = get_mono_object();
  1306. ERR_FAIL_NULL(mono_object);
  1307. _call_multilevel(mono_object, p_method, p_args, p_argcount);
  1308. }
  1309. }
  1310. void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
  1311. GD_MONO_ASSERT_THREAD_ATTACHED;
  1312. GDMonoClass *top = script->script_class;
  1313. while (top && top != script->native) {
  1314. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1315. if (method) {
  1316. method->invoke(p_mono_object, p_args);
  1317. return;
  1318. }
  1319. top = top->get_parent_class();
  1320. }
  1321. }
  1322. void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1323. // Sorry, the method is the one that controls the call order
  1324. call_multilevel(p_method, p_args, p_argcount);
  1325. }
  1326. bool CSharpInstance::_reference_owner_unsafe() {
  1327. #ifdef DEBUG_ENABLED
  1328. CRASH_COND(!base_ref);
  1329. CRASH_COND(owner == NULL);
  1330. CRASH_COND(unsafe_referenced); // already referenced
  1331. #endif
  1332. // Unsafe refcount increment. The managed instance also counts as a reference.
  1333. // This way if the unmanaged world has no references to our owner
  1334. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1335. // See: _unreference_owner_unsafe()
  1336. // May not me referenced yet, so we must use init_ref() instead of reference()
  1337. if (static_cast<Reference *>(owner)->init_ref()) {
  1338. CSharpLanguage::get_singleton()->post_unsafe_reference(owner);
  1339. unsafe_referenced = true;
  1340. }
  1341. return unsafe_referenced;
  1342. }
  1343. bool CSharpInstance::_unreference_owner_unsafe() {
  1344. #ifdef DEBUG_ENABLED
  1345. CRASH_COND(!base_ref);
  1346. CRASH_COND(owner == NULL);
  1347. #endif
  1348. if (!unsafe_referenced)
  1349. return false; // Already unreferenced
  1350. unsafe_referenced = false;
  1351. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1352. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1353. // See: _reference_owner_unsafe()
  1354. // Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
  1355. CSharpLanguage::get_singleton()->pre_unsafe_unreference(owner);
  1356. return static_cast<Reference *>(owner)->unreference();
  1357. }
  1358. MonoObject *CSharpInstance::_internal_new_managed() {
  1359. #ifdef DEBUG_ENABLED
  1360. CRASH_COND(!gchandle.is_valid());
  1361. #endif
  1362. // Search the constructor first, to fail with an error if it's not found before allocating anything else.
  1363. GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1364. ERR_FAIL_NULL_V_MSG(ctor, NULL,
  1365. "Cannot create script instance because the class does not define a parameterless constructor: '" + script->get_path() + "'.");
  1366. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1367. ERR_FAIL_NULL_V(owner, NULL);
  1368. ERR_FAIL_COND_V(script.is_null(), NULL);
  1369. MonoObject *mono_object = mono_object_new(mono_domain_get(), script->script_class->get_mono_ptr());
  1370. if (!mono_object) {
  1371. // Important to clear this before destroying the script instance here
  1372. script = Ref<CSharpScript>();
  1373. bool die = _unreference_owner_unsafe();
  1374. // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
  1375. CRASH_COND(die);
  1376. owner = NULL;
  1377. ERR_FAIL_V_MSG(NULL, "Failed to allocate memory for the object.");
  1378. }
  1379. // Tie managed to unmanaged
  1380. gchandle = MonoGCHandle::create_strong(mono_object);
  1381. if (base_ref)
  1382. _reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  1383. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, owner);
  1384. // Construct
  1385. ctor->invoke_raw(mono_object, NULL);
  1386. return mono_object;
  1387. }
  1388. void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
  1389. #ifdef DEBUG_ENABLED
  1390. CRASH_COND(base_ref);
  1391. CRASH_COND(gchandle.is_null());
  1392. #endif
  1393. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1394. }
  1395. void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
  1396. #ifdef DEBUG_ENABLED
  1397. CRASH_COND(!base_ref);
  1398. CRASH_COND(gchandle.is_null());
  1399. #endif
  1400. r_remove_script_instance = false;
  1401. if (_unreference_owner_unsafe()) {
  1402. // Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
  1403. r_delete_owner = true;
  1404. } else {
  1405. r_delete_owner = false;
  1406. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1407. if (!p_is_finalizer) {
  1408. // If the native instance is still alive and Dispose() was called
  1409. // (instead of the finalizer), then we remove the script instance.
  1410. r_remove_script_instance = true;
  1411. } else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
  1412. // If the native instance is still alive and this is called from the finalizer,
  1413. // then it was referenced from another thread before the finalizer could
  1414. // unreference and delete it, so we want to keep it.
  1415. // GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
  1416. // could have already been collected. Instead we will create a new managed instance here.
  1417. MonoObject *new_managed = _internal_new_managed();
  1418. if (!new_managed) {
  1419. r_remove_script_instance = true;
  1420. }
  1421. }
  1422. }
  1423. }
  1424. void CSharpInstance::refcount_incremented() {
  1425. #ifdef DEBUG_ENABLED
  1426. CRASH_COND(!base_ref);
  1427. CRASH_COND(owner == NULL);
  1428. #endif
  1429. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1430. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1431. GD_MONO_SCOPE_THREAD_ATTACH;
  1432. // The reference count was increased after the managed side was the only one referencing our owner.
  1433. // This means the owner is being referenced again by the unmanaged side,
  1434. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1435. // Release the current weak handle and replace it with a strong handle.
  1436. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(gchandle->get_target());
  1437. gchandle->release();
  1438. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  1439. }
  1440. }
  1441. bool CSharpInstance::refcount_decremented() {
  1442. #ifdef DEBUG_ENABLED
  1443. CRASH_COND(!base_ref);
  1444. CRASH_COND(owner == NULL);
  1445. #endif
  1446. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1447. int refcount = ref_owner->reference_get_count();
  1448. if (refcount == 1 && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1449. GD_MONO_SCOPE_THREAD_ATTACH;
  1450. // If owner owner is no longer referenced by the unmanaged side,
  1451. // the managed instance takes responsibility of deleting the owner when GCed.
  1452. // Release the current strong handle and replace it with a weak handle.
  1453. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(gchandle->get_target());
  1454. gchandle->release();
  1455. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  1456. return false;
  1457. }
  1458. ref_dying = (refcount == 0);
  1459. return ref_dying;
  1460. }
  1461. MultiplayerAPI::RPCMode CSharpInstance::_member_get_rpc_mode(IMonoClassMember *p_member) const {
  1462. if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
  1463. return MultiplayerAPI::RPC_MODE_REMOTE;
  1464. if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
  1465. return MultiplayerAPI::RPC_MODE_MASTER;
  1466. if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute)))
  1467. return MultiplayerAPI::RPC_MODE_PUPPET;
  1468. if (p_member->has_attribute(CACHED_CLASS(SlaveAttribute)))
  1469. return MultiplayerAPI::RPC_MODE_PUPPET;
  1470. if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute)))
  1471. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1472. if (p_member->has_attribute(CACHED_CLASS(SyncAttribute)))
  1473. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1474. if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute)))
  1475. return MultiplayerAPI::RPC_MODE_MASTERSYNC;
  1476. if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute)))
  1477. return MultiplayerAPI::RPC_MODE_PUPPETSYNC;
  1478. return MultiplayerAPI::RPC_MODE_DISABLED;
  1479. }
  1480. MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const {
  1481. GD_MONO_SCOPE_THREAD_ATTACH;
  1482. GDMonoClass *top = script->script_class;
  1483. while (top && top != script->native) {
  1484. GDMonoMethod *method = top->get_fetched_method_unknown_params(p_method);
  1485. if (method && !method->is_static())
  1486. return _member_get_rpc_mode(method);
  1487. top = top->get_parent_class();
  1488. }
  1489. return MultiplayerAPI::RPC_MODE_DISABLED;
  1490. }
  1491. MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const {
  1492. GD_MONO_SCOPE_THREAD_ATTACH;
  1493. GDMonoClass *top = script->script_class;
  1494. while (top && top != script->native) {
  1495. GDMonoField *field = top->get_field(p_variable);
  1496. if (field && !field->is_static())
  1497. return _member_get_rpc_mode(field);
  1498. GDMonoProperty *property = top->get_property(p_variable);
  1499. if (property && !property->is_static())
  1500. return _member_get_rpc_mode(property);
  1501. top = top->get_parent_class();
  1502. }
  1503. return MultiplayerAPI::RPC_MODE_DISABLED;
  1504. }
  1505. void CSharpInstance::notification(int p_notification) {
  1506. GD_MONO_SCOPE_THREAD_ATTACH;
  1507. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1508. // When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
  1509. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
  1510. // to be sent at least once, which happens right before the call to the destructor.
  1511. predelete_notified = true;
  1512. if (base_ref) {
  1513. // It's not safe to proceed if the owner derives Reference and the refcount reached 0.
  1514. // At this point, Dispose() was already called (manually or from the finalizer) so
  1515. // that's not a problem. The refcount wouldn't have reached 0 otherwise, since the
  1516. // managed side references it and Dispose() needs to be called to release it.
  1517. // However, this means C# Reference scripts can't receive NOTIFICATION_PREDELETE, but
  1518. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1519. return;
  1520. }
  1521. _call_notification(p_notification);
  1522. MonoObject *mono_object = get_mono_object();
  1523. ERR_FAIL_NULL(mono_object);
  1524. MonoException *exc = NULL;
  1525. GDMonoUtils::dispose(mono_object, &exc);
  1526. if (exc) {
  1527. GDMonoUtils::set_pending_exception(exc);
  1528. }
  1529. return;
  1530. }
  1531. _call_notification(p_notification);
  1532. }
  1533. void CSharpInstance::_call_notification(int p_notification) {
  1534. GD_MONO_ASSERT_THREAD_ATTACHED;
  1535. MonoObject *mono_object = get_mono_object();
  1536. ERR_FAIL_NULL(mono_object);
  1537. // Custom version of _call_multilevel, optimized for _notification
  1538. uint32_t arg = p_notification;
  1539. void *args[1] = { &arg };
  1540. StringName method_name = CACHED_STRING_NAME(_notification);
  1541. GDMonoClass *top = script->script_class;
  1542. while (top && top != script->native) {
  1543. GDMonoMethod *method = top->get_method(method_name, 1);
  1544. if (method) {
  1545. method->invoke_raw(mono_object, args);
  1546. return;
  1547. }
  1548. top = top->get_parent_class();
  1549. }
  1550. }
  1551. String CSharpInstance::to_string(bool *r_valid) {
  1552. GD_MONO_SCOPE_THREAD_ATTACH;
  1553. MonoObject *mono_object = get_mono_object();
  1554. if (mono_object == NULL) {
  1555. if (r_valid)
  1556. *r_valid = false;
  1557. return String();
  1558. }
  1559. MonoException *exc = NULL;
  1560. MonoString *result = GDMonoUtils::object_to_string(mono_object, &exc);
  1561. if (exc) {
  1562. GDMonoUtils::set_pending_exception(exc);
  1563. if (r_valid)
  1564. *r_valid = false;
  1565. return String();
  1566. }
  1567. if (result == NULL) {
  1568. if (r_valid)
  1569. *r_valid = false;
  1570. return String();
  1571. }
  1572. return GDMonoMarshal::mono_string_to_godot(result);
  1573. }
  1574. Ref<Script> CSharpInstance::get_script() const {
  1575. return script;
  1576. }
  1577. ScriptLanguage *CSharpInstance::get_language() {
  1578. return CSharpLanguage::get_singleton();
  1579. }
  1580. CSharpInstance::CSharpInstance() :
  1581. owner(NULL),
  1582. base_ref(false),
  1583. ref_dying(false),
  1584. unsafe_referenced(false),
  1585. predelete_notified(false),
  1586. destructing_script_instance(false) {
  1587. }
  1588. CSharpInstance::~CSharpInstance() {
  1589. GD_MONO_SCOPE_THREAD_ATTACH;
  1590. destructing_script_instance = true;
  1591. if (gchandle.is_valid()) {
  1592. if (!predelete_notified && !ref_dying) {
  1593. // This destructor is not called from the owners destructor.
  1594. // This could be being called from the owner's set_script_instance method,
  1595. // meaning this script is being replaced with another one. If this is the case,
  1596. // we must call Dispose here, because Dispose calls owner->set_script_instance(NULL)
  1597. // and that would mess up with the new script instance if called later.
  1598. MonoObject *mono_object = gchandle->get_target();
  1599. if (mono_object) {
  1600. MonoException *exc = NULL;
  1601. GDMonoUtils::dispose(mono_object, &exc);
  1602. if (exc) {
  1603. GDMonoUtils::set_pending_exception(exc);
  1604. }
  1605. }
  1606. }
  1607. gchandle->release(); // Make sure the gchandle is released
  1608. }
  1609. // If not being called from the owner's destructor, and we still hold a reference to the owner
  1610. if (base_ref && !ref_dying && owner && unsafe_referenced) {
  1611. // The owner's script or script instance is being replaced (or removed)
  1612. // Transfer ownership to an "instance binding"
  1613. Reference *ref_owner = static_cast<Reference *>(owner);
  1614. // We will unreference the owner before referencing it again, so we need to keep it alive
  1615. Ref<Reference> scope_keep_owner_alive(ref_owner);
  1616. (void)scope_keep_owner_alive;
  1617. // Unreference the owner here, before the new "instance binding" references it.
  1618. // Otherwise, the unsafe reference debug checks will incorrectly detect a bug.
  1619. bool die = _unreference_owner_unsafe();
  1620. CRASH_COND(die); // `owner_keep_alive` holds a reference, so it can't die
  1621. void *data = owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  1622. CRASH_COND(data == NULL);
  1623. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  1624. if (!script_binding.inited) {
  1625. MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());
  1626. if (!script_binding.inited) { // Other thread may have set it up
  1627. // Already had a binding that needs to be setup
  1628. CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, owner);
  1629. CRASH_COND(!script_binding.inited);
  1630. }
  1631. }
  1632. #ifdef DEBUG_ENABLED
  1633. // The "instance binding" holds a reference so the refcount should be at least 2 before `scope_keep_owner_alive` goes out of scope
  1634. CRASH_COND(ref_owner->reference_get_count() <= 1);
  1635. #endif
  1636. }
  1637. if (script.is_valid() && owner) {
  1638. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  1639. #ifdef DEBUG_ENABLED
  1640. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1641. Set<Object *>::Element *match = script->instances.find(owner);
  1642. CRASH_COND(!match);
  1643. script->instances.erase(match);
  1644. #else
  1645. script->instances.erase(owner);
  1646. #endif
  1647. }
  1648. }
  1649. #ifdef TOOLS_ENABLED
  1650. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1651. placeholders.erase(p_placeholder);
  1652. }
  1653. #endif
  1654. #ifdef TOOLS_ENABLED
  1655. void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1656. if (base_cache.is_valid()) {
  1657. base_cache->_update_exports_values(values, propnames);
  1658. }
  1659. for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) {
  1660. values[E->key()] = E->get();
  1661. }
  1662. for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) {
  1663. propnames.push_back(E->get());
  1664. }
  1665. }
  1666. void CSharpScript::_update_member_info_no_exports() {
  1667. if (exports_invalidated) {
  1668. GD_MONO_ASSERT_THREAD_ATTACHED;
  1669. exports_invalidated = false;
  1670. member_info.clear();
  1671. GDMonoClass *top = script_class;
  1672. while (top && top != native) {
  1673. PropertyInfo prop_info;
  1674. bool exported;
  1675. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1676. for (int i = fields.size() - 1; i >= 0; i--) {
  1677. GDMonoField *field = fields[i];
  1678. if (_get_member_export(field, /* inspect export: */ false, prop_info, exported)) {
  1679. StringName member_name = field->get_name();
  1680. member_info[member_name] = prop_info;
  1681. exported_members_cache.push_front(prop_info);
  1682. exported_members_defval_cache[member_name] = Variant();
  1683. }
  1684. }
  1685. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1686. for (int i = properties.size() - 1; i >= 0; i--) {
  1687. GDMonoProperty *property = properties[i];
  1688. if (_get_member_export(property, /* inspect export: */ false, prop_info, exported)) {
  1689. StringName member_name = property->get_name();
  1690. member_info[member_name] = prop_info;
  1691. exported_members_cache.push_front(prop_info);
  1692. exported_members_defval_cache[member_name] = Variant();
  1693. }
  1694. }
  1695. top = top->get_parent_class();
  1696. }
  1697. }
  1698. }
  1699. #endif
  1700. bool CSharpScript::_update_exports() {
  1701. #ifdef TOOLS_ENABLED
  1702. bool is_editor = Engine::get_singleton()->is_editor_hint();
  1703. if (is_editor)
  1704. placeholder_fallback_enabled = true; // until proven otherwise
  1705. #endif
  1706. if (!valid)
  1707. return false;
  1708. bool changed = false;
  1709. #ifdef TOOLS_ENABLED
  1710. if (!is_editor || exports_invalidated)
  1711. #endif
  1712. {
  1713. GD_MONO_SCOPE_THREAD_ATTACH;
  1714. changed = true;
  1715. member_info.clear();
  1716. #ifdef TOOLS_ENABLED
  1717. MonoObject *tmp_object = nullptr;
  1718. Object *tmp_native = nullptr;
  1719. uint32_t tmp_pinned_gchandle = 0;
  1720. if (is_editor) {
  1721. exports_invalidated = false;
  1722. exported_members_cache.clear();
  1723. exported_members_defval_cache.clear();
  1724. // Here we create a temporary managed instance of the class to get the initial values
  1725. tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
  1726. if (!tmp_object) {
  1727. ERR_PRINT("Failed to allocate temporary MonoObject.");
  1728. return false;
  1729. }
  1730. tmp_pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(tmp_object); // pin it (not sure if needed)
  1731. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1732. ERR_FAIL_NULL_V_MSG(ctor, NULL,
  1733. "Cannot construct temporary MonoObject because the class does not define a parameterless constructor: '" + get_path() + "'.");
  1734. MonoException *ctor_exc = NULL;
  1735. ctor->invoke(tmp_object, NULL, &ctor_exc);
  1736. tmp_native = GDMonoMarshal::unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(tmp_object));
  1737. if (ctor_exc) {
  1738. // TODO: Should we free 'tmp_native' if the exception was thrown after its creation?
  1739. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1740. tmp_object = NULL;
  1741. ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
  1742. GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
  1743. return false;
  1744. }
  1745. }
  1746. #endif
  1747. GDMonoClass *top = script_class;
  1748. while (top && top != native) {
  1749. PropertyInfo prop_info;
  1750. bool exported;
  1751. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1752. for (int i = fields.size() - 1; i >= 0; i--) {
  1753. GDMonoField *field = fields[i];
  1754. if (_get_member_export(field, /* inspect export: */ true, prop_info, exported)) {
  1755. StringName member_name = field->get_name();
  1756. member_info[member_name] = prop_info;
  1757. if (exported) {
  1758. #ifdef TOOLS_ENABLED
  1759. if (is_editor) {
  1760. exported_members_cache.push_front(prop_info);
  1761. if (tmp_object) {
  1762. exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
  1763. }
  1764. }
  1765. #endif
  1766. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  1767. exported_members_names.insert(member_name);
  1768. #endif
  1769. }
  1770. }
  1771. }
  1772. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1773. for (int i = properties.size() - 1; i >= 0; i--) {
  1774. GDMonoProperty *property = properties[i];
  1775. if (_get_member_export(property, /* inspect export: */ true, prop_info, exported)) {
  1776. StringName member_name = property->get_name();
  1777. member_info[member_name] = prop_info;
  1778. if (exported) {
  1779. #ifdef TOOLS_ENABLED
  1780. if (is_editor) {
  1781. exported_members_cache.push_front(prop_info);
  1782. if (tmp_object) {
  1783. MonoException *exc = nullptr;
  1784. MonoObject *ret = property->get_value(tmp_object, &exc);
  1785. if (exc) {
  1786. exported_members_defval_cache[member_name] = Variant();
  1787. GDMonoUtils::debug_print_unhandled_exception(exc);
  1788. } else {
  1789. exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
  1790. }
  1791. }
  1792. }
  1793. #endif
  1794. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  1795. exported_members_names.insert(member_name);
  1796. #endif
  1797. }
  1798. }
  1799. }
  1800. top = top->get_parent_class();
  1801. }
  1802. #ifdef TOOLS_ENABLED
  1803. if (is_editor) {
  1804. // Need to check this here, before disposal
  1805. bool base_ref = Object::cast_to<Reference>(tmp_native) != NULL;
  1806. // Dispose the temporary managed instance
  1807. MonoException *exc = NULL;
  1808. GDMonoUtils::dispose(tmp_object, &exc);
  1809. if (exc) {
  1810. ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
  1811. GDMonoUtils::debug_print_unhandled_exception(exc);
  1812. }
  1813. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1814. tmp_object = NULL;
  1815. if (tmp_native && !base_ref) {
  1816. Node *node = Object::cast_to<Node>(tmp_native);
  1817. if (node && node->is_inside_tree()) {
  1818. ERR_PRINTS("Temporary instance was added to the scene tree.");
  1819. } else {
  1820. memdelete(tmp_native);
  1821. }
  1822. }
  1823. }
  1824. #endif
  1825. }
  1826. #ifdef TOOLS_ENABLED
  1827. if (is_editor) {
  1828. placeholder_fallback_enabled = false;
  1829. if (placeholders.size()) {
  1830. // Update placeholders if any
  1831. Map<StringName, Variant> values;
  1832. List<PropertyInfo> propnames;
  1833. _update_exports_values(values, propnames);
  1834. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  1835. E->get()->update(propnames, values);
  1836. }
  1837. }
  1838. }
  1839. #endif
  1840. return changed;
  1841. }
  1842. void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class) {
  1843. // no need to load the script's signals more than once
  1844. if (!signals_invalidated) {
  1845. return;
  1846. }
  1847. // make sure this classes signals are empty when loading for the first time
  1848. _signals.clear();
  1849. GD_MONO_SCOPE_THREAD_ATTACH;
  1850. GDMonoClass *top = p_class;
  1851. while (top && top != p_native_class) {
  1852. const Vector<GDMonoClass *> &delegates = top->get_all_delegates();
  1853. for (int i = delegates.size() - 1; i >= 0; --i) {
  1854. Vector<Argument> parameters;
  1855. GDMonoClass *delegate = delegates[i];
  1856. if (_get_signal(top, delegate, parameters)) {
  1857. _signals[delegate->get_name()] = parameters;
  1858. }
  1859. }
  1860. top = top->get_parent_class();
  1861. }
  1862. signals_invalidated = false;
  1863. }
  1864. bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Vector<Argument> &params) {
  1865. GD_MONO_ASSERT_THREAD_ATTACHED;
  1866. if (p_delegate->has_attribute(CACHED_CLASS(SignalAttribute))) {
  1867. MonoType *raw_type = p_delegate->get_mono_type();
  1868. if (mono_type_get_type(raw_type) == MONO_TYPE_CLASS) {
  1869. // Arguments are accessibles as arguments of .Invoke method
  1870. GDMonoMethod *invoke = p_delegate->get_method("Invoke", -1);
  1871. Vector<StringName> names;
  1872. Vector<ManagedType> types;
  1873. invoke->get_parameter_names(names);
  1874. invoke->get_parameter_types(types);
  1875. if (names.size() == types.size()) {
  1876. for (int i = 0; i < names.size(); ++i) {
  1877. Argument arg;
  1878. arg.name = names[i];
  1879. arg.type = GDMonoMarshal::managed_to_variant_type(types[i]);
  1880. if (arg.type == Variant::NIL) {
  1881. ERR_PRINTS("Unknown type of signal parameter: '" + arg.name + "' in '" + p_class->get_full_name() + "'.");
  1882. return false;
  1883. }
  1884. params.push_back(arg);
  1885. }
  1886. return true;
  1887. }
  1888. }
  1889. }
  1890. return false;
  1891. }
  1892. /**
  1893. * Returns false if there was an error, otherwise true.
  1894. * If there was an error, r_prop_info and r_exported are not assigned any value.
  1895. */
  1896. bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported) {
  1897. GD_MONO_ASSERT_THREAD_ATTACHED;
  1898. // Goddammit, C++. All I wanted was some nested functions.
  1899. #define MEMBER_FULL_QUALIFIED_NAME(m_member) \
  1900. (m_member->get_enclosing_class()->get_full_name() + "." + (String)m_member->get_name())
  1901. if (p_member->is_static()) {
  1902. #ifdef TOOLS_ENABLED
  1903. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
  1904. ERR_PRINTS("Cannot export member because it is static: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1905. #endif
  1906. return false;
  1907. }
  1908. if (member_info.has(p_member->get_name()))
  1909. return false;
  1910. ManagedType type;
  1911. if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_FIELD) {
  1912. type = static_cast<GDMonoField *>(p_member)->get_type();
  1913. } else if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1914. type = static_cast<GDMonoProperty *>(p_member)->get_type();
  1915. } else {
  1916. CRASH_NOW();
  1917. }
  1918. bool exported = p_member->has_attribute(CACHED_CLASS(ExportAttribute));
  1919. if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1920. GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
  1921. if (!property->has_getter()) {
  1922. #ifdef TOOLS_ENABLED
  1923. if (exported)
  1924. ERR_PRINT("Cannot export a property without a getter: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1925. #endif
  1926. return false;
  1927. }
  1928. if (!property->has_setter()) {
  1929. #ifdef TOOLS_ENABLED
  1930. if (exported)
  1931. ERR_PRINT("Cannot export a property without a setter: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1932. #endif
  1933. return false;
  1934. }
  1935. }
  1936. Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
  1937. if (!p_inspect_export || !exported) {
  1938. r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
  1939. r_exported = false;
  1940. return true;
  1941. }
  1942. #ifdef TOOLS_ENABLED
  1943. MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
  1944. #endif
  1945. PropertyHint hint = PROPERTY_HINT_NONE;
  1946. String hint_string;
  1947. if (variant_type == Variant::NIL) {
  1948. #ifdef TOOLS_ENABLED
  1949. ERR_PRINTS("Unknown exported member type: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1950. #endif
  1951. return false;
  1952. }
  1953. #ifdef TOOLS_ENABLED
  1954. int hint_res = _try_get_member_export_hint(p_member, type, variant_type, /* allow_generics: */ true, hint, hint_string);
  1955. ERR_FAIL_COND_V_MSG(hint_res == -1, false,
  1956. "Error while trying to determine information about the exported member: '" +
  1957. MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
  1958. if (hint_res == 0) {
  1959. hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
  1960. hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
  1961. }
  1962. #endif
  1963. r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE);
  1964. r_exported = true;
  1965. return true;
  1966. #undef MEMBER_FULL_QUALIFIED_NAME
  1967. }
  1968. #ifdef TOOLS_ENABLED
  1969. int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string) {
  1970. GD_MONO_ASSERT_THREAD_ATTACHED;
  1971. if (p_variant_type == Variant::INT && p_type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(p_type.type_class->get_mono_ptr())) {
  1972. r_hint = PROPERTY_HINT_ENUM;
  1973. Vector<MonoClassField *> fields = p_type.type_class->get_enum_fields();
  1974. MonoType *enum_basetype = mono_class_enum_basetype(p_type.type_class->get_mono_ptr());
  1975. String name_only_hint_string;
  1976. // True: enum Foo { Bar, Baz, Quux }
  1977. // True: enum Foo { Bar = 0, Baz = 1, Quux = 2 }
  1978. // False: enum Foo { Bar = 0, Baz = 7, Quux = 5 }
  1979. bool uses_default_values = true;
  1980. for (int i = 0; i < fields.size(); i++) {
  1981. MonoClassField *field = fields[i];
  1982. if (i > 0) {
  1983. r_hint_string += ",";
  1984. name_only_hint_string += ",";
  1985. }
  1986. String enum_field_name = String::utf8(mono_field_get_name(field));
  1987. r_hint_string += enum_field_name;
  1988. name_only_hint_string += enum_field_name;
  1989. // TODO:
  1990. // Instead of using mono_field_get_value_object, we can do this without boxing. Check the
  1991. // internal mono functions: ves_icall_System_Enum_GetEnumValuesAndNames and the get_enum_field.
  1992. MonoObject *val_obj = mono_field_get_value_object(mono_domain_get(), field, NULL);
  1993. ERR_FAIL_NULL_V_MSG(val_obj, -1, "Failed to get '" + enum_field_name + "' constant enum value.");
  1994. bool r_error;
  1995. uint64_t val = GDMonoUtils::unbox_enum_value(val_obj, enum_basetype, r_error);
  1996. ERR_FAIL_COND_V_MSG(r_error, -1, "Failed to unbox '" + enum_field_name + "' constant enum value.");
  1997. if (val != (unsigned int)i) {
  1998. uses_default_values = false;
  1999. }
  2000. r_hint_string += ":";
  2001. r_hint_string += String::num_uint64(val);
  2002. }
  2003. if (uses_default_values) {
  2004. // If we use the format NAME:VAL, that's what the editor displays.
  2005. // That's annoying if the user is not using custom values for the enum constants.
  2006. // This may not be needed in the future if the editor is changed to not display values.
  2007. r_hint_string = name_only_hint_string;
  2008. }
  2009. } else if (p_variant_type == Variant::OBJECT && CACHED_CLASS(GodotResource)->is_assignable_from(p_type.type_class)) {
  2010. GDMonoClass *field_native_class = GDMonoUtils::get_class_native_base(p_type.type_class);
  2011. CRASH_COND(field_native_class == NULL);
  2012. r_hint = PROPERTY_HINT_RESOURCE_TYPE;
  2013. r_hint_string = NATIVE_GDMONOCLASS_NAME(field_native_class);
  2014. } else if (p_allow_generics && p_variant_type == Variant::ARRAY) {
  2015. // Nested arrays are not supported in the inspector
  2016. ManagedType elem_type;
  2017. if (!GDMonoMarshal::try_get_array_element_type(p_type, elem_type))
  2018. return 0;
  2019. Variant::Type elem_variant_type = GDMonoMarshal::managed_to_variant_type(elem_type);
  2020. PropertyHint elem_hint = PROPERTY_HINT_NONE;
  2021. String elem_hint_string;
  2022. ERR_FAIL_COND_V_MSG(elem_variant_type == Variant::NIL, -1, "Unknown array element type.");
  2023. int hint_res = _try_get_member_export_hint(p_member, elem_type, elem_variant_type, /* allow_generics: */ false, elem_hint, elem_hint_string);
  2024. ERR_FAIL_COND_V_MSG(hint_res == -1, -1, "Error while trying to determine information about the array element type.");
  2025. // Format: type/hint:hint_string
  2026. r_hint_string = itos(elem_variant_type) + "/" + itos(elem_hint) + ":" + elem_hint_string;
  2027. r_hint = PROPERTY_HINT_TYPE_STRING;
  2028. } else if (p_allow_generics && p_variant_type == Variant::DICTIONARY) {
  2029. // TODO: Dictionaries are not supported in the inspector
  2030. } else {
  2031. return 0;
  2032. }
  2033. return 1;
  2034. }
  2035. #endif
  2036. void CSharpScript::_clear() {
  2037. tool = false;
  2038. valid = false;
  2039. base = NULL;
  2040. native = NULL;
  2041. script_class = NULL;
  2042. }
  2043. Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  2044. if (unlikely(GDMono::get_singleton() == NULL)) {
  2045. // Probably not the best error but eh.
  2046. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  2047. return Variant();
  2048. }
  2049. GD_MONO_SCOPE_THREAD_ATTACH;
  2050. GDMonoClass *top = script_class;
  2051. while (top && top != native) {
  2052. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  2053. if (method && method->is_static()) {
  2054. MonoObject *result = method->invoke(NULL, p_args);
  2055. if (result) {
  2056. return GDMonoMarshal::mono_object_to_variant(result);
  2057. } else {
  2058. return Variant();
  2059. }
  2060. }
  2061. top = top->get_parent_class();
  2062. }
  2063. // No static method found. Try regular instance calls
  2064. return Script::call(p_method, p_args, p_argcount, r_error);
  2065. }
  2066. void CSharpScript::_resource_path_changed() {
  2067. String path = get_path();
  2068. if (!path.empty()) {
  2069. name = get_path().get_file().get_basename();
  2070. }
  2071. }
  2072. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  2073. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  2074. r_ret = get_source_code();
  2075. return true;
  2076. }
  2077. return false;
  2078. }
  2079. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  2080. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  2081. set_source_code(p_value);
  2082. reload();
  2083. return true;
  2084. }
  2085. return false;
  2086. }
  2087. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  2088. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  2089. }
  2090. void CSharpScript::_bind_methods() {
  2091. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
  2092. }
  2093. Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
  2094. // This method should not fail, only assertions allowed
  2095. CRASH_COND(p_class == NULL);
  2096. // TODO OPTIMIZE: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time
  2097. Ref<CSharpScript> script = memnew(CSharpScript);
  2098. initialize_for_managed_type(script, p_class, p_native);
  2099. return script;
  2100. }
  2101. void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native) {
  2102. // This method should not fail, only assertions allowed
  2103. CRASH_COND(p_class == NULL);
  2104. p_script->name = p_class->get_name();
  2105. p_script->script_class = p_class;
  2106. p_script->native = p_native;
  2107. CRASH_COND(p_script->native == NULL);
  2108. GDMonoClass *base = p_script->script_class->get_parent_class();
  2109. if (base != p_script->native)
  2110. p_script->base = base;
  2111. p_script->valid = true;
  2112. p_script->tool = p_script->script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2113. if (!p_script->tool) {
  2114. GDMonoClass *nesting_class = p_script->script_class->get_nesting_class();
  2115. p_script->tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2116. }
  2117. #if TOOLS_ENABLED
  2118. if (!p_script->tool) {
  2119. p_script->tool = p_script->script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
  2120. }
  2121. #endif
  2122. #ifdef DEBUG_ENABLED
  2123. // For debug builds, we must fetch from all native base methods as well.
  2124. // Native base methods must be fetched before the current class.
  2125. // Not needed if the script class itself is a native class.
  2126. if (p_script->script_class != p_script->native) {
  2127. GDMonoClass *native_top = p_script->native;
  2128. while (native_top) {
  2129. native_top->fetch_methods_with_godot_api_checks(p_script->native);
  2130. if (native_top == CACHED_CLASS(GodotObject))
  2131. break;
  2132. native_top = native_top->get_parent_class();
  2133. }
  2134. }
  2135. #endif
  2136. p_script->script_class->fetch_methods_with_godot_api_checks(p_script->native);
  2137. // Need to fetch method from base classes as well
  2138. GDMonoClass *top = p_script->script_class;
  2139. while (top && top != p_script->native) {
  2140. top->fetch_methods_with_godot_api_checks(p_script->native);
  2141. top = top->get_parent_class();
  2142. }
  2143. p_script->load_script_signals(p_script->script_class, p_script->native);
  2144. #ifdef TOOLS_ENABLED
  2145. p_script->_update_member_info_no_exports();
  2146. #endif
  2147. }
  2148. bool CSharpScript::can_instance() const {
  2149. #ifdef TOOLS_ENABLED
  2150. bool extra_cond = tool || ScriptServer::is_scripting_enabled();
  2151. #else
  2152. bool extra_cond = true;
  2153. #endif
  2154. // FIXME Need to think this through better.
  2155. // For tool scripts, this will never fire if the class is not found. That's because we
  2156. // don't know if it's a tool script if we can't find the class to access the attributes.
  2157. if (extra_cond && !script_class) {
  2158. if (GDMono::get_singleton()->get_project_assembly() == NULL) {
  2159. // The project assembly is not loaded
  2160. ERR_FAIL_V_MSG(NULL, "Cannot instance script because the project assembly is not loaded. Script: '" + get_path() + "'.");
  2161. } else {
  2162. // The project assembly is loaded, but the class could not found
  2163. ERR_FAIL_V_MSG(NULL, "Cannot instance script because the class '" + name + "' could not be found. Script: '" + get_path() + "'.");
  2164. }
  2165. }
  2166. return valid && extra_cond;
  2167. }
  2168. StringName CSharpScript::get_instance_base_type() const {
  2169. if (native)
  2170. return native->get_name();
  2171. else
  2172. return StringName();
  2173. }
  2174. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  2175. GD_MONO_ASSERT_THREAD_ATTACHED;
  2176. /* STEP 1, CREATE */
  2177. // Search the constructor first, to fail with an error if it's not found before allocating anything else.
  2178. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
  2179. if (ctor == NULL) {
  2180. ERR_FAIL_COND_V_MSG(p_argcount == 0, NULL,
  2181. "Cannot create script instance. The class '" + script_class->get_full_name() +
  2182. "' does not define a parameterless constructor." +
  2183. (get_path().empty() ? String() : " Path: '" + get_path() + "'."));
  2184. ERR_FAIL_V_MSG(NULL, "Constructor not found.");
  2185. }
  2186. Ref<Reference> ref;
  2187. if (p_isref) {
  2188. // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
  2189. ref = Ref<Reference>(static_cast<Reference *>(p_owner));
  2190. }
  2191. // If the object had a script instance binding, dispose it before adding the CSharpInstance
  2192. if (p_owner->has_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index())) {
  2193. void *data = p_owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
  2194. CRASH_COND(data == NULL);
  2195. CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
  2196. if (script_binding.inited && script_binding.gchandle.is_valid()) {
  2197. MonoObject *mono_object = script_binding.gchandle->get_target();
  2198. if (mono_object) {
  2199. MonoException *exc = NULL;
  2200. GDMonoUtils::dispose(mono_object, &exc);
  2201. if (exc) {
  2202. GDMonoUtils::set_pending_exception(exc);
  2203. }
  2204. }
  2205. script_binding.inited = false;
  2206. }
  2207. }
  2208. CSharpInstance *instance = memnew(CSharpInstance);
  2209. instance->base_ref = p_isref;
  2210. instance->script = Ref<CSharpScript>(this);
  2211. instance->owner = p_owner;
  2212. instance->owner->set_script_instance(instance);
  2213. /* STEP 2, INITIALIZE AND CONSTRUCT */
  2214. MonoObject *mono_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());
  2215. if (!mono_object) {
  2216. // Important to clear this before destroying the script instance here
  2217. instance->script = Ref<CSharpScript>();
  2218. instance->owner = NULL;
  2219. bool die = instance->_unreference_owner_unsafe();
  2220. // Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
  2221. CRASH_COND(die);
  2222. p_owner->set_script_instance(NULL);
  2223. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  2224. ERR_FAIL_V_MSG(NULL, "Failed to allocate memory for the object.");
  2225. }
  2226. // Tie managed to unmanaged
  2227. instance->gchandle = MonoGCHandle::create_strong(mono_object);
  2228. if (instance->base_ref)
  2229. instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)
  2230. {
  2231. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2232. instances.insert(instance->owner);
  2233. }
  2234. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);
  2235. // Construct
  2236. ctor->invoke(mono_object, p_args);
  2237. /* STEP 3, PARTY */
  2238. //@TODO make thread safe
  2239. return instance;
  2240. }
  2241. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  2242. if (!valid) {
  2243. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  2244. return Variant();
  2245. }
  2246. r_error.error = Variant::CallError::CALL_OK;
  2247. ERR_FAIL_NULL_V(native, Variant());
  2248. GD_MONO_SCOPE_THREAD_ATTACH;
  2249. Object *owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native));
  2250. REF ref;
  2251. Reference *r = Object::cast_to<Reference>(owner);
  2252. if (r) {
  2253. ref = REF(r);
  2254. }
  2255. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  2256. if (!instance) {
  2257. if (ref.is_null()) {
  2258. memdelete(owner); //no owner, sorry
  2259. }
  2260. return Variant();
  2261. }
  2262. if (ref.is_valid()) {
  2263. return ref;
  2264. } else {
  2265. return owner;
  2266. }
  2267. }
  2268. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  2269. #ifdef DEBUG_ENABLED
  2270. CRASH_COND(!valid);
  2271. #endif
  2272. if (native) {
  2273. String native_name = NATIVE_GDMONOCLASS_NAME(native);
  2274. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  2275. if (ScriptDebugger::get_singleton()) {
  2276. CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  2277. }
  2278. ERR_FAIL_V_MSG(NULL, "Script inherits from native type '" + native_name +
  2279. "', so it can't be instanced in object of type: '" + p_this->get_class() + "'.");
  2280. }
  2281. }
  2282. GD_MONO_SCOPE_THREAD_ATTACH;
  2283. Variant::CallError unchecked_error;
  2284. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this) != NULL, unchecked_error);
  2285. }
  2286. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  2287. #ifdef TOOLS_ENABLED
  2288. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  2289. placeholders.insert(si);
  2290. _update_exports();
  2291. return si;
  2292. #else
  2293. return NULL;
  2294. #endif
  2295. }
  2296. bool CSharpScript::instance_has(const Object *p_this) const {
  2297. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2298. return instances.has((Object *)p_this);
  2299. }
  2300. bool CSharpScript::has_source_code() const {
  2301. return !source.empty();
  2302. }
  2303. String CSharpScript::get_source_code() const {
  2304. return source;
  2305. }
  2306. void CSharpScript::set_source_code(const String &p_code) {
  2307. if (source == p_code)
  2308. return;
  2309. source = p_code;
  2310. #ifdef TOOLS_ENABLED
  2311. source_changed_cache = true;
  2312. #endif
  2313. }
  2314. void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
  2315. if (!script_class)
  2316. return;
  2317. GD_MONO_SCOPE_THREAD_ATTACH;
  2318. // TODO: Filter out things unsuitable for explicit calls, like constructors.
  2319. const Vector<GDMonoMethod *> &methods = script_class->get_all_methods();
  2320. for (int i = 0; i < methods.size(); ++i) {
  2321. p_list->push_back(methods[i]->get_method_info());
  2322. }
  2323. }
  2324. bool CSharpScript::has_method(const StringName &p_method) const {
  2325. if (!script_class)
  2326. return false;
  2327. GD_MONO_SCOPE_THREAD_ATTACH;
  2328. return script_class->has_fetched_method_unknown_params(p_method);
  2329. }
  2330. MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
  2331. if (!script_class)
  2332. return MethodInfo();
  2333. GD_MONO_SCOPE_THREAD_ATTACH;
  2334. GDMonoClass *top = script_class;
  2335. while (top && top != native) {
  2336. GDMonoMethod *params = top->get_fetched_method_unknown_params(p_method);
  2337. if (params) {
  2338. return params->get_method_info();
  2339. }
  2340. top = top->get_parent_class();
  2341. }
  2342. return MethodInfo();
  2343. }
  2344. Error CSharpScript::reload(bool p_keep_state) {
  2345. bool has_instances;
  2346. {
  2347. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2348. has_instances = instances.size();
  2349. }
  2350. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  2351. GD_MONO_SCOPE_THREAD_ATTACH;
  2352. GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly();
  2353. if (project_assembly) {
  2354. const Variant *script_metadata_var = CSharpLanguage::get_singleton()->get_scripts_metadata().getptr(get_path());
  2355. if (script_metadata_var) {
  2356. Dictionary script_metadata = script_metadata_var->operator Dictionary()["class"];
  2357. const Variant *namespace_ = script_metadata.getptr("namespace");
  2358. const Variant *class_name = script_metadata.getptr("class_name");
  2359. ERR_FAIL_NULL_V(namespace_, ERR_BUG);
  2360. ERR_FAIL_NULL_V(class_name, ERR_BUG);
  2361. GDMonoClass *klass = project_assembly->get_class(namespace_->operator String(), class_name->operator String());
  2362. if (klass && CACHED_CLASS(GodotObject)->is_assignable_from(klass)) {
  2363. script_class = klass;
  2364. }
  2365. } else {
  2366. // Missing script metadata. Fallback to legacy method
  2367. script_class = project_assembly->get_object_derived_class(name);
  2368. }
  2369. valid = script_class != NULL;
  2370. if (script_class) {
  2371. #ifdef DEBUG_ENABLED
  2372. print_verbose("Found class " + script_class->get_full_name() + " for script " + get_path());
  2373. #endif
  2374. tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2375. if (!tool) {
  2376. GDMonoClass *nesting_class = script_class->get_nesting_class();
  2377. tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
  2378. }
  2379. #if TOOLS_ENABLED
  2380. if (!tool) {
  2381. tool = script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
  2382. }
  2383. #endif
  2384. native = GDMonoUtils::get_class_native_base(script_class);
  2385. CRASH_COND(native == NULL);
  2386. GDMonoClass *base_class = script_class->get_parent_class();
  2387. if (base_class != native)
  2388. base = base_class;
  2389. #ifdef DEBUG_ENABLED
  2390. // For debug builds, we must fetch from all native base methods as well.
  2391. // Native base methods must be fetched before the current class.
  2392. // Not needed if the script class itself is a native class.
  2393. if (script_class != native) {
  2394. GDMonoClass *native_top = native;
  2395. while (native_top) {
  2396. native_top->fetch_methods_with_godot_api_checks(native);
  2397. if (native_top == CACHED_CLASS(GodotObject))
  2398. break;
  2399. native_top = native_top->get_parent_class();
  2400. }
  2401. }
  2402. #endif
  2403. script_class->fetch_methods_with_godot_api_checks(native);
  2404. // Need to fetch method from base classes as well
  2405. GDMonoClass *top = script_class;
  2406. while (top && top != native) {
  2407. top->fetch_methods_with_godot_api_checks(native);
  2408. top = top->get_parent_class();
  2409. }
  2410. load_script_signals(script_class, native);
  2411. _update_exports();
  2412. }
  2413. return OK;
  2414. }
  2415. return ERR_FILE_MISSING_DEPENDENCIES;
  2416. }
  2417. ScriptLanguage *CSharpScript::get_language() const {
  2418. return CSharpLanguage::get_singleton();
  2419. }
  2420. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  2421. #ifdef TOOLS_ENABLED
  2422. const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
  2423. if (E) {
  2424. r_value = E->get();
  2425. return true;
  2426. }
  2427. if (base_cache.is_valid()) {
  2428. return base_cache->get_property_default_value(p_property, r_value);
  2429. }
  2430. #endif
  2431. return false;
  2432. }
  2433. void CSharpScript::update_exports() {
  2434. #ifdef TOOLS_ENABLED
  2435. _update_exports();
  2436. #endif
  2437. }
  2438. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  2439. return _signals.has(p_signal);
  2440. }
  2441. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  2442. for (const Map<StringName, Vector<Argument> >::Element *E = _signals.front(); E; E = E->next()) {
  2443. MethodInfo mi;
  2444. mi.name = E->key();
  2445. for (int i = 0; i < E->get().size(); i++) {
  2446. PropertyInfo arg;
  2447. arg.name = E->get()[i].name;
  2448. mi.arguments.push_back(arg);
  2449. }
  2450. r_signals->push_back(mi);
  2451. }
  2452. }
  2453. Ref<Script> CSharpScript::get_base_script() const {
  2454. // TODO search in metadata file once we have it, not important any way?
  2455. return Ref<Script>();
  2456. }
  2457. void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  2458. for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
  2459. p_list->push_back(E->value());
  2460. }
  2461. }
  2462. int CSharpScript::get_member_line(const StringName &p_member) const {
  2463. // TODO omnisharp
  2464. return -1;
  2465. }
  2466. Error CSharpScript::load_source_code(const String &p_path) {
  2467. Error ferr = read_all_file_utf8(p_path, source);
  2468. ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
  2469. ferr == ERR_INVALID_DATA ?
  2470. "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
  2471. " Please ensure that scripts are saved in valid UTF-8 unicode." :
  2472. "Failed to read file: '" + p_path + "'.");
  2473. #ifdef TOOLS_ENABLED
  2474. source_changed_cache = true;
  2475. #endif
  2476. return OK;
  2477. }
  2478. StringName CSharpScript::get_script_name() const {
  2479. return name;
  2480. }
  2481. CSharpScript::CSharpScript() :
  2482. script_list(this) {
  2483. _clear();
  2484. #ifdef TOOLS_ENABLED
  2485. source_changed_cache = false;
  2486. placeholder_fallback_enabled = false;
  2487. exports_invalidated = true;
  2488. #endif
  2489. signals_invalidated = true;
  2490. _resource_path_changed();
  2491. #ifdef DEBUG_ENABLED
  2492. {
  2493. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2494. CSharpLanguage::get_singleton()->script_list.add(&this->script_list);
  2495. }
  2496. #endif
  2497. }
  2498. CSharpScript::~CSharpScript() {
  2499. #ifdef DEBUG_ENABLED
  2500. MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
  2501. CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
  2502. #endif
  2503. }
  2504. void CSharpScript::get_members(Set<StringName> *p_members) {
  2505. #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
  2506. if (p_members) {
  2507. for (Set<StringName>::Element *E = exported_members_names.front(); E; E = E->next()) {
  2508. p_members->insert(E->get());
  2509. }
  2510. }
  2511. #endif
  2512. }
  2513. /*************** RESOURCE ***************/
  2514. RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  2515. if (r_error)
  2516. *r_error = ERR_FILE_CANT_OPEN;
  2517. // TODO ignore anything inside bin/ and obj/ in tools builds?
  2518. CSharpScript *script = memnew(CSharpScript);
  2519. Ref<CSharpScript> scriptres(script);
  2520. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  2521. Error err = script->load_source_code(p_path);
  2522. ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load C# script file '" + p_path + "'.");
  2523. #endif
  2524. script->set_path(p_original_path);
  2525. script->reload();
  2526. if (r_error)
  2527. *r_error = OK;
  2528. return scriptres;
  2529. }
  2530. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2531. p_extensions->push_back("cs");
  2532. }
  2533. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2534. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2535. }
  2536. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2537. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  2538. }
  2539. Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  2540. Ref<CSharpScript> sqscr = p_resource;
  2541. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2542. String source = sqscr->get_source_code();
  2543. #ifdef TOOLS_ENABLED
  2544. if (!FileAccess::exists(p_path)) {
  2545. // The file does not yet exists, let's assume the user just created this script
  2546. if (_create_project_solution_if_needed()) {
  2547. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  2548. "Compile",
  2549. ProjectSettings::get_singleton()->globalize_path(p_path));
  2550. } else {
  2551. ERR_PRINTS("C# project could not be created; cannot add file: '" + p_path + "'.");
  2552. }
  2553. }
  2554. #endif
  2555. Error err;
  2556. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2557. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'.");
  2558. file->store_string(source);
  2559. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2560. memdelete(file);
  2561. return ERR_CANT_CREATE;
  2562. }
  2563. file->close();
  2564. memdelete(file);
  2565. #ifdef TOOLS_ENABLED
  2566. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2567. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2568. }
  2569. #endif
  2570. return OK;
  2571. }
  2572. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  2573. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2574. p_extensions->push_back("cs");
  2575. }
  2576. }
  2577. bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
  2578. return Object::cast_to<CSharpScript>(p_resource.ptr()) != NULL;
  2579. }
  2580. CSharpLanguage::StringNameCache::StringNameCache() {
  2581. _signal_callback = StaticCString::create("_signal_callback");
  2582. _set = StaticCString::create("_set");
  2583. _get = StaticCString::create("_get");
  2584. _get_property_list = StaticCString::create("_get_property_list");
  2585. _notification = StaticCString::create("_notification");
  2586. _script_source = StaticCString::create("script/source");
  2587. on_before_serialize = StaticCString::create("OnBeforeSerialize");
  2588. on_after_deserialize = StaticCString::create("OnAfterDeserialize");
  2589. dotctor = StaticCString::create(".ctor");
  2590. }