csharp_script.cpp 61 KB

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