csharp_script.cpp 52 KB

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