csharp_script.cpp 58 KB

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