csharp_script.cpp 95 KB

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