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