csharp_script.cpp 61 KB

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