csharp_script.cpp 95 KB

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