csharp_script.cpp 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767
  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 "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include "core/os/thread.h"
  35. #include "core/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. #ifndef MONO_GLUE_ENABLED
  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", false);
  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. script_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.write[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. if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != NULL) {
  450. const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoUtils::mono_cache.task_scheduler_handle;
  451. if (task_scheduler_handle.is_valid()) {
  452. MonoObject *task_scheduler = task_scheduler_handle->get_target();
  453. if (task_scheduler) {
  454. GDMonoUtils::GodotTaskScheduler_Activate thunk = CACHED_METHOD_THUNK(GodotTaskScheduler, Activate);
  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. }
  465. struct CSharpScriptDepSort {
  466. // must support sorting so inheritance works properly (parent must be reloaded first)
  467. bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
  468. if (A == B)
  469. return false; // shouldn't happen but..
  470. GDMonoClass *I = B->base;
  471. while (I) {
  472. if (I == A->script_class) {
  473. // A is a base of B
  474. return true;
  475. }
  476. I = I->get_parent_class();
  477. }
  478. return false; // not a base
  479. }
  480. };
  481. void CSharpLanguage::reload_all_scripts() {
  482. #ifdef DEBUG_ENABLED
  483. #ifndef NO_THREADS
  484. lock->lock();
  485. #endif
  486. List<Ref<CSharpScript> > scripts;
  487. SelfList<CSharpScript> *elem = script_list.first();
  488. while (elem) {
  489. if (elem->self()->get_path().is_resource_file()) {
  490. scripts.push_back(Ref<CSharpScript>(elem->self())); //cast to gdscript to avoid being erased by accident
  491. }
  492. elem = elem->next();
  493. }
  494. #ifndef NO_THREADS
  495. lock->unlock();
  496. #endif
  497. //as scripts are going to be reloaded, must proceed without locking here
  498. scripts.sort_custom<CSharpScriptDepSort>(); //update in inheritance dependency order
  499. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  500. E->get()->load_source_code(E->get()->get_path());
  501. E->get()->reload(true);
  502. }
  503. #endif
  504. }
  505. void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
  506. (void)p_script; // UNUSED
  507. #ifdef TOOLS_ENABLED
  508. MonoReloadNode::get_singleton()->restart_reload_timer();
  509. reload_assemblies_if_needed(p_soft_reload);
  510. #endif
  511. }
  512. #ifdef TOOLS_ENABLED
  513. void CSharpLanguage::reload_assemblies_if_needed(bool p_soft_reload) {
  514. if (!gdmono->is_runtime_initialized())
  515. return;
  516. GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();
  517. String name = ProjectSettings::get_singleton()->get("application/config/name");
  518. if (name.empty()) {
  519. name = "UnnamedProject";
  520. }
  521. name += ".dll";
  522. if (proj_assembly) {
  523. String proj_asm_path = proj_assembly->get_path();
  524. if (!FileAccess::exists(proj_assembly->get_path())) {
  525. // Maybe it wasn't loaded from the default path, so check this as well
  526. proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name);
  527. if (!FileAccess::exists(proj_asm_path))
  528. return; // No assembly to load
  529. }
  530. if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
  531. return; // Already up to date
  532. } else {
  533. if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name)))
  534. return; // No assembly to load
  535. }
  536. if (!gdmono->get_core_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_CORE))
  537. return; // The core API assembly to load is invalidated
  538. if (!gdmono->get_editor_api_assembly() && gdmono->metadata_is_api_assembly_invalidated(APIAssembly::API_EDITOR))
  539. return; // The editor API assembly to load is invalidated
  540. #ifndef NO_THREADS
  541. lock->lock();
  542. #endif
  543. List<Ref<CSharpScript> > scripts;
  544. SelfList<CSharpScript> *elem = script_list.first();
  545. while (elem) {
  546. if (elem->self()->get_path().is_resource_file()) {
  547. scripts.push_back(Ref<CSharpScript>(elem->self())); //cast to CSharpScript to avoid being erased by accident
  548. }
  549. elem = elem->next();
  550. }
  551. #ifndef NO_THREADS
  552. lock->unlock();
  553. #endif
  554. //when someone asks you why dynamically typed languages are easier to write....
  555. Map<Ref<CSharpScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload;
  556. //as scripts are going to be reloaded, must proceed without locking here
  557. scripts.sort_custom<CSharpScriptDepSort>(); //update in inheritance dependency order
  558. for (List<Ref<CSharpScript> >::Element *E = scripts.front(); E; E = E->next()) {
  559. to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >());
  560. if (!p_soft_reload) {
  561. //save state and remove script from instances
  562. Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()];
  563. while (E->get()->instances.front()) {
  564. Object *obj = E->get()->instances.front()->get();
  565. //save instance info
  566. List<Pair<StringName, Variant> > state;
  567. if (obj->get_script_instance()) {
  568. obj->get_script_instance()->get_property_state(state);
  569. Ref<MonoGCHandle> gchandle = CAST_CSHARP_INSTANCE(obj->get_script_instance())->gchandle;
  570. if (gchandle.is_valid())
  571. gchandle->release();
  572. map[obj->get_instance_id()] = state;
  573. obj->set_script(RefPtr());
  574. }
  575. }
  576. //same thing for placeholders
  577. while (E->get()->placeholders.size()) {
  578. Object *obj = E->get()->placeholders.front()->get()->get_owner();
  579. //save instance info
  580. List<Pair<StringName, Variant> > state;
  581. if (obj->get_script_instance()) {
  582. obj->get_script_instance()->get_property_state(state);
  583. map[obj->get_instance_id()] = state;
  584. obj->set_script(RefPtr());
  585. } else {
  586. // no instance found. Let's remove it so we don't loop forever
  587. E->get()->placeholders.erase(E->get()->placeholders.front()->get());
  588. }
  589. }
  590. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) {
  591. map[F->key()] = F->get(); //pending to reload, use this one instead
  592. }
  593. E->get()->_clear();
  594. }
  595. }
  596. if (gdmono->reload_scripts_domain() != OK) {
  597. // Failed to reload the scripts domain
  598. // Make sure to add the scripts back to their owners before returning
  599. for (Map<Ref<CSharpScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) {
  600. Ref<CSharpScript> scr = E->key();
  601. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
  602. Object *obj = ObjectDB::get_instance(F->key());
  603. if (!obj)
  604. continue;
  605. obj->set_script(scr.get_ref_ptr());
  606. // Save reload state for next time if not saved
  607. if (!scr->pending_reload_state.has(obj->get_instance_id())) {
  608. scr->pending_reload_state[obj->get_instance_id()] = F->get();
  609. }
  610. }
  611. }
  612. return;
  613. }
  614. for (Map<Ref<CSharpScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) {
  615. Ref<CSharpScript> scr = E->key();
  616. scr->exports_invalidated = true;
  617. scr->signals_invalidated = true;
  618. scr->reload(p_soft_reload);
  619. scr->update_exports();
  620. //restore state if saved
  621. for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
  622. Object *obj = ObjectDB::get_instance(F->key());
  623. if (!obj)
  624. continue;
  625. if (!p_soft_reload) {
  626. //clear it just in case (may be a pending reload state)
  627. obj->set_script(RefPtr());
  628. }
  629. obj->set_script(scr.get_ref_ptr());
  630. if (!obj->get_script_instance()) {
  631. //failed, save reload state for next time if not saved
  632. if (!scr->pending_reload_state.has(obj->get_instance_id())) {
  633. scr->pending_reload_state[obj->get_instance_id()] = F->get();
  634. }
  635. continue;
  636. }
  637. if (scr->valid && scr->is_tool() && obj->get_script_instance()->is_placeholder()) {
  638. // Script instance was a placeholder, but now the script was built successfully and is a tool script.
  639. // We have to replace the placeholder with an actual C# script instance.
  640. scr->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(obj->get_script_instance()));
  641. ScriptInstance *script_instance = scr->instance_create(obj);
  642. obj->set_script_instance(script_instance); // Not necessary as it's already done in instance_create, but just in case...
  643. }
  644. for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) {
  645. obj->get_script_instance()->set(G->get().first, G->get().second);
  646. }
  647. scr->pending_reload_state.erase(obj->get_instance_id()); //as it reloaded, remove pending state
  648. }
  649. //if instance states were saved, set them!
  650. }
  651. if (Engine::get_singleton()->is_editor_hint()) {
  652. EditorNode::get_singleton()->get_inspector()->update_tree();
  653. NodeDock::singleton->update_lists();
  654. }
  655. }
  656. #endif
  657. void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  658. p_extensions->push_back("cs");
  659. }
  660. #ifdef TOOLS_ENABLED
  661. Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
  662. return GodotSharpEditor::get_singleton()->open_in_external_editor(p_script, p_line, p_col);
  663. }
  664. bool CSharpLanguage::overrides_external_editor() {
  665. return GodotSharpEditor::get_singleton()->overrides_external_editor();
  666. }
  667. #endif
  668. void CSharpLanguage::thread_enter() {
  669. #if 0
  670. if (mono->is_runtime_initialized()) {
  671. GDMonoUtils::attach_current_thread();
  672. }
  673. #endif
  674. }
  675. void CSharpLanguage::thread_exit() {
  676. #if 0
  677. if (mono->is_runtime_initialized()) {
  678. GDMonoUtils::detach_current_thread();
  679. }
  680. #endif
  681. }
  682. bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  683. // Break because of parse error
  684. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  685. // TODO
  686. //_debug_parse_err_line = p_line;
  687. //_debug_parse_err_file = p_file;
  688. //_debug_error = p_error;
  689. ScriptDebugger::get_singleton()->debug(this, false);
  690. return true;
  691. } else {
  692. return false;
  693. }
  694. }
  695. bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  696. if (ScriptDebugger::get_singleton() && Thread::get_caller_id() == Thread::get_main_id()) {
  697. // TODO
  698. //_debug_parse_err_line = -1;
  699. //_debug_parse_err_file = "";
  700. //_debug_error = p_error;
  701. ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
  702. return true;
  703. } else {
  704. return false;
  705. }
  706. }
  707. void CSharpLanguage::set_language_index(int p_idx) {
  708. ERR_FAIL_COND(lang_idx != -1);
  709. lang_idx = p_idx;
  710. }
  711. void CSharpLanguage::release_script_gchandle(Ref<MonoGCHandle> &p_gchandle) {
  712. if (!p_gchandle->is_released()) { // Do not locking unnecessarily
  713. #ifndef NO_THREADS
  714. get_singleton()->script_gchandle_release_lock->lock();
  715. #endif
  716. p_gchandle->release();
  717. #ifndef NO_THREADS
  718. get_singleton()->script_gchandle_release_lock->unlock();
  719. #endif
  720. }
  721. }
  722. void CSharpLanguage::release_script_gchandle(MonoObject *p_pinned_expected_obj, Ref<MonoGCHandle> &p_gchandle) {
  723. uint32_t pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(p_pinned_expected_obj); // we might lock after this, so pin it
  724. if (!p_gchandle->is_released()) { // Do not locking unnecessarily
  725. #ifndef NO_THREADS
  726. get_singleton()->script_gchandle_release_lock->lock();
  727. #endif
  728. MonoObject *target = p_gchandle->get_target();
  729. // We release the gchandle if it points to the MonoObject* we expect (otherwise it was
  730. // already released and could have been replaced) or if we can't get its target MonoObject*
  731. // (which doesn't necessarily mean it was released, and we want it released in order to
  732. // avoid locking other threads unnecessarily).
  733. if (target == p_pinned_expected_obj || target == NULL) {
  734. p_gchandle->release();
  735. }
  736. #ifndef NO_THREADS
  737. get_singleton()->script_gchandle_release_lock->unlock();
  738. #endif
  739. }
  740. MonoGCHandle::free_handle(pinned_gchandle);
  741. }
  742. CSharpLanguage::CSharpLanguage() {
  743. ERR_FAIL_COND(singleton);
  744. singleton = this;
  745. finalizing = false;
  746. gdmono = NULL;
  747. #ifdef NO_THREADS
  748. lock = NULL;
  749. gchandle_bind_lock = NULL;
  750. script_gchandle_release_lock = NULL;
  751. #else
  752. lock = Mutex::create();
  753. script_bind_lock = Mutex::create();
  754. script_gchandle_release_lock = Mutex::create();
  755. #endif
  756. lang_idx = -1;
  757. }
  758. CSharpLanguage::~CSharpLanguage() {
  759. finish();
  760. if (lock) {
  761. memdelete(lock);
  762. lock = NULL;
  763. }
  764. if (script_bind_lock) {
  765. memdelete(script_bind_lock);
  766. script_bind_lock = NULL;
  767. }
  768. if (script_gchandle_release_lock) {
  769. memdelete(script_gchandle_release_lock);
  770. script_gchandle_release_lock = NULL;
  771. }
  772. singleton = NULL;
  773. }
  774. void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
  775. #ifdef DEBUG_ENABLED
  776. // I don't trust you
  777. if (p_object->get_script_instance())
  778. CRASH_COND(NULL != CAST_CSHARP_INSTANCE(p_object->get_script_instance()));
  779. #endif
  780. StringName type_name = p_object->get_class_name();
  781. // ¯\_(ツ)_/¯
  782. const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
  783. while (classinfo && !classinfo->exposed)
  784. classinfo = classinfo->inherits_ptr;
  785. ERR_FAIL_NULL_V(classinfo, NULL);
  786. type_name = classinfo->name;
  787. GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);
  788. ERR_FAIL_NULL_V(type_class, NULL);
  789. MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);
  790. ERR_FAIL_NULL_V(mono_object, NULL);
  791. CSharpScriptBinding script_binding;
  792. script_binding.type_name = type_name;
  793. script_binding.wrapper_class = type_class; // cache
  794. script_binding.gchandle = MonoGCHandle::create_strong(mono_object);
  795. #ifndef NO_THREADS
  796. script_bind_lock->lock();
  797. #endif
  798. void *data = (void *)script_bindings.insert(p_object, script_binding);
  799. #ifndef NO_THREADS
  800. script_bind_lock->unlock();
  801. #endif
  802. // Tie managed to unmanaged
  803. Reference *ref = Object::cast_to<Reference>(p_object);
  804. if (ref) {
  805. // Unsafe refcount increment. The managed instance also counts as a reference.
  806. // This way if the unmanaged world has no references to our owner
  807. // but the managed instance is alive, the refcount will be 1 instead of 0.
  808. // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)
  809. ref->reference();
  810. }
  811. return data;
  812. }
  813. void CSharpLanguage::free_instance_binding_data(void *p_data) {
  814. if (GDMono::get_singleton() == NULL) {
  815. #ifdef DEBUG_ENABLED
  816. CRASH_COND(!script_bindings.empty());
  817. #endif
  818. // Mono runtime finalized, all the gchandle bindings were already released
  819. return;
  820. }
  821. if (finalizing)
  822. return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there
  823. #ifndef NO_THREADS
  824. script_bind_lock->lock();
  825. #endif
  826. Map<Object *, CSharpScriptBinding>::Element *data = (Map<Object *, CSharpScriptBinding>::Element *)p_data;
  827. // Set the native instance field to IntPtr.Zero, if not yet garbage collected
  828. MonoObject *mono_object = data->value().gchandle->get_target();
  829. if (mono_object) {
  830. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL);
  831. }
  832. script_bindings.erase(data);
  833. #ifndef NO_THREADS
  834. script_bind_lock->unlock();
  835. #endif
  836. }
  837. void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
  838. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  839. #ifdef DEBUG_ENABLED
  840. CRASH_COND(!ref_owner);
  841. #endif
  842. void *data = p_object->get_script_instance_binding(get_language_index());
  843. if (!data)
  844. return;
  845. Ref<MonoGCHandle> &gchandle = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get().gchandle;
  846. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  847. // The reference count was increased after the managed side was the only one referencing our owner.
  848. // This means the owner is being referenced again by the unmanaged side,
  849. // so the owner must hold the managed side alive again to avoid it from being GCed.
  850. MonoObject *target = gchandle->get_target();
  851. if (!target)
  852. return; // Called after the managed side was collected, so nothing to do here
  853. // Release the current weak handle and replace it with a strong handle.
  854. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(target);
  855. gchandle->release();
  856. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  857. }
  858. }
  859. bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
  860. Reference *ref_owner = Object::cast_to<Reference>(p_object);
  861. #ifdef DEBUG_ENABLED
  862. CRASH_COND(!ref_owner);
  863. #endif
  864. int refcount = ref_owner->reference_get_count();
  865. void *data = p_object->get_script_instance_binding(get_language_index());
  866. if (!data)
  867. return refcount == 0;
  868. Ref<MonoGCHandle> &gchandle = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get().gchandle;
  869. if (refcount == 1 && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  870. // If owner owner is no longer referenced by the unmanaged side,
  871. // the managed instance takes responsibility of deleting the owner when GCed.
  872. MonoObject *target = gchandle->get_target();
  873. if (!target)
  874. return refcount == 0; // Called after the managed side was collected, so nothing to do here
  875. // Release the current strong handle and replace it with a weak handle.
  876. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(target);
  877. gchandle->release();
  878. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  879. return false;
  880. }
  881. return refcount == 0;
  882. }
  883. CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle) {
  884. CSharpInstance *instance = memnew(CSharpInstance);
  885. Reference *ref = Object::cast_to<Reference>(p_owner);
  886. instance->base_ref = ref != NULL;
  887. instance->script = Ref<CSharpScript>(p_script);
  888. instance->owner = p_owner;
  889. instance->gchandle = p_gchandle;
  890. if (instance->base_ref)
  891. instance->_reference_owner_unsafe();
  892. p_script->instances.insert(p_owner);
  893. return instance;
  894. }
  895. MonoObject *CSharpInstance::get_mono_object() const {
  896. ERR_FAIL_COND_V(gchandle.is_null(), NULL);
  897. return gchandle->get_target();
  898. }
  899. bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
  900. ERR_FAIL_COND_V(!script.is_valid(), false);
  901. MonoObject *mono_object = get_mono_object();
  902. ERR_FAIL_NULL_V(mono_object, false);
  903. GDMonoClass *top = script->script_class;
  904. while (top && top != script->native) {
  905. GDMonoField *field = script->script_class->get_field(p_name);
  906. if (field) {
  907. field->set_value_from_variant(mono_object, p_value);
  908. return true;
  909. }
  910. GDMonoProperty *property = script->script_class->get_property(p_name);
  911. if (property) {
  912. property->set_value(mono_object, GDMonoMarshal::variant_to_mono_object(p_value, property->get_type()));
  913. return true;
  914. }
  915. top = top->get_parent_class();
  916. }
  917. // Call _set
  918. top = script->script_class;
  919. while (top && top != script->native) {
  920. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);
  921. if (method) {
  922. Variant name = p_name;
  923. const Variant *args[2] = { &name, &p_value };
  924. MonoObject *ret = method->invoke(mono_object, args);
  925. if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret))
  926. return true;
  927. break;
  928. }
  929. top = top->get_parent_class();
  930. }
  931. return false;
  932. }
  933. bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
  934. ERR_FAIL_COND_V(!script.is_valid(), false);
  935. MonoObject *mono_object = get_mono_object();
  936. ERR_FAIL_NULL_V(mono_object, false);
  937. GDMonoClass *top = script->script_class;
  938. while (top && top != script->native) {
  939. GDMonoField *field = top->get_field(p_name);
  940. if (field) {
  941. MonoObject *value = field->get_value(mono_object);
  942. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  943. return true;
  944. }
  945. GDMonoProperty *property = top->get_property(p_name);
  946. if (property) {
  947. MonoException *exc = NULL;
  948. MonoObject *value = property->get_value(mono_object, &exc);
  949. if (exc) {
  950. r_ret = Variant();
  951. GDMonoUtils::set_pending_exception(exc);
  952. } else {
  953. r_ret = GDMonoMarshal::mono_object_to_variant(value);
  954. }
  955. return true;
  956. }
  957. top = top->get_parent_class();
  958. }
  959. // Call _get
  960. top = script->script_class;
  961. while (top && top != script->native) {
  962. GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);
  963. if (method) {
  964. Variant name = p_name;
  965. const Variant *args[1] = { &name };
  966. MonoObject *ret = method->invoke(mono_object, args);
  967. if (ret) {
  968. r_ret = GDMonoMarshal::mono_object_to_variant(ret);
  969. return true;
  970. }
  971. break;
  972. }
  973. top = top->get_parent_class();
  974. }
  975. return false;
  976. }
  977. void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
  978. for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
  979. p_properties->push_back(E->value());
  980. }
  981. }
  982. Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
  983. if (script->member_info.has(p_name)) {
  984. if (r_is_valid)
  985. *r_is_valid = true;
  986. return script->member_info[p_name].type;
  987. }
  988. if (r_is_valid)
  989. *r_is_valid = false;
  990. return Variant::NIL;
  991. }
  992. bool CSharpInstance::has_method(const StringName &p_method) const {
  993. if (!script.is_valid())
  994. return false;
  995. GDMonoClass *top = script->script_class;
  996. while (top && top != script->native) {
  997. if (top->has_fetched_method_unknown_params(p_method)) {
  998. return true;
  999. }
  1000. top = top->get_parent_class();
  1001. }
  1002. return false;
  1003. }
  1004. Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1005. MonoObject *mono_object = get_mono_object();
  1006. if (!mono_object) {
  1007. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1008. ERR_FAIL_V(Variant());
  1009. }
  1010. if (!script.is_valid())
  1011. ERR_FAIL_V(Variant());
  1012. GDMonoClass *top = script->script_class;
  1013. while (top && top != script->native) {
  1014. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1015. if (method) {
  1016. MonoObject *return_value = method->invoke(mono_object, p_args);
  1017. r_error.error = Variant::CallError::CALL_OK;
  1018. if (return_value) {
  1019. return GDMonoMarshal::mono_object_to_variant(return_value);
  1020. } else {
  1021. return Variant();
  1022. }
  1023. }
  1024. top = top->get_parent_class();
  1025. }
  1026. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1027. return Variant();
  1028. }
  1029. void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1030. if (script.is_valid()) {
  1031. MonoObject *mono_object = get_mono_object();
  1032. ERR_FAIL_NULL(mono_object);
  1033. _call_multilevel(mono_object, p_method, p_args, p_argcount);
  1034. }
  1035. }
  1036. void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
  1037. GDMonoClass *top = script->script_class;
  1038. while (top && top != script->native) {
  1039. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1040. if (method) {
  1041. method->invoke(p_mono_object, p_args);
  1042. return;
  1043. }
  1044. top = top->get_parent_class();
  1045. }
  1046. }
  1047. void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
  1048. // Sorry, the method is the one that controls the call order
  1049. call_multilevel(p_method, p_args, p_argcount);
  1050. }
  1051. bool CSharpInstance::_reference_owner_unsafe() {
  1052. #ifdef DEBUG_ENABLED
  1053. CRASH_COND(!base_ref);
  1054. CRASH_COND(owner == NULL);
  1055. CRASH_COND(unsafe_referenced); // already referenced
  1056. #endif
  1057. // Unsafe refcount increment. The managed instance also counts as a reference.
  1058. // This way if the unmanaged world has no references to our owner
  1059. // but the managed instance is alive, the refcount will be 1 instead of 0.
  1060. // See: _unreference_owner_unsafe()
  1061. // May not me referenced yet, so we must use init_ref() instead of reference()
  1062. bool success = Object::cast_to<Reference>(owner)->init_ref();
  1063. unsafe_referenced = success;
  1064. return success;
  1065. }
  1066. bool CSharpInstance::_unreference_owner_unsafe() {
  1067. #ifdef DEBUG_ENABLED
  1068. CRASH_COND(!base_ref);
  1069. CRASH_COND(owner == NULL);
  1070. #endif
  1071. if (!unsafe_referenced)
  1072. return false; // Already unreferenced
  1073. // Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()
  1074. // Unsafe refcount decrement. The managed instance also counts as a reference.
  1075. // See: _reference_owner_unsafe()
  1076. bool die = static_cast<Reference *>(owner)->unreference();
  1077. if (die) {
  1078. memdelete(owner);
  1079. owner = NULL;
  1080. }
  1081. return die;
  1082. }
  1083. MonoObject *CSharpInstance::_internal_new_managed() {
  1084. #ifdef DEBUG_ENABLED
  1085. CRASH_COND(!gchandle.is_valid());
  1086. #endif
  1087. CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);
  1088. ERR_FAIL_NULL_V(owner, NULL);
  1089. ERR_FAIL_COND_V(script.is_null(), NULL);
  1090. if (base_ref)
  1091. _reference_owner_unsafe();
  1092. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script->script_class->get_mono_ptr());
  1093. if (!mono_object) {
  1094. script = Ref<CSharpScript>();
  1095. owner->set_script_instance(NULL);
  1096. ERR_EXPLAIN("Failed to allocate memory for the object");
  1097. ERR_FAIL_V(NULL);
  1098. }
  1099. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, owner);
  1100. // Construct
  1101. GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1102. ctor->invoke_raw(mono_object, NULL);
  1103. // Tie managed to unmanaged
  1104. gchandle = MonoGCHandle::create_strong(mono_object);
  1105. return mono_object;
  1106. }
  1107. void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
  1108. #ifdef DEBUG_ENABLED
  1109. CRASH_COND(base_ref);
  1110. CRASH_COND(gchandle.is_null());
  1111. #endif
  1112. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1113. }
  1114. void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_owner_deleted) {
  1115. #ifdef DEBUG_ENABLED
  1116. CRASH_COND(!base_ref);
  1117. CRASH_COND(gchandle.is_null());
  1118. #endif
  1119. if (_unreference_owner_unsafe()) {
  1120. r_owner_deleted = true;
  1121. } else {
  1122. r_owner_deleted = false;
  1123. CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
  1124. if (p_is_finalizer) {
  1125. // If the native instance is still alive, then it was
  1126. // referenced from another thread before the finalizer could
  1127. // unreference it and delete it, so we want to keep it.
  1128. // GC.ReRegisterForFinalize(this) is not safe because the objects
  1129. // referenced by this could have already been collected.
  1130. // Instead we will create a new managed instance here.
  1131. _internal_new_managed();
  1132. }
  1133. }
  1134. }
  1135. void CSharpInstance::refcount_incremented() {
  1136. #ifdef DEBUG_ENABLED
  1137. CRASH_COND(!base_ref);
  1138. CRASH_COND(owner == NULL);
  1139. #endif
  1140. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1141. if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1142. // The reference count was increased after the managed side was the only one referencing our owner.
  1143. // This means the owner is being referenced again by the unmanaged side,
  1144. // so the owner must hold the managed side alive again to avoid it from being GCed.
  1145. // Release the current weak handle and replace it with a strong handle.
  1146. uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(gchandle->get_target());
  1147. gchandle->release();
  1148. gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE);
  1149. }
  1150. }
  1151. bool CSharpInstance::refcount_decremented() {
  1152. #ifdef DEBUG_ENABLED
  1153. CRASH_COND(!base_ref);
  1154. CRASH_COND(owner == NULL);
  1155. #endif
  1156. Reference *ref_owner = Object::cast_to<Reference>(owner);
  1157. int refcount = ref_owner->reference_get_count();
  1158. if (refcount == 1 && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
  1159. // If owner owner is no longer referenced by the unmanaged side,
  1160. // the managed instance takes responsibility of deleting the owner when GCed.
  1161. // Release the current strong handle and replace it with a weak handle.
  1162. uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(gchandle->get_target());
  1163. gchandle->release();
  1164. gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE);
  1165. return false;
  1166. }
  1167. ref_dying = (refcount == 0);
  1168. return ref_dying;
  1169. }
  1170. MultiplayerAPI::RPCMode CSharpInstance::_member_get_rpc_mode(GDMonoClassMember *p_member) const {
  1171. if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
  1172. return MultiplayerAPI::RPC_MODE_REMOTE;
  1173. if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
  1174. return MultiplayerAPI::RPC_MODE_MASTER;
  1175. if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute)))
  1176. return MultiplayerAPI::RPC_MODE_PUPPET;
  1177. if (p_member->has_attribute(CACHED_CLASS(SlaveAttribute)))
  1178. return MultiplayerAPI::RPC_MODE_PUPPET;
  1179. if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute)))
  1180. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1181. if (p_member->has_attribute(CACHED_CLASS(SyncAttribute)))
  1182. return MultiplayerAPI::RPC_MODE_REMOTESYNC;
  1183. if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute)))
  1184. return MultiplayerAPI::RPC_MODE_MASTERSYNC;
  1185. if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute)))
  1186. return MultiplayerAPI::RPC_MODE_PUPPETSYNC;
  1187. return MultiplayerAPI::RPC_MODE_DISABLED;
  1188. }
  1189. MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const {
  1190. GDMonoClass *top = script->script_class;
  1191. while (top && top != script->native) {
  1192. GDMonoMethod *method = top->get_fetched_method_unknown_params(p_method);
  1193. if (method && !method->is_static())
  1194. return _member_get_rpc_mode(method);
  1195. top = top->get_parent_class();
  1196. }
  1197. return MultiplayerAPI::RPC_MODE_DISABLED;
  1198. }
  1199. MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const {
  1200. GDMonoClass *top = script->script_class;
  1201. while (top && top != script->native) {
  1202. GDMonoField *field = top->get_field(p_variable);
  1203. if (field && !field->is_static())
  1204. return _member_get_rpc_mode(field);
  1205. GDMonoProperty *property = top->get_property(p_variable);
  1206. if (property && !property->is_static())
  1207. return _member_get_rpc_mode(property);
  1208. top = top->get_parent_class();
  1209. }
  1210. return MultiplayerAPI::RPC_MODE_DISABLED;
  1211. }
  1212. void CSharpInstance::notification(int p_notification) {
  1213. if (p_notification == Object::NOTIFICATION_PREDELETE) {
  1214. // When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
  1215. // It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
  1216. // to be sent at least once, which happens right before the call to the destructor.
  1217. if (base_ref) {
  1218. // It's not safe to proceed if the owner derives Reference and the refcount reached 0.
  1219. // At this point, Dispose() was already called (manually or from the finalizer) so
  1220. // that's not a problem. The refcount wouldn't have reached 0 otherwise, since the
  1221. // managed side references it and Dispose() needs to be called to release it.
  1222. // However, this means C# Reference scripts can't receive NOTIFICATION_PREDELETE, but
  1223. // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
  1224. return;
  1225. }
  1226. _call_notification(p_notification);
  1227. MonoObject *mono_object = get_mono_object();
  1228. ERR_FAIL_NULL(mono_object);
  1229. GDMonoUtils::GodotObject_Dispose thunk = CACHED_METHOD_THUNK(GodotObject, Dispose);
  1230. MonoException *exc = NULL;
  1231. thunk(mono_object, (MonoObject **)&exc);
  1232. if (exc) {
  1233. GDMonoUtils::set_pending_exception(exc);
  1234. }
  1235. return;
  1236. }
  1237. _call_notification(p_notification);
  1238. }
  1239. void CSharpInstance::_call_notification(int p_notification) {
  1240. MonoObject *mono_object = get_mono_object();
  1241. ERR_FAIL_NULL(mono_object);
  1242. // Custom version of _call_multilevel, optimized for _notification
  1243. uint32_t arg = p_notification;
  1244. void *args[1] = { &arg };
  1245. StringName method_name = CACHED_STRING_NAME(_notification);
  1246. GDMonoClass *top = script->script_class;
  1247. while (top && top != script->native) {
  1248. GDMonoMethod *method = top->get_method(method_name, 1);
  1249. if (method) {
  1250. method->invoke_raw(mono_object, args);
  1251. return;
  1252. }
  1253. top = top->get_parent_class();
  1254. }
  1255. }
  1256. Ref<Script> CSharpInstance::get_script() const {
  1257. return script;
  1258. }
  1259. ScriptLanguage *CSharpInstance::get_language() {
  1260. return CSharpLanguage::get_singleton();
  1261. }
  1262. CSharpInstance::CSharpInstance() :
  1263. owner(NULL),
  1264. base_ref(false),
  1265. ref_dying(false),
  1266. unsafe_referenced(false) {
  1267. }
  1268. CSharpInstance::~CSharpInstance() {
  1269. if (gchandle.is_valid()) {
  1270. gchandle->release(); // Make sure it's released
  1271. }
  1272. if (base_ref && !ref_dying && owner) { // it may be called from the owner's destructor
  1273. _unreference_owner_unsafe();
  1274. }
  1275. if (script.is_valid() && owner) {
  1276. #ifndef NO_THREADS
  1277. CSharpLanguage::singleton->lock->lock();
  1278. #endif
  1279. #ifdef DEBUG_ENABLED
  1280. // CSharpInstance must not be created unless it's going to be added to the list for sure
  1281. Set<Object *>::Element *match = script->instances.find(owner);
  1282. CRASH_COND(!match);
  1283. script->instances.erase(match);
  1284. #else
  1285. script->instances.erase(owner);
  1286. #endif
  1287. #ifndef NO_THREADS
  1288. CSharpLanguage::singleton->lock->unlock();
  1289. #endif
  1290. }
  1291. }
  1292. #ifdef TOOLS_ENABLED
  1293. void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
  1294. placeholders.erase(p_placeholder);
  1295. }
  1296. #endif
  1297. #ifdef TOOLS_ENABLED
  1298. void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
  1299. if (base_cache.is_valid()) {
  1300. base_cache->_update_exports_values(values, propnames);
  1301. }
  1302. for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) {
  1303. values[E->key()] = E->get();
  1304. }
  1305. for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) {
  1306. propnames.push_back(E->get());
  1307. }
  1308. }
  1309. #endif
  1310. bool CSharpScript::_update_exports() {
  1311. #ifdef TOOLS_ENABLED
  1312. if (!valid) {
  1313. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  1314. E->get()->set_build_failed(true);
  1315. }
  1316. return false;
  1317. }
  1318. bool changed = false;
  1319. if (exports_invalidated) {
  1320. exports_invalidated = false;
  1321. changed = true;
  1322. member_info.clear();
  1323. exported_members_cache.clear();
  1324. exported_members_defval_cache.clear();
  1325. // Here we create a temporary managed instance of the class to get the initial values
  1326. MonoObject *tmp_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
  1327. if (!tmp_object) {
  1328. ERR_PRINT("Failed to create temporary MonoObject");
  1329. return false;
  1330. }
  1331. uint32_t tmp_pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(tmp_object); // pin it (not sure if needed)
  1332. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
  1333. MonoException *ctor_exc = NULL;
  1334. ctor->invoke(tmp_object, NULL, &ctor_exc);
  1335. if (ctor_exc) {
  1336. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1337. tmp_object = NULL;
  1338. ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
  1339. GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
  1340. return false;
  1341. }
  1342. GDMonoClass *top = script_class;
  1343. while (top && top != native) {
  1344. PropertyInfo prop_info;
  1345. bool exported;
  1346. const Vector<GDMonoField *> &fields = top->get_all_fields();
  1347. for (int i = fields.size() - 1; i >= 0; i--) {
  1348. GDMonoField *field = fields[i];
  1349. if (_get_member_export(top, field, prop_info, exported)) {
  1350. StringName name = field->get_name();
  1351. if (exported) {
  1352. member_info[name] = prop_info;
  1353. exported_members_cache.push_front(prop_info);
  1354. if (tmp_object) {
  1355. exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
  1356. }
  1357. } else {
  1358. member_info[name] = prop_info;
  1359. }
  1360. }
  1361. }
  1362. const Vector<GDMonoProperty *> &properties = top->get_all_properties();
  1363. for (int i = properties.size() - 1; i >= 0; i--) {
  1364. GDMonoProperty *property = properties[i];
  1365. if (_get_member_export(top, property, prop_info, exported)) {
  1366. StringName name = property->get_name();
  1367. if (exported) {
  1368. member_info[name] = prop_info;
  1369. exported_members_cache.push_front(prop_info);
  1370. if (tmp_object) {
  1371. MonoException *exc = NULL;
  1372. MonoObject *ret = property->get_value(tmp_object, &exc);
  1373. if (exc) {
  1374. exported_members_defval_cache[name] = Variant();
  1375. GDMonoUtils::debug_print_unhandled_exception(exc);
  1376. } else {
  1377. exported_members_defval_cache[name] = GDMonoMarshal::mono_object_to_variant(ret);
  1378. }
  1379. }
  1380. } else {
  1381. member_info[name] = prop_info;
  1382. }
  1383. }
  1384. }
  1385. top = top->get_parent_class();
  1386. }
  1387. // Dispose the temporary managed instance
  1388. GDMonoUtils::GodotObject_Dispose thunk = CACHED_METHOD_THUNK(GodotObject, Dispose);
  1389. MonoException *exc = NULL;
  1390. thunk(tmp_object, (MonoObject **)&exc);
  1391. if (exc) {
  1392. ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
  1393. GDMonoUtils::debug_print_unhandled_exception(exc);
  1394. }
  1395. MonoGCHandle::free_handle(tmp_pinned_gchandle);
  1396. tmp_object = NULL;
  1397. }
  1398. if (placeholders.size()) {
  1399. // Update placeholders if any
  1400. Map<StringName, Variant> values;
  1401. List<PropertyInfo> propnames;
  1402. _update_exports_values(values, propnames);
  1403. for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
  1404. E->get()->set_build_failed(false);
  1405. E->get()->update(propnames, values);
  1406. }
  1407. }
  1408. return changed;
  1409. #endif
  1410. return false;
  1411. }
  1412. void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class) {
  1413. // no need to load the script's signals more than once
  1414. if (!signals_invalidated) {
  1415. return;
  1416. }
  1417. // make sure this classes signals are empty when loading for the first time
  1418. _signals.clear();
  1419. GDMonoClass *top = p_class;
  1420. while (top && top != p_native_class) {
  1421. const Vector<GDMonoClass *> &delegates = top->get_all_delegates();
  1422. for (int i = delegates.size() - 1; i >= 0; --i) {
  1423. Vector<Argument> parameters;
  1424. GDMonoClass *delegate = delegates[i];
  1425. if (_get_signal(top, delegate, parameters)) {
  1426. _signals[delegate->get_name()] = parameters;
  1427. }
  1428. }
  1429. top = top->get_parent_class();
  1430. }
  1431. signals_invalidated = false;
  1432. }
  1433. bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoClass *p_delegate, Vector<Argument> &params) {
  1434. if (p_delegate->has_attribute(CACHED_CLASS(SignalAttribute))) {
  1435. MonoType *raw_type = p_delegate->get_mono_type();
  1436. if (mono_type_get_type(raw_type) == MONO_TYPE_CLASS) {
  1437. // Arguments are accessibles as arguments of .Invoke method
  1438. GDMonoMethod *invoke = p_delegate->get_method("Invoke", -1);
  1439. Vector<StringName> names;
  1440. Vector<ManagedType> types;
  1441. invoke->get_parameter_names(names);
  1442. invoke->get_parameter_types(types);
  1443. if (names.size() == types.size()) {
  1444. for (int i = 0; i < names.size(); ++i) {
  1445. Argument arg;
  1446. arg.name = names[i];
  1447. arg.type = GDMonoMarshal::managed_to_variant_type(types[i]);
  1448. if (arg.type == Variant::NIL) {
  1449. ERR_PRINTS("Unknown type of signal parameter: " + arg.name + " in " + p_class->get_full_name());
  1450. return false;
  1451. }
  1452. params.push_back(arg);
  1453. }
  1454. return true;
  1455. }
  1456. }
  1457. }
  1458. return false;
  1459. }
  1460. #ifdef TOOLS_ENABLED
  1461. /**
  1462. * Returns false if there was an error, otherwise true.
  1463. * If there was an error, r_prop_info and r_exported are not assigned any value.
  1464. */
  1465. bool CSharpScript::_get_member_export(GDMonoClass *p_class, GDMonoClassMember *p_member, PropertyInfo &r_prop_info, bool &r_exported) {
  1466. StringName name = p_member->get_name();
  1467. if (p_member->is_static()) {
  1468. if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
  1469. ERR_PRINTS("Cannot export member because it is static: " + p_class->get_full_name() + "." + name.operator String());
  1470. return false;
  1471. }
  1472. if (member_info.has(name))
  1473. return false;
  1474. ManagedType type;
  1475. if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_FIELD) {
  1476. type = static_cast<GDMonoField *>(p_member)->get_type();
  1477. } else if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1478. type = static_cast<GDMonoProperty *>(p_member)->get_type();
  1479. } else {
  1480. CRASH_NOW();
  1481. }
  1482. Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type);
  1483. if (!p_member->has_attribute(CACHED_CLASS(ExportAttribute))) {
  1484. r_prop_info = PropertyInfo(variant_type, name.operator String(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
  1485. r_exported = false;
  1486. return true;
  1487. }
  1488. if (p_member->get_member_type() == GDMonoClassMember::MEMBER_TYPE_PROPERTY) {
  1489. GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
  1490. if (!property->has_getter() || !property->has_setter()) {
  1491. ERR_PRINTS("Cannot export property because it does not provide a getter or a setter: " + p_class->get_full_name() + "." + name.operator String());
  1492. return false;
  1493. }
  1494. }
  1495. MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));
  1496. PropertyHint hint = PROPERTY_HINT_NONE;
  1497. String hint_string;
  1498. if (variant_type == Variant::NIL) {
  1499. ERR_PRINTS("Unknown type of exported member: " + p_class->get_full_name() + "." + name.operator String());
  1500. return false;
  1501. } else if (variant_type == Variant::INT && type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(type.type_class->get_mono_ptr())) {
  1502. variant_type = Variant::INT;
  1503. hint = PROPERTY_HINT_ENUM;
  1504. Vector<MonoClassField *> fields = type.type_class->get_enum_fields();
  1505. MonoType *enum_basetype = mono_class_enum_basetype(type.type_class->get_mono_ptr());
  1506. String name_only_hint_string;
  1507. // True: enum Foo { Bar, Baz, Quux }
  1508. // True: enum Foo { Bar = 0, Baz = 1, Quux = 2 }
  1509. // False: enum Foo { Bar = 0, Baz = 7, Quux = 5 }
  1510. bool uses_default_values = true;
  1511. for (int i = 0; i < fields.size(); i++) {
  1512. MonoClassField *field = fields[i];
  1513. if (i > 0) {
  1514. hint_string += ",";
  1515. name_only_hint_string += ",";
  1516. }
  1517. String enum_field_name = mono_field_get_name(field);
  1518. hint_string += enum_field_name;
  1519. name_only_hint_string += enum_field_name;
  1520. // TODO:
  1521. // Instead of using mono_field_get_value_object, we can do this without boxing. Check the
  1522. // internal mono functions: ves_icall_System_Enum_GetEnumValuesAndNames and the get_enum_field.
  1523. MonoObject *val_obj = mono_field_get_value_object(mono_domain_get(), field, NULL);
  1524. if (val_obj == NULL) {
  1525. ERR_PRINTS("Failed to get '" + enum_field_name + "' constant enum value of exported member: " +
  1526. p_class->get_full_name() + "." + name.operator String());
  1527. return false;
  1528. }
  1529. bool r_error;
  1530. uint64_t val = GDMonoUtils::unbox_enum_value(val_obj, enum_basetype, r_error);
  1531. if (r_error) {
  1532. ERR_PRINTS("Failed to unbox '" + enum_field_name + "' constant enum value of exported member: " +
  1533. p_class->get_full_name() + "." + name.operator String());
  1534. return false;
  1535. }
  1536. if (val != i) {
  1537. uses_default_values = false;
  1538. }
  1539. hint_string += ":";
  1540. hint_string += String::num_uint64(val);
  1541. }
  1542. if (uses_default_values) {
  1543. // If we use the format NAME:VAL, that's what the editor displays.
  1544. // That's annoying if the user is not using custom values for the enum constants.
  1545. // This may not be needed in the future if the editor is changed to not display values.
  1546. hint_string = name_only_hint_string;
  1547. }
  1548. } else if (variant_type == Variant::OBJECT && CACHED_CLASS(GodotReference)->is_assignable_from(type.type_class)) {
  1549. hint = PROPERTY_HINT_RESOURCE_TYPE;
  1550. hint_string = NATIVE_GDMONOCLASS_NAME(type.type_class);
  1551. } else {
  1552. hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
  1553. hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
  1554. }
  1555. r_prop_info = PropertyInfo(variant_type, name.operator String(), hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE);
  1556. r_exported = true;
  1557. return true;
  1558. }
  1559. #endif
  1560. void CSharpScript::_clear() {
  1561. tool = false;
  1562. valid = false;
  1563. base = NULL;
  1564. native = NULL;
  1565. script_class = NULL;
  1566. }
  1567. Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1568. if (unlikely(GDMono::get_singleton() == NULL)) {
  1569. // Probably not the best error but eh.
  1570. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1571. return Variant();
  1572. }
  1573. GDMonoClass *top = script_class;
  1574. while (top && top != native) {
  1575. GDMonoMethod *method = top->get_method(p_method, p_argcount);
  1576. if (method && method->is_static()) {
  1577. MonoObject *result = method->invoke(NULL, p_args);
  1578. if (result) {
  1579. return GDMonoMarshal::mono_object_to_variant(result);
  1580. } else {
  1581. return Variant();
  1582. }
  1583. }
  1584. top = top->get_parent_class();
  1585. }
  1586. // No static method found. Try regular instance calls
  1587. return Script::call(p_method, p_args, p_argcount, r_error);
  1588. }
  1589. void CSharpScript::_resource_path_changed() {
  1590. String path = get_path();
  1591. if (!path.empty()) {
  1592. name = get_path().get_file().get_basename();
  1593. }
  1594. }
  1595. bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
  1596. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1597. r_ret = get_source_code();
  1598. return true;
  1599. }
  1600. return false;
  1601. }
  1602. bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
  1603. if (p_name == CSharpLanguage::singleton->string_names._script_source) {
  1604. set_source_code(p_value);
  1605. reload();
  1606. return true;
  1607. }
  1608. return false;
  1609. }
  1610. void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
  1611. p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  1612. }
  1613. void CSharpScript::_bind_methods() {
  1614. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo(Variant::OBJECT, "new"));
  1615. }
  1616. Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class) {
  1617. // This method should not fail
  1618. CRASH_COND(!p_class);
  1619. Ref<CSharpScript> script = memnew(CSharpScript);
  1620. script->name = p_class->get_name();
  1621. script->script_class = p_class;
  1622. script->native = GDMonoUtils::get_class_native_base(script->script_class);
  1623. CRASH_COND(script->native == NULL);
  1624. GDMonoClass *base = script->script_class->get_parent_class();
  1625. if (base != script->native)
  1626. script->base = base;
  1627. #ifdef DEBUG_ENABLED
  1628. // For debug builds, we must fetch from all native base methods as well.
  1629. // Native base methods must be fetched before the current class.
  1630. // Not needed if the script class itself is a native class.
  1631. if (script->script_class != script->native) {
  1632. GDMonoClass *native_top = script->native;
  1633. while (native_top) {
  1634. native_top->fetch_methods_with_godot_api_checks(script->native);
  1635. if (native_top == CACHED_CLASS(GodotObject))
  1636. break;
  1637. native_top = native_top->get_parent_class();
  1638. }
  1639. }
  1640. #endif
  1641. script->script_class->fetch_methods_with_godot_api_checks(script->native);
  1642. // Need to fetch method from base classes as well
  1643. GDMonoClass *top = script->script_class;
  1644. while (top && top != script->native) {
  1645. top->fetch_methods_with_godot_api_checks(script->native);
  1646. top = top->get_parent_class();
  1647. }
  1648. script->load_script_signals(script->script_class, script->native);
  1649. return script;
  1650. }
  1651. bool CSharpScript::can_instance() const {
  1652. #ifdef TOOLS_ENABLED
  1653. if (Engine::get_singleton()->is_editor_hint()) {
  1654. if (get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted...
  1655. if (_create_project_solution_if_needed()) {
  1656. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  1657. "Compile",
  1658. ProjectSettings::get_singleton()->globalize_path(get_path()));
  1659. } else {
  1660. ERR_PRINTS("Cannot add " + get_path() + " to the C# project because it could not be created.");
  1661. }
  1662. }
  1663. }
  1664. #endif
  1665. #ifdef TOOLS_ENABLED
  1666. return valid && (tool || ScriptServer::is_scripting_enabled());
  1667. #else
  1668. return valid;
  1669. #endif
  1670. }
  1671. StringName CSharpScript::get_instance_base_type() const {
  1672. if (native)
  1673. return native->get_name();
  1674. else
  1675. return StringName();
  1676. }
  1677. CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
  1678. /* STEP 1, CREATE */
  1679. CSharpInstance *instance = memnew(CSharpInstance);
  1680. instance->base_ref = p_isref;
  1681. instance->script = Ref<CSharpScript>(this);
  1682. instance->owner = p_owner;
  1683. instance->owner->set_script_instance(instance);
  1684. if (instance->base_ref)
  1685. instance->_reference_owner_unsafe();
  1686. /* STEP 2, INITIALIZE AND CONSTRUCT */
  1687. MonoObject *mono_object = mono_object_new(SCRIPTS_DOMAIN, script_class->get_mono_ptr());
  1688. if (!mono_object) {
  1689. instance->script = Ref<CSharpScript>();
  1690. instance->owner->set_script_instance(NULL);
  1691. r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
  1692. ERR_EXPLAIN("Failed to allocate memory for the object");
  1693. ERR_FAIL_V(NULL);
  1694. }
  1695. uint32_t pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(mono_object); // we might lock after this, so pin it
  1696. #ifndef NO_THREADS
  1697. CSharpLanguage::singleton->lock->lock();
  1698. #endif
  1699. instances.insert(instance->owner);
  1700. #ifndef NO_THREADS
  1701. CSharpLanguage::singleton->lock->unlock();
  1702. #endif
  1703. CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);
  1704. // Construct
  1705. GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
  1706. ctor->invoke(mono_object, p_args);
  1707. // Tie managed to unmanaged
  1708. instance->gchandle = MonoGCHandle::create_strong(mono_object);
  1709. /* STEP 3, PARTY */
  1710. MonoGCHandle::free_handle(pinned_gchandle);
  1711. //@TODO make thread safe
  1712. return instance;
  1713. }
  1714. Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  1715. if (!valid) {
  1716. r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
  1717. return Variant();
  1718. }
  1719. r_error.error = Variant::CallError::CALL_OK;
  1720. REF ref;
  1721. Object *owner = NULL;
  1722. ERR_FAIL_NULL_V(native, Variant());
  1723. owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native));
  1724. Reference *r = Object::cast_to<Reference>(owner);
  1725. if (r) {
  1726. ref = REF(r);
  1727. }
  1728. CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
  1729. if (!instance) {
  1730. if (ref.is_null()) {
  1731. memdelete(owner); //no owner, sorry
  1732. }
  1733. return Variant();
  1734. }
  1735. if (ref.is_valid()) {
  1736. return ref;
  1737. } else {
  1738. return owner;
  1739. }
  1740. }
  1741. ScriptInstance *CSharpScript::instance_create(Object *p_this) {
  1742. #ifdef DEBUG_ENABLED
  1743. CRASH_COND(!valid);
  1744. #endif
  1745. if (!script_class) {
  1746. if (GDMono::get_singleton()->get_project_assembly() == NULL) {
  1747. // The project assembly is not loaded
  1748. ERR_EXPLAIN("Cannot instance script because the project assembly is not loaded. Script: " + get_path());
  1749. ERR_FAIL_V(NULL);
  1750. } else {
  1751. // The project assembly is loaded, but the class could not found
  1752. ERR_EXPLAIN("Cannot instance script because the class '" + name + "' could not be found. Script: " + get_path());
  1753. ERR_FAIL_V(NULL);
  1754. }
  1755. }
  1756. ERR_FAIL_COND_V(!valid, NULL);
  1757. if (native) {
  1758. String native_name = native->get_name();
  1759. if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
  1760. if (ScriptDebugger::get_singleton()) {
  1761. 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() + "'");
  1762. }
  1763. ERR_EXPLAIN("Script inherits from native type '" + native_name + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
  1764. ERR_FAIL_V(NULL);
  1765. }
  1766. }
  1767. Variant::CallError unchecked_error;
  1768. return _create_instance(NULL, 0, p_this, Object::cast_to<Reference>(p_this), unchecked_error);
  1769. }
  1770. PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
  1771. #ifdef TOOLS_ENABLED
  1772. PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
  1773. placeholders.insert(si);
  1774. _update_exports();
  1775. return si;
  1776. #else
  1777. return NULL;
  1778. #endif
  1779. }
  1780. bool CSharpScript::instance_has(const Object *p_this) const {
  1781. #ifndef NO_THREADS
  1782. CSharpLanguage::singleton->lock->lock();
  1783. #endif
  1784. bool ret = instances.has((Object *)p_this);
  1785. #ifndef NO_THREADS
  1786. CSharpLanguage::singleton->lock->unlock();
  1787. #endif
  1788. return ret;
  1789. }
  1790. bool CSharpScript::has_source_code() const {
  1791. return !source.empty();
  1792. }
  1793. String CSharpScript::get_source_code() const {
  1794. return source;
  1795. }
  1796. void CSharpScript::set_source_code(const String &p_code) {
  1797. if (source == p_code)
  1798. return;
  1799. source = p_code;
  1800. #ifdef TOOLS_ENABLED
  1801. source_changed_cache = true;
  1802. #endif
  1803. }
  1804. bool CSharpScript::has_method(const StringName &p_method) const {
  1805. if (!script_class)
  1806. return false;
  1807. return script_class->has_fetched_method_unknown_params(p_method);
  1808. }
  1809. Error CSharpScript::reload(bool p_keep_state) {
  1810. #ifndef NO_THREADS
  1811. CSharpLanguage::singleton->lock->lock();
  1812. #endif
  1813. bool has_instances = instances.size();
  1814. #ifndef NO_THREADS
  1815. CSharpLanguage::singleton->lock->unlock();
  1816. #endif
  1817. ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
  1818. GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly();
  1819. if (project_assembly) {
  1820. script_class = project_assembly->get_object_derived_class(name);
  1821. valid = script_class != NULL;
  1822. if (script_class) {
  1823. #ifdef DEBUG_ENABLED
  1824. print_verbose("Found class " + script_class->get_namespace() + "." + script_class->get_name() + " for script " + get_path());
  1825. #endif
  1826. tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));
  1827. native = GDMonoUtils::get_class_native_base(script_class);
  1828. CRASH_COND(native == NULL);
  1829. GDMonoClass *base_class = script_class->get_parent_class();
  1830. if (base_class != native)
  1831. base = base_class;
  1832. #ifdef DEBUG_ENABLED
  1833. // For debug builds, we must fetch from all native base methods as well.
  1834. // Native base methods must be fetched before the current class.
  1835. // Not needed if the script class itself is a native class.
  1836. if (script_class != native) {
  1837. GDMonoClass *native_top = native;
  1838. while (native_top) {
  1839. native_top->fetch_methods_with_godot_api_checks(native);
  1840. if (native_top == CACHED_CLASS(GodotObject))
  1841. break;
  1842. native_top = native_top->get_parent_class();
  1843. }
  1844. }
  1845. #endif
  1846. script_class->fetch_methods_with_godot_api_checks(native);
  1847. // Need to fetch method from base classes as well
  1848. GDMonoClass *top = script_class;
  1849. while (top && top != native) {
  1850. top->fetch_methods_with_godot_api_checks(native);
  1851. top = top->get_parent_class();
  1852. }
  1853. load_script_signals(script_class, native);
  1854. }
  1855. return OK;
  1856. }
  1857. return ERR_FILE_MISSING_DEPENDENCIES;
  1858. }
  1859. ScriptLanguage *CSharpScript::get_language() const {
  1860. return CSharpLanguage::get_singleton();
  1861. }
  1862. bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
  1863. #ifdef TOOLS_ENABLED
  1864. const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
  1865. if (E) {
  1866. r_value = E->get();
  1867. return true;
  1868. }
  1869. if (base_cache.is_valid()) {
  1870. return base_cache->get_property_default_value(p_property, r_value);
  1871. }
  1872. #endif
  1873. return false;
  1874. }
  1875. void CSharpScript::update_exports() {
  1876. #ifdef TOOLS_ENABLED
  1877. _update_exports();
  1878. #endif
  1879. }
  1880. bool CSharpScript::has_script_signal(const StringName &p_signal) const {
  1881. if (_signals.has(p_signal))
  1882. return true;
  1883. return false;
  1884. }
  1885. void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
  1886. for (const Map<StringName, Vector<Argument> >::Element *E = _signals.front(); E; E = E->next()) {
  1887. MethodInfo mi;
  1888. mi.name = E->key();
  1889. for (int i = 0; i < E->get().size(); i++) {
  1890. PropertyInfo arg;
  1891. arg.name = E->get()[i].name;
  1892. mi.arguments.push_back(arg);
  1893. }
  1894. r_signals->push_back(mi);
  1895. }
  1896. }
  1897. Ref<Script> CSharpScript::get_base_script() const {
  1898. // TODO search in metadata file once we have it, not important any way?
  1899. return Ref<Script>();
  1900. }
  1901. void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
  1902. for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
  1903. p_list->push_back(E->value());
  1904. }
  1905. }
  1906. int CSharpScript::get_member_line(const StringName &p_member) const {
  1907. // TODO omnisharp
  1908. return -1;
  1909. }
  1910. Error CSharpScript::load_source_code(const String &p_path) {
  1911. PoolVector<uint8_t> sourcef;
  1912. Error err;
  1913. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  1914. ERR_FAIL_COND_V(err != OK, err);
  1915. int len = f->get_len();
  1916. sourcef.resize(len + 1);
  1917. PoolVector<uint8_t>::Write w = sourcef.write();
  1918. int r = f->get_buffer(w.ptr(), len);
  1919. f->close();
  1920. memdelete(f);
  1921. ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
  1922. w[len] = 0;
  1923. String s;
  1924. if (s.parse_utf8((const char *)w.ptr())) {
  1925. 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.");
  1926. ERR_FAIL_V(ERR_INVALID_DATA);
  1927. }
  1928. source = s;
  1929. #ifdef TOOLS_ENABLED
  1930. source_changed_cache = true;
  1931. #endif
  1932. return OK;
  1933. }
  1934. StringName CSharpScript::get_script_name() const {
  1935. return name;
  1936. }
  1937. CSharpScript::CSharpScript() :
  1938. script_list(this) {
  1939. _clear();
  1940. #ifdef TOOLS_ENABLED
  1941. source_changed_cache = false;
  1942. exports_invalidated = true;
  1943. #endif
  1944. signals_invalidated = true;
  1945. _resource_path_changed();
  1946. #ifdef DEBUG_ENABLED
  1947. #ifndef NO_THREADS
  1948. CSharpLanguage::get_singleton()->lock->lock();
  1949. #endif
  1950. CSharpLanguage::get_singleton()->script_list.add(&script_list);
  1951. #ifndef NO_THREADS
  1952. CSharpLanguage::get_singleton()->lock->unlock();
  1953. #endif
  1954. #endif // DEBUG_ENABLED
  1955. }
  1956. CSharpScript::~CSharpScript() {
  1957. #ifdef DEBUG_ENABLED
  1958. #ifndef NO_THREADS
  1959. CSharpLanguage::get_singleton()->lock->lock();
  1960. #endif
  1961. CSharpLanguage::get_singleton()->script_list.remove(&script_list);
  1962. #ifndef NO_THREADS
  1963. CSharpLanguage::get_singleton()->lock->unlock();
  1964. #endif
  1965. #endif // DEBUG_ENABLED
  1966. }
  1967. /*************** RESOURCE ***************/
  1968. RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
  1969. if (r_error)
  1970. *r_error = ERR_FILE_CANT_OPEN;
  1971. // TODO ignore anything inside bin/ and obj/ in tools builds?
  1972. CSharpScript *script = memnew(CSharpScript);
  1973. Ref<CSharpScript> scriptres(script);
  1974. #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
  1975. Error err = script->load_source_code(p_path);
  1976. ERR_FAIL_COND_V(err != OK, RES());
  1977. #endif
  1978. script->set_path(p_original_path);
  1979. #ifndef TOOLS_ENABLED
  1980. #ifdef DEBUG_ENABLED
  1981. // User is responsible for thread attach/detach
  1982. ERR_EXPLAIN("Thread is not attached");
  1983. CRASH_COND(mono_domain_get() == NULL);
  1984. #endif
  1985. #endif
  1986. #ifdef TOOLS_ENABLED
  1987. if (Engine::get_singleton()->is_editor_hint() && mono_domain_get() == NULL) {
  1988. CRASH_COND(Thread::get_caller_id() == Thread::get_main_id());
  1989. // Thread is not attached, but we will make an exception in this case
  1990. // because this may be called by one of the editor's worker threads.
  1991. // Attach this thread temporarily to reload the script.
  1992. if (SCRIPTS_DOMAIN) {
  1993. MonoThread *mono_thread = mono_thread_attach(SCRIPTS_DOMAIN);
  1994. CRASH_COND(mono_thread == NULL);
  1995. script->reload();
  1996. mono_thread_detach(mono_thread);
  1997. }
  1998. } else { // just reload it normally
  1999. #endif
  2000. script->reload();
  2001. #ifdef TOOLS_ENABLED
  2002. }
  2003. #endif
  2004. if (r_error)
  2005. *r_error = OK;
  2006. return scriptres;
  2007. }
  2008. void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
  2009. p_extensions->push_back("cs");
  2010. }
  2011. bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
  2012. return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
  2013. }
  2014. String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
  2015. return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
  2016. }
  2017. Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  2018. Ref<CSharpScript> sqscr = p_resource;
  2019. ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
  2020. String source = sqscr->get_source_code();
  2021. #ifdef TOOLS_ENABLED
  2022. if (!FileAccess::exists(p_path)) {
  2023. // The file does not yet exists, let's assume the user just created this script
  2024. if (_create_project_solution_if_needed()) {
  2025. CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
  2026. "Compile",
  2027. ProjectSettings::get_singleton()->globalize_path(p_path));
  2028. } else {
  2029. ERR_PRINTS("Cannot add " + p_path + " to the C# project because it could not be created.");
  2030. }
  2031. }
  2032. #endif
  2033. Error err;
  2034. FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  2035. ERR_FAIL_COND_V(err, err);
  2036. file->store_string(source);
  2037. if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
  2038. memdelete(file);
  2039. return ERR_CANT_CREATE;
  2040. }
  2041. file->close();
  2042. memdelete(file);
  2043. if (ScriptServer::is_reload_scripts_on_save_enabled()) {
  2044. CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
  2045. }
  2046. return OK;
  2047. }
  2048. void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  2049. if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
  2050. p_extensions->push_back("cs");
  2051. }
  2052. }
  2053. bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
  2054. return Object::cast_to<CSharpScript>(p_resource.ptr()) != NULL;
  2055. }
  2056. CSharpLanguage::StringNameCache::StringNameCache() {
  2057. _signal_callback = StaticCString::create("_signal_callback");
  2058. _set = StaticCString::create("_set");
  2059. _get = StaticCString::create("_get");
  2060. _notification = StaticCString::create("_notification");
  2061. _script_source = StaticCString::create("script/source");
  2062. dotctor = StaticCString::create(".ctor");
  2063. }