csharp_script.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
  1. /*************************************************************************/
  2. /* csharp_script.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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 "os/file_access.h"
  33. #include "os/os.h"
  34. #include "os/thread.h"
  35. #include "project_settings.h"
  36. #ifdef TOOLS_ENABLED
  37. #include "editor/bindings_generator.h"
  38. #include "editor/csharp_project.h"
  39. #include "editor/editor_node.h"
  40. #include "editor/godotsharp_editor.h"
  41. #include "utils/string_utils.h"
  42. #endif
  43. #include "godotsharp_dirs.h"
  44. #include "mono_gd/gd_mono_class.h"
  45. #include "mono_gd/gd_mono_marshal.h"
  46. #include "signal_awaiter_utils.h"
  47. #define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var)
  48. #ifdef TOOLS_ENABLED
  49. static bool _create_project_solution_if_needed() {
  50. String sln_path = GodotSharpDirs::get_project_sln_path();
  51. String csproj_path = GodotSharpDirs::get_project_csproj_path();
  52. if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
  53. // A solution does not yet exist, create a new one
  54. CRASH_COND(GodotSharpEditor::get_singleton() == NULL);
  55. return GodotSharpEditor::get_singleton()->call("_create_project_solution");
  56. }
  57. return true;
  58. }
  59. #endif
  60. CSharpLanguage *CSharpLanguage::singleton = NULL;
  61. String CSharpLanguage::get_name() const {
  62. return "C#";
  63. }
  64. String CSharpLanguage::get_type() const {
  65. return "CSharpScript";
  66. }
  67. String CSharpLanguage::get_extension() const {
  68. return "cs";
  69. }
  70. Error CSharpLanguage::execute_file(const String &p_path) {
  71. // ??
  72. return OK;
  73. }
  74. #ifdef TOOLS_ENABLED
  75. void gdsharp_editor_init_callback() {
  76. EditorNode *editor = EditorNode::get_singleton();
  77. editor->add_child(memnew(GodotSharpEditor(editor)));
  78. }
  79. #endif
  80. void CSharpLanguage::init() {
  81. gdmono = memnew(GDMono);
  82. gdmono->initialize();
  83. #ifdef MONO_GLUE_DISABLED
  84. WARN_PRINT("This binary is built with `mono_glue=no` and cannot be used for scripting");
  85. #endif
  86. #if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
  87. if (gdmono->get_editor_tools_assembly() != NULL) {
  88. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  89. BindingsGenerator::handle_cmdline_args(cmdline_args);
  90. }
  91. #endif
  92. #ifdef TOOLS_ENABLED
  93. EditorNode::add_init_callback(&gdsharp_editor_init_callback);
  94. GLOBAL_DEF("mono/export/include_scripts_content", true);
  95. #endif
  96. }
  97. void CSharpLanguage::finish() {
  98. finalizing = true;
  99. #ifdef TOOLS_ENABLED
  100. // Must be here, to avoid StringName leaks
  101. if (BindingsGenerator::singleton) {
  102. memdelete(BindingsGenerator::singleton);
  103. BindingsGenerator::singleton = NULL;
  104. }
  105. #endif
  106. // Release gchandle bindings before finalizing mono runtime
  107. gchandle_bindings.clear();
  108. if (gdmono) {
  109. memdelete(gdmono);
  110. gdmono = NULL;
  111. }
  112. finalizing = false;
  113. }
  114. void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
  115. static const char *_reserved_words[] = {
  116. // Reserved keywords
  117. "abstract",
  118. "as",
  119. "base",
  120. "bool",
  121. "break",
  122. "byte",
  123. "case",
  124. "catch",
  125. "char",
  126. "checked",
  127. "class",
  128. "const",
  129. "continue",
  130. "decimal",
  131. "default",
  132. "delegate",
  133. "do",
  134. "double",
  135. "else",
  136. "enum",
  137. "event",
  138. "explicit",
  139. "extern",
  140. "false",
  141. "finally",
  142. "fixed",
  143. "float",
  144. "for",
  145. "foreach",
  146. "goto",
  147. "if",
  148. "implicit",
  149. "in",
  150. "int",
  151. "interface",
  152. "internal",
  153. "is",
  154. "lock",
  155. "long",
  156. "namespace",
  157. "new",
  158. "null",
  159. "object",
  160. "operator",
  161. "out",
  162. "override",
  163. "params",
  164. "private",
  165. "protected",
  166. "public",
  167. "readonly",
  168. "ref",
  169. "return",
  170. "sbyte",
  171. "sealed",
  172. "short",
  173. "sizeof",
  174. "stackalloc",
  175. "static",
  176. "string",
  177. "struct",
  178. "switch",
  179. "this",
  180. "throw",
  181. "true",
  182. "try",
  183. "typeof",
  184. "uint",
  185. "ulong",
  186. "unchecked",
  187. "unsafe",
  188. "ushort",
  189. "using",
  190. "virtual",
  191. "void",
  192. "volatile",
  193. "while",
  194. // Contextual keywords. Not reserved words, but I guess we should include
  195. // them because this seems to be used only for syntax highlighting.
  196. "add",
  197. "alias",
  198. "ascending",
  199. "async",
  200. "await",
  201. "by",
  202. "descending",
  203. "dynamic",
  204. "equals",
  205. "from",
  206. "get",
  207. "global",
  208. "group",
  209. "into",
  210. "join",
  211. "let",
  212. "nameof",
  213. "on",
  214. "orderby",
  215. "partial",
  216. "remove",
  217. "select",
  218. "set",
  219. "value",
  220. "var",
  221. "when",
  222. "where",
  223. "yield",
  224. 0
  225. };
  226. const char **w = _reserved_words;
  227. while (*w) {
  228. p_words->push_back(*w);
  229. w++;
  230. }
  231. }
  232. void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  233. p_delimiters->push_back("//"); // single-line comment
  234. p_delimiters->push_back("/* */"); // delimited comment
  235. }
  236. void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  237. p_delimiters->push_back("' '"); // character literal
  238. p_delimiters->push_back("\" \""); // regular string literal
  239. p_delimiters->push_back("@\" \""); // verbatim string literal
  240. }
  241. Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
  242. String script_template = "using " BINDINGS_NAMESPACE ";\n"
  243. "using System;\n"
  244. "\n"
  245. "public class %CLASS_NAME% : %BASE_CLASS_NAME%\n"
  246. "{\n"
  247. " // Member variables here, example:\n"
  248. " // private int a = 2;\n"
  249. " // private string b = \"textvar\";\n"
  250. "\n"
  251. " public override void _Ready()\n"
  252. " {\n"
  253. " // Called every time the node is added to the scene.\n"
  254. " // Initialization here\n"
  255. " \n"
  256. " }\n"
  257. "\n"
  258. "// public override void _Process(float delta)\n"
  259. "// {\n"
  260. "// // Called every frame. Delta is time since last frame.\n"
  261. "// // Update game logic here.\n"
  262. "// \n"
  263. "// }\n"
  264. "}\n";
  265. script_template = script_template.replace("%BASE_CLASS_NAME%", p_base_class_name)
  266. .replace("%CLASS_NAME%", p_class_name);
  267. Ref<CSharpScript> script;
  268. script.instance();
  269. script->set_source_code(script_template);
  270. script->set_name(p_class_name);
  271. return script;
  272. }
  273. bool CSharpLanguage::is_using_templates() {
  274. return true;
  275. }
  276. void CSharpLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
  277. String src = p_script->get_source_code();
  278. src = src.replace("%BASE%", p_base_class_name)
  279. .replace("%CLASS%", p_class_name)
  280. .replace("%TS%", _get_indentation());
  281. p_script->set_source_code(src);
  282. }
  283. Script *CSharpLanguage::create_script() const {
  284. return memnew(CSharpScript);
  285. }
  286. bool CSharpLanguage::has_named_classes() const {
  287. return false;
  288. }
  289. bool CSharpLanguage::supports_builtin_mode() const {
  290. return false;
  291. }
  292. static String variant_type_to_managed_name(const String &p_var_type_name) {
  293. if (p_var_type_name.empty())
  294. return "object";
  295. if (!ClassDB::class_exists(p_var_type_name)) {
  296. Variant::Type var_types[] = {
  297. Variant::BOOL,
  298. Variant::INT,
  299. Variant::REAL,
  300. Variant::STRING,
  301. Variant::VECTOR2,
  302. Variant::RECT2,
  303. Variant::VECTOR3,
  304. Variant::TRANSFORM2D,
  305. Variant::PLANE,
  306. Variant::QUAT,
  307. Variant::AABB,
  308. Variant::BASIS,
  309. Variant::TRANSFORM,
  310. Variant::COLOR,
  311. Variant::NODE_PATH,
  312. Variant::_RID
  313. };
  314. for (int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) {
  315. if (p_var_type_name == Variant::get_type_name(var_types[i]))
  316. return p_var_type_name;
  317. }
  318. if (p_var_type_name == "String")
  319. return "string"; // I prefer this one >:[
  320. // TODO these will be rewritten later into custom containers
  321. if (p_var_type_name == "Array")
  322. return "object[]";
  323. if (p_var_type_name == "Dictionary")
  324. return "Dictionary<object, object>";
  325. if (p_var_type_name == "PoolByteArray")
  326. return "byte[]";
  327. if (p_var_type_name == "PoolIntArray")
  328. return "int[]";
  329. if (p_var_type_name == "PoolRealArray")
  330. return "float[]";
  331. if (p_var_type_name == "PoolStringArray")
  332. return "string[]";
  333. if (p_var_type_name == "PoolVector2Array")
  334. return "Vector2[]";
  335. if (p_var_type_name == "PoolVector3Array")
  336. return "Vector3[]";
  337. if (p_var_type_name == "PoolColorArray")
  338. return "Color[]";
  339. return "object";
  340. }
  341. return p_var_type_name;
  342. }
  343. String CSharpLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const {
  344. #ifdef TOOLS_ENABLED
  345. // FIXME
  346. // - Due to Godot's API limitation this just appends the function to the end of the file
  347. // - Use fully qualified name if there is ambiguity
  348. String s = "private void " + p_name + "(";
  349. for (int i = 0; i < p_args.size(); i++) {
  350. const String &arg = p_args[i];
  351. if (i > 0)
  352. s += ", ";
  353. s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
  354. }
  355. s += ")\n{\n // Replace with function body\n}\n";
  356. return s;
  357. #else
  358. return String();
  359. #endif
  360. }
  361. String CSharpLanguage::_get_indentation() const {
  362. #ifdef TOOLS_ENABLED
  363. if (Engine::get_singleton()->is_editor_hint()) {
  364. bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", 0);
  365. if (use_space_indentation) {
  366. int indent_size = EDITOR_DEF("text_editor/indent/size", 4);
  367. String space_indent = "";
  368. for (int i = 0; i < indent_size; i++) {
  369. space_indent += " ";
  370. }
  371. return space_indent;
  372. }
  373. }
  374. #endif
  375. return "\t";
  376. }
  377. Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
  378. #ifdef DEBUG_ENABLED
  379. // Printing an error here will result in endless recursion, so we must be careful
  380. if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_api_assembly() || !GDMonoUtils::mono_cache.corlib_cache_updated)
  381. return Vector<StackInfo>();
  382. MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr());
  383. MonoBoolean need_file_info = true;
  384. void *ctor_args[1] = { &need_file_info };
  385. CACHED_METHOD(System_Diagnostics_StackTrace, ctor_bool)->invoke_raw(stack_trace, ctor_args);
  386. Vector<StackInfo> si;
  387. si = stack_trace_get_info(stack_trace);
  388. return si;
  389. #else
  390. return Vector<StackInfo>();
  391. #endif
  392. }
  393. #ifdef DEBUG_ENABLED
  394. Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObject *p_stack_trace) {
  395. // Printing an error here could result in endless recursion, so we must be careful
  396. MonoObject *exc = NULL;
  397. GDMonoUtils::StackTrace_GetFrames st_get_frames = CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames);
  398. MonoArray *frames = st_get_frames(p_stack_trace, &exc);
  399. if (exc) {
  400. GDMonoUtils::print_unhandled_exception(exc, true /* fail silently to avoid endless recursion */);
  401. return Vector<StackInfo>();
  402. }
  403. int frame_count = mono_array_length(frames);
  404. if (frame_count <= 0)
  405. return Vector<StackInfo>();
  406. GDMonoUtils::DebugUtils_StackFrameInfo get_sf_info = CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo);
  407. Vector<StackInfo> si;
  408. si.resize(frame_count);
  409. for (int i = 0; i < frame_count; i++) {
  410. StackInfo &sif = si[i];
  411. MonoObject *frame = mono_array_get(frames, MonoObject *, i);
  412. MonoString *file_name;
  413. int file_line_num;
  414. MonoString *method_decl;
  415. get_sf_info(frame, &file_name, &file_line_num, &method_decl, &exc);
  416. if (exc) {
  417. GDMonoUtils::print_unhandled_exception(exc, true /* fail silently to avoid endless recursion */);
  418. return Vector<StackInfo>();
  419. }
  420. // TODO
  421. // what if the StackFrame method is null (method_decl is empty). should we skip this frame?
  422. // can reproduce with a MissingMethodException on internal calls
  423. sif.file = GDMonoMarshal::mono_string_to_godot(file_name);
  424. sif.line = file_line_num;
  425. sif.func = GDMonoMarshal::mono_string_to_godot(method_decl);
  426. }
  427. return si;
  428. }
  429. #endif
  430. void CSharpLanguage::frame() {
  431. const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoUtils::mono_cache.task_scheduler_handle;
  432. if (task_scheduler_handle.is_valid()) {
  433. MonoObject *task_scheduler = task_scheduler_handle->get_target();
  434. if (task_scheduler) {
  435. GDMonoUtils::GodotTaskScheduler_Activate thunk = CACHED_METHOD_THUNK(GodotTaskScheduler, Activate);
  436. ERR_FAIL_NULL(thunk);
  437. MonoObject *ex;
  438. thunk(task_scheduler, &ex);
  439. if (ex) {
  440. mono_print_unhandled_exception(ex);
  441. ERR_FAIL();
  442. }
  443. }
  444. }
  445. }
  446. struct CSharpScriptDepSort {
  447. // must support sorting so inheritance works properly (parent must be reloaded first)
  448. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  449. if (A == B)
  450. return false; // shouldn't happen but..
  451. GDMonoClass *I = B->base;
  452. while (I) {
  453. if (I == A->script_class) {
  454. // A is a base of B
  455. return true;
  456. }
  457. I = I->get_parent_class();
  458. }
  459. return false; // not a base
  460. }
  461. };
  462. void CSharpLanguage::reload_all_scripts() {
  463. #ifdef DEBUG_ENABLED
  464. #ifndef NO_THREADS
  465. lock->lock();
  466. #endif
  467. List<Ref<CSharpScript> > scripts;
  468. SelfList<CSharpScript> *elem = script_list.first();
  469. while (elem) {
  470. if (elem->self()->get_path().is_resource_file()) {
  471. scripts.push_back(Ref<CSharpScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  472. }
  473. elem = elem->next();
  474. }
  475. #ifndef NO_THREADS
  476. lock->unlock();
  477. #endif
  478. //as scripts are going to be reloaded, must proceed without locking here
  479. scripts.sort_custom<CSharpScriptDepSort>(); //update in inheritance dependency order
  480. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  481. E->get()->load_source_code(E->get()->get_path());
  482. E->get()->reload(true);
  483. }
  484. #endif
  485. }
  486. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  487. (void)p_script; // UNUSED
  488. #ifdef TOOLS_ENABLED
  489. MonoReloadNode::get_singleton()->restart_reload_timer();
  490. reload_assemblies_if_needed(p_soft_reload);
  491. #endif
  492. }
  493. #ifdef TOOLS_ENABLED
  494. void CSharpLanguage::reload_assemblies_if_needed(bool p_soft_reload) {
  495. if (gdmono->is_runtime_initialized()) {
  496. GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
  497. String name = ProjectSettings::get_singleton()->get("application/config/name");
  498. if (name.empty()) {
  499. name = "UnnamedProject";
  500. }
  501. if (proj_assembly) {
  502. String proj_asm_path = proj_assembly->get_path();
  503. if (!FileAccess::exists(proj_assembly->get_path())) {
  504. // Maybe it wasn't loaded from the default path, so check this as well
  505. proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name);
  506. if (!FileAccess::exists(proj_asm_path))
  507. return; // No assembly to load
  508. }
  509. if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
  510. return; // Already up to date
  511. } else {
  512. if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name)))
  513. return; // No assembly to load
  514. }
  515. }
  516. #ifndef NO_THREADS
  517. lock->lock();
  518. #endif
  519. List<Ref<CSharpScript> > scripts;
  520. SelfList<CSharpScript> *elem = script_list.first();
  521. while (elem) {
  522. if (elem->self()->get_path().is_resource_file()) {
  523. scripts.push_back(Ref<CSharpScript>(elem->self())); //cast to CSharpScript to avoid being erased by accident
  524. }
  525. elem = elem->next();
  526. }
  527. #ifndef NO_THREADS
  528. lock->unlock();
  529. #endif
  530. //when someone asks you why dynamically typed languages are easier to write....
  531. Map<Ref<CSharpScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload;
  532. //as scripts are going to be reloaded, must proceed without locking here
  533. scripts.sort_custom<CSharpScriptDepSort>(); //update in inheritance dependency order
  534. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  535. to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >());
  536. if (!p_soft_reload) {
  537. //save state and remove script from instances
  538. Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()];
  539. while (E->get()->instances.front()) {
  540. Object *obj = E->get()->instances.front()->get();
  541. //save instance info
  542. List<Pair<StringName, Variant> > state;
  543. if (obj->get_script_instance()) {
  544. obj->get_script_instance()->get_property_state(state);
  545. Ref<MonoGCHandle> gchandle = CAST_CSHARP_INSTANCE(obj->get_script_instance())->gchandle;
  546. if (gchandle.is_valid())
  547. gchandle->release();
  548. map[obj->get_instance_id()] = state;
  549. obj->set_script(RefPtr());
  550. }
  551. }
  552. //same thing for placeholders
  553. while (E->get()->placeholders.size()) {
  554. Object *obj = E->get()->placeholders.front()->get()->get_owner();
  555. //save instance info
  556. List<Pair<StringName, Variant> > state;
  557. if (obj->get_script_instance()) {
  558. obj->get_script_instance()->get_property_state(state);
  559. map[obj->get_instance_id()] = state;
  560. obj->set_script(RefPtr());
  561. }
  562. }
  563. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) {
  564. map[F->key()] = F->get(); //pending to reload, use this one instead
  565. }
  566. E->get()->_clear();
  567. }
  568. }
  569. if (gdmono->reload_scripts_domain() != OK)
  570. return;
  571. for (Map<Ref<CSharpScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) {
  572. Ref<CSharpScript> scr = E->key();
  573. scr->signals_invalidated = true;
  574. scr->exports_invalidated = true;
  575. scr->reload(p_soft_reload);
  576. scr->update_signals();
  577. scr->update_exports();
  578. //restore state if saved
  579. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
  580. Object *obj = ObjectDB::get_instance(F->key());
  581. if (!obj)
  582. continue;
  583. if (!p_soft_reload) {
  584. //clear it just in case (may be a pending reload state)
  585. obj->set_script(RefPtr());
  586. }
  587. obj->set_script(scr.get_ref_ptr());
  588. if (!obj->get_script_instance()) {
  589. //failed, save reload state for next time if not saved
  590. if (!scr->pending_reload_state.has(obj->get_instance_id())) {
  591. scr->pending_reload_state[obj->get_instance_id()] = F->get();
  592. }
  593. continue;
  594. }
  595. for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) {
  596. obj->get_script_instance()->set(G->get().first, G->get().second);
  597. }
  598. scr->pending_reload_state.erase(obj->get_instance_id()); //as it reloaded, remove pending state
  599. }
  600. //if instance states were saved, set them!
  601. }
  602. if (Engine::get_singleton()->is_editor_hint()) {
  603. EditorNode::get_singleton()->get_property_editor()->update_tree();
  604. NodeDock::singleton->update_lists();
  605. }
  606. }
  607. #endif
  608. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  609. p_extensions->push_back("cs");
  610. }
  611. #ifdef TOOLS_ENABLED
  612. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  613. return GodotSharpEditor::get_singleton()->open_in_external_editor(p_script, p_line, p_col);
  614. }
  615. bool CSharpLanguage::overrides_external_editor() {
  616. return GodotSharpEditor::get_singleton()->overrides_external_editor();
  617. }
  618. #endif
  619. void CSharpLanguage::thread_enter() {
  620. #if 0
  621. if (mono->is_runtime_initialized()) {
  622. GDMonoUtils::attach_current_thread();
  623. }
  624. #endif
  625. }
  626. void CSharpLanguage::thread_exit() {
  627. #if 0
  628. if (mono->is_runtime_initialized()) {
  629. GDMonoUtils::detach_current_thread();
  630. }
  631. #endif
  632. }
  633. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  634. // Break because of parse error
  635. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  636. // TODO
  637. //_debug_parse_err_line = p_line;
  638. //_debug_parse_err_file = p_file;
  639. //_debug_error = p_error;
  640. ScriptDebugger::get_singleton()->debug(this, false);
  641. return true;
  642. } else {
  643. return false;
  644. }
  645. }
  646. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  647. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  648. // TODO
  649. //_debug_parse_err_line = -1;
  650. //_debug_parse_err_file = "";
  651. //_debug_error = p_error;
  652. ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
  653. return true;
  654. } else {
  655. return false;
  656. }
  657. }
  658. void CSharpLanguage::set_language_index(int p_idx) {
  659. ERR_FAIL_COND(lang_idx != -1);
  660. lang_idx = p_idx;
  661. }
  662. CSharpLanguage::CSharpLanguage() {
  663. ERR_FAIL_COND(singleton);
  664. singleton = this;
  665. finalizing = false;
  666. gdmono = NULL;
  667. #ifdef NO_THREADS
  668. lock = NULL;
  669. gchandle_bind_lock = NULL;
  670. #else
  671. lock = Mutex::create();
  672. script_bind_lock = Mutex::create();
  673. #endif
  674. lang_idx = -1;
  675. }
  676. CSharpLanguage::~CSharpLanguage() {
  677. finish();
  678. if (lock) {
  679. memdelete(lock);
  680. lock = NULL;
  681. }
  682. if (script_bind_lock) {
  683. memdelete(script_bind_lock);
  684. script_bind_lock = NULL;
  685. }
  686. singleton = NULL;
  687. }
  688. void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
  689. #ifdef DEBUG_ENABLED
  690. // I don't trust you
  691. if (p_object->get_script_instance())
  692. CRASH_COND(NULL != CAST_CSHARP_INSTANCE(p_object->get_script_instance()));
  693. #endif
  694. StringName type_name = p_object->get_class_name();
  695. // ¯\_(ツ)_/¯
  696. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  697. while (classinfo && !classinfo->exposed)
  698. classinfo = classinfo->inherits_ptr;
  699. ERR_FAIL_NULL_V(classinfo, NULL);
  700. type_name = classinfo->name;
  701. GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);
  702. ERR_FAIL_NULL_V(type_class, NULL);
  703. MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);
  704. ERR_FAIL_NULL_V(mono_object, NULL);
  705. // Tie managed to unmanaged
  706. Reference *ref = Object::cast_to<Reference>(p_object);
  707. if (ref) {
  708. // Unsafe refcount increment. The managed instance also counts as a reference.
  709. // This way if the unmanaged world has no references to our owner
  710. // but the managed instance is alive, the refcount will be 1 instead of 0.
  711. // See: _GodotSharp::_dispose_object(Object *p_object)
  712. ref->reference();
  713. }
  714. Ref<MonoGCHandle> gchandle = MonoGCHandle::create_strong(mono_object);
  715. #ifndef NO_THREADS
  716. script_bind_lock->lock();
  717. #endif
  718. void *data = (void *)gchandle_bindings.insert(p_object, gchandle);
  719. #ifndef NO_THREADS
  720. script_bind_lock->unlock();
  721. #endif
  722. return data;
  723. }
  724. void CSharpLanguage::free_instance_binding_data(void *p_data) {
  725. if (GDMono::get_singleton() == NULL) {
  726. #ifdef DEBUG_ENABLED
  727. CRASH_COND(!gchandle_bindings.empty());
  728. #endif
  729. // Mono runtime finalized, all the gchandle bindings were already released
  730. return;
  731. }
  732. if (finalizing)
  733. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  734. #ifndef NO_THREADS
  735. script_bind_lock->lock();
  736. #endif
  737. Map<Object *, Ref<MonoGCHandle> >::Element *data = (Map<Object *, Ref<MonoGCHandle> >::Element *)p_data;
  738. // Set the native instance field to IntPtr.Zero, if not yet garbage collected
  739. MonoObject *mono_object = data->value()->get_target();
  740. if (mono_object) {
  741. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  742. }
  743. gchandle_bindings.erase(data);
  744. #ifndef NO_THREADS
  745. script_bind_lock->unlock();
  746. #endif
  747. }
  748. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle) {
  749. CSharpInstance *instance = memnew(CSharpInstance);
  750. Reference *ref = Object::cast_to<Reference>(p_owner);
  751. instance->base_ref = ref != NULL;
  752. instance->script = Ref<CSharpScript>(p_script);
  753. instance->owner = p_owner;
  754. instance->gchandle = p_gchandle;
  755. if (instance->base_ref)
  756. instance->_reference_owner_unsafe();
  757. p_script->instances.insert(p_owner);
  758. return instance;
  759. }
  760. MonoObject *CSharpInstance::get_mono_object() const {
  761. #ifdef DEBUG_ENABLED
  762. CRASH_COND(gchandle.is_null());
  763. #endif
  764. return gchandle->get_target();
  765. }
  766. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  767. ERR_FAIL_COND_V(!script.is_valid(), false);
  768. MonoObject *mono_object = get_mono_object();
  769. ERR_FAIL_NULL_V(mono_object, false);
  770. GDMonoClass *top = script->script_class;
  771. while (top && top != script->native) {
  772. GDMonoField *field = script->script_class->get_field(p_name);
  773. if (field) {
  774. field->set_value_from_variant(mono_object, p_value);
  775. return true;
  776. }
  777. GDMonoProperty *property = script->script_class->get_property(p_name);
  778. if (property) {
  779. property->set_value(mono_object, GDMonoMarshal::variant_to_mono_object(p_value));
  780. return true;
  781. }
  782. top = top->get_parent_class();
  783. }
  784. // Call _set
  785. top = script->script_class;
  786. while (top && top != script->native) {
  787. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);
  788. if (method) {
  789. Variant name = p_name;
  790. const Variant *args[2] = { &name, &p_value };
  791. MonoObject *ret = method->invoke(mono_object, args);
  792. if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret) == true)
  793. return true;
  794. break;
  795. }
  796. top = top->get_parent_class();
  797. }
  798. return false;
  799. }
  800. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  801. ERR_FAIL_COND_V(!script.is_valid(), false);
  802. MonoObject *mono_object = get_mono_object();
  803. ERR_FAIL_NULL_V(mono_object, false);
  804. GDMonoClass *top = script->script_class;
  805. while (top && top != script->native) {
  806. GDMonoField *field = top->get_field(p_name);
  807. if (field) {
  808. MonoObject *value = field->get_value(mono_object);
  809. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  810. return true;
  811. }
  812. GDMonoProperty *property = top->get_property(p_name);
  813. if (property) {
  814. MonoObject *exc = NULL;
  815. MonoObject *value = property->get_value(mono_object, &exc);
  816. if (exc) {
  817. r_ret = Variant();
  818. GDMonoUtils::print_unhandled_exception(exc);
  819. } else {
  820. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  821. }
  822. return true;
  823. }
  824. top = top->get_parent_class();
  825. }
  826. // Call _get
  827. top = script->script_class;
  828. while (top && top != script->native) {
  829. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);
  830. if (method) {
  831. Variant name = p_name;
  832. const Variant *args[1] = { &name };
  833. MonoObject *ret = method->invoke(mono_object, args);
  834. if (ret) {
  835. r_ret = GDMonoMarshal::mono_object_to_variant(ret);
  836. return true;
  837. }
  838. break;
  839. }
  840. top = top->get_parent_class();
  841. }
  842. return false;
  843. }
  844. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  845. for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
  846. p_properties->push_back(E->value());
  847. }
  848. }
  849. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  850. if (script->member_info.has(p_name)) {
  851. if (r_is_valid)
  852. *r_is_valid = true;
  853. return script->member_info[p_name].type;
  854. }
  855. if (r_is_valid)
  856. *r_is_valid = false;
  857. return Variant::NIL;
  858. }
  859. bool CSharpInstance::has_method(const StringName &p_method) const {
  860. if (!script.is_valid())
  861. return false;
  862. GDMonoClass *top = script->script_class;
  863. while (top && top != script->native) {
  864. if (top->has_fetched_method_unknown_params(p_method)) {
  865. return true;
  866. }
  867. top = top->get_parent_class();
  868. }
  869. return false;
  870. }
  871. Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  872. MonoObject *mono_object = get_mono_object();
  873. if (!mono_object) {
  874. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  875. ERR_FAIL_V(Variant());
  876. }
  877. if (!script.is_valid())
  878. ERR_FAIL_V(Variant());
  879. GDMonoClass *top = script->script_class;
  880. while (top && top != script->native) {
  881. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  882. if (method) {
  883. MonoObject *return_value = method->invoke(mono_object, p_args);
  884. r_error.error = Variant::CallError::CALL_OK;
  885. if (return_value) {
  886. return GDMonoMarshal::mono_object_to_variant(return_value);
  887. } else {
  888. return Variant();
  889. }
  890. }
  891. top = top->get_parent_class();
  892. }
  893. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  894. return Variant();
  895. }
  896. void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  897. if (script.is_valid()) {
  898. MonoObject *mono_object = get_mono_object();
  899. ERR_FAIL_NULL(mono_object);
  900. _call_multilevel(mono_object, p_method, p_args, p_argcount);
  901. }
  902. }
  903. void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
  904. GDMonoClass *top = script->script_class;
  905. while (top && top != script->native) {
  906. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  907. if (method) {
  908. method->invoke(p_mono_object, p_args);
  909. return;
  910. }
  911. top = top->get_parent_class();
  912. }
  913. }
  914. void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  915. // Sorry, the method is the one that controls the call order
  916. call_multilevel(p_method, p_args, p_argcount);
  917. }
  918. void CSharpInstance::_reference_owner_unsafe() {
  919. #ifdef DEBUG_ENABLED
  920. CRASH_COND(!base_ref);
  921. #endif
  922. // Unsafe refcount increment. The managed instance also counts as a reference.
  923. // This way if the unmanaged world has no references to our owner
  924. // but the managed instance is alive, the refcount will be 1 instead of 0.
  925. // See: _unreference_owner_unsafe()
  926. // May not me referenced yet, so we must use init_ref() instead of reference()
  927. Object::cast_to<Reference>(owner)->init_ref();
  928. }
  929. void CSharpInstance::_unreference_owner_unsafe() {
  930. #ifdef DEBUG_ENABLED
  931. CRASH_COND(!base_ref);
  932. #endif
  933. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  934. // Unsafe refcount decrement. The managed instance also counts as a reference.
  935. // See: _reference_owner_unsafe()
  936. if (Object::cast_to<Reference>(owner)->unreference()) {
  937. memdelete(owner);
  938. owner = NULL;
  939. }
  940. }
  941. void CSharpInstance::mono_object_disposed() {
  942. if (base_ref)
  943. _unreference_owner_unsafe();
  944. }
  945. void CSharpInstance::refcount_incremented() {
  946. CRASH_COND(!base_ref);
  947. Reference *ref_owner = Object::cast_to<Reference>(owner);
  948. if (ref_owner->reference_get_count() > 1) { // The managed side also holds a reference, hence 1 instead of 0
  949. // The reference count was increased after the managed side was the only one referencing our owner.
  950. // This means the owner is being referenced again by the unmanaged side,
  951. // so the owner must hold the managed side alive again to avoid it from being GCed.
  952. // Release the current weak handle and replace it with a strong handle.
  953. uint32_t strong_gchandle = MonoGCHandle::make_strong_handle(gchandle->get_target());
  954. gchandle->release();
  955. gchandle->set_handle(strong_gchandle);
  956. }
  957. }
  958. bool CSharpInstance::refcount_decremented() {
  959. CRASH_COND(!base_ref);
  960. Reference *ref_owner = Object::cast_to<Reference>(owner);
  961. int refcount = ref_owner->reference_get_count();
  962. if (refcount == 1) { // The managed side also holds a reference, hence 1 instead of 0
  963. // If owner owner is no longer referenced by the unmanaged side,
  964. // the managed instance takes responsibility of deleting the owner when GCed.
  965. // Release the current strong handle and replace it with a weak handle.
  966. uint32_t weak_gchandle = MonoGCHandle::make_weak_handle(gchandle->get_target());
  967. gchandle->release();
  968. gchandle->set_handle(weak_gchandle);
  969. return false;
  970. }
  971. ref_dying = (refcount == 0);
  972. return ref_dying;
  973. }
  974. ScriptInstance::RPCMode CSharpInstance::_member_get_rpc_mode(GDMonoClassMember *p_member) const {
  975. if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
  976. return RPC_MODE_REMOTE;
  977. if (p_member->has_attribute(CACHED_CLASS(SyncAttribute)))
  978. return RPC_MODE_SYNC;
  979. if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
  980. return RPC_MODE_MASTER;
  981. if (p_member->has_attribute(CACHED_CLASS(SlaveAttribute)))
  982. return RPC_MODE_SLAVE;
  983. return RPC_MODE_DISABLED;
  984. }
  985. ScriptInstance::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const {
  986. GDMonoClass *top = script->script_class;
  987. while (top && top != script->native) {
  988. GDMonoMethod *method = top->get_fetched_method_unknown_params(p_method);
  989. if (method && !method->is_static())
  990. return _member_get_rpc_mode(method);
  991. top = top->get_parent_class();
  992. }
  993. return RPC_MODE_DISABLED;
  994. }
  995. ScriptInstance::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const {
  996. GDMonoClass *top = script->script_class;
  997. while (top && top != script->native) {
  998. GDMonoField *field = top->get_field(p_variable);
  999. if (field && !field->is_static())
  1000. return _member_get_rpc_mode(field);
  1001. GDMonoProperty *property = top->get_property(p_variable);
  1002. if (property && !property->is_static())
  1003. return _member_get_rpc_mode(property);
  1004. top = top->get_parent_class();
  1005. }
  1006. return RPC_MODE_DISABLED;
  1007. }
  1008. void CSharpInstance::notification(int p_notification) {
  1009. MonoObject *mono_object = get_mono_object();
  1010. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1011. if (mono_object != NULL) { // otherwise it was collected, and the finalizer already called NOTIFICATION_PREDELETE
  1012. call_notification_no_check(mono_object, p_notification);
  1013. // Set the native instance field to IntPtr.Zero
  1014. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  1015. }
  1016. return;
  1017. }
  1018. call_notification_no_check(mono_object, p_notification);
  1019. }
  1020. void CSharpInstance::call_notification_no_check(MonoObject *p_mono_object, int p_notification) {
  1021. Variant value = p_notification;
  1022. const Variant *args[1] = { &value };
  1023. _call_multilevel(p_mono_object, CACHED_STRING_NAME(_notification), args, 1);
  1024. }
  1025. Ref<Script> CSharpInstance::get_script() const {
  1026. return script;
  1027. }
  1028. ScriptLanguage *CSharpInstance::get_language() {
  1029. return CSharpLanguage::get_singleton();
  1030. }
  1031. CSharpInstance::CSharpInstance() {
  1032. owner = NULL;
  1033. base_ref = false;
  1034. ref_dying = false;
  1035. }
  1036. CSharpInstance::~CSharpInstance() {
  1037. if (gchandle.is_valid()) {
  1038. gchandle->release(); // Make sure it's released
  1039. }
  1040. if (base_ref && !ref_dying) { // it may be called from the owner's destructor
  1041. #ifdef DEBUG_ENABLED
  1042. CRASH_COND(!owner); // dunno, just in case
  1043. #endif
  1044. _unreference_owner_unsafe();
  1045. }
  1046. if (script.is_valid() && owner) {
  1047. #ifndef NO_THREADS
  1048. CSharpLanguage::singleton->lock->lock();
  1049. #endif
  1050. #ifdef DEBUG_ENABLED
  1051. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1052. Set<Object *>::Element *match = script->instances.find(owner);
  1053. CRASH_COND(!match);
  1054. script->instances.erase(match);
  1055. #else
  1056. script->instances.erase(owner);
  1057. #endif
  1058. #ifndef NO_THREADS
  1059. CSharpLanguage::singleton->lock->unlock();
  1060. #endif
  1061. }
  1062. }
  1063. #ifdef TOOLS_ENABLED
  1064. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1065. placeholders.erase(p_placeholder);
  1066. }
  1067. #endif
  1068. #ifdef TOOLS_ENABLED
  1069. void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1070. if (base_cache.is_valid()) {
  1071. base_cache->_update_exports_values(values, propnames);
  1072. }
  1073. for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) {
  1074. values[E->key()] = E->get();
  1075. }
  1076. for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) {
  1077. propnames.push_back(E->get());
  1078. }
  1079. }
  1080. #endif
  1081. bool CSharpScript::_update_exports() {
  1082. #ifdef TOOLS_ENABLED
  1083. if (!valid)
  1084. return false;
  1085. bool changed = false;
  1086. if (exports_invalidated) {
  1087. exports_invalidated = false;
  1088. changed = true;
  1089. member_info.clear();
  1090. exported_members_cache.clear();
  1091. exported_members_defval_cache.clear();
  1092. // We are creating a temporary new instance of the class here to get the default value
  1093. // TODO Workaround. Should be replaced with IL opcodes analysis
  1094. MonoObject *tmp_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
  1095. if (tmp_object) {
  1096. CACHED_FIELD(GodotObject, ptr)->set_value_raw(tmp_object, tmp_object); // FIXME WTF is this workaround
  1097. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1098. MonoObject *ex = NULL;
  1099. ctor->invoke(tmp_object, NULL, &ex);
  1100. if (ex) {
  1101. ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
  1102. mono_print_unhandled_exception(ex);
  1103. tmp_object = NULL;
  1104. ERR_FAIL_V(false);
  1105. }
  1106. } else {
  1107. ERR_PRINT("Failed to create temporary MonoObject");
  1108. return false;
  1109. }
  1110. GDMonoClass *top = script_class;
  1111. while (top && top != native) {
  1112. PropertyInfo prop_info;
  1113. bool exported;
  1114. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1115. for (int i = fields.size() - 1; i >= 0; i--) {
  1116. GDMonoField *field = fields[i];
  1117. if (_get_member_export(top, field, prop_info, exported)) {
  1118. StringName name = field->get_name();
  1119. if (exported) {
  1120. member_info[name] = prop_info;
  1121. exported_members_cache.push_front(prop_info);
  1122. if (tmp_object) {
  1123. exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
  1124. }
  1125. } else {
  1126. member_info[name] = prop_info;
  1127. }
  1128. }
  1129. }
  1130. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1131. for (int i = properties.size() - 1; i >= 0; i--) {
  1132. GDMonoProperty *property = properties[i];
  1133. if (_get_member_export(top, property, prop_info, exported)) {
  1134. StringName name = property->get_name();
  1135. if (exported) {
  1136. member_info[name] = prop_info;
  1137. exported_members_cache.push_front(prop_info);
  1138. if (tmp_object) {
  1139. MonoObject *exc = NULL;
  1140. MonoObject *ret = property->get_value(tmp_object, &exc);
  1141. if (exc) {
  1142. exported_members_defval_cache[name] = Variant();
  1143. GDMonoUtils::print_unhandled_exception(exc);
  1144. } else {
  1145. exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(ret);
  1146. }
  1147. }
  1148. } else {
  1149. member_info[name] = prop_info;
  1150. }
  1151. }
  1152. }
  1153. top = top->get_parent_class();
  1154. }
  1155. }
  1156. if (placeholders.size()) {
  1157. // Update placeholders if any
  1158. Map<StringName, Variant> values;
  1159. List<PropertyInfo> propnames;
  1160. _update_exports_values(values, propnames);
  1161. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  1162. E->get()->update(propnames, values);
  1163. }
  1164. }
  1165. return changed;
  1166. #endif
  1167. return false;
  1168. }
  1169. bool CSharpScript::_update_signals() {
  1170. if (!valid)
  1171. return false;
  1172. bool changed = false;
  1173. if (signals_invalidated) {
  1174. signals_invalidated = false;
  1175. GDMonoClass *top = script_class;
  1176. _signals.clear();
  1177. changed = true; // TODO Do a real check for change
  1178. while (top && top != native) {
  1179. const Vector<GDMonoClass *> &delegates = top->get_all_delegates();
  1180. for (int i = delegates.size() - 1; i >= 0; --i) {
  1181. Vector<Argument> parameters;
  1182. GDMonoClass *delegate = delegates[i];
  1183. if (_get_signal(top, delegate, parameters)) {
  1184. _signals[delegate->get_name()] = parameters;
  1185. }
  1186. }
  1187. top = top->get_parent_class();
  1188. }
  1189. }
  1190. return changed;
  1191. }
  1192. bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Vector<Argument> &params) {
  1193. if (p_delegate->has_attribute(CACHED_CLASS(SignalAttribute))) {
  1194. MonoType *raw_type = GDMonoClass::get_raw_type(p_delegate);
  1195. if (mono_type_get_type(raw_type) == MONO_TYPE_CLASS) {
  1196. // Arguments are accessibles as arguments of .Invoke method
  1197. GDMonoMethod *invoke = p_delegate->get_method("Invoke", -1);
  1198. Vector<StringName> names;
  1199. Vector<ManagedType> types;
  1200. invoke->get_parameter_names(names);
  1201. invoke->get_parameter_types(types);
  1202. if (names.size() == types.size()) {
  1203. for (int i = 0; i < names.size(); ++i) {
  1204. Argument arg;
  1205. arg.name = names[i];
  1206. arg.type = GDMonoMarshal::managed_to_variant_type(types[i]);
  1207. if (arg.type == Variant::NIL) {
  1208. ERR_PRINTS("Unknown type of signal parameter: " + arg.name + " in " + p_class->get_full_name());
  1209. return false;
  1210. }
  1211. params.push_back(arg);
  1212. }
  1213. return true;
  1214. }
  1215. }
  1216. }
  1217. return false;
  1218. }
  1219. #ifdef TOOLS_ENABLED
  1220. bool CSharpScript::_get_member_export(GDMonoClass *p_class, GDMonoClassMember *p_member, PropertyInfo &r_prop_info, bool &r_exported) {
  1221. StringName name = p_member->get_name();
  1222. if (p_member->is_static()) {
  1223. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
  1224. ERR_PRINTS("Cannot export member because it is static: " + p_class->get_full_name() + "." + name.operator String());
  1225. return false;
  1226. }
  1227. if (member_info.has(name))
  1228. return false;
  1229. ManagedType type;
  1230. if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_FIELD) {
  1231. type = static_cast<GDMonoField *>(p_member)->get_type();
  1232. } else if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1233. type = static_cast<GDMonoProperty *>(p_member)->get_type();
  1234. } else {
  1235. CRASH_NOW();
  1236. }
  1237. Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
  1238. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute))) {
  1239. if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1240. GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
  1241. if (!property->has_getter() || !property->has_setter()) {
  1242. ERR_PRINTS("Cannot export property because it does not provide a getter or a setter: " + p_class->get_full_name() + "." + name.operator String());
  1243. return false;
  1244. }
  1245. }
  1246. MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
  1247. PropertyHint hint;
  1248. String hint_string;
  1249. if (variant_type == Variant::NIL) {
  1250. ERR_PRINTS("Unknown type of exported member: " + p_class->get_full_name() + "." + name.operator String());
  1251. return false;
  1252. } else if (variant_type == Variant::INT && type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(type.type_class->get_mono_ptr())) {
  1253. variant_type = Variant::INT;
  1254. hint = PROPERTY_HINT_ENUM;
  1255. Vector<MonoClassField *> fields = type.type_class->get_enum_fields();
  1256. for (int i = 0; i < fields.size(); i++) {
  1257. if (i > 0)
  1258. hint_string += ",";
  1259. hint_string += mono_field_get_name(fields[i]);
  1260. }
  1261. } else if (variant_type == Variant::OBJECT && CACHED_CLASS(GodotReference)->is_assignable_from(type.type_class)) {
  1262. hint = PROPERTY_HINT_RESOURCE_TYPE;
  1263. hint_string = NATIVE_GDMONOCLASS_NAME(type.type_class);
  1264. } else {
  1265. hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
  1266. hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
  1267. }
  1268. r_prop_info = PropertyInfo(variant_type, name.operator String(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE);
  1269. r_exported = true;
  1270. } else {
  1271. r_prop_info = PropertyInfo(variant_type, name.operator String(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
  1272. r_exported = false;
  1273. }
  1274. return true;
  1275. }
  1276. #endif
  1277. void CSharpScript::_clear() {
  1278. tool = false;
  1279. valid = false;
  1280. base = NULL;
  1281. native = NULL;
  1282. script_class = NULL;
  1283. }
  1284. Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1285. GDMonoClass *top = script_class;
  1286. while (top && top != native) {
  1287. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1288. if (method && method->is_static()) {
  1289. MonoObject *result = method->invoke(NULL, p_args);
  1290. if (result) {
  1291. return GDMonoMarshal::mono_object_to_variant(result);
  1292. } else {
  1293. return Variant();
  1294. }
  1295. }
  1296. top = top->get_parent_class();
  1297. }
  1298. // No static method found. Try regular instance calls
  1299. return Script::call(p_method, p_args, p_argcount, r_error);
  1300. }
  1301. void CSharpScript::_resource_path_changed() {
  1302. String path = get_path();
  1303. if (!path.empty()) {
  1304. name = get_path().get_file().get_basename();
  1305. }
  1306. }
  1307. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1308. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1309. r_ret = get_source_code();
  1310. return true;
  1311. }
  1312. return false;
  1313. }
  1314. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1315. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1316. set_source_code(p_value);
  1317. reload();
  1318. return true;
  1319. }
  1320. return false;
  1321. }
  1322. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1323. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  1324. }
  1325. void CSharpScript::_bind_methods() {
  1326. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo(Variant::OBJECT, "new"));
  1327. }
  1328. Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class) {
  1329. // This method should not fail
  1330. CRASH_COND(!p_class);
  1331. Ref<CSharpScript> script = memnew(CSharpScript);
  1332. script->name = p_class->get_name();
  1333. script->script_class = p_class;
  1334. script->native = GDMonoUtils::get_class_native_base(script->script_class);
  1335. CRASH_COND(script->native == NULL);
  1336. GDMonoClass *base = script->script_class->get_parent_class();
  1337. if (base != script->native)
  1338. script->base = base;
  1339. #ifdef DEBUG_ENABLED
  1340. // For debug builds, we must fetch from all native base methods as well.
  1341. // Native base methods must be fetched before the current class.
  1342. // Not needed if the script class itself is a native class.
  1343. if (script->script_class != script->native) {
  1344. GDMonoClass *native_top = script->native;
  1345. while (native_top) {
  1346. native_top->fetch_methods_with_godot_api_checks(script->native);
  1347. if (native_top == CACHED_CLASS(GodotObject))
  1348. break;
  1349. native_top = native_top->get_parent_class();
  1350. }
  1351. }
  1352. #endif
  1353. script->script_class->fetch_methods_with_godot_api_checks(script->native);
  1354. // Need to fetch method from base classes as well
  1355. GDMonoClass *top = script->script_class;
  1356. while (top && top != script->native) {
  1357. top->fetch_methods_with_godot_api_checks(script->native);
  1358. top = top->get_parent_class();
  1359. }
  1360. return script;
  1361. }
  1362. bool CSharpScript::can_instance() const {
  1363. #ifdef TOOLS_ENABLED
  1364. if (Engine::get_singleton()->is_editor_hint()) {
  1365. if (get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted...
  1366. if (_create_project_solution_if_needed()) {
  1367. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  1368. "Compile",
  1369. ProjectSettings::get_singleton()->globalize_path(get_path()));
  1370. } else {
  1371. ERR_PRINTS("Cannot add " + get_path() + " to the C# project because it could not be created.");
  1372. }
  1373. }
  1374. }
  1375. #endif
  1376. return valid || (!tool && !ScriptServer::is_scripting_enabled());
  1377. }
  1378. StringName CSharpScript::get_instance_base_type() const {
  1379. if (native)
  1380. return native->get_name();
  1381. else
  1382. return StringName();
  1383. }
  1384. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  1385. /* STEP 1, CREATE */
  1386. CSharpInstance *instance = memnew(CSharpInstance);
  1387. instance->base_ref = p_isref;
  1388. instance->script = Ref<CSharpScript>(this);
  1389. instance->owner = p_owner;
  1390. instance->owner->set_script_instance(instance);
  1391. if (instance->base_ref)
  1392. instance->_reference_owner_unsafe();
  1393. /* STEP 2, INITIALIZE AND CONSTRUCT */
  1394. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
  1395. if (!mono_object) {
  1396. instance->script = Ref<CSharpScript>();
  1397. instance->owner->set_script_instance(NULL);
  1398. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1399. ERR_EXPLAIN("Failed to allocate memory for the object");
  1400. ERR_FAIL_V(NULL);
  1401. }
  1402. #ifndef NO_THREADS
  1403. CSharpLanguage::singleton->lock->lock();
  1404. #endif
  1405. instances.insert(instance->owner);
  1406. #ifndef NO_THREADS
  1407. CSharpLanguage::singleton->lock->unlock();
  1408. #endif
  1409. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);
  1410. // Construct
  1411. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
  1412. ctor->invoke(mono_object, p_args, NULL);
  1413. // Tie managed to unmanaged
  1414. instance->gchandle = MonoGCHandle::create_strong(mono_object);
  1415. /* STEP 3, PARTY */
  1416. //@TODO make thread safe
  1417. return instance;
  1418. }
  1419. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1420. if (!valid) {
  1421. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1422. return Variant();
  1423. }
  1424. r_error.error = Variant::CallError::CALL_OK;
  1425. REF ref;
  1426. Object *owner = NULL;
  1427. ERR_FAIL_NULL_V(native, Variant());
  1428. owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native));
  1429. Reference *r = Object::cast_to<Reference>(owner);
  1430. if (r) {
  1431. ref = REF(r);
  1432. }
  1433. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  1434. if (!instance) {
  1435. if (ref.is_null()) {
  1436. memdelete(owner); //no owner, sorry
  1437. }
  1438. return Variant();
  1439. }
  1440. if (ref.is_valid()) {
  1441. return ref;
  1442. } else {
  1443. return owner;
  1444. }
  1445. }
  1446. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  1447. if (!valid)
  1448. return NULL;
  1449. if (!tool && !ScriptServer::is_scripting_enabled()) {
  1450. #ifdef TOOLS_ENABLED
  1451. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  1452. placeholders.insert(si);
  1453. _update_exports();
  1454. _update_signals();
  1455. return si;
  1456. #else
  1457. return NULL;
  1458. #endif
  1459. }
  1460. update_signals();
  1461. if (native) {
  1462. String native_name = native->get_name();
  1463. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  1464. if (ScriptDebugger::get_singleton()) {
  1465. 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() + "'");
  1466. }
  1467. ERR_EXPLAIN("Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  1468. ERR_FAIL_V(NULL);
  1469. }
  1470. }
  1471. Variant::CallError unchecked_error;
  1472. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error);
  1473. }
  1474. bool CSharpScript::instance_has(const Object *p_this) const {
  1475. #ifndef NO_THREADS
  1476. CSharpLanguage::singleton->lock->lock();
  1477. #endif
  1478. bool ret = instances.has((Object *)p_this);
  1479. #ifndef NO_THREADS
  1480. CSharpLanguage::singleton->lock->unlock();
  1481. #endif
  1482. return ret;
  1483. }
  1484. bool CSharpScript::has_source_code() const {
  1485. return !source.empty();
  1486. }
  1487. String CSharpScript::get_source_code() const {
  1488. return source;
  1489. }
  1490. void CSharpScript::set_source_code(const String &p_code) {
  1491. if (source == p_code)
  1492. return;
  1493. source = p_code;
  1494. #ifdef TOOLS_ENABLED
  1495. source_changed_cache = true;
  1496. #endif
  1497. }
  1498. bool CSharpScript::has_method(const StringName &p_method) const {
  1499. return script_class->has_fetched_method_unknown_params(p_method);
  1500. }
  1501. Error CSharpScript::reload(bool p_keep_state) {
  1502. #ifndef NO_THREADS
  1503. CSharpLanguage::singleton->lock->lock();
  1504. #endif
  1505. bool has_instances = instances.size();
  1506. #ifndef NO_THREADS
  1507. CSharpLanguage::singleton->lock->unlock();
  1508. #endif
  1509. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  1510. GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly();
  1511. if (project_assembly) {
  1512. script_class = project_assembly->get_object_derived_class(name);
  1513. if (!script_class) {
  1514. ERR_PRINTS("Cannot find class " + name + " for script " + get_path());
  1515. }
  1516. #ifdef DEBUG_ENABLED
  1517. else if (OS::get_singleton()->is_stdout_verbose()) {
  1518. OS::get_singleton()->print(String("Found class " + script_class->get_namespace() + "." +
  1519. script_class->get_name() + " for script " + get_path() + "\n")
  1520. .utf8());
  1521. }
  1522. #endif
  1523. valid = script_class != NULL;
  1524. if (script_class) {
  1525. tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  1526. native = GDMonoUtils::get_class_native_base(script_class);
  1527. CRASH_COND(native == NULL);
  1528. GDMonoClass *base_class = script_class->get_parent_class();
  1529. if (base_class != native)
  1530. base = base_class;
  1531. #ifdef DEBUG_ENABLED
  1532. // For debug builds, we must fetch from all native base methods as well.
  1533. // Native base methods must be fetched before the current class.
  1534. // Not needed if the script class itself is a native class.
  1535. if (script_class != native) {
  1536. GDMonoClass *native_top = native;
  1537. while (native_top) {
  1538. native_top->fetch_methods_with_godot_api_checks(native);
  1539. if (native_top == CACHED_CLASS(GodotObject))
  1540. break;
  1541. native_top = native_top->get_parent_class();
  1542. }
  1543. }
  1544. #endif
  1545. script_class->fetch_methods_with_godot_api_checks(native);
  1546. // Need to fetch method from base classes as well
  1547. GDMonoClass *top = script_class;
  1548. while (top && top != native) {
  1549. top->fetch_methods_with_godot_api_checks(native);
  1550. top = top->get_parent_class();
  1551. }
  1552. }
  1553. return OK;
  1554. }
  1555. return ERR_FILE_MISSING_DEPENDENCIES;
  1556. }
  1557. ScriptLanguage *CSharpScript::get_language() const {
  1558. return CSharpLanguage::get_singleton();
  1559. }
  1560. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  1561. #ifdef TOOLS_ENABLED
  1562. const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
  1563. if (E) {
  1564. r_value = E->get();
  1565. return true;
  1566. }
  1567. if (base_cache.is_valid()) {
  1568. return base_cache->get_property_default_value(p_property, r_value);
  1569. }
  1570. #endif
  1571. return false;
  1572. }
  1573. void CSharpScript::update_exports() {
  1574. #ifdef TOOLS_ENABLED
  1575. _update_exports();
  1576. #endif
  1577. }
  1578. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  1579. if (_signals.has(p_signal))
  1580. return true;
  1581. return false;
  1582. }
  1583. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  1584. for (const Map<StringName, Vector<Argument> >::Element *E = _signals.front(); E; E = E->next()) {
  1585. MethodInfo mi;
  1586. mi.name = E->key();
  1587. for (int i = 0; i < E->get().size(); i++) {
  1588. PropertyInfo arg;
  1589. arg.name = E->get()[i].name;
  1590. mi.arguments.push_back(arg);
  1591. }
  1592. r_signals->push_back(mi);
  1593. }
  1594. }
  1595. void CSharpScript::update_signals() {
  1596. _update_signals();
  1597. }
  1598. Ref<Script> CSharpScript::get_base_script() const {
  1599. // TODO search in metadata file once we have it, not important any way?
  1600. return Ref<Script>();
  1601. }
  1602. void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  1603. for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
  1604. p_list->push_back(E->value());
  1605. }
  1606. }
  1607. int CSharpScript::get_member_line(const StringName &p_member) const {
  1608. // TODO omnisharp
  1609. return -1;
  1610. }
  1611. Error CSharpScript::load_source_code(const String &p_path) {
  1612. PoolVector<uint8_t> sourcef;
  1613. Error err;
  1614. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  1615. ERR_FAIL_COND_V(err != OK, err);
  1616. int len = f->get_len();
  1617. sourcef.resize(len + 1);
  1618. PoolVector<uint8_t>::Write w = sourcef.write();
  1619. int r = f->get_buffer(w.ptr(), len);
  1620. f->close();
  1621. memdelete(f);
  1622. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  1623. w[len] = 0;
  1624. String s;
  1625. if (s.parse_utf8((const char *)w.ptr())) {
  1626. ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode.");
  1627. ERR_FAIL_V(ERR_INVALID_DATA);
  1628. }
  1629. source = s;
  1630. #ifdef TOOLS_ENABLED
  1631. source_changed_cache = true;
  1632. #endif
  1633. return OK;
  1634. }
  1635. StringName CSharpScript::get_script_name() const {
  1636. return name;
  1637. }
  1638. CSharpScript::CSharpScript() :
  1639. script_list(this) {
  1640. _clear();
  1641. #ifdef TOOLS_ENABLED
  1642. source_changed_cache = false;
  1643. exports_invalidated = true;
  1644. signals_invalidated = true;
  1645. #endif
  1646. _resource_path_changed();
  1647. #ifdef DEBUG_ENABLED
  1648. #ifndef NO_THREADS
  1649. CSharpLanguage::get_singleton()->lock->lock();
  1650. #endif
  1651. CSharpLanguage::get_singleton()->script_list.add(&script_list);
  1652. #ifndef NO_THREADS
  1653. CSharpLanguage::get_singleton()->lock->unlock();
  1654. #endif
  1655. #endif // DEBUG_ENABLED
  1656. }
  1657. CSharpScript::~CSharpScript() {
  1658. #ifdef DEBUG_ENABLED
  1659. #ifndef NO_THREADS
  1660. CSharpLanguage::get_singleton()->lock->lock();
  1661. #endif
  1662. CSharpLanguage::get_singleton()->script_list.remove(&script_list);
  1663. #ifndef NO_THREADS
  1664. CSharpLanguage::get_singleton()->lock->unlock();
  1665. #endif
  1666. #endif // DEBUG_ENABLED
  1667. }
  1668. /*************** RESOURCE ***************/
  1669. RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  1670. if (r_error)
  1671. *r_error = ERR_FILE_CANT_OPEN;
  1672. // TODO ignore anything inside bin/ and obj/ in tools builds?
  1673. CSharpScript *script = memnew(CSharpScript);
  1674. Ref<CSharpScript> scriptres(script);
  1675. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  1676. Error err = script->load_source_code(p_path);
  1677. ERR_FAIL_COND_V(err != OK, RES());
  1678. #endif
  1679. script->set_path(p_original_path);
  1680. #ifndef TOOLS_ENABLED
  1681. #ifdef DEBUG_ENABLED
  1682. // User is responsible for thread attach/detach
  1683. ERR_EXPLAIN("Thread is not attached");
  1684. CRASH_COND(mono_domain_get() == NULL);
  1685. #endif
  1686. #else
  1687. if (Engine::get_singleton()->is_editor_hint() && mono_domain_get() == NULL) {
  1688. CRASH_COND(Thread::get_caller_id() == Thread::get_main_id());
  1689. // Thread is not attached, but we will make an exception in this case
  1690. // because this may be called by one of the editor's worker threads.
  1691. // Attach this thread temporarily to reload the script.
  1692. MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN);
  1693. CRASH_COND(mono_thread == NULL);
  1694. script->reload();
  1695. mono_thread_detach(mono_thread);
  1696. } else // just reload it normally
  1697. #endif
  1698. script->reload();
  1699. if (r_error)
  1700. *r_error = OK;
  1701. return scriptres;
  1702. }
  1703. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  1704. p_extensions->push_back("cs");
  1705. }
  1706. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  1707. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  1708. }
  1709. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  1710. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  1711. }
  1712. Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1713. Ref<CSharpScript> sqscr = p_resource;
  1714. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  1715. String source = sqscr->get_source_code();
  1716. #ifdef TOOLS_ENABLED
  1717. if (!FileAccess::exists(p_path)) {
  1718. // The file does not yet exists, let's assume the user just created this script
  1719. if (_create_project_solution_if_needed()) {
  1720. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  1721. "Compile",
  1722. ProjectSettings::get_singleton()->globalize_path(p_path));
  1723. } else {
  1724. ERR_PRINTS("Cannot add " + p_path + " to the C# project because it could not be created.");
  1725. }
  1726. }
  1727. #endif
  1728. Error err;
  1729. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1730. ERR_FAIL_COND_V(err, err);
  1731. file->store_string(source);
  1732. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  1733. memdelete(file);
  1734. return ERR_CANT_CREATE;
  1735. }
  1736. file->close();
  1737. memdelete(file);
  1738. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  1739. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  1740. }
  1741. return OK;
  1742. }
  1743. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1744. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  1745. p_extensions->push_back("cs");
  1746. }
  1747. }
  1748. bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
  1749. return Object::cast_to<CSharpScript>(p_resource.ptr()) != NULL;
  1750. }
  1751. CSharpLanguage::StringNameCache::StringNameCache() {
  1752. _signal_callback = StaticCString::create("_signal_callback");
  1753. _set = StaticCString::create("_set");
  1754. _get = StaticCString::create("_get");
  1755. _notification = StaticCString::create("_notification");
  1756. _script_source = StaticCString::create("script/source");
  1757. dotctor = StaticCString::create(".ctor");
  1758. }